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 isIE = ua.indexOf("msie") > -1,
57 isIE7 = ua.indexOf("msie 7") > -1,
58 isGecko = !isSafari && ua.indexOf("gecko") > -1,
59 isBorderBox = isIE && !isStrict,
60 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
61 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
62 isLinux = (ua.indexOf("linux") != -1),
63 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
64 isTouch = (function() {
66 document.createEvent("TouchEvent");
73 // remove css image flicker
76 document.execCommand("BackgroundImageCache", false, true);
82 * True if the browser is in strict mode
87 * True if the page is running over SSL
92 * True when the document is fully initialized and ready for action
97 * Turn on debugging output (currently only the factory uses this)
104 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
107 enableGarbageCollector : true,
110 * True to automatically purge event listeners after uncaching an element (defaults to false).
111 * Note: this only happens if enableGarbageCollector is true.
114 enableListenerCollection:false,
117 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
118 * the IE insecure content warning (defaults to javascript:false).
121 SSL_SECURE_URL : "javascript:false",
124 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
125 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
128 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
130 emptyFn : function(){},
133 * Copies all the properties of config to obj if they don't already exist.
134 * @param {Object} obj The receiver of the properties
135 * @param {Object} config The source of the properties
136 * @return {Object} returns obj
138 applyIf : function(o, c){
141 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
148 * Applies event listeners to elements by selectors when the document is ready.
149 * The event name is specified with an @ suffix.
152 // add a listener for click on all anchors in element with id foo
153 '#foo a@click' : function(e, t){
157 // add the same listener to multiple selectors (separated by comma BEFORE the @)
158 '#foo a, #bar span.some-class@mouseover' : function(){
163 * @param {Object} obj The list of behaviors to apply
165 addBehaviors : function(o){
167 Roo.onReady(function(){
172 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
174 var parts = b.split('@');
175 if(parts[1]){ // for Object prototype breakers
178 cache[s] = Roo.select(s);
180 cache[s].on(parts[1], o[b]);
187 * Generates unique ids. If the element already has an id, it is unchanged
188 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
189 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
190 * @return {String} The generated Id.
192 id : function(el, prefix){
193 prefix = prefix || "roo-gen";
195 var id = prefix + (++idSeed);
196 return el ? (el.id ? el.id : (el.id = id)) : id;
201 * Extends one class with another class and optionally overrides members with the passed literal. This class
202 * also adds the function "override()" to the class that can be used to override
203 * members on an instance.
204 * @param {Object} subclass The class inheriting the functionality
205 * @param {Object} superclass The class being extended
206 * @param {Object} overrides (optional) A literal with members
211 var io = function(o){
216 return function(sb, sp, overrides){
217 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
220 sb = function(){sp.apply(this, arguments);};
222 var F = function(){}, sbp, spp = sp.prototype;
224 sbp = sb.prototype = new F();
228 if(spp.constructor == Object.prototype.constructor){
233 sb.override = function(o){
237 Roo.override(sb, overrides);
243 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
245 Roo.override(MyClass, {
246 newMethod1: function(){
249 newMethod2: function(foo){
254 * @param {Object} origclass The class to override
255 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
256 * containing one or more methods.
259 override : function(origclass, overrides){
261 var p = origclass.prototype;
262 for(var method in overrides){
263 p[method] = overrides[method];
268 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
270 Roo.namespace('Company', 'Company.data');
271 Company.Widget = function() { ... }
272 Company.data.CustomStore = function(config) { ... }
274 * @param {String} namespace1
275 * @param {String} namespace2
276 * @param {String} etc
279 namespace : function(){
280 var a=arguments, o=null, i, j, d, rt;
281 for (i=0; i<a.length; ++i) {
285 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
286 for (j=1; j<d.length; ++j) {
287 o[d[j]]=o[d[j]] || {};
293 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
295 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
296 Roo.factory(conf, Roo.data);
298 * @param {String} classname
299 * @param {String} namespace (optional)
303 factory : function(c, ns)
305 // no xtype, no ns or c.xns - or forced off by c.xns
306 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
309 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
310 if (c.constructor == ns[c.xtype]) {// already created...
314 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
315 var ret = new ns[c.xtype](c);
319 c.xns = false; // prevent recursion..
323 * Logs to console if it can.
325 * @param {String|Object} string
330 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
337 * 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.
341 urlEncode : function(o){
347 var ov = o[key], k = Roo.encodeURIComponent(key);
348 var type = typeof ov;
349 if(type == 'undefined'){
351 }else if(type != "function" && type != "object"){
352 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
353 }else if(ov instanceof Array){
355 for(var i = 0, len = ov.length; i < len; i++) {
356 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
367 * Safe version of encodeURIComponent
368 * @param {String} data
372 encodeURIComponent : function (data)
375 return encodeURIComponent(data);
376 } catch(e) {} // should be an uri encode error.
378 if (data == '' || data == null){
381 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
382 function nibble_to_hex(nibble){
383 var chars = '0123456789ABCDEF';
384 return chars.charAt(nibble);
386 data = data.toString();
388 for(var i=0; i<data.length; i++){
389 var c = data.charCodeAt(i);
390 var bs = new Array();
393 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
394 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
395 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
396 bs[3] = 0x80 | (c & 0x3F);
397 }else if (c > 0x800){
399 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
400 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
401 bs[2] = 0x80 | (c & 0x3F);
404 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
405 bs[1] = 0x80 | (c & 0x3F);
410 for(var j=0; j<bs.length; j++){
412 var hex = nibble_to_hex((b & 0xF0) >>> 4)
413 + nibble_to_hex(b &0x0F);
422 * 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]}.
423 * @param {String} string
424 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
425 * @return {Object} A literal with members
427 urlDecode : function(string, overwrite){
428 if(!string || !string.length){
432 var pairs = string.split('&');
433 var pair, name, value;
434 for(var i = 0, len = pairs.length; i < len; i++){
435 pair = pairs[i].split('=');
436 name = decodeURIComponent(pair[0]);
437 value = decodeURIComponent(pair[1]);
438 if(overwrite !== true){
439 if(typeof obj[name] == "undefined"){
441 }else if(typeof obj[name] == "string"){
442 obj[name] = [obj[name]];
443 obj[name].push(value);
445 obj[name].push(value);
455 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
456 * passed array is not really an array, your function is called once with it.
457 * The supplied function is called with (Object item, Number index, Array allItems).
458 * @param {Array/NodeList/Mixed} array
459 * @param {Function} fn
460 * @param {Object} scope
462 each : function(array, fn, scope){
463 if(typeof array.length == "undefined" || typeof array == "string"){
466 for(var i = 0, len = array.length; i < len; i++){
467 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
472 combine : function(){
473 var as = arguments, l = as.length, r = [];
474 for(var i = 0; i < l; i++){
476 if(a instanceof Array){
478 }else if(a.length !== undefined && !a.substr){
479 r = r.concat(Array.prototype.slice.call(a, 0));
488 * Escapes the passed string for use in a regular expression
489 * @param {String} str
492 escapeRe : function(s) {
493 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
497 callback : function(cb, scope, args, delay){
498 if(typeof cb == "function"){
500 cb.defer(delay, scope, args || []);
502 cb.apply(scope, args || []);
508 * Return the dom node for the passed string (id), dom node, or Roo.Element
509 * @param {String/HTMLElement/Roo.Element} el
510 * @return HTMLElement
512 getDom : function(el){
516 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
520 * Shorthand for {@link Roo.ComponentMgr#get}
522 * @return Roo.Component
524 getCmp : function(id){
525 return Roo.ComponentMgr.get(id);
528 num : function(v, defaultValue){
529 if(typeof v != 'number'){
535 destroy : function(){
536 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
540 as.removeAllListeners();
544 if(typeof as.purgeListeners == 'function'){
547 if(typeof as.destroy == 'function'){
554 // inpired by a similar function in mootools library
556 * Returns the type of object that is passed in. If the object passed in is null or undefined it
557 * return false otherwise it returns one of the following values:<ul>
558 * <li><b>string</b>: If the object passed is a string</li>
559 * <li><b>number</b>: If the object passed is a number</li>
560 * <li><b>boolean</b>: If the object passed is a boolean value</li>
561 * <li><b>function</b>: If the object passed is a function reference</li>
562 * <li><b>object</b>: If the object passed is an object</li>
563 * <li><b>array</b>: If the object passed is an array</li>
564 * <li><b>regexp</b>: If the object passed is a regular expression</li>
565 * <li><b>element</b>: If the object passed is a DOM Element</li>
566 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
567 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
568 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
569 * @param {Mixed} object
573 if(o === undefined || o === null){
580 if(t == 'object' && o.nodeName) {
582 case 1: return 'element';
583 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
586 if(t == 'object' || t == 'function') {
587 switch(o.constructor) {
588 case Array: return 'array';
589 case RegExp: return 'regexp';
591 if(typeof o.length == 'number' && typeof o.item == 'function') {
599 * Returns true if the passed value is null, undefined or an empty string (optional).
600 * @param {Mixed} value The value to test
601 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
604 isEmpty : function(v, allowBlank){
605 return v === null || v === undefined || (!allowBlank ? v === '' : false);
619 isBorderBox : isBorderBox,
621 isWindows : isWindows,
630 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
631 * you may want to set this to true.
634 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
639 * Selects a single element as a Roo Element
640 * This is about as close as you can get to jQuery's $('do crazy stuff')
641 * @param {String} selector The selector/xpath query
642 * @param {Node} root (optional) The start of the query (defaults to document).
643 * @return {Roo.Element}
645 selectNode : function(selector, root)
647 var node = Roo.DomQuery.selectNode(selector,root);
648 return node ? Roo.get(node) : new Roo.Element(false);
656 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
657 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
660 "Roo.bootstrap.dash");
663 * Ext JS Library 1.1.1
664 * Copyright(c) 2006-2007, Ext JS, LLC.
666 * Originally Released Under LGPL - original licence link has changed is not relivant.
669 * <script type="text/javascript">
673 // wrappedn so fnCleanup is not in global scope...
675 function fnCleanUp() {
676 var p = Function.prototype;
677 delete p.createSequence;
679 delete p.createDelegate;
680 delete p.createCallback;
681 delete p.createInterceptor;
683 window.detachEvent("onunload", fnCleanUp);
685 window.attachEvent("onunload", fnCleanUp);
692 * These functions are available on every Function object (any JavaScript function).
694 Roo.apply(Function.prototype, {
696 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
697 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
698 * Will create a function that is bound to those 2 args.
699 * @return {Function} The new function
701 createCallback : function(/*args...*/){
702 // make args available, in function below
703 var args = arguments;
706 return method.apply(window, args);
711 * Creates a delegate (callback) that sets the scope to obj.
712 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
713 * Will create a function that is automatically scoped to this.
714 * @param {Object} obj (optional) The object for which the scope is set
715 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
716 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
717 * if a number the args are inserted at the specified position
718 * @return {Function} The new function
720 createDelegate : function(obj, args, appendArgs){
723 var callArgs = args || arguments;
724 if(appendArgs === true){
725 callArgs = Array.prototype.slice.call(arguments, 0);
726 callArgs = callArgs.concat(args);
727 }else if(typeof appendArgs == "number"){
728 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
729 var applyArgs = [appendArgs, 0].concat(args); // create method call params
730 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
732 return method.apply(obj || window, callArgs);
737 * Calls this function after the number of millseconds specified.
738 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
739 * @param {Object} obj (optional) The object for which the scope is set
740 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
741 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
742 * if a number the args are inserted at the specified position
743 * @return {Number} The timeout id that can be used with clearTimeout
745 defer : function(millis, obj, args, appendArgs){
746 var fn = this.createDelegate(obj, args, appendArgs);
748 return setTimeout(fn, millis);
754 * Create a combined function call sequence of the original function + the passed function.
755 * The resulting function returns the results of the original function.
756 * The passed fcn is called with the parameters of the original function
757 * @param {Function} fcn The function to sequence
758 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
759 * @return {Function} The new function
761 createSequence : function(fcn, scope){
762 if(typeof fcn != "function"){
767 var retval = method.apply(this || window, arguments);
768 fcn.apply(scope || this || window, arguments);
774 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
775 * The resulting function returns the results of the original function.
776 * The passed fcn is called with the parameters of the original function.
778 * @param {Function} fcn The function to call before the original
779 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
780 * @return {Function} The new function
782 createInterceptor : function(fcn, scope){
783 if(typeof fcn != "function"){
790 if(fcn.apply(scope || this || window, arguments) === false){
793 return method.apply(this || window, arguments);
799 * Ext JS Library 1.1.1
800 * Copyright(c) 2006-2007, Ext JS, LLC.
802 * Originally Released Under LGPL - original licence link has changed is not relivant.
805 * <script type="text/javascript">
808 Roo.applyIf(String, {
813 * Escapes the passed string for ' and \
814 * @param {String} string The string to escape
815 * @return {String} The escaped string
818 escape : function(string) {
819 return string.replace(/('|\\)/g, "\\$1");
823 * Pads the left side of a string with a specified character. This is especially useful
824 * for normalizing number and date strings. Example usage:
826 var s = String.leftPad('123', 5, '0');
827 // s now contains the string: '00123'
829 * @param {String} string The original string
830 * @param {Number} size The total length of the output string
831 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
832 * @return {String} The padded string
835 leftPad : function (val, size, ch) {
836 var result = new String(val);
837 if(ch === null || ch === undefined || ch === '') {
840 while (result.length < size) {
841 result = ch + result;
847 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
848 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
850 var cls = 'my-class', text = 'Some text';
851 var s = String.format('<div class="{0}">{1}</div>', cls, text);
852 // s now contains the string: '<div class="my-class">Some text</div>'
854 * @param {String} string The tokenized string to be formatted
855 * @param {String} value1 The value to replace token {0}
856 * @param {String} value2 Etc...
857 * @return {String} The formatted string
860 format : function(format){
861 var args = Array.prototype.slice.call(arguments, 1);
862 return format.replace(/\{(\d+)\}/g, function(m, i){
863 return Roo.util.Format.htmlEncode(args[i]);
869 * Utility function that allows you to easily switch a string between two alternating values. The passed value
870 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
871 * they are already different, the first value passed in is returned. Note that this method returns the new value
872 * but does not change the current string.
874 // alternate sort directions
875 sort = sort.toggle('ASC', 'DESC');
877 // instead of conditional logic:
878 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
880 * @param {String} value The value to compare to the current string
881 * @param {String} other The new value to use if the string already equals the first value passed in
882 * @return {String} The new value
885 String.prototype.toggle = function(value, other){
886 return this == value ? other : value;
889 * Ext JS Library 1.1.1
890 * Copyright(c) 2006-2007, Ext JS, LLC.
892 * Originally Released Under LGPL - original licence link has changed is not relivant.
895 * <script type="text/javascript">
901 Roo.applyIf(Number.prototype, {
903 * Checks whether or not the current number is within a desired range. If the number is already within the
904 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
905 * exceeded. Note that this method returns the constrained value but does not change the current number.
906 * @param {Number} min The minimum number in the range
907 * @param {Number} max The maximum number in the range
908 * @return {Number} The constrained value if outside the range, otherwise the current value
910 constrain : function(min, max){
911 return Math.min(Math.max(this, min), max);
915 * Ext JS Library 1.1.1
916 * Copyright(c) 2006-2007, Ext JS, LLC.
918 * Originally Released Under LGPL - original licence link has changed is not relivant.
921 * <script type="text/javascript">
926 Roo.applyIf(Array.prototype, {
929 * Checks whether or not the specified object exists in the array.
930 * @param {Object} o The object to check for
931 * @return {Number} The index of o in the array (or -1 if it is not found)
933 indexOf : function(o){
934 for (var i = 0, len = this.length; i < len; i++){
935 if(this[i] == o) return i;
941 * Removes the specified object from the array. If the object is not found nothing happens.
942 * @param {Object} o The object to remove
944 remove : function(o){
945 var index = this.indexOf(o);
947 this.splice(index, 1);
951 * Map (JS 1.6 compatibility)
952 * @param {Function} function to call
956 var len = this.length >>> 0;
957 if (typeof fun != "function")
958 throw new TypeError();
960 var res = new Array(len);
961 var thisp = arguments[1];
962 for (var i = 0; i < len; i++)
965 res[i] = fun.call(thisp, this[i], i, this);
976 * Ext JS Library 1.1.1
977 * Copyright(c) 2006-2007, Ext JS, LLC.
979 * Originally Released Under LGPL - original licence link has changed is not relivant.
982 * <script type="text/javascript">
988 * The date parsing and format syntax is a subset of
989 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
990 * supported will provide results equivalent to their PHP versions.
992 * Following is the list of all currently supported formats:
995 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
997 Format Output Description
998 ------ ---------- --------------------------------------------------------------
999 d 10 Day of the month, 2 digits with leading zeros
1000 D Wed A textual representation of a day, three letters
1001 j 10 Day of the month without leading zeros
1002 l Wednesday A full textual representation of the day of the week
1003 S th English ordinal day of month suffix, 2 chars (use with j)
1004 w 3 Numeric representation of the day of the week
1005 z 9 The julian date, or day of the year (0-365)
1006 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1007 F January A full textual representation of the month
1008 m 01 Numeric representation of a month, with leading zeros
1009 M Jan Month name abbreviation, three letters
1010 n 1 Numeric representation of a month, without leading zeros
1011 t 31 Number of days in the given month
1012 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1013 Y 2007 A full numeric representation of a year, 4 digits
1014 y 07 A two digit representation of a year
1015 a pm Lowercase Ante meridiem and Post meridiem
1016 A PM Uppercase Ante meridiem and Post meridiem
1017 g 3 12-hour format of an hour without leading zeros
1018 G 15 24-hour format of an hour without leading zeros
1019 h 03 12-hour format of an hour with leading zeros
1020 H 15 24-hour format of an hour with leading zeros
1021 i 05 Minutes with leading zeros
1022 s 01 Seconds, with leading zeros
1023 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1024 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1025 T CST Timezone setting of the machine running the code
1026 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1029 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1031 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1032 document.write(dt.format('Y-m-d')); //2007-01-10
1033 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1034 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
1037 * Here are some standard date/time patterns that you might find helpful. They
1038 * are not part of the source of Date.js, but to use them you can simply copy this
1039 * block of code into any script that is included after Date.js and they will also become
1040 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1043 ISO8601Long:"Y-m-d H:i:s",
1044 ISO8601Short:"Y-m-d",
1046 LongDate: "l, F d, Y",
1047 FullDateTime: "l, F d, Y g:i:s A",
1050 LongTime: "g:i:s A",
1051 SortableDateTime: "Y-m-d\\TH:i:s",
1052 UniversalSortableDateTime: "Y-m-d H:i:sO",
1059 var dt = new Date();
1060 document.write(dt.format(Date.patterns.ShortDate));
1065 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1066 * They generate precompiled functions from date formats instead of parsing and
1067 * processing the pattern every time you format a date. These functions are available
1068 * on every Date object (any javascript function).
1070 * The original article and download are here:
1071 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1078 Returns the number of milliseconds between this date and date
1079 @param {Date} date (optional) Defaults to now
1080 @return {Number} The diff in milliseconds
1081 @member Date getElapsed
1083 Date.prototype.getElapsed = function(date) {
1084 return Math.abs((date || new Date()).getTime()-this.getTime());
1086 // was in date file..
1090 Date.parseFunctions = {count:0};
1092 Date.parseRegexes = [];
1094 Date.formatFunctions = {count:0};
1097 Date.prototype.dateFormat = function(format) {
1098 if (Date.formatFunctions[format] == null) {
1099 Date.createNewFormat(format);
1101 var func = Date.formatFunctions[format];
1102 return this[func]();
1107 * Formats a date given the supplied format string
1108 * @param {String} format The format string
1109 * @return {String} The formatted date
1112 Date.prototype.format = Date.prototype.dateFormat;
1115 Date.createNewFormat = function(format) {
1116 var funcName = "format" + Date.formatFunctions.count++;
1117 Date.formatFunctions[format] = funcName;
1118 var code = "Date.prototype." + funcName + " = function(){return ";
1119 var special = false;
1121 for (var i = 0; i < format.length; ++i) {
1122 ch = format.charAt(i);
1123 if (!special && ch == "\\") {
1128 code += "'" + String.escape(ch) + "' + ";
1131 code += Date.getFormatCode(ch);
1134 /** eval:var:zzzzzzzzzzzzz */
1135 eval(code.substring(0, code.length - 3) + ";}");
1139 Date.getFormatCode = function(character) {
1140 switch (character) {
1142 return "String.leftPad(this.getDate(), 2, '0') + ";
1144 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1146 return "this.getDate() + ";
1148 return "Date.dayNames[this.getDay()] + ";
1150 return "this.getSuffix() + ";
1152 return "this.getDay() + ";
1154 return "this.getDayOfYear() + ";
1156 return "this.getWeekOfYear() + ";
1158 return "Date.monthNames[this.getMonth()] + ";
1160 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1162 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1164 return "(this.getMonth() + 1) + ";
1166 return "this.getDaysInMonth() + ";
1168 return "(this.isLeapYear() ? 1 : 0) + ";
1170 return "this.getFullYear() + ";
1172 return "('' + this.getFullYear()).substring(2, 4) + ";
1174 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1176 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1178 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1180 return "this.getHours() + ";
1182 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1184 return "String.leftPad(this.getHours(), 2, '0') + ";
1186 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1188 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1190 return "this.getGMTOffset() + ";
1192 return "this.getGMTColonOffset() + ";
1194 return "this.getTimezone() + ";
1196 return "(this.getTimezoneOffset() * -60) + ";
1198 return "'" + String.escape(character) + "' + ";
1203 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1204 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1205 * the date format that is not specified will default to the current date value for that part. Time parts can also
1206 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1207 * string or the parse operation will fail.
1210 //dt = Fri May 25 2007 (current date)
1211 var dt = new Date();
1213 //dt = Thu May 25 2006 (today's month/day in 2006)
1214 dt = Date.parseDate("2006", "Y");
1216 //dt = Sun Jan 15 2006 (all date parts specified)
1217 dt = Date.parseDate("2006-1-15", "Y-m-d");
1219 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1220 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1222 * @param {String} input The unparsed date as a string
1223 * @param {String} format The format the date is in
1224 * @return {Date} The parsed date
1227 Date.parseDate = function(input, format) {
1228 if (Date.parseFunctions[format] == null) {
1229 Date.createParser(format);
1231 var func = Date.parseFunctions[format];
1232 return Date[func](input);
1238 Date.createParser = function(format) {
1239 var funcName = "parse" + Date.parseFunctions.count++;
1240 var regexNum = Date.parseRegexes.length;
1241 var currentGroup = 1;
1242 Date.parseFunctions[format] = funcName;
1244 var code = "Date." + funcName + " = function(input){\n"
1245 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1246 + "var d = new Date();\n"
1247 + "y = d.getFullYear();\n"
1248 + "m = d.getMonth();\n"
1249 + "d = d.getDate();\n"
1250 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1251 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1252 + "if (results && results.length > 0) {";
1255 var special = false;
1257 for (var i = 0; i < format.length; ++i) {
1258 ch = format.charAt(i);
1259 if (!special && ch == "\\") {
1264 regex += String.escape(ch);
1267 var obj = Date.formatCodeToRegex(ch, currentGroup);
1268 currentGroup += obj.g;
1270 if (obj.g && obj.c) {
1276 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1277 + "{v = new Date(y, m, d, h, i, s);}\n"
1278 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1279 + "{v = new Date(y, m, d, h, i);}\n"
1280 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1281 + "{v = new Date(y, m, d, h);}\n"
1282 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1283 + "{v = new Date(y, m, d);}\n"
1284 + "else if (y >= 0 && m >= 0)\n"
1285 + "{v = new Date(y, m);}\n"
1286 + "else if (y >= 0)\n"
1287 + "{v = new Date(y);}\n"
1288 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1289 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1290 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1293 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1294 /** eval:var:zzzzzzzzzzzzz */
1299 Date.formatCodeToRegex = function(character, currentGroup) {
1300 switch (character) {
1304 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1307 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1308 s:"(\\d{1,2})"}; // day of month without leading zeroes
1311 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1312 s:"(\\d{2})"}; // day of month with leading zeroes
1316 s:"(?:" + Date.dayNames.join("|") + ")"};
1320 s:"(?:st|nd|rd|th)"};
1335 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1336 s:"(" + Date.monthNames.join("|") + ")"};
1339 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1340 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1343 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1344 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1347 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1348 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1359 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1363 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1364 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1368 c:"if (results[" + currentGroup + "] == 'am') {\n"
1369 + "if (h == 12) { h = 0; }\n"
1370 + "} else { if (h < 12) { h += 12; }}",
1374 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1375 + "if (h == 12) { h = 0; }\n"
1376 + "} else { if (h < 12) { h += 12; }}",
1381 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1382 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1386 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1387 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1390 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1394 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1399 "o = results[", currentGroup, "];\n",
1400 "var sn = o.substring(0,1);\n", // get + / - sign
1401 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1402 "var mn = o.substring(3,5) % 60;\n", // get minutes
1403 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1404 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1406 s:"([+\-]\\d{2,4})"};
1412 "o = results[", currentGroup, "];\n",
1413 "var sn = o.substring(0,1);\n",
1414 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1415 "var mn = o.substring(4,6) % 60;\n",
1416 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1417 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1423 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1426 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1427 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1428 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1432 s:String.escape(character)};
1437 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1438 * @return {String} The abbreviated timezone name (e.g. 'CST')
1440 Date.prototype.getTimezone = function() {
1441 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1445 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1446 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1448 Date.prototype.getGMTOffset = function() {
1449 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1450 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1451 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1455 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1456 * @return {String} 2-characters representing hours and 2-characters representing minutes
1457 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1459 Date.prototype.getGMTColonOffset = function() {
1460 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1461 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1463 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1467 * Get the numeric day number of the year, adjusted for leap year.
1468 * @return {Number} 0 through 364 (365 in leap years)
1470 Date.prototype.getDayOfYear = function() {
1472 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1473 for (var i = 0; i < this.getMonth(); ++i) {
1474 num += Date.daysInMonth[i];
1476 return num + this.getDate() - 1;
1480 * Get the string representation of the numeric week number of the year
1481 * (equivalent to the format specifier 'W').
1482 * @return {String} '00' through '52'
1484 Date.prototype.getWeekOfYear = function() {
1485 // Skip to Thursday of this week
1486 var now = this.getDayOfYear() + (4 - this.getDay());
1487 // Find the first Thursday of the year
1488 var jan1 = new Date(this.getFullYear(), 0, 1);
1489 var then = (7 - jan1.getDay() + 4);
1490 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1494 * Whether or not the current date is in a leap year.
1495 * @return {Boolean} True if the current date is in a leap year, else false
1497 Date.prototype.isLeapYear = function() {
1498 var year = this.getFullYear();
1499 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1503 * Get the first day of the current month, adjusted for leap year. The returned value
1504 * is the numeric day index within the week (0-6) which can be used in conjunction with
1505 * the {@link #monthNames} array to retrieve the textual day name.
1508 var dt = new Date('1/10/2007');
1509 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1511 * @return {Number} The day number (0-6)
1513 Date.prototype.getFirstDayOfMonth = function() {
1514 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1515 return (day < 0) ? (day + 7) : day;
1519 * Get the last day of the current month, adjusted for leap year. The returned value
1520 * is the numeric day index within the week (0-6) which can be used in conjunction with
1521 * the {@link #monthNames} array to retrieve the textual day name.
1524 var dt = new Date('1/10/2007');
1525 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1527 * @return {Number} The day number (0-6)
1529 Date.prototype.getLastDayOfMonth = function() {
1530 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1531 return (day < 0) ? (day + 7) : day;
1536 * Get the first date of this date's month
1539 Date.prototype.getFirstDateOfMonth = function() {
1540 return new Date(this.getFullYear(), this.getMonth(), 1);
1544 * Get the last date of this date's month
1547 Date.prototype.getLastDateOfMonth = function() {
1548 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1551 * Get the number of days in the current month, adjusted for leap year.
1552 * @return {Number} The number of days in the month
1554 Date.prototype.getDaysInMonth = function() {
1555 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1556 return Date.daysInMonth[this.getMonth()];
1560 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1561 * @return {String} 'st, 'nd', 'rd' or 'th'
1563 Date.prototype.getSuffix = function() {
1564 switch (this.getDate()) {
1581 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1584 * An array of textual month names.
1585 * Override these values for international dates, for example...
1586 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1605 * An array of textual day names.
1606 * Override these values for international dates, for example...
1607 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1623 Date.monthNumbers = {
1638 * Creates and returns a new Date instance with the exact same date value as the called instance.
1639 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1640 * variable will also be changed. When the intention is to create a new variable that will not
1641 * modify the original instance, you should create a clone.
1643 * Example of correctly cloning a date:
1646 var orig = new Date('10/1/2006');
1649 document.write(orig); //returns 'Thu Oct 05 2006'!
1652 var orig = new Date('10/1/2006');
1653 var copy = orig.clone();
1655 document.write(orig); //returns 'Thu Oct 01 2006'
1657 * @return {Date} The new Date instance
1659 Date.prototype.clone = function() {
1660 return new Date(this.getTime());
1664 * Clears any time information from this date
1665 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1666 @return {Date} this or the clone
1668 Date.prototype.clearTime = function(clone){
1670 return this.clone().clearTime();
1675 this.setMilliseconds(0);
1680 // safari setMonth is broken
1682 Date.brokenSetMonth = Date.prototype.setMonth;
1683 Date.prototype.setMonth = function(num){
1685 var n = Math.ceil(-num);
1686 var back_year = Math.ceil(n/12);
1687 var month = (n % 12) ? 12 - n % 12 : 0 ;
1688 this.setFullYear(this.getFullYear() - back_year);
1689 return Date.brokenSetMonth.call(this, month);
1691 return Date.brokenSetMonth.apply(this, arguments);
1696 /** Date interval constant
1700 /** Date interval constant
1704 /** Date interval constant
1708 /** Date interval constant
1712 /** Date interval constant
1716 /** Date interval constant
1720 /** Date interval constant
1726 * Provides a convenient method of performing basic date arithmetic. This method
1727 * does not modify the Date instance being called - it creates and returns
1728 * a new Date instance containing the resulting date value.
1733 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1734 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1736 //Negative values will subtract correctly:
1737 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1738 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1740 //You can even chain several calls together in one line!
1741 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1742 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1745 * @param {String} interval A valid date interval enum value
1746 * @param {Number} value The amount to add to the current date
1747 * @return {Date} The new Date instance
1749 Date.prototype.add = function(interval, value){
1750 var d = this.clone();
1751 if (!interval || value === 0) return d;
1752 switch(interval.toLowerCase()){
1754 d.setMilliseconds(this.getMilliseconds() + value);
1757 d.setSeconds(this.getSeconds() + value);
1760 d.setMinutes(this.getMinutes() + value);
1763 d.setHours(this.getHours() + value);
1766 d.setDate(this.getDate() + value);
1769 var day = this.getDate();
1771 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1774 d.setMonth(this.getMonth() + value);
1777 d.setFullYear(this.getFullYear() + value);
1784 * Ext JS Library 1.1.1
1785 * Copyright(c) 2006-2007, Ext JS, LLC.
1787 * Originally Released Under LGPL - original licence link has changed is not relivant.
1790 * <script type="text/javascript">
1794 * @class Roo.lib.Dom
1797 * Dom utils (from YIU afaik)
1802 * Get the view width
1803 * @param {Boolean} full True will get the full document, otherwise it's the view width
1804 * @return {Number} The width
1807 getViewWidth : function(full) {
1808 return full ? this.getDocumentWidth() : this.getViewportWidth();
1811 * Get the view height
1812 * @param {Boolean} full True will get the full document, otherwise it's the view height
1813 * @return {Number} The height
1815 getViewHeight : function(full) {
1816 return full ? this.getDocumentHeight() : this.getViewportHeight();
1819 getDocumentHeight: function() {
1820 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1821 return Math.max(scrollHeight, this.getViewportHeight());
1824 getDocumentWidth: function() {
1825 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1826 return Math.max(scrollWidth, this.getViewportWidth());
1829 getViewportHeight: function() {
1830 var height = self.innerHeight;
1831 var mode = document.compatMode;
1833 if ((mode || Roo.isIE) && !Roo.isOpera) {
1834 height = (mode == "CSS1Compat") ?
1835 document.documentElement.clientHeight :
1836 document.body.clientHeight;
1842 getViewportWidth: function() {
1843 var width = self.innerWidth;
1844 var mode = document.compatMode;
1846 if (mode || Roo.isIE) {
1847 width = (mode == "CSS1Compat") ?
1848 document.documentElement.clientWidth :
1849 document.body.clientWidth;
1854 isAncestor : function(p, c) {
1861 if (p.contains && !Roo.isSafari) {
1862 return p.contains(c);
1863 } else if (p.compareDocumentPosition) {
1864 return !!(p.compareDocumentPosition(c) & 16);
1866 var parent = c.parentNode;
1871 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1874 parent = parent.parentNode;
1880 getRegion : function(el) {
1881 return Roo.lib.Region.getRegion(el);
1884 getY : function(el) {
1885 return this.getXY(el)[1];
1888 getX : function(el) {
1889 return this.getXY(el)[0];
1892 getXY : function(el) {
1893 var p, pe, b, scroll, bd = document.body;
1894 el = Roo.getDom(el);
1895 var fly = Roo.lib.AnimBase.fly;
1896 if (el.getBoundingClientRect) {
1897 b = el.getBoundingClientRect();
1898 scroll = fly(document).getScroll();
1899 return [b.left + scroll.left, b.top + scroll.top];
1905 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1912 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1919 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1920 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1927 if (p != el && pe.getStyle('overflow') != 'visible') {
1935 if (Roo.isSafari && hasAbsolute) {
1940 if (Roo.isGecko && !hasAbsolute) {
1942 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1943 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1947 while (p && p != bd) {
1948 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1960 setXY : function(el, xy) {
1961 el = Roo.fly(el, '_setXY');
1963 var pts = el.translatePoints(xy);
1964 if (xy[0] !== false) {
1965 el.dom.style.left = pts.left + "px";
1967 if (xy[1] !== false) {
1968 el.dom.style.top = pts.top + "px";
1972 setX : function(el, x) {
1973 this.setXY(el, [x, false]);
1976 setY : function(el, y) {
1977 this.setXY(el, [false, y]);
1981 * Portions of this file are based on pieces of Yahoo User Interface Library
1982 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1983 * YUI licensed under the BSD License:
1984 * http://developer.yahoo.net/yui/license.txt
1985 * <script type="text/javascript">
1989 Roo.lib.Event = function() {
1990 var loadComplete = false;
1992 var unloadListeners = [];
1994 var onAvailStack = [];
1996 var lastError = null;
2009 startInterval: function() {
2010 if (!this._interval) {
2012 var callback = function() {
2013 self._tryPreloadAttach();
2015 this._interval = setInterval(callback, this.POLL_INTERVAL);
2020 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2021 onAvailStack.push({ id: p_id,
2024 override: p_override,
2025 checkReady: false });
2027 retryCount = this.POLL_RETRYS;
2028 this.startInterval();
2032 addListener: function(el, eventName, fn) {
2033 el = Roo.getDom(el);
2038 if ("unload" == eventName) {
2039 unloadListeners[unloadListeners.length] =
2040 [el, eventName, fn];
2044 var wrappedFn = function(e) {
2045 return fn(Roo.lib.Event.getEvent(e));
2048 var li = [el, eventName, fn, wrappedFn];
2050 var index = listeners.length;
2051 listeners[index] = li;
2053 this.doAdd(el, eventName, wrappedFn, false);
2059 removeListener: function(el, eventName, fn) {
2062 el = Roo.getDom(el);
2065 return this.purgeElement(el, false, eventName);
2069 if ("unload" == eventName) {
2071 for (i = 0,len = unloadListeners.length; i < len; i++) {
2072 var li = unloadListeners[i];
2075 li[1] == eventName &&
2077 unloadListeners.splice(i, 1);
2085 var cacheItem = null;
2088 var index = arguments[3];
2090 if ("undefined" == typeof index) {
2091 index = this._getCacheIndex(el, eventName, fn);
2095 cacheItem = listeners[index];
2098 if (!el || !cacheItem) {
2102 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2104 delete listeners[index][this.WFN];
2105 delete listeners[index][this.FN];
2106 listeners.splice(index, 1);
2113 getTarget: function(ev, resolveTextNode) {
2114 ev = ev.browserEvent || ev;
2115 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2116 var t = ev.target || ev.srcElement;
2117 return this.resolveTextNode(t);
2121 resolveTextNode: function(node) {
2122 if (Roo.isSafari && node && 3 == node.nodeType) {
2123 return node.parentNode;
2130 getPageX: function(ev) {
2131 ev = ev.browserEvent || ev;
2132 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2134 if (!x && 0 !== x) {
2135 x = ev.clientX || 0;
2138 x += this.getScroll()[1];
2146 getPageY: function(ev) {
2147 ev = ev.browserEvent || ev;
2148 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2150 if (!y && 0 !== y) {
2151 y = ev.clientY || 0;
2154 y += this.getScroll()[0];
2163 getXY: function(ev) {
2164 ev = ev.browserEvent || ev;
2165 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2166 return [this.getPageX(ev), this.getPageY(ev)];
2170 getRelatedTarget: function(ev) {
2171 ev = ev.browserEvent || ev;
2172 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2173 var t = ev.relatedTarget;
2175 if (ev.type == "mouseout") {
2177 } else if (ev.type == "mouseover") {
2182 return this.resolveTextNode(t);
2186 getTime: function(ev) {
2187 ev = ev.browserEvent || ev;
2188 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2190 var t = new Date().getTime();
2194 this.lastError = ex;
2203 stopEvent: function(ev) {
2204 this.stopPropagation(ev);
2205 this.preventDefault(ev);
2209 stopPropagation: function(ev) {
2210 ev = ev.browserEvent || ev;
2211 if (ev.stopPropagation) {
2212 ev.stopPropagation();
2214 ev.cancelBubble = true;
2219 preventDefault: function(ev) {
2220 ev = ev.browserEvent || ev;
2221 if(ev.preventDefault) {
2222 ev.preventDefault();
2224 ev.returnValue = false;
2229 getEvent: function(e) {
2230 var ev = e || window.event;
2232 var c = this.getEvent.caller;
2234 ev = c.arguments[0];
2235 if (ev && Event == ev.constructor) {
2245 getCharCode: function(ev) {
2246 ev = ev.browserEvent || ev;
2247 return ev.charCode || ev.keyCode || 0;
2251 _getCacheIndex: function(el, eventName, fn) {
2252 for (var i = 0,len = listeners.length; i < len; ++i) {
2253 var li = listeners[i];
2255 li[this.FN] == fn &&
2256 li[this.EL] == el &&
2257 li[this.TYPE] == eventName) {
2269 getEl: function(id) {
2270 return document.getElementById(id);
2274 clearCache: function() {
2278 _load: function(e) {
2279 loadComplete = true;
2280 var EU = Roo.lib.Event;
2284 EU.doRemove(window, "load", EU._load);
2289 _tryPreloadAttach: function() {
2298 var tryAgain = !loadComplete;
2300 tryAgain = (retryCount > 0);
2305 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2306 var item = onAvailStack[i];
2308 var el = this.getEl(item.id);
2311 if (!item.checkReady ||
2314 (document && document.body)) {
2317 if (item.override) {
2318 if (item.override === true) {
2321 scope = item.override;
2324 item.fn.call(scope, item.obj);
2325 onAvailStack[i] = null;
2328 notAvail.push(item);
2333 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2337 this.startInterval();
2339 clearInterval(this._interval);
2340 this._interval = null;
2343 this.locked = false;
2350 purgeElement: function(el, recurse, eventName) {
2351 var elListeners = this.getListeners(el, eventName);
2353 for (var i = 0,len = elListeners.length; i < len; ++i) {
2354 var l = elListeners[i];
2355 this.removeListener(el, l.type, l.fn);
2359 if (recurse && el && el.childNodes) {
2360 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2361 this.purgeElement(el.childNodes[i], recurse, eventName);
2367 getListeners: function(el, eventName) {
2368 var results = [], searchLists;
2370 searchLists = [listeners, unloadListeners];
2371 } else if (eventName == "unload") {
2372 searchLists = [unloadListeners];
2374 searchLists = [listeners];
2377 for (var j = 0; j < searchLists.length; ++j) {
2378 var searchList = searchLists[j];
2379 if (searchList && searchList.length > 0) {
2380 for (var i = 0,len = searchList.length; i < len; ++i) {
2381 var l = searchList[i];
2382 if (l && l[this.EL] === el &&
2383 (!eventName || eventName === l[this.TYPE])) {
2388 adjust: l[this.ADJ_SCOPE],
2396 return (results.length) ? results : null;
2400 _unload: function(e) {
2402 var EU = Roo.lib.Event, i, j, l, len, index;
2404 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2405 l = unloadListeners[i];
2408 if (l[EU.ADJ_SCOPE]) {
2409 if (l[EU.ADJ_SCOPE] === true) {
2412 scope = l[EU.ADJ_SCOPE];
2415 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2416 unloadListeners[i] = null;
2422 unloadListeners = null;
2424 if (listeners && listeners.length > 0) {
2425 j = listeners.length;
2428 l = listeners[index];
2430 EU.removeListener(l[EU.EL], l[EU.TYPE],
2440 EU.doRemove(window, "unload", EU._unload);
2445 getScroll: function() {
2446 var dd = document.documentElement, db = document.body;
2447 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2448 return [dd.scrollTop, dd.scrollLeft];
2450 return [db.scrollTop, db.scrollLeft];
2457 doAdd: function () {
2458 if (window.addEventListener) {
2459 return function(el, eventName, fn, capture) {
2460 el.addEventListener(eventName, fn, (capture));
2462 } else if (window.attachEvent) {
2463 return function(el, eventName, fn, capture) {
2464 el.attachEvent("on" + eventName, fn);
2473 doRemove: function() {
2474 if (window.removeEventListener) {
2475 return function (el, eventName, fn, capture) {
2476 el.removeEventListener(eventName, fn, (capture));
2478 } else if (window.detachEvent) {
2479 return function (el, eventName, fn) {
2480 el.detachEvent("on" + eventName, fn);
2492 var E = Roo.lib.Event;
2493 E.on = E.addListener;
2494 E.un = E.removeListener;
2496 if (document && document.body) {
2499 E.doAdd(window, "load", E._load);
2501 E.doAdd(window, "unload", E._unload);
2502 E._tryPreloadAttach();
2506 * Portions of this file are based on pieces of Yahoo User Interface Library
2507 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2508 * YUI licensed under the BSD License:
2509 * http://developer.yahoo.net/yui/license.txt
2510 * <script type="text/javascript">
2516 * @class Roo.lib.Ajax
2523 request : function(method, uri, cb, data, options) {
2525 var hs = options.headers;
2528 if(hs.hasOwnProperty(h)){
2529 this.initHeader(h, hs[h], false);
2533 if(options.xmlData){
2534 this.initHeader('Content-Type', 'text/xml', false);
2536 data = options.xmlData;
2540 return this.asyncRequest(method, uri, cb, data);
2543 serializeForm : function(form) {
2544 if(typeof form == 'string') {
2545 form = (document.getElementById(form) || document.forms[form]);
2548 var el, name, val, disabled, data = '', hasSubmit = false;
2549 for (var i = 0; i < form.elements.length; i++) {
2550 el = form.elements[i];
2551 disabled = form.elements[i].disabled;
2552 name = form.elements[i].name;
2553 val = form.elements[i].value;
2555 if (!disabled && name){
2559 case 'select-multiple':
2560 for (var j = 0; j < el.options.length; j++) {
2561 if (el.options[j].selected) {
2563 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2566 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2574 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2587 if(hasSubmit == false) {
2588 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2593 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2598 data = data.substr(0, data.length - 1);
2606 useDefaultHeader:true,
2608 defaultPostHeader:'application/x-www-form-urlencoded',
2610 useDefaultXhrHeader:true,
2612 defaultXhrHeader:'XMLHttpRequest',
2614 hasDefaultHeaders:true,
2626 setProgId:function(id)
2628 this.activeX.unshift(id);
2631 setDefaultPostHeader:function(b)
2633 this.useDefaultHeader = b;
2636 setDefaultXhrHeader:function(b)
2638 this.useDefaultXhrHeader = b;
2641 setPollingInterval:function(i)
2643 if (typeof i == 'number' && isFinite(i)) {
2644 this.pollInterval = i;
2648 createXhrObject:function(transactionId)
2654 http = new XMLHttpRequest();
2656 obj = { conn:http, tId:transactionId };
2660 for (var i = 0; i < this.activeX.length; ++i) {
2664 http = new ActiveXObject(this.activeX[i]);
2666 obj = { conn:http, tId:transactionId };
2679 getConnectionObject:function()
2682 var tId = this.transactionId;
2686 o = this.createXhrObject(tId);
2688 this.transactionId++;
2699 asyncRequest:function(method, uri, callback, postData)
2701 var o = this.getConnectionObject();
2707 o.conn.open(method, uri, true);
2709 if (this.useDefaultXhrHeader) {
2710 if (!this.defaultHeaders['X-Requested-With']) {
2711 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2715 if(postData && this.useDefaultHeader){
2716 this.initHeader('Content-Type', this.defaultPostHeader);
2719 if (this.hasDefaultHeaders || this.hasHeaders) {
2723 this.handleReadyState(o, callback);
2724 o.conn.send(postData || null);
2730 handleReadyState:function(o, callback)
2734 if (callback && callback.timeout) {
2736 this.timeout[o.tId] = window.setTimeout(function() {
2737 oConn.abort(o, callback, true);
2738 }, callback.timeout);
2741 this.poll[o.tId] = window.setInterval(
2743 if (o.conn && o.conn.readyState == 4) {
2744 window.clearInterval(oConn.poll[o.tId]);
2745 delete oConn.poll[o.tId];
2747 if(callback && callback.timeout) {
2748 window.clearTimeout(oConn.timeout[o.tId]);
2749 delete oConn.timeout[o.tId];
2752 oConn.handleTransactionResponse(o, callback);
2755 , this.pollInterval);
2758 handleTransactionResponse:function(o, callback, isAbort)
2762 this.releaseObject(o);
2766 var httpStatus, responseObject;
2770 if (o.conn.status !== undefined && o.conn.status != 0) {
2771 httpStatus = o.conn.status;
2783 if (httpStatus >= 200 && httpStatus < 300) {
2784 responseObject = this.createResponseObject(o, callback.argument);
2785 if (callback.success) {
2786 if (!callback.scope) {
2787 callback.success(responseObject);
2792 callback.success.apply(callback.scope, [responseObject]);
2797 switch (httpStatus) {
2805 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2806 if (callback.failure) {
2807 if (!callback.scope) {
2808 callback.failure(responseObject);
2811 callback.failure.apply(callback.scope, [responseObject]);
2816 responseObject = this.createResponseObject(o, callback.argument);
2817 if (callback.failure) {
2818 if (!callback.scope) {
2819 callback.failure(responseObject);
2822 callback.failure.apply(callback.scope, [responseObject]);
2828 this.releaseObject(o);
2829 responseObject = null;
2832 createResponseObject:function(o, callbackArg)
2839 var headerStr = o.conn.getAllResponseHeaders();
2840 var header = headerStr.split('\n');
2841 for (var i = 0; i < header.length; i++) {
2842 var delimitPos = header[i].indexOf(':');
2843 if (delimitPos != -1) {
2844 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2852 obj.status = o.conn.status;
2853 obj.statusText = o.conn.statusText;
2854 obj.getResponseHeader = headerObj;
2855 obj.getAllResponseHeaders = headerStr;
2856 obj.responseText = o.conn.responseText;
2857 obj.responseXML = o.conn.responseXML;
2859 if (typeof callbackArg !== undefined) {
2860 obj.argument = callbackArg;
2866 createExceptionObject:function(tId, callbackArg, isAbort)
2869 var COMM_ERROR = 'communication failure';
2870 var ABORT_CODE = -1;
2871 var ABORT_ERROR = 'transaction aborted';
2877 obj.status = ABORT_CODE;
2878 obj.statusText = ABORT_ERROR;
2881 obj.status = COMM_CODE;
2882 obj.statusText = COMM_ERROR;
2886 obj.argument = callbackArg;
2892 initHeader:function(label, value, isDefault)
2894 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2896 if (headerObj[label] === undefined) {
2897 headerObj[label] = value;
2902 headerObj[label] = value + "," + headerObj[label];
2906 this.hasDefaultHeaders = true;
2909 this.hasHeaders = true;
2914 setHeader:function(o)
2916 if (this.hasDefaultHeaders) {
2917 for (var prop in this.defaultHeaders) {
2918 if (this.defaultHeaders.hasOwnProperty(prop)) {
2919 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2924 if (this.hasHeaders) {
2925 for (var prop in this.headers) {
2926 if (this.headers.hasOwnProperty(prop)) {
2927 o.conn.setRequestHeader(prop, this.headers[prop]);
2931 this.hasHeaders = false;
2935 resetDefaultHeaders:function() {
2936 delete this.defaultHeaders;
2937 this.defaultHeaders = {};
2938 this.hasDefaultHeaders = false;
2941 abort:function(o, callback, isTimeout)
2943 if(this.isCallInProgress(o)) {
2945 window.clearInterval(this.poll[o.tId]);
2946 delete this.poll[o.tId];
2948 delete this.timeout[o.tId];
2951 this.handleTransactionResponse(o, callback, true);
2961 isCallInProgress:function(o)
2964 return o.conn.readyState != 4 && o.conn.readyState != 0;
2973 releaseObject:function(o)
2982 'MSXML2.XMLHTTP.3.0',
2990 * Portions of this file are based on pieces of Yahoo User Interface Library
2991 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2992 * YUI licensed under the BSD License:
2993 * http://developer.yahoo.net/yui/license.txt
2994 * <script type="text/javascript">
2998 Roo.lib.Region = function(t, r, b, l) {
3008 Roo.lib.Region.prototype = {
3009 contains : function(region) {
3010 return ( region.left >= this.left &&
3011 region.right <= this.right &&
3012 region.top >= this.top &&
3013 region.bottom <= this.bottom );
3017 getArea : function() {
3018 return ( (this.bottom - this.top) * (this.right - this.left) );
3021 intersect : function(region) {
3022 var t = Math.max(this.top, region.top);
3023 var r = Math.min(this.right, region.right);
3024 var b = Math.min(this.bottom, region.bottom);
3025 var l = Math.max(this.left, region.left);
3027 if (b >= t && r >= l) {
3028 return new Roo.lib.Region(t, r, b, l);
3033 union : function(region) {
3034 var t = Math.min(this.top, region.top);
3035 var r = Math.max(this.right, region.right);
3036 var b = Math.max(this.bottom, region.bottom);
3037 var l = Math.min(this.left, region.left);
3039 return new Roo.lib.Region(t, r, b, l);
3042 adjust : function(t, l, b, r) {
3051 Roo.lib.Region.getRegion = function(el) {
3052 var p = Roo.lib.Dom.getXY(el);
3055 var r = p[0] + el.offsetWidth;
3056 var b = p[1] + el.offsetHeight;
3059 return new Roo.lib.Region(t, r, b, l);
3062 * Portions of this file are based on pieces of Yahoo User Interface Library
3063 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3064 * YUI licensed under the BSD License:
3065 * http://developer.yahoo.net/yui/license.txt
3066 * <script type="text/javascript">
3069 //@@dep Roo.lib.Region
3072 Roo.lib.Point = function(x, y) {
3073 if (x instanceof Array) {
3077 this.x = this.right = this.left = this[0] = x;
3078 this.y = this.top = this.bottom = this[1] = y;
3081 Roo.lib.Point.prototype = new Roo.lib.Region();
3083 * Portions of this file are based on pieces of Yahoo User Interface Library
3084 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3085 * YUI licensed under the BSD License:
3086 * http://developer.yahoo.net/yui/license.txt
3087 * <script type="text/javascript">
3094 scroll : function(el, args, duration, easing, cb, scope) {
3095 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3098 motion : function(el, args, duration, easing, cb, scope) {
3099 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3102 color : function(el, args, duration, easing, cb, scope) {
3103 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3106 run : function(el, args, duration, easing, cb, scope, type) {
3107 type = type || Roo.lib.AnimBase;
3108 if (typeof easing == "string") {
3109 easing = Roo.lib.Easing[easing];
3111 var anim = new type(el, args, duration, easing);
3112 anim.animateX(function() {
3113 Roo.callback(cb, scope);
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">
3131 if (!libFlyweight) {
3132 libFlyweight = new Roo.Element.Flyweight();
3134 libFlyweight.dom = el;
3135 return libFlyweight;
3138 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3142 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3144 this.init(el, attributes, duration, method);
3148 Roo.lib.AnimBase.fly = fly;
3152 Roo.lib.AnimBase.prototype = {
3154 toString: function() {
3155 var el = this.getEl();
3156 var id = el.id || el.tagName;
3157 return ("Anim " + id);
3161 noNegatives: /width|height|opacity|padding/i,
3162 offsetAttribute: /^((width|height)|(top|left))$/,
3163 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3164 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3168 doMethod: function(attr, start, end) {
3169 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3173 setAttribute: function(attr, val, unit) {
3174 if (this.patterns.noNegatives.test(attr)) {
3175 val = (val > 0) ? val : 0;
3178 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3182 getAttribute: function(attr) {
3183 var el = this.getEl();
3184 var val = fly(el).getStyle(attr);
3186 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3187 return parseFloat(val);
3190 var a = this.patterns.offsetAttribute.exec(attr) || [];
3191 var pos = !!( a[3] );
3192 var box = !!( a[2] );
3195 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3196 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3205 getDefaultUnit: function(attr) {
3206 if (this.patterns.defaultUnit.test(attr)) {
3213 animateX : function(callback, scope) {
3214 var f = function() {
3215 this.onComplete.removeListener(f);
3216 if (typeof callback == "function") {
3217 callback.call(scope || this, this);
3220 this.onComplete.addListener(f, this);
3225 setRuntimeAttribute: function(attr) {
3228 var attributes = this.attributes;
3230 this.runtimeAttributes[attr] = {};
3232 var isset = function(prop) {
3233 return (typeof prop !== 'undefined');
3236 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3240 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3243 if (isset(attributes[attr]['to'])) {
3244 end = attributes[attr]['to'];
3245 } else if (isset(attributes[attr]['by'])) {
3246 if (start.constructor == Array) {
3248 for (var i = 0, len = start.length; i < len; ++i) {
3249 end[i] = start[i] + attributes[attr]['by'][i];
3252 end = start + attributes[attr]['by'];
3256 this.runtimeAttributes[attr].start = start;
3257 this.runtimeAttributes[attr].end = end;
3260 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3264 init: function(el, attributes, duration, method) {
3266 var isAnimated = false;
3269 var startTime = null;
3272 var actualFrames = 0;
3275 el = Roo.getDom(el);
3278 this.attributes = attributes || {};
3281 this.duration = duration || 1;
3284 this.method = method || Roo.lib.Easing.easeNone;
3287 this.useSeconds = true;
3290 this.currentFrame = 0;
3293 this.totalFrames = Roo.lib.AnimMgr.fps;
3296 this.getEl = function() {
3301 this.isAnimated = function() {
3306 this.getStartTime = function() {
3310 this.runtimeAttributes = {};
3313 this.animate = function() {
3314 if (this.isAnimated()) {
3318 this.currentFrame = 0;
3320 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3322 Roo.lib.AnimMgr.registerElement(this);
3326 this.stop = function(finish) {
3328 this.currentFrame = this.totalFrames;
3329 this._onTween.fire();
3331 Roo.lib.AnimMgr.stop(this);
3334 var onStart = function() {
3335 this.onStart.fire();
3337 this.runtimeAttributes = {};
3338 for (var attr in this.attributes) {
3339 this.setRuntimeAttribute(attr);
3344 startTime = new Date();
3348 var onTween = function() {
3350 duration: new Date() - this.getStartTime(),
3351 currentFrame: this.currentFrame
3354 data.toString = function() {
3356 'duration: ' + data.duration +
3357 ', currentFrame: ' + data.currentFrame
3361 this.onTween.fire(data);
3363 var runtimeAttributes = this.runtimeAttributes;
3365 for (var attr in runtimeAttributes) {
3366 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3372 var onComplete = function() {
3373 var actual_duration = (new Date() - startTime) / 1000 ;
3376 duration: actual_duration,
3377 frames: actualFrames,
3378 fps: actualFrames / actual_duration
3381 data.toString = function() {
3383 'duration: ' + data.duration +
3384 ', frames: ' + data.frames +
3385 ', fps: ' + data.fps
3391 this.onComplete.fire(data);
3395 this._onStart = new Roo.util.Event(this);
3396 this.onStart = new Roo.util.Event(this);
3397 this.onTween = new Roo.util.Event(this);
3398 this._onTween = new Roo.util.Event(this);
3399 this.onComplete = new Roo.util.Event(this);
3400 this._onComplete = new Roo.util.Event(this);
3401 this._onStart.addListener(onStart);
3402 this._onTween.addListener(onTween);
3403 this._onComplete.addListener(onComplete);
3408 * Portions of this file are based on pieces of Yahoo User Interface Library
3409 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3410 * YUI licensed under the BSD License:
3411 * http://developer.yahoo.net/yui/license.txt
3412 * <script type="text/javascript">
3416 Roo.lib.AnimMgr = new function() {
3433 this.registerElement = function(tween) {
3434 queue[queue.length] = tween;
3436 tween._onStart.fire();
3441 this.unRegister = function(tween, index) {
3442 tween._onComplete.fire();
3443 index = index || getIndex(tween);
3445 queue.splice(index, 1);
3449 if (tweenCount <= 0) {
3455 this.start = function() {
3456 if (thread === null) {
3457 thread = setInterval(this.run, this.delay);
3462 this.stop = function(tween) {
3464 clearInterval(thread);
3466 for (var i = 0, len = queue.length; i < len; ++i) {
3467 if (queue[0].isAnimated()) {
3468 this.unRegister(queue[0], 0);
3477 this.unRegister(tween);
3482 this.run = function() {
3483 for (var i = 0, len = queue.length; i < len; ++i) {
3484 var tween = queue[i];
3485 if (!tween || !tween.isAnimated()) {
3489 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3491 tween.currentFrame += 1;
3493 if (tween.useSeconds) {
3494 correctFrame(tween);
3496 tween._onTween.fire();
3499 Roo.lib.AnimMgr.stop(tween, i);
3504 var getIndex = function(anim) {
3505 for (var i = 0, len = queue.length; i < len; ++i) {
3506 if (queue[i] == anim) {
3514 var correctFrame = function(tween) {
3515 var frames = tween.totalFrames;
3516 var frame = tween.currentFrame;
3517 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3518 var elapsed = (new Date() - tween.getStartTime());
3521 if (elapsed < tween.duration * 1000) {
3522 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3524 tweak = frames - (frame + 1);
3526 if (tweak > 0 && isFinite(tweak)) {
3527 if (tween.currentFrame + tweak >= frames) {
3528 tweak = frames - (frame + 1);
3531 tween.currentFrame += tweak;
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">
3544 Roo.lib.Bezier = new function() {
3546 this.getPosition = function(points, t) {
3547 var n = points.length;
3550 for (var i = 0; i < n; ++i) {
3551 tmp[i] = [points[i][0], points[i][1]];
3554 for (var j = 1; j < n; ++j) {
3555 for (i = 0; i < n - j; ++i) {
3556 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3557 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3561 return [ tmp[0][0], tmp[0][1] ];
3565 * Portions of this file are based on pieces of Yahoo User Interface Library
3566 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3567 * YUI licensed under the BSD License:
3568 * http://developer.yahoo.net/yui/license.txt
3569 * <script type="text/javascript">
3574 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3575 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3578 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3580 var fly = Roo.lib.AnimBase.fly;
3582 var superclass = Y.ColorAnim.superclass;
3583 var proto = Y.ColorAnim.prototype;
3585 proto.toString = function() {
3586 var el = this.getEl();
3587 var id = el.id || el.tagName;
3588 return ("ColorAnim " + id);
3591 proto.patterns.color = /color$/i;
3592 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3593 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3594 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3595 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3598 proto.parseColor = function(s) {
3599 if (s.length == 3) {
3603 var c = this.patterns.hex.exec(s);
3604 if (c && c.length == 4) {
3605 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3608 c = this.patterns.rgb.exec(s);
3609 if (c && c.length == 4) {
3610 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3613 c = this.patterns.hex3.exec(s);
3614 if (c && c.length == 4) {
3615 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3620 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3621 proto.getAttribute = function(attr) {
3622 var el = this.getEl();
3623 if (this.patterns.color.test(attr)) {
3624 var val = fly(el).getStyle(attr);
3626 if (this.patterns.transparent.test(val)) {
3627 var parent = el.parentNode;
3628 val = fly(parent).getStyle(attr);
3630 while (parent && this.patterns.transparent.test(val)) {
3631 parent = parent.parentNode;
3632 val = fly(parent).getStyle(attr);
3633 if (parent.tagName.toUpperCase() == 'HTML') {
3639 val = superclass.getAttribute.call(this, attr);
3644 proto.getAttribute = function(attr) {
3645 var el = this.getEl();
3646 if (this.patterns.color.test(attr)) {
3647 var val = fly(el).getStyle(attr);
3649 if (this.patterns.transparent.test(val)) {
3650 var parent = el.parentNode;
3651 val = fly(parent).getStyle(attr);
3653 while (parent && this.patterns.transparent.test(val)) {
3654 parent = parent.parentNode;
3655 val = fly(parent).getStyle(attr);
3656 if (parent.tagName.toUpperCase() == 'HTML') {
3662 val = superclass.getAttribute.call(this, attr);
3668 proto.doMethod = function(attr, start, end) {
3671 if (this.patterns.color.test(attr)) {
3673 for (var i = 0, len = start.length; i < len; ++i) {
3674 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3677 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3680 val = superclass.doMethod.call(this, attr, start, end);
3686 proto.setRuntimeAttribute = function(attr) {
3687 superclass.setRuntimeAttribute.call(this, attr);
3689 if (this.patterns.color.test(attr)) {
3690 var attributes = this.attributes;
3691 var start = this.parseColor(this.runtimeAttributes[attr].start);
3692 var end = this.parseColor(this.runtimeAttributes[attr].end);
3694 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3695 end = this.parseColor(attributes[attr].by);
3697 for (var i = 0, len = start.length; i < len; ++i) {
3698 end[i] = start[i] + end[i];
3702 this.runtimeAttributes[attr].start = start;
3703 this.runtimeAttributes[attr].end = end;
3709 * Portions of this file are based on pieces of Yahoo User Interface Library
3710 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3711 * YUI licensed under the BSD License:
3712 * http://developer.yahoo.net/yui/license.txt
3713 * <script type="text/javascript">
3719 easeNone: function (t, b, c, d) {
3720 return c * t / d + b;
3724 easeIn: function (t, b, c, d) {
3725 return c * (t /= d) * t + b;
3729 easeOut: function (t, b, c, d) {
3730 return -c * (t /= d) * (t - 2) + b;
3734 easeBoth: function (t, b, c, d) {
3735 if ((t /= d / 2) < 1) {
3736 return c / 2 * t * t + b;
3739 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3743 easeInStrong: function (t, b, c, d) {
3744 return c * (t /= d) * t * t * t + b;
3748 easeOutStrong: function (t, b, c, d) {
3749 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3753 easeBothStrong: function (t, b, c, d) {
3754 if ((t /= d / 2) < 1) {
3755 return c / 2 * t * t * t * t + b;
3758 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3763 elasticIn: function (t, b, c, d, a, p) {
3767 if ((t /= d) == 1) {
3774 if (!a || a < Math.abs(c)) {
3779 var s = p / (2 * Math.PI) * Math.asin(c / a);
3782 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3786 elasticOut: function (t, b, c, d, a, p) {
3790 if ((t /= d) == 1) {
3797 if (!a || a < Math.abs(c)) {
3802 var s = p / (2 * Math.PI) * Math.asin(c / a);
3805 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3809 elasticBoth: function (t, b, c, d, a, p) {
3814 if ((t /= d / 2) == 2) {
3822 if (!a || a < Math.abs(c)) {
3827 var s = p / (2 * Math.PI) * Math.asin(c / a);
3831 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3832 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3834 return a * Math.pow(2, -10 * (t -= 1)) *
3835 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3840 backIn: function (t, b, c, d, s) {
3841 if (typeof s == 'undefined') {
3844 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3848 backOut: function (t, b, c, d, s) {
3849 if (typeof s == 'undefined') {
3852 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3856 backBoth: function (t, b, c, d, s) {
3857 if (typeof s == 'undefined') {
3861 if ((t /= d / 2 ) < 1) {
3862 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3864 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3868 bounceIn: function (t, b, c, d) {
3869 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3873 bounceOut: function (t, b, c, d) {
3874 if ((t /= d) < (1 / 2.75)) {
3875 return c * (7.5625 * t * t) + b;
3876 } else if (t < (2 / 2.75)) {
3877 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3878 } else if (t < (2.5 / 2.75)) {
3879 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3881 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3885 bounceBoth: function (t, b, c, d) {
3887 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3889 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3892 * Portions of this file are based on pieces of Yahoo User Interface Library
3893 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3894 * YUI licensed under the BSD License:
3895 * http://developer.yahoo.net/yui/license.txt
3896 * <script type="text/javascript">
3900 Roo.lib.Motion = function(el, attributes, duration, method) {
3902 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3906 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3910 var superclass = Y.Motion.superclass;
3911 var proto = Y.Motion.prototype;
3913 proto.toString = function() {
3914 var el = this.getEl();
3915 var id = el.id || el.tagName;
3916 return ("Motion " + id);
3919 proto.patterns.points = /^points$/i;
3921 proto.setAttribute = function(attr, val, unit) {
3922 if (this.patterns.points.test(attr)) {
3923 unit = unit || 'px';
3924 superclass.setAttribute.call(this, 'left', val[0], unit);
3925 superclass.setAttribute.call(this, 'top', val[1], unit);
3927 superclass.setAttribute.call(this, attr, val, unit);
3931 proto.getAttribute = function(attr) {
3932 if (this.patterns.points.test(attr)) {
3934 superclass.getAttribute.call(this, 'left'),
3935 superclass.getAttribute.call(this, 'top')
3938 val = superclass.getAttribute.call(this, attr);
3944 proto.doMethod = function(attr, start, end) {
3947 if (this.patterns.points.test(attr)) {
3948 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3949 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3951 val = superclass.doMethod.call(this, attr, start, end);
3956 proto.setRuntimeAttribute = function(attr) {
3957 if (this.patterns.points.test(attr)) {
3958 var el = this.getEl();
3959 var attributes = this.attributes;
3961 var control = attributes['points']['control'] || [];
3965 if (control.length > 0 && !(control[0] instanceof Array)) {
3966 control = [control];
3969 for (i = 0,len = control.length; i < len; ++i) {
3970 tmp[i] = control[i];
3975 Roo.fly(el).position();
3977 if (isset(attributes['points']['from'])) {
3978 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3981 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3984 start = this.getAttribute('points');
3987 if (isset(attributes['points']['to'])) {
3988 end = translateValues.call(this, attributes['points']['to'], start);
3990 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3991 for (i = 0,len = control.length; i < len; ++i) {
3992 control[i] = translateValues.call(this, control[i], start);
3996 } else if (isset(attributes['points']['by'])) {
3997 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
3999 for (i = 0,len = control.length; i < len; ++i) {
4000 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4004 this.runtimeAttributes[attr] = [start];
4006 if (control.length > 0) {
4007 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4010 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4013 superclass.setRuntimeAttribute.call(this, attr);
4017 var translateValues = function(val, start) {
4018 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4019 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4024 var isset = function(prop) {
4025 return (typeof prop !== 'undefined');
4029 * Portions of this file are based on pieces of Yahoo User Interface Library
4030 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4031 * YUI licensed under the BSD License:
4032 * http://developer.yahoo.net/yui/license.txt
4033 * <script type="text/javascript">
4037 Roo.lib.Scroll = function(el, attributes, duration, method) {
4039 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4043 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4047 var superclass = Y.Scroll.superclass;
4048 var proto = Y.Scroll.prototype;
4050 proto.toString = function() {
4051 var el = this.getEl();
4052 var id = el.id || el.tagName;
4053 return ("Scroll " + id);
4056 proto.doMethod = function(attr, start, end) {
4059 if (attr == 'scroll') {
4061 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4062 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4066 val = superclass.doMethod.call(this, attr, start, end);
4071 proto.getAttribute = function(attr) {
4073 var el = this.getEl();
4075 if (attr == 'scroll') {
4076 val = [ el.scrollLeft, el.scrollTop ];
4078 val = superclass.getAttribute.call(this, attr);
4084 proto.setAttribute = function(attr, val, unit) {
4085 var el = this.getEl();
4087 if (attr == 'scroll') {
4088 el.scrollLeft = val[0];
4089 el.scrollTop = val[1];
4091 superclass.setAttribute.call(this, attr, val, unit);
4097 * Ext JS Library 1.1.1
4098 * Copyright(c) 2006-2007, Ext JS, LLC.
4100 * Originally Released Under LGPL - original licence link has changed is not relivant.
4103 * <script type="text/javascript">
4107 // nasty IE9 hack - what a pile of crap that is..
4109 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4110 Range.prototype.createContextualFragment = function (html) {
4111 var doc = window.document;
4112 var container = doc.createElement("div");
4113 container.innerHTML = html;
4114 var frag = doc.createDocumentFragment(), n;
4115 while ((n = container.firstChild)) {
4116 frag.appendChild(n);
4123 * @class Roo.DomHelper
4124 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4125 * 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>.
4128 Roo.DomHelper = function(){
4129 var tempTableEl = null;
4130 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4131 var tableRe = /^table|tbody|tr|td$/i;
4133 // build as innerHTML where available
4135 var createHtml = function(o){
4136 if(typeof o == 'string'){
4145 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4146 if(attr == "style"){
4148 if(typeof s == "function"){
4151 if(typeof s == "string"){
4152 b += ' style="' + s + '"';
4153 }else if(typeof s == "object"){
4156 if(typeof s[key] != "function"){
4157 b += key + ":" + s[key] + ";";
4164 b += ' class="' + o["cls"] + '"';
4165 }else if(attr == "htmlFor"){
4166 b += ' for="' + o["htmlFor"] + '"';
4168 b += " " + attr + '="' + o[attr] + '"';
4172 if(emptyTags.test(o.tag)){
4176 var cn = o.children || o.cn;
4178 //http://bugs.kde.org/show_bug.cgi?id=71506
4179 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4180 for(var i = 0, len = cn.length; i < len; i++) {
4181 b += createHtml(cn[i], b);
4184 b += createHtml(cn, b);
4190 b += "</" + o.tag + ">";
4197 var createDom = function(o, parentNode){
4199 // defininition craeted..
4201 if (o.ns && o.ns != 'html') {
4203 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4204 xmlns[o.ns] = o.xmlns;
4207 if (typeof(xmlns[o.ns]) == 'undefined') {
4208 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4214 if (typeof(o) == 'string') {
4215 return parentNode.appendChild(document.createTextNode(o));
4217 o.tag = o.tag || div;
4218 if (o.ns && Roo.isIE) {
4220 o.tag = o.ns + ':' + o.tag;
4223 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4224 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4227 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4228 attr == "style" || typeof o[attr] == "function") continue;
4230 if(attr=="cls" && Roo.isIE){
4231 el.className = o["cls"];
4233 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4234 else el[attr] = o[attr];
4237 Roo.DomHelper.applyStyles(el, o.style);
4238 var cn = o.children || o.cn;
4240 //http://bugs.kde.org/show_bug.cgi?id=71506
4241 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4242 for(var i = 0, len = cn.length; i < len; i++) {
4243 createDom(cn[i], el);
4250 el.innerHTML = o.html;
4253 parentNode.appendChild(el);
4258 var ieTable = function(depth, s, h, e){
4259 tempTableEl.innerHTML = [s, h, e].join('');
4260 var i = -1, el = tempTableEl;
4267 // kill repeat to save bytes
4271 tbe = '</tbody>'+te,
4277 * Nasty code for IE's broken table implementation
4279 var insertIntoTable = function(tag, where, el, html){
4281 tempTableEl = document.createElement('div');
4286 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4289 if(where == 'beforebegin'){
4293 before = el.nextSibling;
4296 node = ieTable(4, trs, html, tre);
4298 else if(tag == 'tr'){
4299 if(where == 'beforebegin'){
4302 node = ieTable(3, tbs, html, tbe);
4303 } else if(where == 'afterend'){
4304 before = el.nextSibling;
4306 node = ieTable(3, tbs, html, tbe);
4307 } else{ // INTO a TR
4308 if(where == 'afterbegin'){
4309 before = el.firstChild;
4311 node = ieTable(4, trs, html, tre);
4313 } else if(tag == 'tbody'){
4314 if(where == 'beforebegin'){
4317 node = ieTable(2, ts, html, te);
4318 } else if(where == 'afterend'){
4319 before = el.nextSibling;
4321 node = ieTable(2, ts, html, te);
4323 if(where == 'afterbegin'){
4324 before = el.firstChild;
4326 node = ieTable(3, tbs, html, tbe);
4329 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4332 if(where == 'afterbegin'){
4333 before = el.firstChild;
4335 node = ieTable(2, ts, html, te);
4337 el.insertBefore(node, before);
4342 /** True to force the use of DOM instead of html fragments @type Boolean */
4346 * Returns the markup for the passed Element(s) config
4347 * @param {Object} o The Dom object spec (and children)
4350 markup : function(o){
4351 return createHtml(o);
4355 * Applies a style specification to an element
4356 * @param {String/HTMLElement} el The element to apply styles to
4357 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4358 * a function which returns such a specification.
4360 applyStyles : function(el, styles){
4363 if(typeof styles == "string"){
4364 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4366 while ((matches = re.exec(styles)) != null){
4367 el.setStyle(matches[1], matches[2]);
4369 }else if (typeof styles == "object"){
4370 for (var style in styles){
4371 el.setStyle(style, styles[style]);
4373 }else if (typeof styles == "function"){
4374 Roo.DomHelper.applyStyles(el, styles.call());
4380 * Inserts an HTML fragment into the Dom
4381 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4382 * @param {HTMLElement} el The context element
4383 * @param {String} html The HTML fragmenet
4384 * @return {HTMLElement} The new node
4386 insertHtml : function(where, el, html){
4387 where = where.toLowerCase();
4388 if(el.insertAdjacentHTML){
4389 if(tableRe.test(el.tagName)){
4391 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4397 el.insertAdjacentHTML('BeforeBegin', html);
4398 return el.previousSibling;
4400 el.insertAdjacentHTML('AfterBegin', html);
4401 return el.firstChild;
4403 el.insertAdjacentHTML('BeforeEnd', html);
4404 return el.lastChild;
4406 el.insertAdjacentHTML('AfterEnd', html);
4407 return el.nextSibling;
4409 throw 'Illegal insertion point -> "' + where + '"';
4411 var range = el.ownerDocument.createRange();
4415 range.setStartBefore(el);
4416 frag = range.createContextualFragment(html);
4417 el.parentNode.insertBefore(frag, el);
4418 return el.previousSibling;
4421 range.setStartBefore(el.firstChild);
4422 frag = range.createContextualFragment(html);
4423 el.insertBefore(frag, el.firstChild);
4424 return el.firstChild;
4426 el.innerHTML = html;
4427 return el.firstChild;
4431 range.setStartAfter(el.lastChild);
4432 frag = range.createContextualFragment(html);
4433 el.appendChild(frag);
4434 return el.lastChild;
4436 el.innerHTML = html;
4437 return el.lastChild;
4440 range.setStartAfter(el);
4441 frag = range.createContextualFragment(html);
4442 el.parentNode.insertBefore(frag, el.nextSibling);
4443 return el.nextSibling;
4445 throw 'Illegal insertion point -> "' + where + '"';
4449 * Creates new Dom element(s) and inserts them before el
4450 * @param {String/HTMLElement/Element} el The context element
4451 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4452 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4453 * @return {HTMLElement/Roo.Element} The new node
4455 insertBefore : function(el, o, returnElement){
4456 return this.doInsert(el, o, returnElement, "beforeBegin");
4460 * Creates new Dom element(s) and inserts them after el
4461 * @param {String/HTMLElement/Element} el The context element
4462 * @param {Object} o The Dom object spec (and children)
4463 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4464 * @return {HTMLElement/Roo.Element} The new node
4466 insertAfter : function(el, o, returnElement){
4467 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4471 * Creates new Dom element(s) and inserts them as the first child of el
4472 * @param {String/HTMLElement/Element} el The context element
4473 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4474 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4475 * @return {HTMLElement/Roo.Element} The new node
4477 insertFirst : function(el, o, returnElement){
4478 return this.doInsert(el, o, returnElement, "afterBegin");
4482 doInsert : function(el, o, returnElement, pos, sibling){
4483 el = Roo.getDom(el);
4485 if(this.useDom || o.ns){
4486 newNode = createDom(o, null);
4487 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4489 var html = createHtml(o);
4490 newNode = this.insertHtml(pos, el, html);
4492 return returnElement ? Roo.get(newNode, true) : newNode;
4496 * Creates new Dom element(s) and appends them to el
4497 * @param {String/HTMLElement/Element} el The context element
4498 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4499 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4500 * @return {HTMLElement/Roo.Element} The new node
4502 append : function(el, o, returnElement){
4503 el = Roo.getDom(el);
4505 if(this.useDom || o.ns){
4506 newNode = createDom(o, null);
4507 el.appendChild(newNode);
4509 var html = createHtml(o);
4510 newNode = this.insertHtml("beforeEnd", el, html);
4512 return returnElement ? Roo.get(newNode, true) : newNode;
4516 * Creates new Dom element(s) and overwrites the contents of el with them
4517 * @param {String/HTMLElement/Element} el The context element
4518 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4519 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4520 * @return {HTMLElement/Roo.Element} The new node
4522 overwrite : function(el, o, returnElement){
4523 el = Roo.getDom(el);
4526 while (el.childNodes.length) {
4527 el.removeChild(el.firstChild);
4531 el.innerHTML = createHtml(o);
4534 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4538 * Creates a new Roo.DomHelper.Template from the Dom object spec
4539 * @param {Object} o The Dom object spec (and children)
4540 * @return {Roo.DomHelper.Template} The new template
4542 createTemplate : function(o){
4543 var html = createHtml(o);
4544 return new Roo.Template(html);
4550 * Ext JS Library 1.1.1
4551 * Copyright(c) 2006-2007, Ext JS, LLC.
4553 * Originally Released Under LGPL - original licence link has changed is not relivant.
4556 * <script type="text/javascript">
4560 * @class Roo.Template
4561 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4562 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4565 var t = new Roo.Template({
4566 html : '<div name="{id}">' +
4567 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4569 myformat: function (value, allValues) {
4570 return 'XX' + value;
4573 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4575 * For more information see this blog post with examples:
4576 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4577 - Create Elements using DOM, HTML fragments and Templates</a>.
4579 * @param {Object} cfg - Configuration object.
4581 Roo.Template = function(cfg){
4583 if(cfg instanceof Array){
4585 }else if(arguments.length > 1){
4586 cfg = Array.prototype.join.call(arguments, "");
4590 if (typeof(cfg) == 'object') {
4601 Roo.Template.prototype = {
4604 * @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..
4605 * it should be fixed so that template is observable...
4609 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4613 * Returns an HTML fragment of this template with the specified values applied.
4614 * @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'})
4615 * @return {String} The HTML fragment
4617 applyTemplate : function(values){
4621 return this.compiled(values);
4623 var useF = this.disableFormats !== true;
4624 var fm = Roo.util.Format, tpl = this;
4625 var fn = function(m, name, format, args){
4627 if(format.substr(0, 5) == "this."){
4628 return tpl.call(format.substr(5), values[name], values);
4631 // quoted values are required for strings in compiled templates,
4632 // but for non compiled we need to strip them
4633 // quoted reversed for jsmin
4634 var re = /^\s*['"](.*)["']\s*$/;
4635 args = args.split(',');
4636 for(var i = 0, len = args.length; i < len; i++){
4637 args[i] = args[i].replace(re, "$1");
4639 args = [values[name]].concat(args);
4641 args = [values[name]];
4643 return fm[format].apply(fm, args);
4646 return values[name] !== undefined ? values[name] : "";
4649 return this.html.replace(this.re, fn);
4667 this.loading = true;
4668 this.compiled = false;
4670 var cx = new Roo.data.Connection();
4674 success : function (response) {
4676 _t.html = response.responseText;
4680 failure : function(response) {
4681 Roo.log("Template failed to load from " + _t.url);
4688 * Sets the HTML used as the template and optionally compiles it.
4689 * @param {String} html
4690 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4691 * @return {Roo.Template} this
4693 set : function(html, compile){
4695 this.compiled = null;
4703 * True to disable format functions (defaults to false)
4706 disableFormats : false,
4709 * The regular expression used to match template variables
4713 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4716 * Compiles the template into an internal function, eliminating the RegEx overhead.
4717 * @return {Roo.Template} this
4719 compile : function(){
4720 var fm = Roo.util.Format;
4721 var useF = this.disableFormats !== true;
4722 var sep = Roo.isGecko ? "+" : ",";
4723 var fn = function(m, name, format, args){
4725 args = args ? ',' + args : "";
4726 if(format.substr(0, 5) != "this."){
4727 format = "fm." + format + '(';
4729 format = 'this.call("'+ format.substr(5) + '", ';
4733 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4735 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4738 // branched to use + in gecko and [].join() in others
4740 body = "this.compiled = function(values){ return '" +
4741 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4744 body = ["this.compiled = function(values){ return ['"];
4745 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4746 body.push("'].join('');};");
4747 body = body.join('');
4757 // private function used to call members
4758 call : function(fnName, value, allValues){
4759 return this[fnName](value, allValues);
4763 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4764 * @param {String/HTMLElement/Roo.Element} el The context element
4765 * @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'})
4766 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4767 * @return {HTMLElement/Roo.Element} The new node or Element
4769 insertFirst: function(el, values, returnElement){
4770 return this.doInsert('afterBegin', el, values, returnElement);
4774 * Applies the supplied values to the template and inserts the new node(s) before el.
4775 * @param {String/HTMLElement/Roo.Element} el The context element
4776 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4777 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4778 * @return {HTMLElement/Roo.Element} The new node or Element
4780 insertBefore: function(el, values, returnElement){
4781 return this.doInsert('beforeBegin', el, values, returnElement);
4785 * Applies the supplied values to the template and inserts the new node(s) after el.
4786 * @param {String/HTMLElement/Roo.Element} el The context element
4787 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4788 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4789 * @return {HTMLElement/Roo.Element} The new node or Element
4791 insertAfter : function(el, values, returnElement){
4792 return this.doInsert('afterEnd', el, values, returnElement);
4796 * Applies the supplied values to the template and appends the new node(s) to el.
4797 * @param {String/HTMLElement/Roo.Element} el The context element
4798 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4799 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4800 * @return {HTMLElement/Roo.Element} The new node or Element
4802 append : function(el, values, returnElement){
4803 return this.doInsert('beforeEnd', el, values, returnElement);
4806 doInsert : function(where, el, values, returnEl){
4807 el = Roo.getDom(el);
4808 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4809 return returnEl ? Roo.get(newNode, true) : newNode;
4813 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4814 * @param {String/HTMLElement/Roo.Element} el The context element
4815 * @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'})
4816 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4817 * @return {HTMLElement/Roo.Element} The new node or Element
4819 overwrite : function(el, values, returnElement){
4820 el = Roo.getDom(el);
4821 el.innerHTML = this.applyTemplate(values);
4822 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4826 * Alias for {@link #applyTemplate}
4829 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4832 Roo.DomHelper.Template = Roo.Template;
4835 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4836 * @param {String/HTMLElement} el A DOM element or its id
4837 * @returns {Roo.Template} The created template
4840 Roo.Template.from = function(el){
4841 el = Roo.getDom(el);
4842 return new Roo.Template(el.value || el.innerHTML);
4845 * Ext JS Library 1.1.1
4846 * Copyright(c) 2006-2007, Ext JS, LLC.
4848 * Originally Released Under LGPL - original licence link has changed is not relivant.
4851 * <script type="text/javascript">
4856 * This is code is also distributed under MIT license for use
4857 * with jQuery and prototype JavaScript libraries.
4860 * @class Roo.DomQuery
4861 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).
4863 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>
4866 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.
4868 <h4>Element Selectors:</h4>
4870 <li> <b>*</b> any element</li>
4871 <li> <b>E</b> an element with the tag E</li>
4872 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4873 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4874 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4875 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4877 <h4>Attribute Selectors:</h4>
4878 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4880 <li> <b>E[foo]</b> has an attribute "foo"</li>
4881 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4882 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4883 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4884 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4885 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4886 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4888 <h4>Pseudo Classes:</h4>
4890 <li> <b>E:first-child</b> E is the first child of its parent</li>
4891 <li> <b>E:last-child</b> E is the last child of its parent</li>
4892 <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>
4893 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4894 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4895 <li> <b>E:only-child</b> E is the only child of its parent</li>
4896 <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>
4897 <li> <b>E:first</b> the first E in the resultset</li>
4898 <li> <b>E:last</b> the last E in the resultset</li>
4899 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4900 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4901 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4902 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4903 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4904 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4905 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4906 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4907 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4909 <h4>CSS Value Selectors:</h4>
4911 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4912 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4913 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4914 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4915 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4916 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4920 Roo.DomQuery = function(){
4921 var cache = {}, simpleCache = {}, valueCache = {};
4922 var nonSpace = /\S/;
4923 var trimRe = /^\s+|\s+$/g;
4924 var tplRe = /\{(\d+)\}/g;
4925 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4926 var tagTokenRe = /^(#)?([\w-\*]+)/;
4927 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4929 function child(p, index){
4931 var n = p.firstChild;
4933 if(n.nodeType == 1){
4944 while((n = n.nextSibling) && n.nodeType != 1);
4949 while((n = n.previousSibling) && n.nodeType != 1);
4953 function children(d){
4954 var n = d.firstChild, ni = -1;
4956 var nx = n.nextSibling;
4957 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4967 function byClassName(c, a, v){
4971 var r = [], ri = -1, cn;
4972 for(var i = 0, ci; ci = c[i]; i++){
4973 if((' '+ci.className+' ').indexOf(v) != -1){
4980 function attrValue(n, attr){
4981 if(!n.tagName && typeof n.length != "undefined"){
4990 if(attr == "class" || attr == "className"){
4993 return n.getAttribute(attr) || n[attr];
4997 function getNodes(ns, mode, tagName){
4998 var result = [], ri = -1, cs;
5002 tagName = tagName || "*";
5003 if(typeof ns.getElementsByTagName != "undefined"){
5007 for(var i = 0, ni; ni = ns[i]; i++){
5008 cs = ni.getElementsByTagName(tagName);
5009 for(var j = 0, ci; ci = cs[j]; j++){
5013 }else if(mode == "/" || mode == ">"){
5014 var utag = tagName.toUpperCase();
5015 for(var i = 0, ni, cn; ni = ns[i]; i++){
5016 cn = ni.children || ni.childNodes;
5017 for(var j = 0, cj; cj = cn[j]; j++){
5018 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5023 }else if(mode == "+"){
5024 var utag = tagName.toUpperCase();
5025 for(var i = 0, n; n = ns[i]; i++){
5026 while((n = n.nextSibling) && n.nodeType != 1);
5027 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5031 }else if(mode == "~"){
5032 for(var i = 0, n; n = ns[i]; i++){
5033 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5042 function concat(a, b){
5046 for(var i = 0, l = b.length; i < l; i++){
5052 function byTag(cs, tagName){
5053 if(cs.tagName || cs == document){
5059 var r = [], ri = -1;
5060 tagName = tagName.toLowerCase();
5061 for(var i = 0, ci; ci = cs[i]; i++){
5062 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5069 function byId(cs, attr, id){
5070 if(cs.tagName || cs == document){
5076 var r = [], ri = -1;
5077 for(var i = 0,ci; ci = cs[i]; i++){
5078 if(ci && ci.id == id){
5086 function byAttribute(cs, attr, value, op, custom){
5087 var r = [], ri = -1, st = custom=="{";
5088 var f = Roo.DomQuery.operators[op];
5089 for(var i = 0, ci; ci = cs[i]; i++){
5092 a = Roo.DomQuery.getStyle(ci, attr);
5094 else if(attr == "class" || attr == "className"){
5096 }else if(attr == "for"){
5098 }else if(attr == "href"){
5099 a = ci.getAttribute("href", 2);
5101 a = ci.getAttribute(attr);
5103 if((f && f(a, value)) || (!f && a)){
5110 function byPseudo(cs, name, value){
5111 return Roo.DomQuery.pseudos[name](cs, value);
5114 // This is for IE MSXML which does not support expandos.
5115 // IE runs the same speed using setAttribute, however FF slows way down
5116 // and Safari completely fails so they need to continue to use expandos.
5117 var isIE = window.ActiveXObject ? true : false;
5119 // this eval is stop the compressor from
5120 // renaming the variable to something shorter
5122 /** eval:var:batch */
5127 function nodupIEXml(cs){
5129 cs[0].setAttribute("_nodup", d);
5131 for(var i = 1, len = cs.length; i < len; i++){
5133 if(!c.getAttribute("_nodup") != d){
5134 c.setAttribute("_nodup", d);
5138 for(var i = 0, len = cs.length; i < len; i++){
5139 cs[i].removeAttribute("_nodup");
5148 var len = cs.length, c, i, r = cs, cj, ri = -1;
5149 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5152 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5153 return nodupIEXml(cs);
5157 for(i = 1; c = cs[i]; i++){
5162 for(var j = 0; j < i; j++){
5165 for(j = i+1; cj = cs[j]; j++){
5177 function quickDiffIEXml(c1, c2){
5179 for(var i = 0, len = c1.length; i < len; i++){
5180 c1[i].setAttribute("_qdiff", d);
5183 for(var i = 0, len = c2.length; i < len; i++){
5184 if(c2[i].getAttribute("_qdiff") != d){
5185 r[r.length] = c2[i];
5188 for(var i = 0, len = c1.length; i < len; i++){
5189 c1[i].removeAttribute("_qdiff");
5194 function quickDiff(c1, c2){
5195 var len1 = c1.length;
5199 if(isIE && c1[0].selectSingleNode){
5200 return quickDiffIEXml(c1, c2);
5203 for(var i = 0; i < len1; i++){
5207 for(var i = 0, len = c2.length; i < len; i++){
5208 if(c2[i]._qdiff != d){
5209 r[r.length] = c2[i];
5215 function quickId(ns, mode, root, id){
5217 var d = root.ownerDocument || root;
5218 return d.getElementById(id);
5220 ns = getNodes(ns, mode, "*");
5221 return byId(ns, null, id);
5225 getStyle : function(el, name){
5226 return Roo.fly(el).getStyle(name);
5229 * Compiles a selector/xpath query into a reusable function. The returned function
5230 * takes one parameter "root" (optional), which is the context node from where the query should start.
5231 * @param {String} selector The selector/xpath query
5232 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5233 * @return {Function}
5235 compile : function(path, type){
5236 type = type || "select";
5238 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5239 var q = path, mode, lq;
5240 var tk = Roo.DomQuery.matchers;
5241 var tklen = tk.length;
5244 // accept leading mode switch
5245 var lmode = q.match(modeRe);
5246 if(lmode && lmode[1]){
5247 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5248 q = q.replace(lmode[1], "");
5250 // strip leading slashes
5251 while(path.substr(0, 1)=="/"){
5252 path = path.substr(1);
5255 while(q && lq != q){
5257 var tm = q.match(tagTokenRe);
5258 if(type == "select"){
5261 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5263 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5265 q = q.replace(tm[0], "");
5266 }else if(q.substr(0, 1) != '@'){
5267 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5272 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5274 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5276 q = q.replace(tm[0], "");
5279 while(!(mm = q.match(modeRe))){
5280 var matched = false;
5281 for(var j = 0; j < tklen; j++){
5283 var m = q.match(t.re);
5285 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5288 q = q.replace(m[0], "");
5293 // prevent infinite loop on bad selector
5295 throw 'Error parsing selector, parsing failed at "' + q + '"';
5299 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5300 q = q.replace(mm[1], "");
5303 fn[fn.length] = "return nodup(n);\n}";
5306 * list of variables that need from compression as they are used by eval.
5316 * eval:var:byClassName
5318 * eval:var:byAttribute
5319 * eval:var:attrValue
5327 * Selects a group of elements.
5328 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5329 * @param {Node} root (optional) The start of the query (defaults to document).
5332 select : function(path, root, type){
5333 if(!root || root == document){
5336 if(typeof root == "string"){
5337 root = document.getElementById(root);
5339 var paths = path.split(",");
5341 for(var i = 0, len = paths.length; i < len; i++){
5342 var p = paths[i].replace(trimRe, "");
5344 cache[p] = Roo.DomQuery.compile(p);
5346 throw p + " is not a valid selector";
5349 var result = cache[p](root);
5350 if(result && result != document){
5351 results = results.concat(result);
5354 if(paths.length > 1){
5355 return nodup(results);
5361 * Selects a single element.
5362 * @param {String} selector The selector/xpath query
5363 * @param {Node} root (optional) The start of the query (defaults to document).
5366 selectNode : function(path, root){
5367 return Roo.DomQuery.select(path, root)[0];
5371 * Selects the value of a node, optionally replacing null with the defaultValue.
5372 * @param {String} selector The selector/xpath query
5373 * @param {Node} root (optional) The start of the query (defaults to document).
5374 * @param {String} defaultValue
5376 selectValue : function(path, root, defaultValue){
5377 path = path.replace(trimRe, "");
5378 if(!valueCache[path]){
5379 valueCache[path] = Roo.DomQuery.compile(path, "select");
5381 var n = valueCache[path](root);
5382 n = n[0] ? n[0] : n;
5383 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5384 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5388 * Selects the value of a node, parsing integers and floats.
5389 * @param {String} selector The selector/xpath query
5390 * @param {Node} root (optional) The start of the query (defaults to document).
5391 * @param {Number} defaultValue
5394 selectNumber : function(path, root, defaultValue){
5395 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5396 return parseFloat(v);
5400 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5401 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5402 * @param {String} selector The simple selector to test
5405 is : function(el, ss){
5406 if(typeof el == "string"){
5407 el = document.getElementById(el);
5409 var isArray = (el instanceof Array);
5410 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5411 return isArray ? (result.length == el.length) : (result.length > 0);
5415 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5416 * @param {Array} el An array of elements to filter
5417 * @param {String} selector The simple selector to test
5418 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5419 * the selector instead of the ones that match
5422 filter : function(els, ss, nonMatches){
5423 ss = ss.replace(trimRe, "");
5424 if(!simpleCache[ss]){
5425 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5427 var result = simpleCache[ss](els);
5428 return nonMatches ? quickDiff(result, els) : result;
5432 * Collection of matching regular expressions and code snippets.
5436 select: 'n = byClassName(n, null, " {1} ");'
5438 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5439 select: 'n = byPseudo(n, "{1}", "{2}");'
5441 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5442 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5445 select: 'n = byId(n, null, "{1}");'
5448 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5453 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5454 * 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, > <.
5457 "=" : function(a, v){
5460 "!=" : function(a, v){
5463 "^=" : function(a, v){
5464 return a && a.substr(0, v.length) == v;
5466 "$=" : function(a, v){
5467 return a && a.substr(a.length-v.length) == v;
5469 "*=" : function(a, v){
5470 return a && a.indexOf(v) !== -1;
5472 "%=" : function(a, v){
5473 return (a % v) == 0;
5475 "|=" : function(a, v){
5476 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5478 "~=" : function(a, v){
5479 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5484 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5485 * and the argument (if any) supplied in the selector.
5488 "first-child" : function(c){
5489 var r = [], ri = -1, n;
5490 for(var i = 0, ci; ci = n = c[i]; i++){
5491 while((n = n.previousSibling) && n.nodeType != 1);
5499 "last-child" : function(c){
5500 var r = [], ri = -1, n;
5501 for(var i = 0, ci; ci = n = c[i]; i++){
5502 while((n = n.nextSibling) && n.nodeType != 1);
5510 "nth-child" : function(c, a) {
5511 var r = [], ri = -1;
5512 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5513 var f = (m[1] || 1) - 0, l = m[2] - 0;
5514 for(var i = 0, n; n = c[i]; i++){
5515 var pn = n.parentNode;
5516 if (batch != pn._batch) {
5518 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5519 if(cn.nodeType == 1){
5526 if (l == 0 || n.nodeIndex == l){
5529 } else if ((n.nodeIndex + l) % f == 0){
5537 "only-child" : function(c){
5538 var r = [], ri = -1;;
5539 for(var i = 0, ci; ci = c[i]; i++){
5540 if(!prev(ci) && !next(ci)){
5547 "empty" : function(c){
5548 var r = [], ri = -1;
5549 for(var i = 0, ci; ci = c[i]; i++){
5550 var cns = ci.childNodes, j = 0, cn, empty = true;
5553 if(cn.nodeType == 1 || cn.nodeType == 3){
5565 "contains" : function(c, v){
5566 var r = [], ri = -1;
5567 for(var i = 0, ci; ci = c[i]; i++){
5568 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5575 "nodeValue" : function(c, v){
5576 var r = [], ri = -1;
5577 for(var i = 0, ci; ci = c[i]; i++){
5578 if(ci.firstChild && ci.firstChild.nodeValue == v){
5585 "checked" : function(c){
5586 var r = [], ri = -1;
5587 for(var i = 0, ci; ci = c[i]; i++){
5588 if(ci.checked == true){
5595 "not" : function(c, ss){
5596 return Roo.DomQuery.filter(c, ss, true);
5599 "odd" : function(c){
5600 return this["nth-child"](c, "odd");
5603 "even" : function(c){
5604 return this["nth-child"](c, "even");
5607 "nth" : function(c, a){
5608 return c[a-1] || [];
5611 "first" : function(c){
5615 "last" : function(c){
5616 return c[c.length-1] || [];
5619 "has" : function(c, ss){
5620 var s = Roo.DomQuery.select;
5621 var r = [], ri = -1;
5622 for(var i = 0, ci; ci = c[i]; i++){
5623 if(s(ss, ci).length > 0){
5630 "next" : function(c, ss){
5631 var is = Roo.DomQuery.is;
5632 var r = [], ri = -1;
5633 for(var i = 0, ci; ci = c[i]; i++){
5642 "prev" : function(c, ss){
5643 var is = Roo.DomQuery.is;
5644 var r = [], ri = -1;
5645 for(var i = 0, ci; ci = c[i]; i++){
5658 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5659 * @param {String} path The selector/xpath query
5660 * @param {Node} root (optional) The start of the query (defaults to document).
5665 Roo.query = Roo.DomQuery.select;
5668 * Ext JS Library 1.1.1
5669 * Copyright(c) 2006-2007, Ext JS, LLC.
5671 * Originally Released Under LGPL - original licence link has changed is not relivant.
5674 * <script type="text/javascript">
5678 * @class Roo.util.Observable
5679 * Base class that provides a common interface for publishing events. Subclasses are expected to
5680 * to have a property "events" with all the events defined.<br>
5683 Employee = function(name){
5690 Roo.extend(Employee, Roo.util.Observable);
5692 * @param {Object} config properties to use (incuding events / listeners)
5695 Roo.util.Observable = function(cfg){
5698 this.addEvents(cfg.events || {});
5700 delete cfg.events; // make sure
5703 Roo.apply(this, cfg);
5706 this.on(this.listeners);
5707 delete this.listeners;
5710 Roo.util.Observable.prototype = {
5712 * @cfg {Object} listeners list of events and functions to call for this object,
5716 'click' : function(e) {
5726 * Fires the specified event with the passed parameters (minus the event name).
5727 * @param {String} eventName
5728 * @param {Object...} args Variable number of parameters are passed to handlers
5729 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5731 fireEvent : function(){
5732 var ce = this.events[arguments[0].toLowerCase()];
5733 if(typeof ce == "object"){
5734 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5741 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5744 * Appends an event handler to this component
5745 * @param {String} eventName The type of event to listen for
5746 * @param {Function} handler The method the event invokes
5747 * @param {Object} scope (optional) The scope in which to execute the handler
5748 * function. The handler function's "this" context.
5749 * @param {Object} options (optional) An object containing handler configuration
5750 * properties. This may contain any of the following properties:<ul>
5751 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5752 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5753 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5754 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5755 * by the specified number of milliseconds. If the event fires again within that time, the original
5756 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5759 * <b>Combining Options</b><br>
5760 * Using the options argument, it is possible to combine different types of listeners:<br>
5762 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5764 el.on('click', this.onClick, this, {
5771 * <b>Attaching multiple handlers in 1 call</b><br>
5772 * The method also allows for a single argument to be passed which is a config object containing properties
5773 * which specify multiple handlers.
5782 fn: this.onMouseOver,
5786 fn: this.onMouseOut,
5792 * Or a shorthand syntax which passes the same scope object to all handlers:
5795 'click': this.onClick,
5796 'mouseover': this.onMouseOver,
5797 'mouseout': this.onMouseOut,
5802 addListener : function(eventName, fn, scope, o){
5803 if(typeof eventName == "object"){
5806 if(this.filterOptRe.test(e)){
5809 if(typeof o[e] == "function"){
5811 this.addListener(e, o[e], o.scope, o);
5813 // individual options
5814 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5819 o = (!o || typeof o == "boolean") ? {} : o;
5820 eventName = eventName.toLowerCase();
5821 var ce = this.events[eventName] || true;
5822 if(typeof ce == "boolean"){
5823 ce = new Roo.util.Event(this, eventName);
5824 this.events[eventName] = ce;
5826 ce.addListener(fn, scope, o);
5830 * Removes a listener
5831 * @param {String} eventName The type of event to listen for
5832 * @param {Function} handler The handler to remove
5833 * @param {Object} scope (optional) The scope (this object) for the handler
5835 removeListener : function(eventName, fn, scope){
5836 var ce = this.events[eventName.toLowerCase()];
5837 if(typeof ce == "object"){
5838 ce.removeListener(fn, scope);
5843 * Removes all listeners for this object
5845 purgeListeners : function(){
5846 for(var evt in this.events){
5847 if(typeof this.events[evt] == "object"){
5848 this.events[evt].clearListeners();
5853 relayEvents : function(o, events){
5854 var createHandler = function(ename){
5856 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5859 for(var i = 0, len = events.length; i < len; i++){
5860 var ename = events[i];
5861 if(!this.events[ename]){ this.events[ename] = true; };
5862 o.on(ename, createHandler(ename), this);
5867 * Used to define events on this Observable
5868 * @param {Object} object The object with the events defined
5870 addEvents : function(o){
5874 Roo.applyIf(this.events, o);
5878 * Checks to see if this object has any listeners for a specified event
5879 * @param {String} eventName The name of the event to check for
5880 * @return {Boolean} True if the event is being listened for, else false
5882 hasListener : function(eventName){
5883 var e = this.events[eventName];
5884 return typeof e == "object" && e.listeners.length > 0;
5888 * Appends an event handler to this element (shorthand for addListener)
5889 * @param {String} eventName The type of event to listen for
5890 * @param {Function} handler The method the event invokes
5891 * @param {Object} scope (optional) The scope in which to execute the handler
5892 * function. The handler function's "this" context.
5893 * @param {Object} options (optional)
5896 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5898 * Removes a listener (shorthand for removeListener)
5899 * @param {String} eventName The type of event to listen for
5900 * @param {Function} handler The handler to remove
5901 * @param {Object} scope (optional) The scope (this object) for the handler
5904 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5907 * Starts capture on the specified Observable. All events will be passed
5908 * to the supplied function with the event name + standard signature of the event
5909 * <b>before</b> the event is fired. If the supplied function returns false,
5910 * the event will not fire.
5911 * @param {Observable} o The Observable to capture
5912 * @param {Function} fn The function to call
5913 * @param {Object} scope (optional) The scope (this object) for the fn
5916 Roo.util.Observable.capture = function(o, fn, scope){
5917 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5921 * Removes <b>all</b> added captures from the Observable.
5922 * @param {Observable} o The Observable to release
5925 Roo.util.Observable.releaseCapture = function(o){
5926 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5931 var createBuffered = function(h, o, scope){
5932 var task = new Roo.util.DelayedTask();
5934 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5938 var createSingle = function(h, e, fn, scope){
5940 e.removeListener(fn, scope);
5941 return h.apply(scope, arguments);
5945 var createDelayed = function(h, o, scope){
5947 var args = Array.prototype.slice.call(arguments, 0);
5948 setTimeout(function(){
5949 h.apply(scope, args);
5954 Roo.util.Event = function(obj, name){
5957 this.listeners = [];
5960 Roo.util.Event.prototype = {
5961 addListener : function(fn, scope, options){
5962 var o = options || {};
5963 scope = scope || this.obj;
5964 if(!this.isListening(fn, scope)){
5965 var l = {fn: fn, scope: scope, options: o};
5968 h = createDelayed(h, o, scope);
5971 h = createSingle(h, this, fn, scope);
5974 h = createBuffered(h, o, scope);
5977 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5978 this.listeners.push(l);
5980 this.listeners = this.listeners.slice(0);
5981 this.listeners.push(l);
5986 findListener : function(fn, scope){
5987 scope = scope || this.obj;
5988 var ls = this.listeners;
5989 for(var i = 0, len = ls.length; i < len; i++){
5991 if(l.fn == fn && l.scope == scope){
5998 isListening : function(fn, scope){
5999 return this.findListener(fn, scope) != -1;
6002 removeListener : function(fn, scope){
6004 if((index = this.findListener(fn, scope)) != -1){
6006 this.listeners.splice(index, 1);
6008 this.listeners = this.listeners.slice(0);
6009 this.listeners.splice(index, 1);
6016 clearListeners : function(){
6017 this.listeners = [];
6021 var ls = this.listeners, scope, len = ls.length;
6024 var args = Array.prototype.slice.call(arguments, 0);
6025 for(var i = 0; i < len; i++){
6027 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
6028 this.firing = false;
6032 this.firing = false;
6039 * Ext JS Library 1.1.1
6040 * Copyright(c) 2006-2007, Ext JS, LLC.
6042 * Originally Released Under LGPL - original licence link has changed is not relivant.
6045 * <script type="text/javascript">
6049 * @class Roo.EventManager
6050 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6051 * several useful events directly.
6052 * See {@link Roo.EventObject} for more details on normalized event objects.
6055 Roo.EventManager = function(){
6056 var docReadyEvent, docReadyProcId, docReadyState = false;
6057 var resizeEvent, resizeTask, textEvent, textSize;
6058 var E = Roo.lib.Event;
6059 var D = Roo.lib.Dom;
6064 var fireDocReady = function(){
6066 docReadyState = true;
6069 clearInterval(docReadyProcId);
6071 if(Roo.isGecko || Roo.isOpera) {
6072 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6075 var defer = document.getElementById("ie-deferred-loader");
6077 defer.onreadystatechange = null;
6078 defer.parentNode.removeChild(defer);
6082 docReadyEvent.fire();
6083 docReadyEvent.clearListeners();
6088 var initDocReady = function(){
6089 docReadyEvent = new Roo.util.Event();
6090 if(Roo.isGecko || Roo.isOpera) {
6091 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6093 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6094 var defer = document.getElementById("ie-deferred-loader");
6095 defer.onreadystatechange = function(){
6096 if(this.readyState == "complete"){
6100 }else if(Roo.isSafari){
6101 docReadyProcId = setInterval(function(){
6102 var rs = document.readyState;
6103 if(rs == "complete") {
6108 // no matter what, make sure it fires on load
6109 E.on(window, "load", fireDocReady);
6112 var createBuffered = function(h, o){
6113 var task = new Roo.util.DelayedTask(h);
6115 // create new event object impl so new events don't wipe out properties
6116 e = new Roo.EventObjectImpl(e);
6117 task.delay(o.buffer, h, null, [e]);
6121 var createSingle = function(h, el, ename, fn){
6123 Roo.EventManager.removeListener(el, ename, fn);
6128 var createDelayed = function(h, o){
6130 // create new event object impl so new events don't wipe out properties
6131 e = new Roo.EventObjectImpl(e);
6132 setTimeout(function(){
6137 var transitionEndVal = false;
6139 var transitionEnd = function()
6141 if (transitionEndVal) {
6142 return transitionEndVal;
6144 var el = document.createElement('div');
6146 var transEndEventNames = {
6147 WebkitTransition : 'webkitTransitionEnd',
6148 MozTransition : 'transitionend',
6149 OTransition : 'oTransitionEnd otransitionend',
6150 transition : 'transitionend'
6153 for (var name in transEndEventNames) {
6154 if (el.style[name] !== undefined) {
6155 transitionEndVal = transEndEventNames[name];
6156 return transitionEndVal ;
6162 var listen = function(element, ename, opt, fn, scope){
6163 var o = (!opt || typeof opt == "boolean") ? {} : opt;
6164 fn = fn || o.fn; scope = scope || o.scope;
6165 var el = Roo.getDom(element);
6169 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6172 if (ename == 'transitionend') {
6173 ename = transitionEnd();
6175 var h = function(e){
6176 e = Roo.EventObject.setEvent(e);
6179 t = e.getTarget(o.delegate, el);
6186 if(o.stopEvent === true){
6189 if(o.preventDefault === true){
6192 if(o.stopPropagation === true){
6193 e.stopPropagation();
6196 if(o.normalized === false){
6200 fn.call(scope || el, e, t, o);
6203 h = createDelayed(h, o);
6206 h = createSingle(h, el, ename, fn);
6209 h = createBuffered(h, o);
6211 fn._handlers = fn._handlers || [];
6214 fn._handlers.push([Roo.id(el), ename, h]);
6219 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6220 el.addEventListener("DOMMouseScroll", h, false);
6221 E.on(window, 'unload', function(){
6222 el.removeEventListener("DOMMouseScroll", h, false);
6225 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6226 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6231 var stopListening = function(el, ename, fn){
6232 var id = Roo.id(el), hds = fn._handlers, hd = fn;
6234 for(var i = 0, len = hds.length; i < len; i++){
6236 if(h[0] == id && h[1] == ename){
6243 E.un(el, ename, hd);
6244 el = Roo.getDom(el);
6245 if(ename == "mousewheel" && el.addEventListener){
6246 el.removeEventListener("DOMMouseScroll", hd, false);
6248 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6249 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6253 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6260 * @scope Roo.EventManager
6265 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6266 * object with a Roo.EventObject
6267 * @param {Function} fn The method the event invokes
6268 * @param {Object} scope An object that becomes the scope of the handler
6269 * @param {boolean} override If true, the obj passed in becomes
6270 * the execution scope of the listener
6271 * @return {Function} The wrapped function
6274 wrap : function(fn, scope, override){
6276 Roo.EventObject.setEvent(e);
6277 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6282 * Appends an event handler to an element (shorthand for addListener)
6283 * @param {String/HTMLElement} element The html element or id to assign the
6284 * @param {String} eventName The type of event to listen for
6285 * @param {Function} handler The method the event invokes
6286 * @param {Object} scope (optional) The scope in which to execute the handler
6287 * function. The handler function's "this" context.
6288 * @param {Object} options (optional) An object containing handler configuration
6289 * properties. This may contain any of the following properties:<ul>
6290 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6291 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6292 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6293 * <li>preventDefault {Boolean} True to prevent the default action</li>
6294 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6295 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6296 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6297 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6298 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6299 * by the specified number of milliseconds. If the event fires again within that time, the original
6300 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6303 * <b>Combining Options</b><br>
6304 * Using the options argument, it is possible to combine different types of listeners:<br>
6306 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6308 el.on('click', this.onClick, this, {
6315 * <b>Attaching multiple handlers in 1 call</b><br>
6316 * The method also allows for a single argument to be passed which is a config object containing properties
6317 * which specify multiple handlers.
6327 fn: this.onMouseOver
6336 * Or a shorthand syntax:<br>
6339 'click' : this.onClick,
6340 'mouseover' : this.onMouseOver,
6341 'mouseout' : this.onMouseOut
6345 addListener : function(element, eventName, fn, scope, options){
6346 if(typeof eventName == "object"){
6352 if(typeof o[e] == "function"){
6354 listen(element, e, o, o[e], o.scope);
6356 // individual options
6357 listen(element, e, o[e]);
6362 return listen(element, eventName, options, fn, scope);
6366 * Removes an event handler
6368 * @param {String/HTMLElement} element The id or html element to remove the
6370 * @param {String} eventName The type of event
6371 * @param {Function} fn
6372 * @return {Boolean} True if a listener was actually removed
6374 removeListener : function(element, eventName, fn){
6375 return stopListening(element, eventName, fn);
6379 * Fires when the document is ready (before onload and before images are loaded). Can be
6380 * accessed shorthanded Roo.onReady().
6381 * @param {Function} fn The method the event invokes
6382 * @param {Object} scope An object that becomes the scope of the handler
6383 * @param {boolean} options
6385 onDocumentReady : function(fn, scope, options){
6386 if(docReadyState){ // if it already fired
6387 docReadyEvent.addListener(fn, scope, options);
6388 docReadyEvent.fire();
6389 docReadyEvent.clearListeners();
6395 docReadyEvent.addListener(fn, scope, options);
6399 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6400 * @param {Function} fn The method the event invokes
6401 * @param {Object} scope An object that becomes the scope of the handler
6402 * @param {boolean} options
6404 onWindowResize : function(fn, scope, options){
6406 resizeEvent = new Roo.util.Event();
6407 resizeTask = new Roo.util.DelayedTask(function(){
6408 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6410 E.on(window, "resize", function(){
6412 resizeTask.delay(50);
6414 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6418 resizeEvent.addListener(fn, scope, options);
6422 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6423 * @param {Function} fn The method the event invokes
6424 * @param {Object} scope An object that becomes the scope of the handler
6425 * @param {boolean} options
6427 onTextResize : function(fn, scope, options){
6429 textEvent = new Roo.util.Event();
6430 var textEl = new Roo.Element(document.createElement('div'));
6431 textEl.dom.className = 'x-text-resize';
6432 textEl.dom.innerHTML = 'X';
6433 textEl.appendTo(document.body);
6434 textSize = textEl.dom.offsetHeight;
6435 setInterval(function(){
6436 if(textEl.dom.offsetHeight != textSize){
6437 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6439 }, this.textResizeInterval);
6441 textEvent.addListener(fn, scope, options);
6445 * Removes the passed window resize listener.
6446 * @param {Function} fn The method the event invokes
6447 * @param {Object} scope The scope of handler
6449 removeResizeListener : function(fn, scope){
6451 resizeEvent.removeListener(fn, scope);
6456 fireResize : function(){
6458 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6462 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6466 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6468 textResizeInterval : 50
6473 * @scopeAlias pub=Roo.EventManager
6477 * Appends an event handler to an element (shorthand for addListener)
6478 * @param {String/HTMLElement} element The html element or id to assign the
6479 * @param {String} eventName The type of event to listen for
6480 * @param {Function} handler The method the event invokes
6481 * @param {Object} scope (optional) The scope in which to execute the handler
6482 * function. The handler function's "this" context.
6483 * @param {Object} options (optional) An object containing handler configuration
6484 * properties. This may contain any of the following properties:<ul>
6485 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6486 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6487 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6488 * <li>preventDefault {Boolean} True to prevent the default action</li>
6489 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6490 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6491 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6492 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6493 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6494 * by the specified number of milliseconds. If the event fires again within that time, the original
6495 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6498 * <b>Combining Options</b><br>
6499 * Using the options argument, it is possible to combine different types of listeners:<br>
6501 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6503 el.on('click', this.onClick, this, {
6510 * <b>Attaching multiple handlers in 1 call</b><br>
6511 * The method also allows for a single argument to be passed which is a config object containing properties
6512 * which specify multiple handlers.
6522 fn: this.onMouseOver
6531 * Or a shorthand syntax:<br>
6534 'click' : this.onClick,
6535 'mouseover' : this.onMouseOver,
6536 'mouseout' : this.onMouseOut
6540 pub.on = pub.addListener;
6541 pub.un = pub.removeListener;
6543 pub.stoppedMouseDownEvent = new Roo.util.Event();
6547 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6548 * @param {Function} fn The method the event invokes
6549 * @param {Object} scope An object that becomes the scope of the handler
6550 * @param {boolean} override If true, the obj passed in becomes
6551 * the execution scope of the listener
6555 Roo.onReady = Roo.EventManager.onDocumentReady;
6557 Roo.onReady(function(){
6558 var bd = Roo.get(document.body);
6563 : Roo.isGecko ? "roo-gecko"
6564 : Roo.isOpera ? "roo-opera"
6565 : Roo.isSafari ? "roo-safari" : ""];
6568 cls.push("roo-mac");
6571 cls.push("roo-linux");
6573 if(Roo.isBorderBox){
6574 cls.push('roo-border-box');
6576 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6577 var p = bd.dom.parentNode;
6579 p.className += ' roo-strict';
6582 bd.addClass(cls.join(' '));
6586 * @class Roo.EventObject
6587 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6588 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6591 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6593 var target = e.getTarget();
6596 var myDiv = Roo.get("myDiv");
6597 myDiv.on("click", handleClick);
6599 Roo.EventManager.on("myDiv", 'click', handleClick);
6600 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6604 Roo.EventObject = function(){
6606 var E = Roo.lib.Event;
6608 // safari keypress events for special keys return bad keycodes
6611 63235 : 39, // right
6614 63276 : 33, // page up
6615 63277 : 34, // page down
6616 63272 : 46, // delete
6621 // normalize button clicks
6622 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6623 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6625 Roo.EventObjectImpl = function(e){
6627 this.setEvent(e.browserEvent || e);
6630 Roo.EventObjectImpl.prototype = {
6632 * Used to fix doc tools.
6633 * @scope Roo.EventObject.prototype
6639 /** The normal browser event */
6640 browserEvent : null,
6641 /** The button pressed in a mouse event */
6643 /** True if the shift key was down during the event */
6645 /** True if the control key was down during the event */
6647 /** True if the alt key was down during the event */
6706 setEvent : function(e){
6707 if(e == this || (e && e.browserEvent)){ // already wrapped
6710 this.browserEvent = e;
6712 // normalize buttons
6713 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6714 if(e.type == 'click' && this.button == -1){
6718 this.shiftKey = e.shiftKey;
6719 // mac metaKey behaves like ctrlKey
6720 this.ctrlKey = e.ctrlKey || e.metaKey;
6721 this.altKey = e.altKey;
6722 // in getKey these will be normalized for the mac
6723 this.keyCode = e.keyCode;
6724 // keyup warnings on firefox.
6725 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6726 // cache the target for the delayed and or buffered events
6727 this.target = E.getTarget(e);
6729 this.xy = E.getXY(e);
6732 this.shiftKey = false;
6733 this.ctrlKey = false;
6734 this.altKey = false;
6744 * Stop the event (preventDefault and stopPropagation)
6746 stopEvent : function(){
6747 if(this.browserEvent){
6748 if(this.browserEvent.type == 'mousedown'){
6749 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6751 E.stopEvent(this.browserEvent);
6756 * Prevents the browsers default handling of the event.
6758 preventDefault : function(){
6759 if(this.browserEvent){
6760 E.preventDefault(this.browserEvent);
6765 isNavKeyPress : function(){
6766 var k = this.keyCode;
6767 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6768 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6771 isSpecialKey : function(){
6772 var k = this.keyCode;
6773 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6774 (k == 16) || (k == 17) ||
6775 (k >= 18 && k <= 20) ||
6776 (k >= 33 && k <= 35) ||
6777 (k >= 36 && k <= 39) ||
6778 (k >= 44 && k <= 45);
6781 * Cancels bubbling of the event.
6783 stopPropagation : function(){
6784 if(this.browserEvent){
6785 if(this.type == 'mousedown'){
6786 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6788 E.stopPropagation(this.browserEvent);
6793 * Gets the key code for the event.
6796 getCharCode : function(){
6797 return this.charCode || this.keyCode;
6801 * Returns a normalized keyCode for the event.
6802 * @return {Number} The key code
6804 getKey : function(){
6805 var k = this.keyCode || this.charCode;
6806 return Roo.isSafari ? (safariKeys[k] || k) : k;
6810 * Gets the x coordinate of the event.
6813 getPageX : function(){
6818 * Gets the y coordinate of the event.
6821 getPageY : function(){
6826 * Gets the time of the event.
6829 getTime : function(){
6830 if(this.browserEvent){
6831 return E.getTime(this.browserEvent);
6837 * Gets the page coordinates of the event.
6838 * @return {Array} The xy values like [x, y]
6845 * Gets the target for the event.
6846 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6847 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6848 search as a number or element (defaults to 10 || document.body)
6849 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6850 * @return {HTMLelement}
6852 getTarget : function(selector, maxDepth, returnEl){
6853 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6856 * Gets the related target.
6857 * @return {HTMLElement}
6859 getRelatedTarget : function(){
6860 if(this.browserEvent){
6861 return E.getRelatedTarget(this.browserEvent);
6867 * Normalizes mouse wheel delta across browsers
6868 * @return {Number} The delta
6870 getWheelDelta : function(){
6871 var e = this.browserEvent;
6873 if(e.wheelDelta){ /* IE/Opera. */
6874 delta = e.wheelDelta/120;
6875 }else if(e.detail){ /* Mozilla case. */
6876 delta = -e.detail/3;
6882 * Returns true if the control, meta, shift or alt key was pressed during this event.
6885 hasModifier : function(){
6886 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6890 * Returns true if the target of this event equals el or is a child of el
6891 * @param {String/HTMLElement/Element} el
6892 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6895 within : function(el, related){
6896 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6897 return t && Roo.fly(el).contains(t);
6900 getPoint : function(){
6901 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6905 return new Roo.EventObjectImpl();
6910 * Ext JS Library 1.1.1
6911 * Copyright(c) 2006-2007, Ext JS, LLC.
6913 * Originally Released Under LGPL - original licence link has changed is not relivant.
6916 * <script type="text/javascript">
6920 // was in Composite Element!??!?!
6923 var D = Roo.lib.Dom;
6924 var E = Roo.lib.Event;
6925 var A = Roo.lib.Anim;
6927 // local style camelizing for speed
6929 var camelRe = /(-[a-z])/gi;
6930 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6931 var view = document.defaultView;
6934 * @class Roo.Element
6935 * Represents an Element in the DOM.<br><br>
6938 var el = Roo.get("my-div");
6941 var el = getEl("my-div");
6943 // or with a DOM element
6944 var el = Roo.get(myDivElement);
6946 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6947 * each call instead of constructing a new one.<br><br>
6948 * <b>Animations</b><br />
6949 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6950 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6952 Option Default Description
6953 --------- -------- ---------------------------------------------
6954 duration .35 The duration of the animation in seconds
6955 easing easeOut The YUI easing method
6956 callback none A function to execute when the anim completes
6957 scope this The scope (this) of the callback function
6959 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6960 * manipulate the animation. Here's an example:
6962 var el = Roo.get("my-div");
6967 // default animation
6968 el.setWidth(100, true);
6970 // animation with some options set
6977 // using the "anim" property to get the Anim object
6983 el.setWidth(100, opt);
6985 if(opt.anim.isAnimated()){
6989 * <b> Composite (Collections of) Elements</b><br />
6990 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
6991 * @constructor Create a new Element directly.
6992 * @param {String/HTMLElement} element
6993 * @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).
6995 Roo.Element = function(element, forceNew){
6996 var dom = typeof element == "string" ?
6997 document.getElementById(element) : element;
6998 if(!dom){ // invalid id/element
7002 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7003 return Roo.Element.cache[id];
7013 * The DOM element ID
7016 this.id = id || Roo.id(dom);
7019 var El = Roo.Element;
7023 * The element's default display mode (defaults to "")
7026 originalDisplay : "",
7030 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7035 * Sets the element's visibility mode. When setVisible() is called it
7036 * will use this to determine whether to set the visibility or the display property.
7037 * @param visMode Element.VISIBILITY or Element.DISPLAY
7038 * @return {Roo.Element} this
7040 setVisibilityMode : function(visMode){
7041 this.visibilityMode = visMode;
7045 * Convenience method for setVisibilityMode(Element.DISPLAY)
7046 * @param {String} display (optional) What to set display to when visible
7047 * @return {Roo.Element} this
7049 enableDisplayMode : function(display){
7050 this.setVisibilityMode(El.DISPLAY);
7051 if(typeof display != "undefined") this.originalDisplay = display;
7056 * 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)
7057 * @param {String} selector The simple selector to test
7058 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7059 search as a number or element (defaults to 10 || document.body)
7060 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7061 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7063 findParent : function(simpleSelector, maxDepth, returnEl){
7064 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7065 maxDepth = maxDepth || 50;
7066 if(typeof maxDepth != "number"){
7067 stopEl = Roo.getDom(maxDepth);
7070 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7071 if(dq.is(p, simpleSelector)){
7072 return returnEl ? Roo.get(p) : p;
7082 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7083 * @param {String} selector The simple selector to test
7084 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7085 search as a number or element (defaults to 10 || document.body)
7086 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7087 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7089 findParentNode : function(simpleSelector, maxDepth, returnEl){
7090 var p = Roo.fly(this.dom.parentNode, '_internal');
7091 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7095 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
7096 * This is a shortcut for findParentNode() that always returns an Roo.Element.
7097 * @param {String} selector The simple selector to test
7098 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7099 search as a number or element (defaults to 10 || document.body)
7100 * @return {Roo.Element} The matching DOM node (or null if no match was found)
7102 up : function(simpleSelector, maxDepth){
7103 return this.findParentNode(simpleSelector, maxDepth, true);
7109 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
7110 * @param {String} selector The simple selector to test
7111 * @return {Boolean} True if this element matches the selector, else false
7113 is : function(simpleSelector){
7114 return Roo.DomQuery.is(this.dom, simpleSelector);
7118 * Perform animation on this element.
7119 * @param {Object} args The YUI animation control args
7120 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
7121 * @param {Function} onComplete (optional) Function to call when animation completes
7122 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
7123 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
7124 * @return {Roo.Element} this
7126 animate : function(args, duration, onComplete, easing, animType){
7127 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7132 * @private Internal animation call
7134 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7135 animType = animType || 'run';
7137 var anim = Roo.lib.Anim[animType](
7139 (opt.duration || defaultDur) || .35,
7140 (opt.easing || defaultEase) || 'easeOut',
7142 Roo.callback(cb, this);
7143 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7151 // private legacy anim prep
7152 preanim : function(a, i){
7153 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7157 * Removes worthless text nodes
7158 * @param {Boolean} forceReclean (optional) By default the element
7159 * keeps track if it has been cleaned already so
7160 * you can call this over and over. However, if you update the element and
7161 * need to force a reclean, you can pass true.
7163 clean : function(forceReclean){
7164 if(this.isCleaned && forceReclean !== true){
7168 var d = this.dom, n = d.firstChild, ni = -1;
7170 var nx = n.nextSibling;
7171 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7178 this.isCleaned = true;
7183 calcOffsetsTo : function(el){
7186 var restorePos = false;
7187 if(el.getStyle('position') == 'static'){
7188 el.position('relative');
7193 while(op && op != d && op.tagName != 'HTML'){
7196 op = op.offsetParent;
7199 el.position('static');
7205 * Scrolls this element into view within the passed container.
7206 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7207 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7208 * @return {Roo.Element} this
7210 scrollIntoView : function(container, hscroll){
7211 var c = Roo.getDom(container) || document.body;
7214 var o = this.calcOffsetsTo(c),
7217 b = t+el.offsetHeight,
7218 r = l+el.offsetWidth;
7220 var ch = c.clientHeight;
7221 var ct = parseInt(c.scrollTop, 10);
7222 var cl = parseInt(c.scrollLeft, 10);
7224 var cr = cl + c.clientWidth;
7232 if(hscroll !== false){
7236 c.scrollLeft = r-c.clientWidth;
7243 scrollChildIntoView : function(child, hscroll){
7244 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7248 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7249 * the new height may not be available immediately.
7250 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7251 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7252 * @param {Function} onComplete (optional) Function to call when animation completes
7253 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7254 * @return {Roo.Element} this
7256 autoHeight : function(animate, duration, onComplete, easing){
7257 var oldHeight = this.getHeight();
7259 this.setHeight(1); // force clipping
7260 setTimeout(function(){
7261 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7263 this.setHeight(height);
7265 if(typeof onComplete == "function"){
7269 this.setHeight(oldHeight); // restore original height
7270 this.setHeight(height, animate, duration, function(){
7272 if(typeof onComplete == "function") onComplete();
7273 }.createDelegate(this), easing);
7275 }.createDelegate(this), 0);
7280 * Returns true if this element is an ancestor of the passed element
7281 * @param {HTMLElement/String} el The element to check
7282 * @return {Boolean} True if this element is an ancestor of el, else false
7284 contains : function(el){
7285 if(!el){return false;}
7286 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7290 * Checks whether the element is currently visible using both visibility and display properties.
7291 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7292 * @return {Boolean} True if the element is currently visible, else false
7294 isVisible : function(deep) {
7295 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7296 if(deep !== true || !vis){
7299 var p = this.dom.parentNode;
7300 while(p && p.tagName.toLowerCase() != "body"){
7301 if(!Roo.fly(p, '_isVisible').isVisible()){
7310 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7311 * @param {String} selector The CSS selector
7312 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7313 * @return {CompositeElement/CompositeElementLite} The composite element
7315 select : function(selector, unique){
7316 return El.select(selector, unique, this.dom);
7320 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7321 * @param {String} selector The CSS selector
7322 * @return {Array} An array of the matched nodes
7324 query : function(selector, unique){
7325 return Roo.DomQuery.select(selector, this.dom);
7329 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7330 * @param {String} selector The CSS selector
7331 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7332 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7334 child : function(selector, returnDom){
7335 var n = Roo.DomQuery.selectNode(selector, this.dom);
7336 return returnDom ? n : Roo.get(n);
7340 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7341 * @param {String} selector The CSS selector
7342 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7343 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7345 down : function(selector, returnDom){
7346 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7347 return returnDom ? n : Roo.get(n);
7351 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7352 * @param {String} group The group the DD object is member of
7353 * @param {Object} config The DD config object
7354 * @param {Object} overrides An object containing methods to override/implement on the DD object
7355 * @return {Roo.dd.DD} The DD object
7357 initDD : function(group, config, overrides){
7358 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7359 return Roo.apply(dd, overrides);
7363 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7364 * @param {String} group The group the DDProxy object is member of
7365 * @param {Object} config The DDProxy config object
7366 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7367 * @return {Roo.dd.DDProxy} The DDProxy object
7369 initDDProxy : function(group, config, overrides){
7370 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7371 return Roo.apply(dd, overrides);
7375 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7376 * @param {String} group The group the DDTarget object is member of
7377 * @param {Object} config The DDTarget config object
7378 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7379 * @return {Roo.dd.DDTarget} The DDTarget object
7381 initDDTarget : function(group, config, overrides){
7382 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7383 return Roo.apply(dd, overrides);
7387 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7388 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7389 * @param {Boolean} visible Whether the element is visible
7390 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7391 * @return {Roo.Element} this
7393 setVisible : function(visible, animate){
7395 if(this.visibilityMode == El.DISPLAY){
7396 this.setDisplayed(visible);
7399 this.dom.style.visibility = visible ? "visible" : "hidden";
7402 // closure for composites
7404 var visMode = this.visibilityMode;
7406 this.setOpacity(.01);
7407 this.setVisible(true);
7409 this.anim({opacity: { to: (visible?1:0) }},
7410 this.preanim(arguments, 1),
7411 null, .35, 'easeIn', function(){
7413 if(visMode == El.DISPLAY){
7414 dom.style.display = "none";
7416 dom.style.visibility = "hidden";
7418 Roo.get(dom).setOpacity(1);
7426 * Returns true if display is not "none"
7429 isDisplayed : function() {
7430 return this.getStyle("display") != "none";
7434 * Toggles the element's visibility or display, depending on visibility mode.
7435 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7436 * @return {Roo.Element} this
7438 toggle : function(animate){
7439 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7444 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7445 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7446 * @return {Roo.Element} this
7448 setDisplayed : function(value) {
7449 if(typeof value == "boolean"){
7450 value = value ? this.originalDisplay : "none";
7452 this.setStyle("display", value);
7457 * Tries to focus the element. Any exceptions are caught and ignored.
7458 * @return {Roo.Element} this
7460 focus : function() {
7468 * Tries to blur the element. Any exceptions are caught and ignored.
7469 * @return {Roo.Element} this
7479 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7480 * @param {String/Array} className The CSS class to add, or an array of classes
7481 * @return {Roo.Element} this
7483 addClass : function(className){
7484 if(className instanceof Array){
7485 for(var i = 0, len = className.length; i < len; i++) {
7486 this.addClass(className[i]);
7489 if(className && !this.hasClass(className)){
7490 this.dom.className = this.dom.className + " " + className;
7497 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7498 * @param {String/Array} className The CSS class to add, or an array of classes
7499 * @return {Roo.Element} this
7501 radioClass : function(className){
7502 var siblings = this.dom.parentNode.childNodes;
7503 for(var i = 0; i < siblings.length; i++) {
7504 var s = siblings[i];
7505 if(s.nodeType == 1){
7506 Roo.get(s).removeClass(className);
7509 this.addClass(className);
7514 * Removes one or more CSS classes from the element.
7515 * @param {String/Array} className The CSS class to remove, or an array of classes
7516 * @return {Roo.Element} this
7518 removeClass : function(className){
7519 if(!className || !this.dom.className){
7522 if(className instanceof Array){
7523 for(var i = 0, len = className.length; i < len; i++) {
7524 this.removeClass(className[i]);
7527 if(this.hasClass(className)){
7528 var re = this.classReCache[className];
7530 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7531 this.classReCache[className] = re;
7533 this.dom.className =
7534 this.dom.className.replace(re, " ");
7544 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7545 * @param {String} className The CSS class to toggle
7546 * @return {Roo.Element} this
7548 toggleClass : function(className){
7549 if(this.hasClass(className)){
7550 this.removeClass(className);
7552 this.addClass(className);
7558 * Checks if the specified CSS class exists on this element's DOM node.
7559 * @param {String} className The CSS class to check for
7560 * @return {Boolean} True if the class exists, else false
7562 hasClass : function(className){
7563 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7567 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7568 * @param {String} oldClassName The CSS class to replace
7569 * @param {String} newClassName The replacement CSS class
7570 * @return {Roo.Element} this
7572 replaceClass : function(oldClassName, newClassName){
7573 this.removeClass(oldClassName);
7574 this.addClass(newClassName);
7579 * Returns an object with properties matching the styles requested.
7580 * For example, el.getStyles('color', 'font-size', 'width') might return
7581 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7582 * @param {String} style1 A style name
7583 * @param {String} style2 A style name
7584 * @param {String} etc.
7585 * @return {Object} The style object
7587 getStyles : function(){
7588 var a = arguments, len = a.length, r = {};
7589 for(var i = 0; i < len; i++){
7590 r[a[i]] = this.getStyle(a[i]);
7596 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7597 * @param {String} property The style property whose value is returned.
7598 * @return {String} The current value of the style property for this element.
7600 getStyle : function(){
7601 return view && view.getComputedStyle ?
7603 var el = this.dom, v, cs, camel;
7604 if(prop == 'float'){
7607 if(el.style && (v = el.style[prop])){
7610 if(cs = view.getComputedStyle(el, "")){
7611 if(!(camel = propCache[prop])){
7612 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7619 var el = this.dom, v, cs, camel;
7620 if(prop == 'opacity'){
7621 if(typeof el.style.filter == 'string'){
7622 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7624 var fv = parseFloat(m[1]);
7626 return fv ? fv / 100 : 0;
7631 }else if(prop == 'float'){
7632 prop = "styleFloat";
7634 if(!(camel = propCache[prop])){
7635 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7637 if(v = el.style[camel]){
7640 if(cs = el.currentStyle){
7648 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7649 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7650 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7651 * @return {Roo.Element} this
7653 setStyle : function(prop, value){
7654 if(typeof prop == "string"){
7656 if (prop == 'float') {
7657 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7662 if(!(camel = propCache[prop])){
7663 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7666 if(camel == 'opacity') {
7667 this.setOpacity(value);
7669 this.dom.style[camel] = value;
7672 for(var style in prop){
7673 if(typeof prop[style] != "function"){
7674 this.setStyle(style, prop[style]);
7682 * More flexible version of {@link #setStyle} for setting style properties.
7683 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7684 * a function which returns such a specification.
7685 * @return {Roo.Element} this
7687 applyStyles : function(style){
7688 Roo.DomHelper.applyStyles(this.dom, style);
7693 * 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).
7694 * @return {Number} The X position of the element
7697 return D.getX(this.dom);
7701 * 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).
7702 * @return {Number} The Y position of the element
7705 return D.getY(this.dom);
7709 * 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).
7710 * @return {Array} The XY position of the element
7713 return D.getXY(this.dom);
7717 * 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).
7718 * @param {Number} The X position of the element
7719 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7720 * @return {Roo.Element} this
7722 setX : function(x, animate){
7724 D.setX(this.dom, x);
7726 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7732 * 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).
7733 * @param {Number} The Y position of the element
7734 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7735 * @return {Roo.Element} this
7737 setY : function(y, animate){
7739 D.setY(this.dom, y);
7741 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7747 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7748 * @param {String} left The left CSS property value
7749 * @return {Roo.Element} this
7751 setLeft : function(left){
7752 this.setStyle("left", this.addUnits(left));
7757 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7758 * @param {String} top The top CSS property value
7759 * @return {Roo.Element} this
7761 setTop : function(top){
7762 this.setStyle("top", this.addUnits(top));
7767 * Sets the element's CSS right style.
7768 * @param {String} right The right CSS property value
7769 * @return {Roo.Element} this
7771 setRight : function(right){
7772 this.setStyle("right", this.addUnits(right));
7777 * Sets the element's CSS bottom style.
7778 * @param {String} bottom The bottom CSS property value
7779 * @return {Roo.Element} this
7781 setBottom : function(bottom){
7782 this.setStyle("bottom", this.addUnits(bottom));
7787 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7788 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7789 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7790 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7791 * @return {Roo.Element} this
7793 setXY : function(pos, animate){
7795 D.setXY(this.dom, pos);
7797 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7803 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7804 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7805 * @param {Number} x X value for new position (coordinates are page-based)
7806 * @param {Number} y Y value for new position (coordinates are page-based)
7807 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7808 * @return {Roo.Element} this
7810 setLocation : function(x, y, animate){
7811 this.setXY([x, y], this.preanim(arguments, 2));
7816 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7817 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7818 * @param {Number} x X value for new position (coordinates are page-based)
7819 * @param {Number} y Y value for new position (coordinates are page-based)
7820 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7821 * @return {Roo.Element} this
7823 moveTo : function(x, y, animate){
7824 this.setXY([x, y], this.preanim(arguments, 2));
7829 * Returns the region of the given element.
7830 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7831 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7833 getRegion : function(){
7834 return D.getRegion(this.dom);
7838 * Returns the offset height of the element
7839 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7840 * @return {Number} The element's height
7842 getHeight : function(contentHeight){
7843 var h = this.dom.offsetHeight || 0;
7844 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7848 * Returns the offset width of the element
7849 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7850 * @return {Number} The element's width
7852 getWidth : function(contentWidth){
7853 var w = this.dom.offsetWidth || 0;
7854 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7858 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7859 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7860 * if a height has not been set using CSS.
7863 getComputedHeight : function(){
7864 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7866 h = parseInt(this.getStyle('height'), 10) || 0;
7867 if(!this.isBorderBox()){
7868 h += this.getFrameWidth('tb');
7875 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7876 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7877 * if a width has not been set using CSS.
7880 getComputedWidth : function(){
7881 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7883 w = parseInt(this.getStyle('width'), 10) || 0;
7884 if(!this.isBorderBox()){
7885 w += this.getFrameWidth('lr');
7892 * Returns the size of the element.
7893 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7894 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7896 getSize : function(contentSize){
7897 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7901 * Returns the width and height of the viewport.
7902 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7904 getViewSize : function(){
7905 var d = this.dom, doc = document, aw = 0, ah = 0;
7906 if(d == doc || d == doc.body){
7907 return {width : D.getViewWidth(), height: D.getViewHeight()};
7910 width : d.clientWidth,
7911 height: d.clientHeight
7917 * Returns the value of the "value" attribute
7918 * @param {Boolean} asNumber true to parse the value as a number
7919 * @return {String/Number}
7921 getValue : function(asNumber){
7922 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7926 adjustWidth : function(width){
7927 if(typeof width == "number"){
7928 if(this.autoBoxAdjust && !this.isBorderBox()){
7929 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7939 adjustHeight : function(height){
7940 if(typeof height == "number"){
7941 if(this.autoBoxAdjust && !this.isBorderBox()){
7942 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7952 * Set the width of the element
7953 * @param {Number} width The new width
7954 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7955 * @return {Roo.Element} this
7957 setWidth : function(width, animate){
7958 width = this.adjustWidth(width);
7960 this.dom.style.width = this.addUnits(width);
7962 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7968 * Set the height of the element
7969 * @param {Number} height The new height
7970 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7971 * @return {Roo.Element} this
7973 setHeight : function(height, animate){
7974 height = this.adjustHeight(height);
7976 this.dom.style.height = this.addUnits(height);
7978 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7984 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7985 * @param {Number} width The new width
7986 * @param {Number} height The new height
7987 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7988 * @return {Roo.Element} this
7990 setSize : function(width, height, animate){
7991 if(typeof width == "object"){ // in case of object from getSize()
7992 height = width.height; width = width.width;
7994 width = this.adjustWidth(width); height = this.adjustHeight(height);
7996 this.dom.style.width = this.addUnits(width);
7997 this.dom.style.height = this.addUnits(height);
7999 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
8005 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
8006 * @param {Number} x X value for new position (coordinates are page-based)
8007 * @param {Number} y Y value for new position (coordinates are page-based)
8008 * @param {Number} width The new width
8009 * @param {Number} height The new height
8010 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8011 * @return {Roo.Element} this
8013 setBounds : function(x, y, width, height, animate){
8015 this.setSize(width, height);
8016 this.setLocation(x, y);
8018 width = this.adjustWidth(width); height = this.adjustHeight(height);
8019 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
8020 this.preanim(arguments, 4), 'motion');
8026 * 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.
8027 * @param {Roo.lib.Region} region The region to fill
8028 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8029 * @return {Roo.Element} this
8031 setRegion : function(region, animate){
8032 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8037 * Appends an event handler
8039 * @param {String} eventName The type of event to append
8040 * @param {Function} fn The method the event invokes
8041 * @param {Object} scope (optional) The scope (this object) of the fn
8042 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8044 addListener : function(eventName, fn, scope, options){
8046 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
8051 * Removes an event handler from this element
8052 * @param {String} eventName the type of event to remove
8053 * @param {Function} fn the method the event invokes
8054 * @return {Roo.Element} this
8056 removeListener : function(eventName, fn){
8057 Roo.EventManager.removeListener(this.dom, eventName, fn);
8062 * Removes all previous added listeners from this element
8063 * @return {Roo.Element} this
8065 removeAllListeners : function(){
8066 E.purgeElement(this.dom);
8070 relayEvent : function(eventName, observable){
8071 this.on(eventName, function(e){
8072 observable.fireEvent(eventName, e);
8077 * Set the opacity of the element
8078 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
8079 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8080 * @return {Roo.Element} this
8082 setOpacity : function(opacity, animate){
8084 var s = this.dom.style;
8087 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
8088 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
8090 s.opacity = opacity;
8093 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
8099 * Gets the left X coordinate
8100 * @param {Boolean} local True to get the local css position instead of page coordinate
8103 getLeft : function(local){
8107 return parseInt(this.getStyle("left"), 10) || 0;
8112 * Gets the right X coordinate of the element (element X position + element width)
8113 * @param {Boolean} local True to get the local css position instead of page coordinate
8116 getRight : function(local){
8118 return this.getX() + this.getWidth();
8120 return (this.getLeft(true) + this.getWidth()) || 0;
8125 * Gets the top Y coordinate
8126 * @param {Boolean} local True to get the local css position instead of page coordinate
8129 getTop : function(local) {
8133 return parseInt(this.getStyle("top"), 10) || 0;
8138 * Gets the bottom Y coordinate of the element (element Y position + element height)
8139 * @param {Boolean} local True to get the local css position instead of page coordinate
8142 getBottom : function(local){
8144 return this.getY() + this.getHeight();
8146 return (this.getTop(true) + this.getHeight()) || 0;
8151 * Initializes positioning on this element. If a desired position is not passed, it will make the
8152 * the element positioned relative IF it is not already positioned.
8153 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8154 * @param {Number} zIndex (optional) The zIndex to apply
8155 * @param {Number} x (optional) Set the page X position
8156 * @param {Number} y (optional) Set the page Y position
8158 position : function(pos, zIndex, x, y){
8160 if(this.getStyle('position') == 'static'){
8161 this.setStyle('position', 'relative');
8164 this.setStyle("position", pos);
8167 this.setStyle("z-index", zIndex);
8169 if(x !== undefined && y !== undefined){
8171 }else if(x !== undefined){
8173 }else if(y !== undefined){
8179 * Clear positioning back to the default when the document was loaded
8180 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8181 * @return {Roo.Element} this
8183 clearPositioning : function(value){
8191 "position" : "static"
8197 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8198 * snapshot before performing an update and then restoring the element.
8201 getPositioning : function(){
8202 var l = this.getStyle("left");
8203 var t = this.getStyle("top");
8205 "position" : this.getStyle("position"),
8207 "right" : l ? "" : this.getStyle("right"),
8209 "bottom" : t ? "" : this.getStyle("bottom"),
8210 "z-index" : this.getStyle("z-index")
8215 * Gets the width of the border(s) for the specified side(s)
8216 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8217 * passing lr would get the border (l)eft width + the border (r)ight width.
8218 * @return {Number} The width of the sides passed added together
8220 getBorderWidth : function(side){
8221 return this.addStyles(side, El.borders);
8225 * Gets the width of the padding(s) for the specified side(s)
8226 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8227 * passing lr would get the padding (l)eft + the padding (r)ight.
8228 * @return {Number} The padding of the sides passed added together
8230 getPadding : function(side){
8231 return this.addStyles(side, El.paddings);
8235 * Set positioning with an object returned by getPositioning().
8236 * @param {Object} posCfg
8237 * @return {Roo.Element} this
8239 setPositioning : function(pc){
8240 this.applyStyles(pc);
8241 if(pc.right == "auto"){
8242 this.dom.style.right = "";
8244 if(pc.bottom == "auto"){
8245 this.dom.style.bottom = "";
8251 fixDisplay : function(){
8252 if(this.getStyle("display") == "none"){
8253 this.setStyle("visibility", "hidden");
8254 this.setStyle("display", this.originalDisplay); // first try reverting to default
8255 if(this.getStyle("display") == "none"){ // if that fails, default to block
8256 this.setStyle("display", "block");
8262 * Quick set left and top adding default units
8263 * @param {String} left The left CSS property value
8264 * @param {String} top The top CSS property value
8265 * @return {Roo.Element} this
8267 setLeftTop : function(left, top){
8268 this.dom.style.left = this.addUnits(left);
8269 this.dom.style.top = this.addUnits(top);
8274 * Move this element relative to its current position.
8275 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8276 * @param {Number} distance How far to move the element in pixels
8277 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8278 * @return {Roo.Element} this
8280 move : function(direction, distance, animate){
8281 var xy = this.getXY();
8282 direction = direction.toLowerCase();
8286 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8290 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8295 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8300 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8307 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8308 * @return {Roo.Element} this
8311 if(!this.isClipped){
8312 this.isClipped = true;
8313 this.originalClip = {
8314 "o": this.getStyle("overflow"),
8315 "x": this.getStyle("overflow-x"),
8316 "y": this.getStyle("overflow-y")
8318 this.setStyle("overflow", "hidden");
8319 this.setStyle("overflow-x", "hidden");
8320 this.setStyle("overflow-y", "hidden");
8326 * Return clipping (overflow) to original clipping before clip() was called
8327 * @return {Roo.Element} this
8329 unclip : function(){
8331 this.isClipped = false;
8332 var o = this.originalClip;
8333 if(o.o){this.setStyle("overflow", o.o);}
8334 if(o.x){this.setStyle("overflow-x", o.x);}
8335 if(o.y){this.setStyle("overflow-y", o.y);}
8342 * Gets the x,y coordinates specified by the anchor position on the element.
8343 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8344 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8345 * {width: (target width), height: (target height)} (defaults to the element's current size)
8346 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8347 * @return {Array} [x, y] An array containing the element's x and y coordinates
8349 getAnchorXY : function(anchor, local, s){
8350 //Passing a different size is useful for pre-calculating anchors,
8351 //especially for anchored animations that change the el size.
8353 var w, h, vp = false;
8356 if(d == document.body || d == document){
8358 w = D.getViewWidth(); h = D.getViewHeight();
8360 w = this.getWidth(); h = this.getHeight();
8363 w = s.width; h = s.height;
8365 var x = 0, y = 0, r = Math.round;
8366 switch((anchor || "tl").toLowerCase()){
8408 var sc = this.getScroll();
8409 return [x + sc.left, y + sc.top];
8411 //Add the element's offset xy
8412 var o = this.getXY();
8413 return [x+o[0], y+o[1]];
8417 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8418 * supported position values.
8419 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8420 * @param {String} position The position to align to.
8421 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8422 * @return {Array} [x, y]
8424 getAlignToXY : function(el, p, o){
8428 throw "Element.alignTo with an element that doesn't exist";
8430 var c = false; //constrain to viewport
8431 var p1 = "", p2 = "";
8438 }else if(p.indexOf("-") == -1){
8441 p = p.toLowerCase();
8442 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8444 throw "Element.alignTo with an invalid alignment " + p;
8446 p1 = m[1]; p2 = m[2]; c = !!m[3];
8448 //Subtract the aligned el's internal xy from the target's offset xy
8449 //plus custom offset to get the aligned el's new offset xy
8450 var a1 = this.getAnchorXY(p1, true);
8451 var a2 = el.getAnchorXY(p2, false);
8452 var x = a2[0] - a1[0] + o[0];
8453 var y = a2[1] - a1[1] + o[1];
8455 //constrain the aligned el to viewport if necessary
8456 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8457 // 5px of margin for ie
8458 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8460 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8461 //perpendicular to the vp border, allow the aligned el to slide on that border,
8462 //otherwise swap the aligned el to the opposite border of the target.
8463 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8464 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8465 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8466 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8469 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8470 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8472 if((x+w) > dw + scrollX){
8473 x = swapX ? r.left-w : dw+scrollX-w;
8476 x = swapX ? r.right : scrollX;
8478 if((y+h) > dh + scrollY){
8479 y = swapY ? r.top-h : dh+scrollY-h;
8482 y = swapY ? r.bottom : scrollY;
8489 getConstrainToXY : function(){
8490 var os = {top:0, left:0, bottom:0, right: 0};
8492 return function(el, local, offsets, proposedXY){
8494 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8496 var vw, vh, vx = 0, vy = 0;
8497 if(el.dom == document.body || el.dom == document){
8498 vw = Roo.lib.Dom.getViewWidth();
8499 vh = Roo.lib.Dom.getViewHeight();
8501 vw = el.dom.clientWidth;
8502 vh = el.dom.clientHeight;
8504 var vxy = el.getXY();
8510 var s = el.getScroll();
8512 vx += offsets.left + s.left;
8513 vy += offsets.top + s.top;
8515 vw -= offsets.right;
8516 vh -= offsets.bottom;
8521 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8522 var x = xy[0], y = xy[1];
8523 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8525 // only move it if it needs it
8528 // first validate right/bottom
8537 // then make sure top/left isn't negative
8546 return moved ? [x, y] : false;
8551 adjustForConstraints : function(xy, parent, offsets){
8552 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8556 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8557 * document it aligns it to the viewport.
8558 * The position parameter is optional, and can be specified in any one of the following formats:
8560 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8561 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8562 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8563 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8564 * <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
8565 * element's anchor point, and the second value is used as the target's anchor point.</li>
8567 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8568 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8569 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8570 * that specified in order to enforce the viewport constraints.
8571 * Following are all of the supported anchor positions:
8574 ----- -----------------------------
8575 tl The top left corner (default)
8576 t The center of the top edge
8577 tr The top right corner
8578 l The center of the left edge
8579 c In the center of the element
8580 r The center of the right edge
8581 bl The bottom left corner
8582 b The center of the bottom edge
8583 br The bottom right corner
8587 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8588 el.alignTo("other-el");
8590 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8591 el.alignTo("other-el", "tr?");
8593 // align the bottom right corner of el with the center left edge of other-el
8594 el.alignTo("other-el", "br-l?");
8596 // align the center of el with the bottom left corner of other-el and
8597 // adjust the x position by -6 pixels (and the y position by 0)
8598 el.alignTo("other-el", "c-bl", [-6, 0]);
8600 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8601 * @param {String} position The position to align to.
8602 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8603 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8604 * @return {Roo.Element} this
8606 alignTo : function(element, position, offsets, animate){
8607 var xy = this.getAlignToXY(element, position, offsets);
8608 this.setXY(xy, this.preanim(arguments, 3));
8613 * Anchors an element to another element and realigns it when the window is resized.
8614 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8615 * @param {String} position The position to align to.
8616 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8617 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8618 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8619 * is a number, it is used as the buffer delay (defaults to 50ms).
8620 * @param {Function} callback The function to call after the animation finishes
8621 * @return {Roo.Element} this
8623 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8624 var action = function(){
8625 this.alignTo(el, alignment, offsets, animate);
8626 Roo.callback(callback, this);
8628 Roo.EventManager.onWindowResize(action, this);
8629 var tm = typeof monitorScroll;
8630 if(tm != 'undefined'){
8631 Roo.EventManager.on(window, 'scroll', action, this,
8632 {buffer: tm == 'number' ? monitorScroll : 50});
8634 action.call(this); // align immediately
8638 * Clears any opacity settings from this element. Required in some cases for IE.
8639 * @return {Roo.Element} this
8641 clearOpacity : function(){
8642 if (window.ActiveXObject) {
8643 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8644 this.dom.style.filter = "";
8647 this.dom.style.opacity = "";
8648 this.dom.style["-moz-opacity"] = "";
8649 this.dom.style["-khtml-opacity"] = "";
8655 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8656 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8657 * @return {Roo.Element} this
8659 hide : function(animate){
8660 this.setVisible(false, this.preanim(arguments, 0));
8665 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8666 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8667 * @return {Roo.Element} this
8669 show : function(animate){
8670 this.setVisible(true, this.preanim(arguments, 0));
8675 * @private Test if size has a unit, otherwise appends the default
8677 addUnits : function(size){
8678 return Roo.Element.addUnits(size, this.defaultUnit);
8682 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8683 * @return {Roo.Element} this
8685 beginMeasure : function(){
8687 if(el.offsetWidth || el.offsetHeight){
8688 return this; // offsets work already
8691 var p = this.dom, b = document.body; // start with this element
8692 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8693 var pe = Roo.get(p);
8694 if(pe.getStyle('display') == 'none'){
8695 changed.push({el: p, visibility: pe.getStyle("visibility")});
8696 p.style.visibility = "hidden";
8697 p.style.display = "block";
8701 this._measureChanged = changed;
8707 * Restores displays to before beginMeasure was called
8708 * @return {Roo.Element} this
8710 endMeasure : function(){
8711 var changed = this._measureChanged;
8713 for(var i = 0, len = changed.length; i < len; i++) {
8715 r.el.style.visibility = r.visibility;
8716 r.el.style.display = "none";
8718 this._measureChanged = null;
8724 * Update the innerHTML of this element, optionally searching for and processing scripts
8725 * @param {String} html The new HTML
8726 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8727 * @param {Function} callback For async script loading you can be noticed when the update completes
8728 * @return {Roo.Element} this
8730 update : function(html, loadScripts, callback){
8731 if(typeof html == "undefined"){
8734 if(loadScripts !== true){
8735 this.dom.innerHTML = html;
8736 if(typeof callback == "function"){
8744 html += '<span id="' + id + '"></span>';
8746 E.onAvailable(id, function(){
8747 var hd = document.getElementsByTagName("head")[0];
8748 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8749 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8750 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8753 while(match = re.exec(html)){
8754 var attrs = match[1];
8755 var srcMatch = attrs ? attrs.match(srcRe) : false;
8756 if(srcMatch && srcMatch[2]){
8757 var s = document.createElement("script");
8758 s.src = srcMatch[2];
8759 var typeMatch = attrs.match(typeRe);
8760 if(typeMatch && typeMatch[2]){
8761 s.type = typeMatch[2];
8764 }else if(match[2] && match[2].length > 0){
8765 if(window.execScript) {
8766 window.execScript(match[2]);
8774 window.eval(match[2]);
8778 var el = document.getElementById(id);
8779 if(el){el.parentNode.removeChild(el);}
8780 if(typeof callback == "function"){
8784 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8789 * Direct access to the UpdateManager update() method (takes the same parameters).
8790 * @param {String/Function} url The url for this request or a function to call to get the url
8791 * @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}
8792 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8793 * @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.
8794 * @return {Roo.Element} this
8797 var um = this.getUpdateManager();
8798 um.update.apply(um, arguments);
8803 * Gets this element's UpdateManager
8804 * @return {Roo.UpdateManager} The UpdateManager
8806 getUpdateManager : function(){
8807 if(!this.updateManager){
8808 this.updateManager = new Roo.UpdateManager(this);
8810 return this.updateManager;
8814 * Disables text selection for this element (normalized across browsers)
8815 * @return {Roo.Element} this
8817 unselectable : function(){
8818 this.dom.unselectable = "on";
8819 this.swallowEvent("selectstart", true);
8820 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8821 this.addClass("x-unselectable");
8826 * Calculates the x, y to center this element on the screen
8827 * @return {Array} The x, y values [x, y]
8829 getCenterXY : function(){
8830 return this.getAlignToXY(document, 'c-c');
8834 * Centers the Element in either the viewport, or another Element.
8835 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8837 center : function(centerIn){
8838 this.alignTo(centerIn || document, 'c-c');
8843 * Tests various css rules/browsers to determine if this element uses a border box
8846 isBorderBox : function(){
8847 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8851 * Return a box {x, y, width, height} that can be used to set another elements
8852 * size/location to match this element.
8853 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8854 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8855 * @return {Object} box An object in the format {x, y, width, height}
8857 getBox : function(contentBox, local){
8862 var left = parseInt(this.getStyle("left"), 10) || 0;
8863 var top = parseInt(this.getStyle("top"), 10) || 0;
8866 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8868 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8870 var l = this.getBorderWidth("l")+this.getPadding("l");
8871 var r = this.getBorderWidth("r")+this.getPadding("r");
8872 var t = this.getBorderWidth("t")+this.getPadding("t");
8873 var b = this.getBorderWidth("b")+this.getPadding("b");
8874 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)};
8876 bx.right = bx.x + bx.width;
8877 bx.bottom = bx.y + bx.height;
8882 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8883 for more information about the sides.
8884 * @param {String} sides
8887 getFrameWidth : function(sides, onlyContentBox){
8888 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8892 * 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.
8893 * @param {Object} box The box to fill {x, y, width, height}
8894 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8895 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8896 * @return {Roo.Element} this
8898 setBox : function(box, adjust, animate){
8899 var w = box.width, h = box.height;
8900 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8901 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8902 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8904 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8909 * Forces the browser to repaint this element
8910 * @return {Roo.Element} this
8912 repaint : function(){
8914 this.addClass("x-repaint");
8915 setTimeout(function(){
8916 Roo.get(dom).removeClass("x-repaint");
8922 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8923 * then it returns the calculated width of the sides (see getPadding)
8924 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8925 * @return {Object/Number}
8927 getMargins : function(side){
8930 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8931 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8932 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8933 right: parseInt(this.getStyle("margin-right"), 10) || 0
8936 return this.addStyles(side, El.margins);
8941 addStyles : function(sides, styles){
8943 for(var i = 0, len = sides.length; i < len; i++){
8944 v = this.getStyle(styles[sides.charAt(i)]);
8946 w = parseInt(v, 10);
8954 * Creates a proxy element of this element
8955 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8956 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8957 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8958 * @return {Roo.Element} The new proxy element
8960 createProxy : function(config, renderTo, matchBox){
8962 renderTo = Roo.getDom(renderTo);
8964 renderTo = document.body;
8966 config = typeof config == "object" ?
8967 config : {tag : "div", cls: config};
8968 var proxy = Roo.DomHelper.append(renderTo, config, true);
8970 proxy.setBox(this.getBox());
8976 * Puts a mask over this element to disable user interaction. Requires core.css.
8977 * This method can only be applied to elements which accept child nodes.
8978 * @param {String} msg (optional) A message to display in the mask
8979 * @param {String} msgCls (optional) A css class to apply to the msg element
8980 * @return {Element} The mask element
8982 mask : function(msg, msgCls)
8984 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
8985 this.setStyle("position", "relative");
8988 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
8990 this.addClass("x-masked");
8991 this._mask.setDisplayed(true);
8996 while (dom && dom.style) {
8997 if (!isNaN(parseInt(dom.style.zIndex))) {
8998 z = Math.max(z, parseInt(dom.style.zIndex));
9000 dom = dom.parentNode;
9002 // if we are masking the body - then it hides everything..
9003 if (this.dom == document.body) {
9005 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
9006 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
9009 if(typeof msg == 'string'){
9011 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
9013 var mm = this._maskMsg;
9014 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
9015 if (mm.dom.firstChild) { // weird IE issue?
9016 mm.dom.firstChild.innerHTML = msg;
9018 mm.setDisplayed(true);
9020 mm.setStyle('z-index', z + 102);
9022 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
9023 this._mask.setHeight(this.getHeight());
9025 this._mask.setStyle('z-index', z + 100);
9031 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
9032 * it is cached for reuse.
9034 unmask : function(removeEl){
9036 if(removeEl === true){
9037 this._mask.remove();
9040 this._maskMsg.remove();
9041 delete this._maskMsg;
9044 this._mask.setDisplayed(false);
9046 this._maskMsg.setDisplayed(false);
9050 this.removeClass("x-masked");
9054 * Returns true if this element is masked
9057 isMasked : function(){
9058 return this._mask && this._mask.isVisible();
9062 * Creates an iframe shim for this element to keep selects and other windowed objects from
9064 * @return {Roo.Element} The new shim element
9066 createShim : function(){
9067 var el = document.createElement('iframe');
9068 el.frameBorder = 'no';
9069 el.className = 'roo-shim';
9070 if(Roo.isIE && Roo.isSecure){
9071 el.src = Roo.SSL_SECURE_URL;
9073 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
9074 shim.autoBoxAdjust = false;
9079 * Removes this element from the DOM and deletes it from the cache
9081 remove : function(){
9082 if(this.dom.parentNode){
9083 this.dom.parentNode.removeChild(this.dom);
9085 delete El.cache[this.dom.id];
9089 * Sets up event handlers to add and remove a css class when the mouse is over this element
9090 * @param {String} className
9091 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
9092 * mouseout events for children elements
9093 * @return {Roo.Element} this
9095 addClassOnOver : function(className, preventFlicker){
9096 this.on("mouseover", function(){
9097 Roo.fly(this, '_internal').addClass(className);
9099 var removeFn = function(e){
9100 if(preventFlicker !== true || !e.within(this, true)){
9101 Roo.fly(this, '_internal').removeClass(className);
9104 this.on("mouseout", removeFn, this.dom);
9109 * Sets up event handlers to add and remove a css class when this element has the focus
9110 * @param {String} className
9111 * @return {Roo.Element} this
9113 addClassOnFocus : function(className){
9114 this.on("focus", function(){
9115 Roo.fly(this, '_internal').addClass(className);
9117 this.on("blur", function(){
9118 Roo.fly(this, '_internal').removeClass(className);
9123 * 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)
9124 * @param {String} className
9125 * @return {Roo.Element} this
9127 addClassOnClick : function(className){
9129 this.on("mousedown", function(){
9130 Roo.fly(dom, '_internal').addClass(className);
9131 var d = Roo.get(document);
9132 var fn = function(){
9133 Roo.fly(dom, '_internal').removeClass(className);
9134 d.removeListener("mouseup", fn);
9136 d.on("mouseup", fn);
9142 * Stops the specified event from bubbling and optionally prevents the default action
9143 * @param {String} eventName
9144 * @param {Boolean} preventDefault (optional) true to prevent the default action too
9145 * @return {Roo.Element} this
9147 swallowEvent : function(eventName, preventDefault){
9148 var fn = function(e){
9149 e.stopPropagation();
9154 if(eventName instanceof Array){
9155 for(var i = 0, len = eventName.length; i < len; i++){
9156 this.on(eventName[i], fn);
9160 this.on(eventName, fn);
9167 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9170 * Sizes this element to its parent element's dimensions performing
9171 * neccessary box adjustments.
9172 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9173 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9174 * @return {Roo.Element} this
9176 fitToParent : function(monitorResize, targetParent) {
9177 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9178 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9179 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9182 var p = Roo.get(targetParent || this.dom.parentNode);
9183 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9184 if (monitorResize === true) {
9185 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9186 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9192 * Gets the next sibling, skipping text nodes
9193 * @return {HTMLElement} The next sibling or null
9195 getNextSibling : function(){
9196 var n = this.dom.nextSibling;
9197 while(n && n.nodeType != 1){
9204 * Gets the previous sibling, skipping text nodes
9205 * @return {HTMLElement} The previous sibling or null
9207 getPrevSibling : function(){
9208 var n = this.dom.previousSibling;
9209 while(n && n.nodeType != 1){
9210 n = n.previousSibling;
9217 * Appends the passed element(s) to this element
9218 * @param {String/HTMLElement/Array/Element/CompositeElement} el
9219 * @return {Roo.Element} this
9221 appendChild: function(el){
9228 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9229 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
9230 * automatically generated with the specified attributes.
9231 * @param {HTMLElement} insertBefore (optional) a child element of this element
9232 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9233 * @return {Roo.Element} The new child element
9235 createChild: function(config, insertBefore, returnDom){
9236 config = config || {tag:'div'};
9238 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9240 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
9244 * Appends this element to the passed element
9245 * @param {String/HTMLElement/Element} el The new parent element
9246 * @return {Roo.Element} this
9248 appendTo: function(el){
9249 el = Roo.getDom(el);
9250 el.appendChild(this.dom);
9255 * Inserts this element before the passed element in the DOM
9256 * @param {String/HTMLElement/Element} el The element to insert before
9257 * @return {Roo.Element} this
9259 insertBefore: function(el){
9260 el = Roo.getDom(el);
9261 el.parentNode.insertBefore(this.dom, el);
9266 * Inserts this element after the passed element in the DOM
9267 * @param {String/HTMLElement/Element} el The element to insert after
9268 * @return {Roo.Element} this
9270 insertAfter: function(el){
9271 el = Roo.getDom(el);
9272 el.parentNode.insertBefore(this.dom, el.nextSibling);
9277 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9278 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9279 * @return {Roo.Element} The new child
9281 insertFirst: function(el, returnDom){
9283 if(typeof el == 'object' && !el.nodeType){ // dh config
9284 return this.createChild(el, this.dom.firstChild, returnDom);
9286 el = Roo.getDom(el);
9287 this.dom.insertBefore(el, this.dom.firstChild);
9288 return !returnDom ? Roo.get(el) : el;
9293 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9294 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9295 * @param {String} where (optional) 'before' or 'after' defaults to before
9296 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9297 * @return {Roo.Element} the inserted Element
9299 insertSibling: function(el, where, returnDom){
9300 where = where ? where.toLowerCase() : 'before';
9302 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9304 if(typeof el == 'object' && !el.nodeType){ // dh config
9305 if(where == 'after' && !this.dom.nextSibling){
9306 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9308 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9312 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9313 where == 'before' ? this.dom : this.dom.nextSibling);
9322 * Creates and wraps this element with another element
9323 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9324 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9325 * @return {HTMLElement/Element} The newly created wrapper element
9327 wrap: function(config, returnDom){
9329 config = {tag: "div"};
9331 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9332 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9337 * Replaces the passed element with this element
9338 * @param {String/HTMLElement/Element} el The element to replace
9339 * @return {Roo.Element} this
9341 replace: function(el){
9343 this.insertBefore(el);
9349 * Inserts an html fragment into this element
9350 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9351 * @param {String} html The HTML fragment
9352 * @param {Boolean} returnEl True to return an Roo.Element
9353 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9355 insertHtml : function(where, html, returnEl){
9356 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9357 return returnEl ? Roo.get(el) : el;
9361 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9362 * @param {Object} o The object with the attributes
9363 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9364 * @return {Roo.Element} this
9366 set : function(o, useSet){
9368 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9370 if(attr == "style" || typeof o[attr] == "function") continue;
9372 el.className = o["cls"];
9374 if(useSet) el.setAttribute(attr, o[attr]);
9375 else el[attr] = o[attr];
9379 Roo.DomHelper.applyStyles(el, o.style);
9385 * Convenience method for constructing a KeyMap
9386 * @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:
9387 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9388 * @param {Function} fn The function to call
9389 * @param {Object} scope (optional) The scope of the function
9390 * @return {Roo.KeyMap} The KeyMap created
9392 addKeyListener : function(key, fn, scope){
9394 if(typeof key != "object" || key instanceof Array){
9410 return new Roo.KeyMap(this, config);
9414 * Creates a KeyMap for this element
9415 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9416 * @return {Roo.KeyMap} The KeyMap created
9418 addKeyMap : function(config){
9419 return new Roo.KeyMap(this, config);
9423 * Returns true if this element is scrollable.
9426 isScrollable : function(){
9428 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9432 * 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().
9433 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9434 * @param {Number} value The new scroll value
9435 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9436 * @return {Element} this
9439 scrollTo : function(side, value, animate){
9440 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9442 this.dom[prop] = value;
9444 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9445 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9451 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9452 * within this element's scrollable range.
9453 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9454 * @param {Number} distance How far to scroll the element in pixels
9455 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9456 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9457 * was scrolled as far as it could go.
9459 scroll : function(direction, distance, animate){
9460 if(!this.isScrollable()){
9464 var l = el.scrollLeft, t = el.scrollTop;
9465 var w = el.scrollWidth, h = el.scrollHeight;
9466 var cw = el.clientWidth, ch = el.clientHeight;
9467 direction = direction.toLowerCase();
9468 var scrolled = false;
9469 var a = this.preanim(arguments, 2);
9474 var v = Math.min(l + distance, w-cw);
9475 this.scrollTo("left", v, a);
9482 var v = Math.max(l - distance, 0);
9483 this.scrollTo("left", v, a);
9491 var v = Math.max(t - distance, 0);
9492 this.scrollTo("top", v, a);
9500 var v = Math.min(t + distance, h-ch);
9501 this.scrollTo("top", v, a);
9510 * Translates the passed page coordinates into left/top css values for this element
9511 * @param {Number/Array} x The page x or an array containing [x, y]
9512 * @param {Number} y The page y
9513 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9515 translatePoints : function(x, y){
9516 if(typeof x == 'object' || x instanceof Array){
9519 var p = this.getStyle('position');
9520 var o = this.getXY();
9522 var l = parseInt(this.getStyle('left'), 10);
9523 var t = parseInt(this.getStyle('top'), 10);
9526 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9529 t = (p == "relative") ? 0 : this.dom.offsetTop;
9532 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9536 * Returns the current scroll position of the element.
9537 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9539 getScroll : function(){
9540 var d = this.dom, doc = document;
9541 if(d == doc || d == doc.body){
9542 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9543 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9544 return {left: l, top: t};
9546 return {left: d.scrollLeft, top: d.scrollTop};
9551 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9552 * are convert to standard 6 digit hex color.
9553 * @param {String} attr The css attribute
9554 * @param {String} defaultValue The default value to use when a valid color isn't found
9555 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9558 getColor : function(attr, defaultValue, prefix){
9559 var v = this.getStyle(attr);
9560 if(!v || v == "transparent" || v == "inherit") {
9561 return defaultValue;
9563 var color = typeof prefix == "undefined" ? "#" : prefix;
9564 if(v.substr(0, 4) == "rgb("){
9565 var rvs = v.slice(4, v.length -1).split(",");
9566 for(var i = 0; i < 3; i++){
9567 var h = parseInt(rvs[i]).toString(16);
9574 if(v.substr(0, 1) == "#"){
9576 for(var i = 1; i < 4; i++){
9577 var c = v.charAt(i);
9580 }else if(v.length == 7){
9581 color += v.substr(1);
9585 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9589 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9590 * gradient background, rounded corners and a 4-way shadow.
9591 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9592 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9593 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9594 * @return {Roo.Element} this
9596 boxWrap : function(cls){
9597 cls = cls || 'x-box';
9598 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9599 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9604 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9605 * @param {String} namespace The namespace in which to look for the attribute
9606 * @param {String} name The attribute name
9607 * @return {String} The attribute value
9609 getAttributeNS : Roo.isIE ? function(ns, name){
9611 var type = typeof d[ns+":"+name];
9612 if(type != 'undefined' && type != 'unknown'){
9613 return d[ns+":"+name];
9616 } : function(ns, name){
9618 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9623 * Sets or Returns the value the dom attribute value
9624 * @param {String|Object} name The attribute name (or object to set multiple attributes)
9625 * @param {String} value (optional) The value to set the attribute to
9626 * @return {String} The attribute value
9628 attr : function(name){
9629 if (arguments.length > 1) {
9630 this.dom.setAttribute(name, arguments[1]);
9631 return arguments[1];
9633 if (typeof(name) == 'object') {
9634 for(var i in name) {
9635 this.attr(i, name[i]);
9641 if (!this.dom.hasAttribute(name)) {
9644 return this.dom.getAttribute(name);
9651 var ep = El.prototype;
9654 * Appends an event handler (Shorthand for addListener)
9655 * @param {String} eventName The type of event to append
9656 * @param {Function} fn The method the event invokes
9657 * @param {Object} scope (optional) The scope (this object) of the fn
9658 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9661 ep.on = ep.addListener;
9663 ep.mon = ep.addListener;
9666 * Removes an event handler from this element (shorthand for removeListener)
9667 * @param {String} eventName the type of event to remove
9668 * @param {Function} fn the method the event invokes
9669 * @return {Roo.Element} this
9672 ep.un = ep.removeListener;
9675 * true to automatically adjust width and height settings for box-model issues (default to true)
9677 ep.autoBoxAdjust = true;
9680 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9683 El.addUnits = function(v, defaultUnit){
9684 if(v === "" || v == "auto"){
9687 if(v === undefined){
9690 if(typeof v == "number" || !El.unitPattern.test(v)){
9691 return v + (defaultUnit || 'px');
9696 // special markup used throughout Roo when box wrapping elements
9697 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>';
9699 * Visibility mode constant - Use visibility to hide element
9705 * Visibility mode constant - Use display to hide element
9711 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9712 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9713 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9725 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9726 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9727 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9728 * @return {Element} The Element object
9731 El.get = function(el){
9733 if(!el){ return null; }
9734 if(typeof el == "string"){ // element id
9735 if(!(elm = document.getElementById(el))){
9738 if(ex = El.cache[el]){
9741 ex = El.cache[el] = new El(elm);
9744 }else if(el.tagName){ // dom element
9748 if(ex = El.cache[id]){
9751 ex = El.cache[id] = new El(el);
9754 }else if(el instanceof El){
9756 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9757 // catch case where it hasn't been appended
9758 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9761 }else if(el.isComposite){
9763 }else if(el instanceof Array){
9764 return El.select(el);
9765 }else if(el == document){
9766 // create a bogus element object representing the document object
9768 var f = function(){};
9769 f.prototype = El.prototype;
9771 docEl.dom = document;
9779 El.uncache = function(el){
9780 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9782 delete El.cache[a[i].id || a[i]];
9788 // Garbage collection - uncache elements/purge listeners on orphaned elements
9789 // so we don't hold a reference and cause the browser to retain them
9790 El.garbageCollect = function(){
9791 if(!Roo.enableGarbageCollector){
9792 clearInterval(El.collectorThread);
9795 for(var eid in El.cache){
9796 var el = El.cache[eid], d = el.dom;
9797 // -------------------------------------------------------
9798 // Determining what is garbage:
9799 // -------------------------------------------------------
9801 // dom node is null, definitely garbage
9802 // -------------------------------------------------------
9804 // no parentNode == direct orphan, definitely garbage
9805 // -------------------------------------------------------
9806 // !d.offsetParent && !document.getElementById(eid)
9807 // display none elements have no offsetParent so we will
9808 // also try to look it up by it's id. However, check
9809 // offsetParent first so we don't do unneeded lookups.
9810 // This enables collection of elements that are not orphans
9811 // directly, but somewhere up the line they have an orphan
9813 // -------------------------------------------------------
9814 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9815 delete El.cache[eid];
9816 if(d && Roo.enableListenerCollection){
9822 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9826 El.Flyweight = function(dom){
9829 El.Flyweight.prototype = El.prototype;
9831 El._flyweights = {};
9833 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9834 * the dom node can be overwritten by other code.
9835 * @param {String/HTMLElement} el The dom node or id
9836 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9837 * prevent conflicts (e.g. internally Roo uses "_internal")
9839 * @return {Element} The shared Element object
9841 El.fly = function(el, named){
9842 named = named || '_global';
9843 el = Roo.getDom(el);
9847 if(!El._flyweights[named]){
9848 El._flyweights[named] = new El.Flyweight();
9850 El._flyweights[named].dom = el;
9851 return El._flyweights[named];
9855 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9856 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9857 * Shorthand of {@link Roo.Element#get}
9858 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9859 * @return {Element} The Element object
9865 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9866 * the dom node can be overwritten by other code.
9867 * Shorthand of {@link Roo.Element#fly}
9868 * @param {String/HTMLElement} el The dom node or id
9869 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9870 * prevent conflicts (e.g. internally Roo uses "_internal")
9872 * @return {Element} The shared Element object
9878 // speedy lookup for elements never to box adjust
9879 var noBoxAdjust = Roo.isStrict ? {
9882 input:1, select:1, textarea:1
9884 if(Roo.isIE || Roo.isGecko){
9885 noBoxAdjust['button'] = 1;
9889 Roo.EventManager.on(window, 'unload', function(){
9891 delete El._flyweights;
9899 Roo.Element.selectorFunction = Roo.DomQuery.select;
9902 Roo.Element.select = function(selector, unique, root){
9904 if(typeof selector == "string"){
9905 els = Roo.Element.selectorFunction(selector, root);
9906 }else if(selector.length !== undefined){
9909 throw "Invalid selector";
9911 if(unique === true){
9912 return new Roo.CompositeElement(els);
9914 return new Roo.CompositeElementLite(els);
9918 * Selects elements based on the passed CSS selector to enable working on them as 1.
9919 * @param {String/Array} selector The CSS selector or an array of elements
9920 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9921 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9922 * @return {CompositeElementLite/CompositeElement}
9926 Roo.select = Roo.Element.select;
9943 * Ext JS Library 1.1.1
9944 * Copyright(c) 2006-2007, Ext JS, LLC.
9946 * Originally Released Under LGPL - original licence link has changed is not relivant.
9949 * <script type="text/javascript">
9954 //Notifies Element that fx methods are available
9955 Roo.enableFx = true;
9959 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9960 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9961 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9962 * Element effects to work.</p><br/>
9964 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9965 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9966 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9967 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
9968 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9969 * expected results and should be done with care.</p><br/>
9971 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9972 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
9975 ----- -----------------------------
9976 tl The top left corner
9977 t The center of the top edge
9978 tr The top right corner
9979 l The center of the left edge
9980 r The center of the right edge
9981 bl The bottom left corner
9982 b The center of the bottom edge
9983 br The bottom right corner
9985 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9986 * below are common options that can be passed to any Fx method.</b>
9987 * @cfg {Function} callback A function called when the effect is finished
9988 * @cfg {Object} scope The scope of the effect function
9989 * @cfg {String} easing A valid Easing value for the effect
9990 * @cfg {String} afterCls A css class to apply after the effect
9991 * @cfg {Number} duration The length of time (in seconds) that the effect should last
9992 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
9993 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
9994 * effects that end with the element being visually hidden, ignored otherwise)
9995 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
9996 * a function which returns such a specification that will be applied to the Element after the effect finishes
9997 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
9998 * @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
9999 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
10003 * Slides the element into view. An anchor point can be optionally passed to set the point of
10004 * origin for the slide effect. This function automatically handles wrapping the element with
10005 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10008 // default: slide the element in from the top
10011 // custom: slide the element in from the right with a 2-second duration
10012 el.slideIn('r', { duration: 2 });
10014 // common config options shown with default values
10020 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10021 * @param {Object} options (optional) Object literal with any of the Fx config options
10022 * @return {Roo.Element} The Element
10024 slideIn : function(anchor, o){
10025 var el = this.getFxEl();
10028 el.queueFx(o, function(){
10030 anchor = anchor || "t";
10032 // fix display to visibility
10035 // restore values after effect
10036 var r = this.getFxRestore();
10037 var b = this.getBox();
10038 // fixed size for slide
10042 var wrap = this.fxWrap(r.pos, o, "hidden");
10044 var st = this.dom.style;
10045 st.visibility = "visible";
10046 st.position = "absolute";
10048 // clear out temp styles after slide and unwrap
10049 var after = function(){
10050 el.fxUnwrap(wrap, r.pos, o);
10051 st.width = r.width;
10052 st.height = r.height;
10055 // time to calc the positions
10056 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
10058 switch(anchor.toLowerCase()){
10060 wrap.setSize(b.width, 0);
10061 st.left = st.bottom = "0";
10065 wrap.setSize(0, b.height);
10066 st.right = st.top = "0";
10070 wrap.setSize(0, b.height);
10071 wrap.setX(b.right);
10072 st.left = st.top = "0";
10073 a = {width: bw, points: pt};
10076 wrap.setSize(b.width, 0);
10077 wrap.setY(b.bottom);
10078 st.left = st.top = "0";
10079 a = {height: bh, points: pt};
10082 wrap.setSize(0, 0);
10083 st.right = st.bottom = "0";
10084 a = {width: bw, height: bh};
10087 wrap.setSize(0, 0);
10088 wrap.setY(b.y+b.height);
10089 st.right = st.top = "0";
10090 a = {width: bw, height: bh, points: pt};
10093 wrap.setSize(0, 0);
10094 wrap.setXY([b.right, b.bottom]);
10095 st.left = st.top = "0";
10096 a = {width: bw, height: bh, points: pt};
10099 wrap.setSize(0, 0);
10100 wrap.setX(b.x+b.width);
10101 st.left = st.bottom = "0";
10102 a = {width: bw, height: bh, points: pt};
10105 this.dom.style.visibility = "visible";
10108 arguments.callee.anim = wrap.fxanim(a,
10118 * Slides the element out of view. An anchor point can be optionally passed to set the end point
10119 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
10120 * 'hidden') but block elements will still take up space in the document. The element must be removed
10121 * from the DOM using the 'remove' config option if desired. This function automatically handles
10122 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10125 // default: slide the element out to the top
10128 // custom: slide the element out to the right with a 2-second duration
10129 el.slideOut('r', { duration: 2 });
10131 // common config options shown with default values
10139 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10140 * @param {Object} options (optional) Object literal with any of the Fx config options
10141 * @return {Roo.Element} The Element
10143 slideOut : function(anchor, o){
10144 var el = this.getFxEl();
10147 el.queueFx(o, function(){
10149 anchor = anchor || "t";
10151 // restore values after effect
10152 var r = this.getFxRestore();
10154 var b = this.getBox();
10155 // fixed size for slide
10159 var wrap = this.fxWrap(r.pos, o, "visible");
10161 var st = this.dom.style;
10162 st.visibility = "visible";
10163 st.position = "absolute";
10167 var after = function(){
10169 el.setDisplayed(false);
10174 el.fxUnwrap(wrap, r.pos, o);
10176 st.width = r.width;
10177 st.height = r.height;
10182 var a, zero = {to: 0};
10183 switch(anchor.toLowerCase()){
10185 st.left = st.bottom = "0";
10186 a = {height: zero};
10189 st.right = st.top = "0";
10193 st.left = st.top = "0";
10194 a = {width: zero, points: {to:[b.right, b.y]}};
10197 st.left = st.top = "0";
10198 a = {height: zero, points: {to:[b.x, b.bottom]}};
10201 st.right = st.bottom = "0";
10202 a = {width: zero, height: zero};
10205 st.right = st.top = "0";
10206 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10209 st.left = st.top = "0";
10210 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10213 st.left = st.bottom = "0";
10214 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10218 arguments.callee.anim = wrap.fxanim(a,
10228 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
10229 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
10230 * The element must be removed from the DOM using the 'remove' config option if desired.
10236 // common config options shown with default values
10244 * @param {Object} options (optional) Object literal with any of the Fx config options
10245 * @return {Roo.Element} The Element
10247 puff : function(o){
10248 var el = this.getFxEl();
10251 el.queueFx(o, function(){
10252 this.clearOpacity();
10255 // restore values after effect
10256 var r = this.getFxRestore();
10257 var st = this.dom.style;
10259 var after = function(){
10261 el.setDisplayed(false);
10268 el.setPositioning(r.pos);
10269 st.width = r.width;
10270 st.height = r.height;
10275 var width = this.getWidth();
10276 var height = this.getHeight();
10278 arguments.callee.anim = this.fxanim({
10279 width : {to: this.adjustWidth(width * 2)},
10280 height : {to: this.adjustHeight(height * 2)},
10281 points : {by: [-(width * .5), -(height * .5)]},
10283 fontSize: {to:200, unit: "%"}
10294 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10295 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10296 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10302 // all config options shown with default values
10310 * @param {Object} options (optional) Object literal with any of the Fx config options
10311 * @return {Roo.Element} The Element
10313 switchOff : function(o){
10314 var el = this.getFxEl();
10317 el.queueFx(o, function(){
10318 this.clearOpacity();
10321 // restore values after effect
10322 var r = this.getFxRestore();
10323 var st = this.dom.style;
10325 var after = function(){
10327 el.setDisplayed(false);
10333 el.setPositioning(r.pos);
10334 st.width = r.width;
10335 st.height = r.height;
10340 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10341 this.clearOpacity();
10345 points:{by:[0, this.getHeight() * .5]}
10346 }, o, 'motion', 0.3, 'easeIn', after);
10347 }).defer(100, this);
10354 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10355 * changed using the "attr" config option) and then fading back to the original color. If no original
10356 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10359 // default: highlight background to yellow
10362 // custom: highlight foreground text to blue for 2 seconds
10363 el.highlight("0000ff", { attr: 'color', duration: 2 });
10365 // common config options shown with default values
10366 el.highlight("ffff9c", {
10367 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10368 endColor: (current color) or "ffffff",
10373 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10374 * @param {Object} options (optional) Object literal with any of the Fx config options
10375 * @return {Roo.Element} The Element
10377 highlight : function(color, o){
10378 var el = this.getFxEl();
10381 el.queueFx(o, function(){
10382 color = color || "ffff9c";
10383 attr = o.attr || "backgroundColor";
10385 this.clearOpacity();
10388 var origColor = this.getColor(attr);
10389 var restoreColor = this.dom.style[attr];
10390 endColor = (o.endColor || origColor) || "ffffff";
10392 var after = function(){
10393 el.dom.style[attr] = restoreColor;
10398 a[attr] = {from: color, to: endColor};
10399 arguments.callee.anim = this.fxanim(a,
10409 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10412 // default: a single light blue ripple
10415 // custom: 3 red ripples lasting 3 seconds total
10416 el.frame("ff0000", 3, { duration: 3 });
10418 // common config options shown with default values
10419 el.frame("C3DAF9", 1, {
10420 duration: 1 //duration of entire animation (not each individual ripple)
10421 // Note: Easing is not configurable and will be ignored if included
10424 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10425 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10426 * @param {Object} options (optional) Object literal with any of the Fx config options
10427 * @return {Roo.Element} The Element
10429 frame : function(color, count, o){
10430 var el = this.getFxEl();
10433 el.queueFx(o, function(){
10434 color = color || "#C3DAF9";
10435 if(color.length == 6){
10436 color = "#" + color;
10438 count = count || 1;
10439 duration = o.duration || 1;
10442 var b = this.getBox();
10443 var animFn = function(){
10444 var proxy = this.createProxy({
10447 visbility:"hidden",
10448 position:"absolute",
10449 "z-index":"35000", // yee haw
10450 border:"0px solid " + color
10453 var scale = Roo.isBorderBox ? 2 : 1;
10455 top:{from:b.y, to:b.y - 20},
10456 left:{from:b.x, to:b.x - 20},
10457 borderWidth:{from:0, to:10},
10458 opacity:{from:1, to:0},
10459 height:{from:b.height, to:(b.height + (20*scale))},
10460 width:{from:b.width, to:(b.width + (20*scale))}
10461 }, duration, function(){
10465 animFn.defer((duration/2)*1000, this);
10476 * Creates a pause before any subsequent queued effects begin. If there are
10477 * no effects queued after the pause it will have no effect.
10482 * @param {Number} seconds The length of time to pause (in seconds)
10483 * @return {Roo.Element} The Element
10485 pause : function(seconds){
10486 var el = this.getFxEl();
10489 el.queueFx(o, function(){
10490 setTimeout(function(){
10492 }, seconds * 1000);
10498 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10499 * using the "endOpacity" config option.
10502 // default: fade in from opacity 0 to 100%
10505 // custom: fade in from opacity 0 to 75% over 2 seconds
10506 el.fadeIn({ endOpacity: .75, duration: 2});
10508 // common config options shown with default values
10510 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10515 * @param {Object} options (optional) Object literal with any of the Fx config options
10516 * @return {Roo.Element} The Element
10518 fadeIn : function(o){
10519 var el = this.getFxEl();
10521 el.queueFx(o, function(){
10522 this.setOpacity(0);
10524 this.dom.style.visibility = 'visible';
10525 var to = o.endOpacity || 1;
10526 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10527 o, null, .5, "easeOut", function(){
10529 this.clearOpacity();
10538 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10539 * using the "endOpacity" config option.
10542 // default: fade out from the element's current opacity to 0
10545 // custom: fade out from the element's current opacity to 25% over 2 seconds
10546 el.fadeOut({ endOpacity: .25, duration: 2});
10548 // common config options shown with default values
10550 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10557 * @param {Object} options (optional) Object literal with any of the Fx config options
10558 * @return {Roo.Element} The Element
10560 fadeOut : function(o){
10561 var el = this.getFxEl();
10563 el.queueFx(o, function(){
10564 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10565 o, null, .5, "easeOut", function(){
10566 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10567 this.dom.style.display = "none";
10569 this.dom.style.visibility = "hidden";
10571 this.clearOpacity();
10579 * Animates the transition of an element's dimensions from a starting height/width
10580 * to an ending height/width.
10583 // change height and width to 100x100 pixels
10584 el.scale(100, 100);
10586 // common config options shown with default values. The height and width will default to
10587 // the element's existing values if passed as null.
10590 [element's height], {
10595 * @param {Number} width The new width (pass undefined to keep the original width)
10596 * @param {Number} height The new height (pass undefined to keep the original height)
10597 * @param {Object} options (optional) Object literal with any of the Fx config options
10598 * @return {Roo.Element} The Element
10600 scale : function(w, h, o){
10601 this.shift(Roo.apply({}, o, {
10609 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10610 * Any of these properties not specified in the config object will not be changed. This effect
10611 * requires that at least one new dimension, position or opacity setting must be passed in on
10612 * the config object in order for the function to have any effect.
10615 // slide the element horizontally to x position 200 while changing the height and opacity
10616 el.shift({ x: 200, height: 50, opacity: .8 });
10618 // common config options shown with default values.
10620 width: [element's width],
10621 height: [element's height],
10622 x: [element's x position],
10623 y: [element's y position],
10624 opacity: [element's opacity],
10629 * @param {Object} options Object literal with any of the Fx config options
10630 * @return {Roo.Element} The Element
10632 shift : function(o){
10633 var el = this.getFxEl();
10635 el.queueFx(o, function(){
10636 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10637 if(w !== undefined){
10638 a.width = {to: this.adjustWidth(w)};
10640 if(h !== undefined){
10641 a.height = {to: this.adjustHeight(h)};
10643 if(x !== undefined || y !== undefined){
10645 x !== undefined ? x : this.getX(),
10646 y !== undefined ? y : this.getY()
10649 if(op !== undefined){
10650 a.opacity = {to: op};
10652 if(o.xy !== undefined){
10653 a.points = {to: o.xy};
10655 arguments.callee.anim = this.fxanim(a,
10656 o, 'motion', .35, "easeOut", function(){
10664 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10665 * ending point of the effect.
10668 // default: slide the element downward while fading out
10671 // custom: slide the element out to the right with a 2-second duration
10672 el.ghost('r', { duration: 2 });
10674 // common config options shown with default values
10682 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10683 * @param {Object} options (optional) Object literal with any of the Fx config options
10684 * @return {Roo.Element} The Element
10686 ghost : function(anchor, o){
10687 var el = this.getFxEl();
10690 el.queueFx(o, function(){
10691 anchor = anchor || "b";
10693 // restore values after effect
10694 var r = this.getFxRestore();
10695 var w = this.getWidth(),
10696 h = this.getHeight();
10698 var st = this.dom.style;
10700 var after = function(){
10702 el.setDisplayed(false);
10708 el.setPositioning(r.pos);
10709 st.width = r.width;
10710 st.height = r.height;
10715 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10716 switch(anchor.toLowerCase()){
10743 arguments.callee.anim = this.fxanim(a,
10753 * Ensures that all effects queued after syncFx is called on the element are
10754 * run concurrently. This is the opposite of {@link #sequenceFx}.
10755 * @return {Roo.Element} The Element
10757 syncFx : function(){
10758 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10767 * Ensures that all effects queued after sequenceFx is called on the element are
10768 * run in sequence. This is the opposite of {@link #syncFx}.
10769 * @return {Roo.Element} The Element
10771 sequenceFx : function(){
10772 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10774 concurrent : false,
10781 nextFx : function(){
10782 var ef = this.fxQueue[0];
10789 * Returns true if the element has any effects actively running or queued, else returns false.
10790 * @return {Boolean} True if element has active effects, else false
10792 hasActiveFx : function(){
10793 return this.fxQueue && this.fxQueue[0];
10797 * Stops any running effects and clears the element's internal effects queue if it contains
10798 * any additional effects that haven't started yet.
10799 * @return {Roo.Element} The Element
10801 stopFx : function(){
10802 if(this.hasActiveFx()){
10803 var cur = this.fxQueue[0];
10804 if(cur && cur.anim && cur.anim.isAnimated()){
10805 this.fxQueue = [cur]; // clear out others
10806 cur.anim.stop(true);
10813 beforeFx : function(o){
10814 if(this.hasActiveFx() && !o.concurrent){
10825 * Returns true if the element is currently blocking so that no other effect can be queued
10826 * until this effect is finished, else returns false if blocking is not set. This is commonly
10827 * used to ensure that an effect initiated by a user action runs to completion prior to the
10828 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10829 * @return {Boolean} True if blocking, else false
10831 hasFxBlock : function(){
10832 var q = this.fxQueue;
10833 return q && q[0] && q[0].block;
10837 queueFx : function(o, fn){
10841 if(!this.hasFxBlock()){
10842 Roo.applyIf(o, this.fxDefaults);
10844 var run = this.beforeFx(o);
10845 fn.block = o.block;
10846 this.fxQueue.push(fn);
10858 fxWrap : function(pos, o, vis){
10860 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10863 wrapXY = this.getXY();
10865 var div = document.createElement("div");
10866 div.style.visibility = vis;
10867 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10868 wrap.setPositioning(pos);
10869 if(wrap.getStyle("position") == "static"){
10870 wrap.position("relative");
10872 this.clearPositioning('auto');
10874 wrap.dom.appendChild(this.dom);
10876 wrap.setXY(wrapXY);
10883 fxUnwrap : function(wrap, pos, o){
10884 this.clearPositioning();
10885 this.setPositioning(pos);
10887 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10893 getFxRestore : function(){
10894 var st = this.dom.style;
10895 return {pos: this.getPositioning(), width: st.width, height : st.height};
10899 afterFx : function(o){
10901 this.applyStyles(o.afterStyle);
10904 this.addClass(o.afterCls);
10906 if(o.remove === true){
10909 Roo.callback(o.callback, o.scope, [this]);
10911 this.fxQueue.shift();
10917 getFxEl : function(){ // support for composite element fx
10918 return Roo.get(this.dom);
10922 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10923 animType = animType || 'run';
10925 var anim = Roo.lib.Anim[animType](
10927 (opt.duration || defaultDur) || .35,
10928 (opt.easing || defaultEase) || 'easeOut',
10930 Roo.callback(cb, this);
10939 // backwords compat
10940 Roo.Fx.resize = Roo.Fx.scale;
10942 //When included, Roo.Fx is automatically applied to Element so that all basic
10943 //effects are available directly via the Element API
10944 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10946 * Ext JS Library 1.1.1
10947 * Copyright(c) 2006-2007, Ext JS, LLC.
10949 * Originally Released Under LGPL - original licence link has changed is not relivant.
10952 * <script type="text/javascript">
10957 * @class Roo.CompositeElement
10958 * Standard composite class. Creates a Roo.Element for every element in the collection.
10960 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10961 * actions will be performed on all the elements in this collection.</b>
10963 * All methods return <i>this</i> and can be chained.
10965 var els = Roo.select("#some-el div.some-class", true);
10966 // or select directly from an existing element
10967 var el = Roo.get('some-el');
10968 el.select('div.some-class', true);
10970 els.setWidth(100); // all elements become 100 width
10971 els.hide(true); // all elements fade out and hide
10973 els.setWidth(100).hide(true);
10976 Roo.CompositeElement = function(els){
10977 this.elements = [];
10978 this.addElements(els);
10980 Roo.CompositeElement.prototype = {
10982 addElements : function(els){
10983 if(!els) return this;
10984 if(typeof els == "string"){
10985 els = Roo.Element.selectorFunction(els);
10987 var yels = this.elements;
10988 var index = yels.length-1;
10989 for(var i = 0, len = els.length; i < len; i++) {
10990 yels[++index] = Roo.get(els[i]);
10996 * Clears this composite and adds the elements returned by the passed selector.
10997 * @param {String/Array} els A string CSS selector, an array of elements or an element
10998 * @return {CompositeElement} this
11000 fill : function(els){
11001 this.elements = [];
11007 * Filters this composite to only elements that match the passed selector.
11008 * @param {String} selector A string CSS selector
11009 * @param {Boolean} inverse return inverse filter (not matches)
11010 * @return {CompositeElement} this
11012 filter : function(selector, inverse){
11014 inverse = inverse || false;
11015 this.each(function(el){
11016 var match = inverse ? !el.is(selector) : el.is(selector);
11018 els[els.length] = el.dom;
11025 invoke : function(fn, args){
11026 var els = this.elements;
11027 for(var i = 0, len = els.length; i < len; i++) {
11028 Roo.Element.prototype[fn].apply(els[i], args);
11033 * Adds elements to this composite.
11034 * @param {String/Array} els A string CSS selector, an array of elements or an element
11035 * @return {CompositeElement} this
11037 add : function(els){
11038 if(typeof els == "string"){
11039 this.addElements(Roo.Element.selectorFunction(els));
11040 }else if(els.length !== undefined){
11041 this.addElements(els);
11043 this.addElements([els]);
11048 * Calls the passed function passing (el, this, index) for each element in this composite.
11049 * @param {Function} fn The function to call
11050 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11051 * @return {CompositeElement} this
11053 each : function(fn, scope){
11054 var els = this.elements;
11055 for(var i = 0, len = els.length; i < len; i++){
11056 if(fn.call(scope || els[i], els[i], this, i) === false) {
11064 * Returns the Element object at the specified index
11065 * @param {Number} index
11066 * @return {Roo.Element}
11068 item : function(index){
11069 return this.elements[index] || null;
11073 * Returns the first Element
11074 * @return {Roo.Element}
11076 first : function(){
11077 return this.item(0);
11081 * Returns the last Element
11082 * @return {Roo.Element}
11085 return this.item(this.elements.length-1);
11089 * Returns the number of elements in this composite
11092 getCount : function(){
11093 return this.elements.length;
11097 * Returns true if this composite contains the passed element
11100 contains : function(el){
11101 return this.indexOf(el) !== -1;
11105 * Returns true if this composite contains the passed element
11108 indexOf : function(el){
11109 return this.elements.indexOf(Roo.get(el));
11114 * Removes the specified element(s).
11115 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
11116 * or an array of any of those.
11117 * @param {Boolean} removeDom (optional) True to also remove the element from the document
11118 * @return {CompositeElement} this
11120 removeElement : function(el, removeDom){
11121 if(el instanceof Array){
11122 for(var i = 0, len = el.length; i < len; i++){
11123 this.removeElement(el[i]);
11127 var index = typeof el == 'number' ? el : this.indexOf(el);
11130 var d = this.elements[index];
11134 d.parentNode.removeChild(d);
11137 this.elements.splice(index, 1);
11143 * Replaces the specified element with the passed element.
11144 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
11146 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
11147 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
11148 * @return {CompositeElement} this
11150 replaceElement : function(el, replacement, domReplace){
11151 var index = typeof el == 'number' ? el : this.indexOf(el);
11154 this.elements[index].replaceWith(replacement);
11156 this.elements.splice(index, 1, Roo.get(replacement))
11163 * Removes all elements.
11165 clear : function(){
11166 this.elements = [];
11170 Roo.CompositeElement.createCall = function(proto, fnName){
11171 if(!proto[fnName]){
11172 proto[fnName] = function(){
11173 return this.invoke(fnName, arguments);
11177 for(var fnName in Roo.Element.prototype){
11178 if(typeof Roo.Element.prototype[fnName] == "function"){
11179 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11185 * Ext JS Library 1.1.1
11186 * Copyright(c) 2006-2007, Ext JS, LLC.
11188 * Originally Released Under LGPL - original licence link has changed is not relivant.
11191 * <script type="text/javascript">
11195 * @class Roo.CompositeElementLite
11196 * @extends Roo.CompositeElement
11197 * Flyweight composite class. Reuses the same Roo.Element for element operations.
11199 var els = Roo.select("#some-el div.some-class");
11200 // or select directly from an existing element
11201 var el = Roo.get('some-el');
11202 el.select('div.some-class');
11204 els.setWidth(100); // all elements become 100 width
11205 els.hide(true); // all elements fade out and hide
11207 els.setWidth(100).hide(true);
11208 </code></pre><br><br>
11209 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11210 * actions will be performed on all the elements in this collection.</b>
11212 Roo.CompositeElementLite = function(els){
11213 Roo.CompositeElementLite.superclass.constructor.call(this, els);
11214 this.el = new Roo.Element.Flyweight();
11216 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11217 addElements : function(els){
11219 if(els instanceof Array){
11220 this.elements = this.elements.concat(els);
11222 var yels = this.elements;
11223 var index = yels.length-1;
11224 for(var i = 0, len = els.length; i < len; i++) {
11225 yels[++index] = els[i];
11231 invoke : function(fn, args){
11232 var els = this.elements;
11234 for(var i = 0, len = els.length; i < len; i++) {
11236 Roo.Element.prototype[fn].apply(el, args);
11241 * Returns a flyweight Element of the dom element object at the specified index
11242 * @param {Number} index
11243 * @return {Roo.Element}
11245 item : function(index){
11246 if(!this.elements[index]){
11249 this.el.dom = this.elements[index];
11253 // fixes scope with flyweight
11254 addListener : function(eventName, handler, scope, opt){
11255 var els = this.elements;
11256 for(var i = 0, len = els.length; i < len; i++) {
11257 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11263 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11264 * passed is the flyweight (shared) Roo.Element instance, so if you require a
11265 * a reference to the dom node, use el.dom.</b>
11266 * @param {Function} fn The function to call
11267 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11268 * @return {CompositeElement} this
11270 each : function(fn, scope){
11271 var els = this.elements;
11273 for(var i = 0, len = els.length; i < len; i++){
11275 if(fn.call(scope || el, el, this, i) === false){
11282 indexOf : function(el){
11283 return this.elements.indexOf(Roo.getDom(el));
11286 replaceElement : function(el, replacement, domReplace){
11287 var index = typeof el == 'number' ? el : this.indexOf(el);
11289 replacement = Roo.getDom(replacement);
11291 var d = this.elements[index];
11292 d.parentNode.insertBefore(replacement, d);
11293 d.parentNode.removeChild(d);
11295 this.elements.splice(index, 1, replacement);
11300 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11304 * Ext JS Library 1.1.1
11305 * Copyright(c) 2006-2007, Ext JS, LLC.
11307 * Originally Released Under LGPL - original licence link has changed is not relivant.
11310 * <script type="text/javascript">
11316 * @class Roo.data.Connection
11317 * @extends Roo.util.Observable
11318 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11319 * either to a configured URL, or to a URL specified at request time.<br><br>
11321 * Requests made by this class are asynchronous, and will return immediately. No data from
11322 * the server will be available to the statement immediately following the {@link #request} call.
11323 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11325 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11326 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11327 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11328 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11329 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11330 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11331 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11332 * standard DOM methods.
11334 * @param {Object} config a configuration object.
11336 Roo.data.Connection = function(config){
11337 Roo.apply(this, config);
11340 * @event beforerequest
11341 * Fires before a network request is made to retrieve a data object.
11342 * @param {Connection} conn This Connection object.
11343 * @param {Object} options The options config object passed to the {@link #request} method.
11345 "beforerequest" : true,
11347 * @event requestcomplete
11348 * Fires if the request was successfully completed.
11349 * @param {Connection} conn This Connection object.
11350 * @param {Object} response The XHR object containing the response data.
11351 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11352 * @param {Object} options The options config object passed to the {@link #request} method.
11354 "requestcomplete" : true,
11356 * @event requestexception
11357 * Fires if an error HTTP status was returned from the server.
11358 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11359 * @param {Connection} conn This Connection object.
11360 * @param {Object} response The XHR object containing the response data.
11361 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11362 * @param {Object} options The options config object passed to the {@link #request} method.
11364 "requestexception" : true
11366 Roo.data.Connection.superclass.constructor.call(this);
11369 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11371 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11374 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11375 * extra parameters to each request made by this object. (defaults to undefined)
11378 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11379 * to each request made by this object. (defaults to undefined)
11382 * @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)
11385 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11389 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11395 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11398 disableCaching: true,
11401 * Sends an HTTP request to a remote server.
11402 * @param {Object} options An object which may contain the following properties:<ul>
11403 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11404 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11405 * request, a url encoded string or a function to call to get either.</li>
11406 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11407 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11408 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11409 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11410 * <li>options {Object} The parameter to the request call.</li>
11411 * <li>success {Boolean} True if the request succeeded.</li>
11412 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11414 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11415 * The callback is passed the following parameters:<ul>
11416 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11417 * <li>options {Object} The parameter to the request call.</li>
11419 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11420 * The callback is passed the following parameters:<ul>
11421 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11422 * <li>options {Object} The parameter to the request call.</li>
11424 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11425 * for the callback function. Defaults to the browser window.</li>
11426 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11427 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11428 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11429 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11430 * params for the post data. Any params will be appended to the URL.</li>
11431 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11433 * @return {Number} transactionId
11435 request : function(o){
11436 if(this.fireEvent("beforerequest", this, o) !== false){
11439 if(typeof p == "function"){
11440 p = p.call(o.scope||window, o);
11442 if(typeof p == "object"){
11443 p = Roo.urlEncode(o.params);
11445 if(this.extraParams){
11446 var extras = Roo.urlEncode(this.extraParams);
11447 p = p ? (p + '&' + extras) : extras;
11450 var url = o.url || this.url;
11451 if(typeof url == 'function'){
11452 url = url.call(o.scope||window, o);
11456 var form = Roo.getDom(o.form);
11457 url = url || form.action;
11459 var enctype = form.getAttribute("enctype");
11460 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11461 return this.doFormUpload(o, p, url);
11463 var f = Roo.lib.Ajax.serializeForm(form);
11464 p = p ? (p + '&' + f) : f;
11467 var hs = o.headers;
11468 if(this.defaultHeaders){
11469 hs = Roo.apply(hs || {}, this.defaultHeaders);
11476 success: this.handleResponse,
11477 failure: this.handleFailure,
11479 argument: {options: o},
11480 timeout : o.timeout || this.timeout
11483 var method = o.method||this.method||(p ? "POST" : "GET");
11485 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11486 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11489 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11493 }else if(this.autoAbort !== false){
11497 if((method == 'GET' && p) || o.xmlData){
11498 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11501 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11502 return this.transId;
11504 Roo.callback(o.callback, o.scope, [o, null, null]);
11510 * Determine whether this object has a request outstanding.
11511 * @param {Number} transactionId (Optional) defaults to the last transaction
11512 * @return {Boolean} True if there is an outstanding request.
11514 isLoading : function(transId){
11516 return Roo.lib.Ajax.isCallInProgress(transId);
11518 return this.transId ? true : false;
11523 * Aborts any outstanding request.
11524 * @param {Number} transactionId (Optional) defaults to the last transaction
11526 abort : function(transId){
11527 if(transId || this.isLoading()){
11528 Roo.lib.Ajax.abort(transId || this.transId);
11533 handleResponse : function(response){
11534 this.transId = false;
11535 var options = response.argument.options;
11536 response.argument = options ? options.argument : null;
11537 this.fireEvent("requestcomplete", this, response, options);
11538 Roo.callback(options.success, options.scope, [response, options]);
11539 Roo.callback(options.callback, options.scope, [options, true, response]);
11543 handleFailure : function(response, e){
11544 this.transId = false;
11545 var options = response.argument.options;
11546 response.argument = options ? options.argument : null;
11547 this.fireEvent("requestexception", this, response, options, e);
11548 Roo.callback(options.failure, options.scope, [response, options]);
11549 Roo.callback(options.callback, options.scope, [options, false, response]);
11553 doFormUpload : function(o, ps, url){
11555 var frame = document.createElement('iframe');
11558 frame.className = 'x-hidden';
11560 frame.src = Roo.SSL_SECURE_URL;
11562 document.body.appendChild(frame);
11565 document.frames[id].name = id;
11568 var form = Roo.getDom(o.form);
11570 form.method = 'POST';
11571 form.enctype = form.encoding = 'multipart/form-data';
11577 if(ps){ // add dynamic params
11579 ps = Roo.urlDecode(ps, false);
11581 if(ps.hasOwnProperty(k)){
11582 hd = document.createElement('input');
11583 hd.type = 'hidden';
11586 form.appendChild(hd);
11593 var r = { // bogus response object
11598 r.argument = o ? o.argument : null;
11603 doc = frame.contentWindow.document;
11605 doc = (frame.contentDocument || window.frames[id].document);
11607 if(doc && doc.body){
11608 r.responseText = doc.body.innerHTML;
11610 if(doc && doc.XMLDocument){
11611 r.responseXML = doc.XMLDocument;
11613 r.responseXML = doc;
11620 Roo.EventManager.removeListener(frame, 'load', cb, this);
11622 this.fireEvent("requestcomplete", this, r, o);
11623 Roo.callback(o.success, o.scope, [r, o]);
11624 Roo.callback(o.callback, o.scope, [o, true, r]);
11626 setTimeout(function(){document.body.removeChild(frame);}, 100);
11629 Roo.EventManager.on(frame, 'load', cb, this);
11632 if(hiddens){ // remove dynamic params
11633 for(var i = 0, len = hiddens.length; i < len; i++){
11634 form.removeChild(hiddens[i]);
11641 * Ext JS Library 1.1.1
11642 * Copyright(c) 2006-2007, Ext JS, LLC.
11644 * Originally Released Under LGPL - original licence link has changed is not relivant.
11647 * <script type="text/javascript">
11651 * Global Ajax request class.
11654 * @extends Roo.data.Connection
11657 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
11658 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
11659 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
11660 * @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)
11661 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11662 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
11663 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11665 Roo.Ajax = new Roo.data.Connection({
11674 * Serialize the passed form into a url encoded string
11676 * @param {String/HTMLElement} form
11679 serializeForm : function(form){
11680 return Roo.lib.Ajax.serializeForm(form);
11684 * Ext JS Library 1.1.1
11685 * Copyright(c) 2006-2007, Ext JS, LLC.
11687 * Originally Released Under LGPL - original licence link has changed is not relivant.
11690 * <script type="text/javascript">
11695 * @class Roo.UpdateManager
11696 * @extends Roo.util.Observable
11697 * Provides AJAX-style update for Element object.<br><br>
11700 * // Get it from a Roo.Element object
11701 * var el = Roo.get("foo");
11702 * var mgr = el.getUpdateManager();
11703 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11705 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11707 * // or directly (returns the same UpdateManager instance)
11708 * var mgr = new Roo.UpdateManager("myElementId");
11709 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11710 * mgr.on("update", myFcnNeedsToKnow);
11712 // short handed call directly from the element object
11713 Roo.get("foo").load({
11717 text: "Loading Foo..."
11721 * Create new UpdateManager directly.
11722 * @param {String/HTMLElement/Roo.Element} el The element to update
11723 * @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).
11725 Roo.UpdateManager = function(el, forceNew){
11727 if(!forceNew && el.updateManager){
11728 return el.updateManager;
11731 * The Element object
11732 * @type Roo.Element
11736 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11739 this.defaultUrl = null;
11743 * @event beforeupdate
11744 * Fired before an update is made, return false from your handler and the update is cancelled.
11745 * @param {Roo.Element} el
11746 * @param {String/Object/Function} url
11747 * @param {String/Object} params
11749 "beforeupdate": true,
11752 * Fired after successful update is made.
11753 * @param {Roo.Element} el
11754 * @param {Object} oResponseObject The response Object
11759 * Fired on update failure.
11760 * @param {Roo.Element} el
11761 * @param {Object} oResponseObject The response Object
11765 var d = Roo.UpdateManager.defaults;
11767 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11770 this.sslBlankUrl = d.sslBlankUrl;
11772 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11775 this.disableCaching = d.disableCaching;
11777 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11780 this.indicatorText = d.indicatorText;
11782 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11785 this.showLoadIndicator = d.showLoadIndicator;
11787 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11790 this.timeout = d.timeout;
11793 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11796 this.loadScripts = d.loadScripts;
11799 * Transaction object of current executing transaction
11801 this.transaction = null;
11806 this.autoRefreshProcId = null;
11808 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11811 this.refreshDelegate = this.refresh.createDelegate(this);
11813 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11816 this.updateDelegate = this.update.createDelegate(this);
11818 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11821 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11825 this.successDelegate = this.processSuccess.createDelegate(this);
11829 this.failureDelegate = this.processFailure.createDelegate(this);
11831 if(!this.renderer){
11833 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11835 this.renderer = new Roo.UpdateManager.BasicRenderer();
11838 Roo.UpdateManager.superclass.constructor.call(this);
11841 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11843 * Get the Element this UpdateManager is bound to
11844 * @return {Roo.Element} The element
11846 getEl : function(){
11850 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11851 * @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:
11854 url: "your-url.php",<br/>
11855 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11856 callback: yourFunction,<br/>
11857 scope: yourObject, //(optional scope) <br/>
11858 discardUrl: false, <br/>
11859 nocache: false,<br/>
11860 text: "Loading...",<br/>
11862 scripts: false<br/>
11865 * The only required property is url. The optional properties nocache, text and scripts
11866 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11867 * @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}
11868 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11869 * @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.
11871 update : function(url, params, callback, discardUrl){
11872 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11873 var method = this.method,
11875 if(typeof url == "object"){ // must be config object
11878 params = params || cfg.params;
11879 callback = callback || cfg.callback;
11880 discardUrl = discardUrl || cfg.discardUrl;
11881 if(callback && cfg.scope){
11882 callback = callback.createDelegate(cfg.scope);
11884 if(typeof cfg.method != "undefined"){method = cfg.method;};
11885 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11886 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11887 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11888 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11890 this.showLoading();
11892 this.defaultUrl = url;
11894 if(typeof url == "function"){
11895 url = url.call(this);
11898 method = method || (params ? "POST" : "GET");
11899 if(method == "GET"){
11900 url = this.prepareUrl(url);
11903 var o = Roo.apply(cfg ||{}, {
11906 success: this.successDelegate,
11907 failure: this.failureDelegate,
11908 callback: undefined,
11909 timeout: (this.timeout*1000),
11910 argument: {"url": url, "form": null, "callback": callback, "params": params}
11912 Roo.log("updated manager called with timeout of " + o.timeout);
11913 this.transaction = Roo.Ajax.request(o);
11918 * 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.
11919 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11920 * @param {String/HTMLElement} form The form Id or form element
11921 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11922 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11923 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11925 formUpdate : function(form, url, reset, callback){
11926 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11927 if(typeof url == "function"){
11928 url = url.call(this);
11930 form = Roo.getDom(form);
11931 this.transaction = Roo.Ajax.request({
11934 success: this.successDelegate,
11935 failure: this.failureDelegate,
11936 timeout: (this.timeout*1000),
11937 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11939 this.showLoading.defer(1, this);
11944 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11945 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11947 refresh : function(callback){
11948 if(this.defaultUrl == null){
11951 this.update(this.defaultUrl, null, callback, true);
11955 * Set this element to auto refresh.
11956 * @param {Number} interval How often to update (in seconds).
11957 * @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)
11958 * @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}
11959 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11960 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11962 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11964 this.update(url || this.defaultUrl, params, callback, true);
11966 if(this.autoRefreshProcId){
11967 clearInterval(this.autoRefreshProcId);
11969 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11973 * Stop auto refresh on this element.
11975 stopAutoRefresh : function(){
11976 if(this.autoRefreshProcId){
11977 clearInterval(this.autoRefreshProcId);
11978 delete this.autoRefreshProcId;
11982 isAutoRefreshing : function(){
11983 return this.autoRefreshProcId ? true : false;
11986 * Called to update the element to "Loading" state. Override to perform custom action.
11988 showLoading : function(){
11989 if(this.showLoadIndicator){
11990 this.el.update(this.indicatorText);
11995 * Adds unique parameter to query string if disableCaching = true
11998 prepareUrl : function(url){
11999 if(this.disableCaching){
12000 var append = "_dc=" + (new Date().getTime());
12001 if(url.indexOf("?") !== -1){
12002 url += "&" + append;
12004 url += "?" + append;
12013 processSuccess : function(response){
12014 this.transaction = null;
12015 if(response.argument.form && response.argument.reset){
12016 try{ // put in try/catch since some older FF releases had problems with this
12017 response.argument.form.reset();
12020 if(this.loadScripts){
12021 this.renderer.render(this.el, response, this,
12022 this.updateComplete.createDelegate(this, [response]));
12024 this.renderer.render(this.el, response, this);
12025 this.updateComplete(response);
12029 updateComplete : function(response){
12030 this.fireEvent("update", this.el, response);
12031 if(typeof response.argument.callback == "function"){
12032 response.argument.callback(this.el, true, response);
12039 processFailure : function(response){
12040 this.transaction = null;
12041 this.fireEvent("failure", this.el, response);
12042 if(typeof response.argument.callback == "function"){
12043 response.argument.callback(this.el, false, response);
12048 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
12049 * @param {Object} renderer The object implementing the render() method
12051 setRenderer : function(renderer){
12052 this.renderer = renderer;
12055 getRenderer : function(){
12056 return this.renderer;
12060 * Set the defaultUrl used for updates
12061 * @param {String/Function} defaultUrl The url or a function to call to get the url
12063 setDefaultUrl : function(defaultUrl){
12064 this.defaultUrl = defaultUrl;
12068 * Aborts the executing transaction
12070 abort : function(){
12071 if(this.transaction){
12072 Roo.Ajax.abort(this.transaction);
12077 * Returns true if an update is in progress
12078 * @return {Boolean}
12080 isUpdating : function(){
12081 if(this.transaction){
12082 return Roo.Ajax.isLoading(this.transaction);
12089 * @class Roo.UpdateManager.defaults
12090 * @static (not really - but it helps the doc tool)
12091 * The defaults collection enables customizing the default properties of UpdateManager
12093 Roo.UpdateManager.defaults = {
12095 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12101 * True to process scripts by default (Defaults to false).
12104 loadScripts : false,
12107 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12110 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12112 * Whether to append unique parameter on get request to disable caching (Defaults to false).
12115 disableCaching : false,
12117 * Whether to show indicatorText when loading (Defaults to true).
12120 showLoadIndicator : true,
12122 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
12125 indicatorText : '<div class="loading-indicator">Loading...</div>'
12129 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12131 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12132 * @param {String/HTMLElement/Roo.Element} el The element to update
12133 * @param {String} url The url
12134 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12135 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12138 * @member Roo.UpdateManager
12140 Roo.UpdateManager.updateElement = function(el, url, params, options){
12141 var um = Roo.get(el, true).getUpdateManager();
12142 Roo.apply(um, options);
12143 um.update(url, params, options ? options.callback : null);
12145 // alias for backwards compat
12146 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12148 * @class Roo.UpdateManager.BasicRenderer
12149 * Default Content renderer. Updates the elements innerHTML with the responseText.
12151 Roo.UpdateManager.BasicRenderer = function(){};
12153 Roo.UpdateManager.BasicRenderer.prototype = {
12155 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12156 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12157 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12158 * @param {Roo.Element} el The element being rendered
12159 * @param {Object} response The YUI Connect response object
12160 * @param {UpdateManager} updateManager The calling update manager
12161 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12163 render : function(el, response, updateManager, callback){
12164 el.update(response.responseText, updateManager.loadScripts, callback);
12170 * (c)) Alan Knowles
12176 * @class Roo.DomTemplate
12177 * @extends Roo.Template
12178 * An effort at a dom based template engine..
12180 * Similar to XTemplate, except it uses dom parsing to create the template..
12182 * Supported features:
12187 {a_variable} - output encoded.
12188 {a_variable.format:("Y-m-d")} - call a method on the variable
12189 {a_variable:raw} - unencoded output
12190 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
12191 {a_variable:this.method_on_template(...)} - call a method on the template object.
12196 <div roo-for="a_variable or condition.."></div>
12197 <div roo-if="a_variable or condition"></div>
12198 <div roo-exec="some javascript"></div>
12199 <div roo-name="named_template"></div>
12204 Roo.DomTemplate = function()
12206 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
12213 Roo.extend(Roo.DomTemplate, Roo.Template, {
12215 * id counter for sub templates.
12219 * flag to indicate if dom parser is inside a pre,
12220 * it will strip whitespace if not.
12225 * The various sub templates
12233 * basic tag replacing syntax
12236 * // you can fake an object call by doing this
12240 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
12241 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
12243 iterChild : function (node, method) {
12245 var oldPre = this.inPre;
12246 if (node.tagName == 'PRE') {
12249 for( var i = 0; i < node.childNodes.length; i++) {
12250 method.call(this, node.childNodes[i]);
12252 this.inPre = oldPre;
12258 * compile the template
12260 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
12263 compile: function()
12267 // covert the html into DOM...
12271 doc = document.implementation.createHTMLDocument("");
12272 doc.documentElement.innerHTML = this.html ;
12273 div = doc.documentElement;
12275 // old IE... - nasty -- it causes all sorts of issues.. with
12276 // images getting pulled from server..
12277 div = document.createElement('div');
12278 div.innerHTML = this.html;
12280 //doc.documentElement.innerHTML = htmlBody
12286 this.iterChild(div, function(n) {_t.compileNode(n, true); });
12288 var tpls = this.tpls;
12290 // create a top level template from the snippet..
12292 //Roo.log(div.innerHTML);
12299 body : div.innerHTML,
12312 Roo.each(tpls, function(tp){
12313 this.compileTpl(tp);
12314 this.tpls[tp.id] = tp;
12317 this.master = tpls[0];
12323 compileNode : function(node, istop) {
12328 // skip anything not a tag..
12329 if (node.nodeType != 1) {
12330 if (node.nodeType == 3 && !this.inPre) {
12331 // reduce white space..
12332 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
12355 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
12356 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
12357 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
12358 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
12364 // just itterate children..
12365 this.iterChild(node,this.compileNode);
12368 tpl.uid = this.id++;
12369 tpl.value = node.getAttribute('roo-' + tpl.attr);
12370 node.removeAttribute('roo-'+ tpl.attr);
12371 if (tpl.attr != 'name') {
12372 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
12373 node.parentNode.replaceChild(placeholder, node);
12376 var placeholder = document.createElement('span');
12377 placeholder.className = 'roo-tpl-' + tpl.value;
12378 node.parentNode.replaceChild(placeholder, node);
12381 // parent now sees '{domtplXXXX}
12382 this.iterChild(node,this.compileNode);
12384 // we should now have node body...
12385 var div = document.createElement('div');
12386 div.appendChild(node);
12388 // this has the unfortunate side effect of converting tagged attributes
12389 // eg. href="{...}" into %7C...%7D
12390 // this has been fixed by searching for those combo's although it's a bit hacky..
12393 tpl.body = div.innerHTML;
12400 switch (tpl.value) {
12401 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
12402 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
12403 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
12408 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12412 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12416 tpl.id = tpl.value; // replace non characters???
12422 this.tpls.push(tpl);
12432 * Compile a segment of the template into a 'sub-template'
12438 compileTpl : function(tpl)
12440 var fm = Roo.util.Format;
12441 var useF = this.disableFormats !== true;
12443 var sep = Roo.isGecko ? "+\n" : ",\n";
12445 var undef = function(str) {
12446 Roo.debug && Roo.log("Property not found :" + str);
12450 //Roo.log(tpl.body);
12454 var fn = function(m, lbrace, name, format, args)
12457 //Roo.log(arguments);
12458 args = args ? args.replace(/\\'/g,"'") : args;
12459 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
12460 if (typeof(format) == 'undefined') {
12461 format = 'htmlEncode';
12463 if (format == 'raw' ) {
12467 if(name.substr(0, 6) == 'domtpl'){
12468 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
12471 // build an array of options to determine if value is undefined..
12473 // basically get 'xxxx.yyyy' then do
12474 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
12475 // (function () { Roo.log("Property not found"); return ''; })() :
12480 Roo.each(name.split('.'), function(st) {
12481 lookfor += (lookfor.length ? '.': '') + st;
12482 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
12485 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
12488 if(format && useF){
12490 args = args ? ',' + args : "";
12492 if(format.substr(0, 5) != "this."){
12493 format = "fm." + format + '(';
12495 format = 'this.call("'+ format.substr(5) + '", ';
12499 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
12502 if (args && args.length) {
12503 // called with xxyx.yuu:(test,test)
12505 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
12507 // raw.. - :raw modifier..
12508 return "'"+ sep + udef_st + name + ")"+sep+"'";
12512 // branched to use + in gecko and [].join() in others
12514 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
12515 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
12518 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
12519 body.push(tpl.body.replace(/(\r\n|\n)/g,
12520 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
12521 body.push("'].join('');};};");
12522 body = body.join('');
12525 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
12527 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
12534 * same as applyTemplate, except it's done to one of the subTemplates
12535 * when using named templates, you can do:
12537 * var str = pl.applySubTemplate('your-name', values);
12540 * @param {Number} id of the template
12541 * @param {Object} values to apply to template
12542 * @param {Object} parent (normaly the instance of this object)
12544 applySubTemplate : function(id, values, parent)
12548 var t = this.tpls[id];
12552 if(t.ifCall && !t.ifCall.call(this, values, parent)){
12553 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
12557 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
12564 if(t.execCall && t.execCall.call(this, values, parent)){
12568 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12574 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
12575 parent = t.target ? values : parent;
12576 if(t.forCall && vs instanceof Array){
12578 for(var i = 0, len = vs.length; i < len; i++){
12580 buf[buf.length] = t.compiled.call(this, vs[i], parent);
12582 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12584 //Roo.log(t.compiled);
12588 return buf.join('');
12591 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12596 return t.compiled.call(this, vs, parent);
12598 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12600 //Roo.log(t.compiled);
12608 applyTemplate : function(values){
12609 return this.master.compiled.call(this, values, {});
12610 //var s = this.subs;
12613 apply : function(){
12614 return this.applyTemplate.apply(this, arguments);
12619 Roo.DomTemplate.from = function(el){
12620 el = Roo.getDom(el);
12621 return new Roo.Domtemplate(el.value || el.innerHTML);
12624 * Ext JS Library 1.1.1
12625 * Copyright(c) 2006-2007, Ext JS, LLC.
12627 * Originally Released Under LGPL - original licence link has changed is not relivant.
12630 * <script type="text/javascript">
12634 * @class Roo.util.DelayedTask
12635 * Provides a convenient method of performing setTimeout where a new
12636 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12637 * You can use this class to buffer
12638 * the keypress events for a certain number of milliseconds, and perform only if they stop
12639 * for that amount of time.
12640 * @constructor The parameters to this constructor serve as defaults and are not required.
12641 * @param {Function} fn (optional) The default function to timeout
12642 * @param {Object} scope (optional) The default scope of that timeout
12643 * @param {Array} args (optional) The default Array of arguments
12645 Roo.util.DelayedTask = function(fn, scope, args){
12646 var id = null, d, t;
12648 var call = function(){
12649 var now = new Date().getTime();
12653 fn.apply(scope, args || []);
12657 * Cancels any pending timeout and queues a new one
12658 * @param {Number} delay The milliseconds to delay
12659 * @param {Function} newFn (optional) Overrides function passed to constructor
12660 * @param {Object} newScope (optional) Overrides scope passed to constructor
12661 * @param {Array} newArgs (optional) Overrides args passed to constructor
12663 this.delay = function(delay, newFn, newScope, newArgs){
12664 if(id && delay != d){
12668 t = new Date().getTime();
12670 scope = newScope || scope;
12671 args = newArgs || args;
12673 id = setInterval(call, d);
12678 * Cancel the last queued timeout
12680 this.cancel = function(){
12688 * Ext JS Library 1.1.1
12689 * Copyright(c) 2006-2007, Ext JS, LLC.
12691 * Originally Released Under LGPL - original licence link has changed is not relivant.
12694 * <script type="text/javascript">
12698 Roo.util.TaskRunner = function(interval){
12699 interval = interval || 10;
12700 var tasks = [], removeQueue = [];
12702 var running = false;
12704 var stopThread = function(){
12710 var startThread = function(){
12713 id = setInterval(runTasks, interval);
12717 var removeTask = function(task){
12718 removeQueue.push(task);
12724 var runTasks = function(){
12725 if(removeQueue.length > 0){
12726 for(var i = 0, len = removeQueue.length; i < len; i++){
12727 tasks.remove(removeQueue[i]);
12730 if(tasks.length < 1){
12735 var now = new Date().getTime();
12736 for(var i = 0, len = tasks.length; i < len; ++i){
12738 var itime = now - t.taskRunTime;
12739 if(t.interval <= itime){
12740 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12741 t.taskRunTime = now;
12742 if(rt === false || t.taskRunCount === t.repeat){
12747 if(t.duration && t.duration <= (now - t.taskStartTime)){
12754 * Queues a new task.
12755 * @param {Object} task
12757 this.start = function(task){
12759 task.taskStartTime = new Date().getTime();
12760 task.taskRunTime = 0;
12761 task.taskRunCount = 0;
12766 this.stop = function(task){
12771 this.stopAll = function(){
12773 for(var i = 0, len = tasks.length; i < len; i++){
12774 if(tasks[i].onStop){
12783 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12785 * Ext JS Library 1.1.1
12786 * Copyright(c) 2006-2007, Ext JS, LLC.
12788 * Originally Released Under LGPL - original licence link has changed is not relivant.
12791 * <script type="text/javascript">
12796 * @class Roo.util.MixedCollection
12797 * @extends Roo.util.Observable
12798 * A Collection class that maintains both numeric indexes and keys and exposes events.
12800 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12801 * collection (defaults to false)
12802 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12803 * and return the key value for that item. This is used when available to look up the key on items that
12804 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12805 * equivalent to providing an implementation for the {@link #getKey} method.
12807 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12815 * Fires when the collection is cleared.
12820 * Fires when an item is added to the collection.
12821 * @param {Number} index The index at which the item was added.
12822 * @param {Object} o The item added.
12823 * @param {String} key The key associated with the added item.
12828 * Fires when an item is replaced in the collection.
12829 * @param {String} key he key associated with the new added.
12830 * @param {Object} old The item being replaced.
12831 * @param {Object} new The new item.
12836 * Fires when an item is removed from the collection.
12837 * @param {Object} o The item being removed.
12838 * @param {String} key (optional) The key associated with the removed item.
12843 this.allowFunctions = allowFunctions === true;
12845 this.getKey = keyFn;
12847 Roo.util.MixedCollection.superclass.constructor.call(this);
12850 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12851 allowFunctions : false,
12854 * Adds an item to the collection.
12855 * @param {String} key The key to associate with the item
12856 * @param {Object} o The item to add.
12857 * @return {Object} The item added.
12859 add : function(key, o){
12860 if(arguments.length == 1){
12862 key = this.getKey(o);
12864 if(typeof key == "undefined" || key === null){
12866 this.items.push(o);
12867 this.keys.push(null);
12869 var old = this.map[key];
12871 return this.replace(key, o);
12874 this.items.push(o);
12876 this.keys.push(key);
12878 this.fireEvent("add", this.length-1, o, key);
12883 * MixedCollection has a generic way to fetch keys if you implement getKey.
12886 var mc = new Roo.util.MixedCollection();
12887 mc.add(someEl.dom.id, someEl);
12888 mc.add(otherEl.dom.id, otherEl);
12892 var mc = new Roo.util.MixedCollection();
12893 mc.getKey = function(el){
12899 // or via the constructor
12900 var mc = new Roo.util.MixedCollection(false, function(el){
12906 * @param o {Object} The item for which to find the key.
12907 * @return {Object} The key for the passed item.
12909 getKey : function(o){
12914 * Replaces an item in the collection.
12915 * @param {String} key The key associated with the item to replace, or the item to replace.
12916 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12917 * @return {Object} The new item.
12919 replace : function(key, o){
12920 if(arguments.length == 1){
12922 key = this.getKey(o);
12924 var old = this.item(key);
12925 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12926 return this.add(key, o);
12928 var index = this.indexOfKey(key);
12929 this.items[index] = o;
12931 this.fireEvent("replace", key, old, o);
12936 * Adds all elements of an Array or an Object to the collection.
12937 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12938 * an Array of values, each of which are added to the collection.
12940 addAll : function(objs){
12941 if(arguments.length > 1 || objs instanceof Array){
12942 var args = arguments.length > 1 ? arguments : objs;
12943 for(var i = 0, len = args.length; i < len; i++){
12947 for(var key in objs){
12948 if(this.allowFunctions || typeof objs[key] != "function"){
12949 this.add(key, objs[key]);
12956 * Executes the specified function once for every item in the collection, passing each
12957 * item as the first and only parameter. returning false from the function will stop the iteration.
12958 * @param {Function} fn The function to execute for each item.
12959 * @param {Object} scope (optional) The scope in which to execute the function.
12961 each : function(fn, scope){
12962 var items = [].concat(this.items); // each safe for removal
12963 for(var i = 0, len = items.length; i < len; i++){
12964 if(fn.call(scope || items[i], items[i], i, len) === false){
12971 * Executes the specified function once for every key in the collection, passing each
12972 * key, and its associated item as the first two parameters.
12973 * @param {Function} fn The function to execute for each item.
12974 * @param {Object} scope (optional) The scope in which to execute the function.
12976 eachKey : function(fn, scope){
12977 for(var i = 0, len = this.keys.length; i < len; i++){
12978 fn.call(scope || window, this.keys[i], this.items[i], i, len);
12983 * Returns the first item in the collection which elicits a true return value from the
12984 * passed selection function.
12985 * @param {Function} fn The selection function to execute for each item.
12986 * @param {Object} scope (optional) The scope in which to execute the function.
12987 * @return {Object} The first item in the collection which returned true from the selection function.
12989 find : function(fn, scope){
12990 for(var i = 0, len = this.items.length; i < len; i++){
12991 if(fn.call(scope || window, this.items[i], this.keys[i])){
12992 return this.items[i];
12999 * Inserts an item at the specified index in the collection.
13000 * @param {Number} index The index to insert the item at.
13001 * @param {String} key The key to associate with the new item, or the item itself.
13002 * @param {Object} o (optional) If the second parameter was a key, the new item.
13003 * @return {Object} The item inserted.
13005 insert : function(index, key, o){
13006 if(arguments.length == 2){
13008 key = this.getKey(o);
13010 if(index >= this.length){
13011 return this.add(key, o);
13014 this.items.splice(index, 0, o);
13015 if(typeof key != "undefined" && key != null){
13018 this.keys.splice(index, 0, key);
13019 this.fireEvent("add", index, o, key);
13024 * Removed an item from the collection.
13025 * @param {Object} o The item to remove.
13026 * @return {Object} The item removed.
13028 remove : function(o){
13029 return this.removeAt(this.indexOf(o));
13033 * Remove an item from a specified index in the collection.
13034 * @param {Number} index The index within the collection of the item to remove.
13036 removeAt : function(index){
13037 if(index < this.length && index >= 0){
13039 var o = this.items[index];
13040 this.items.splice(index, 1);
13041 var key = this.keys[index];
13042 if(typeof key != "undefined"){
13043 delete this.map[key];
13045 this.keys.splice(index, 1);
13046 this.fireEvent("remove", o, key);
13051 * Removed an item associated with the passed key fom the collection.
13052 * @param {String} key The key of the item to remove.
13054 removeKey : function(key){
13055 return this.removeAt(this.indexOfKey(key));
13059 * Returns the number of items in the collection.
13060 * @return {Number} the number of items in the collection.
13062 getCount : function(){
13063 return this.length;
13067 * Returns index within the collection of the passed Object.
13068 * @param {Object} o The item to find the index of.
13069 * @return {Number} index of the item.
13071 indexOf : function(o){
13072 if(!this.items.indexOf){
13073 for(var i = 0, len = this.items.length; i < len; i++){
13074 if(this.items[i] == o) return i;
13078 return this.items.indexOf(o);
13083 * Returns index within the collection of the passed key.
13084 * @param {String} key The key to find the index of.
13085 * @return {Number} index of the key.
13087 indexOfKey : function(key){
13088 if(!this.keys.indexOf){
13089 for(var i = 0, len = this.keys.length; i < len; i++){
13090 if(this.keys[i] == key) return i;
13094 return this.keys.indexOf(key);
13099 * Returns the item associated with the passed key OR index. Key has priority over index.
13100 * @param {String/Number} key The key or index of the item.
13101 * @return {Object} The item associated with the passed key.
13103 item : function(key){
13104 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
13105 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
13109 * Returns the item at the specified index.
13110 * @param {Number} index The index of the item.
13113 itemAt : function(index){
13114 return this.items[index];
13118 * Returns the item associated with the passed key.
13119 * @param {String/Number} key The key of the item.
13120 * @return {Object} The item associated with the passed key.
13122 key : function(key){
13123 return this.map[key];
13127 * Returns true if the collection contains the passed Object as an item.
13128 * @param {Object} o The Object to look for in the collection.
13129 * @return {Boolean} True if the collection contains the Object as an item.
13131 contains : function(o){
13132 return this.indexOf(o) != -1;
13136 * Returns true if the collection contains the passed Object as a key.
13137 * @param {String} key The key to look for in the collection.
13138 * @return {Boolean} True if the collection contains the Object as a key.
13140 containsKey : function(key){
13141 return typeof this.map[key] != "undefined";
13145 * Removes all items from the collection.
13147 clear : function(){
13152 this.fireEvent("clear");
13156 * Returns the first item in the collection.
13157 * @return {Object} the first item in the collection..
13159 first : function(){
13160 return this.items[0];
13164 * Returns the last item in the collection.
13165 * @return {Object} the last item in the collection..
13168 return this.items[this.length-1];
13171 _sort : function(property, dir, fn){
13172 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
13173 fn = fn || function(a, b){
13176 var c = [], k = this.keys, items = this.items;
13177 for(var i = 0, len = items.length; i < len; i++){
13178 c[c.length] = {key: k[i], value: items[i], index: i};
13180 c.sort(function(a, b){
13181 var v = fn(a[property], b[property]) * dsc;
13183 v = (a.index < b.index ? -1 : 1);
13187 for(var i = 0, len = c.length; i < len; i++){
13188 items[i] = c[i].value;
13191 this.fireEvent("sort", this);
13195 * Sorts this collection with the passed comparison function
13196 * @param {String} direction (optional) "ASC" or "DESC"
13197 * @param {Function} fn (optional) comparison function
13199 sort : function(dir, fn){
13200 this._sort("value", dir, fn);
13204 * Sorts this collection by keys
13205 * @param {String} direction (optional) "ASC" or "DESC"
13206 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
13208 keySort : function(dir, fn){
13209 this._sort("key", dir, fn || function(a, b){
13210 return String(a).toUpperCase()-String(b).toUpperCase();
13215 * Returns a range of items in this collection
13216 * @param {Number} startIndex (optional) defaults to 0
13217 * @param {Number} endIndex (optional) default to the last item
13218 * @return {Array} An array of items
13220 getRange : function(start, end){
13221 var items = this.items;
13222 if(items.length < 1){
13225 start = start || 0;
13226 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
13229 for(var i = start; i <= end; i++) {
13230 r[r.length] = items[i];
13233 for(var i = start; i >= end; i--) {
13234 r[r.length] = items[i];
13241 * Filter the <i>objects</i> in this collection by a specific property.
13242 * Returns a new collection that has been filtered.
13243 * @param {String} property A property on your objects
13244 * @param {String/RegExp} value Either string that the property values
13245 * should start with or a RegExp to test against the property
13246 * @return {MixedCollection} The new filtered collection
13248 filter : function(property, value){
13249 if(!value.exec){ // not a regex
13250 value = String(value);
13251 if(value.length == 0){
13252 return this.clone();
13254 value = new RegExp("^" + Roo.escapeRe(value), "i");
13256 return this.filterBy(function(o){
13257 return o && value.test(o[property]);
13262 * Filter by a function. * Returns a new collection that has been filtered.
13263 * The passed function will be called with each
13264 * object in the collection. If the function returns true, the value is included
13265 * otherwise it is filtered.
13266 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
13267 * @param {Object} scope (optional) The scope of the function (defaults to this)
13268 * @return {MixedCollection} The new filtered collection
13270 filterBy : function(fn, scope){
13271 var r = new Roo.util.MixedCollection();
13272 r.getKey = this.getKey;
13273 var k = this.keys, it = this.items;
13274 for(var i = 0, len = it.length; i < len; i++){
13275 if(fn.call(scope||this, it[i], k[i])){
13276 r.add(k[i], it[i]);
13283 * Creates a duplicate of this collection
13284 * @return {MixedCollection}
13286 clone : function(){
13287 var r = new Roo.util.MixedCollection();
13288 var k = this.keys, it = this.items;
13289 for(var i = 0, len = it.length; i < len; i++){
13290 r.add(k[i], it[i]);
13292 r.getKey = this.getKey;
13297 * Returns the item associated with the passed key or index.
13299 * @param {String/Number} key The key or index of the item.
13300 * @return {Object} The item associated with the passed key.
13302 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
13304 * Ext JS Library 1.1.1
13305 * Copyright(c) 2006-2007, Ext JS, LLC.
13307 * Originally Released Under LGPL - original licence link has changed is not relivant.
13310 * <script type="text/javascript">
13313 * @class Roo.util.JSON
13314 * Modified version of Douglas Crockford"s json.js that doesn"t
13315 * mess with the Object prototype
13316 * http://www.json.org/js.html
13319 Roo.util.JSON = new (function(){
13320 var useHasOwn = {}.hasOwnProperty ? true : false;
13322 // crashes Safari in some instances
13323 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
13325 var pad = function(n) {
13326 return n < 10 ? "0" + n : n;
13339 var encodeString = function(s){
13340 if (/["\\\x00-\x1f]/.test(s)) {
13341 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
13346 c = b.charCodeAt();
13348 Math.floor(c / 16).toString(16) +
13349 (c % 16).toString(16);
13352 return '"' + s + '"';
13355 var encodeArray = function(o){
13356 var a = ["["], b, i, l = o.length, v;
13357 for (i = 0; i < l; i += 1) {
13359 switch (typeof v) {
13368 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
13376 var encodeDate = function(o){
13377 return '"' + o.getFullYear() + "-" +
13378 pad(o.getMonth() + 1) + "-" +
13379 pad(o.getDate()) + "T" +
13380 pad(o.getHours()) + ":" +
13381 pad(o.getMinutes()) + ":" +
13382 pad(o.getSeconds()) + '"';
13386 * Encodes an Object, Array or other value
13387 * @param {Mixed} o The variable to encode
13388 * @return {String} The JSON string
13390 this.encode = function(o)
13392 // should this be extended to fully wrap stringify..
13394 if(typeof o == "undefined" || o === null){
13396 }else if(o instanceof Array){
13397 return encodeArray(o);
13398 }else if(o instanceof Date){
13399 return encodeDate(o);
13400 }else if(typeof o == "string"){
13401 return encodeString(o);
13402 }else if(typeof o == "number"){
13403 return isFinite(o) ? String(o) : "null";
13404 }else if(typeof o == "boolean"){
13407 var a = ["{"], b, i, v;
13409 if(!useHasOwn || o.hasOwnProperty(i)) {
13411 switch (typeof v) {
13420 a.push(this.encode(i), ":",
13421 v === null ? "null" : this.encode(v));
13432 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
13433 * @param {String} json The JSON string
13434 * @return {Object} The resulting object
13436 this.decode = function(json){
13438 return /** eval:var:json */ eval("(" + json + ')');
13442 * Shorthand for {@link Roo.util.JSON#encode}
13443 * @member Roo encode
13445 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
13447 * Shorthand for {@link Roo.util.JSON#decode}
13448 * @member Roo decode
13450 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
13453 * Ext JS Library 1.1.1
13454 * Copyright(c) 2006-2007, Ext JS, LLC.
13456 * Originally Released Under LGPL - original licence link has changed is not relivant.
13459 * <script type="text/javascript">
13463 * @class Roo.util.Format
13464 * Reusable data formatting functions
13467 Roo.util.Format = function(){
13468 var trimRe = /^\s+|\s+$/g;
13471 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
13472 * @param {String} value The string to truncate
13473 * @param {Number} length The maximum length to allow before truncating
13474 * @return {String} The converted text
13476 ellipsis : function(value, len){
13477 if(value && value.length > len){
13478 return value.substr(0, len-3)+"...";
13484 * Checks a reference and converts it to empty string if it is undefined
13485 * @param {Mixed} value Reference to check
13486 * @return {Mixed} Empty string if converted, otherwise the original value
13488 undef : function(value){
13489 return typeof value != "undefined" ? value : "";
13493 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
13494 * @param {String} value The string to encode
13495 * @return {String} The encoded text
13497 htmlEncode : function(value){
13498 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
13502 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13503 * @param {String} value The string to decode
13504 * @return {String} The decoded text
13506 htmlDecode : function(value){
13507 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
13511 * Trims any whitespace from either side of a string
13512 * @param {String} value The text to trim
13513 * @return {String} The trimmed text
13515 trim : function(value){
13516 return String(value).replace(trimRe, "");
13520 * Returns a substring from within an original string
13521 * @param {String} value The original text
13522 * @param {Number} start The start index of the substring
13523 * @param {Number} length The length of the substring
13524 * @return {String} The substring
13526 substr : function(value, start, length){
13527 return String(value).substr(start, length);
13531 * Converts a string to all lower case letters
13532 * @param {String} value The text to convert
13533 * @return {String} The converted text
13535 lowercase : function(value){
13536 return String(value).toLowerCase();
13540 * Converts a string to all upper case letters
13541 * @param {String} value The text to convert
13542 * @return {String} The converted text
13544 uppercase : function(value){
13545 return String(value).toUpperCase();
13549 * Converts the first character only of a string to upper case
13550 * @param {String} value The text to convert
13551 * @return {String} The converted text
13553 capitalize : function(value){
13554 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13558 call : function(value, fn){
13559 if(arguments.length > 2){
13560 var args = Array.prototype.slice.call(arguments, 2);
13561 args.unshift(value);
13563 return /** eval:var:value */ eval(fn).apply(window, args);
13565 /** eval:var:value */
13566 return /** eval:var:value */ eval(fn).call(window, value);
13572 * safer version of Math.toFixed..??/
13573 * @param {Number/String} value The numeric value to format
13574 * @param {Number/String} value Decimal places
13575 * @return {String} The formatted currency string
13577 toFixed : function(v, n)
13579 // why not use to fixed - precision is buggered???
13581 return Math.round(v-0);
13583 var fact = Math.pow(10,n+1);
13584 v = (Math.round((v-0)*fact))/fact;
13585 var z = (''+fact).substring(2);
13586 if (v == Math.floor(v)) {
13587 return Math.floor(v) + '.' + z;
13590 // now just padd decimals..
13591 var ps = String(v).split('.');
13592 var fd = (ps[1] + z);
13593 var r = fd.substring(0,n);
13594 var rm = fd.substring(n);
13596 return ps[0] + '.' + r;
13598 r*=1; // turn it into a number;
13600 if (String(r).length != n) {
13603 r = String(r).substring(1); // chop the end off.
13606 return ps[0] + '.' + r;
13611 * Format a number as US currency
13612 * @param {Number/String} value The numeric value to format
13613 * @return {String} The formatted currency string
13615 usMoney : function(v){
13616 return '$' + Roo.util.Format.number(v);
13621 * eventually this should probably emulate php's number_format
13622 * @param {Number/String} value The numeric value to format
13623 * @param {Number} decimals number of decimal places
13624 * @return {String} The formatted currency string
13626 number : function(v,decimals)
13628 // multiply and round.
13629 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
13630 var mul = Math.pow(10, decimals);
13631 var zero = String(mul).substring(1);
13632 v = (Math.round((v-0)*mul))/mul;
13634 // if it's '0' number.. then
13636 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13638 var ps = v.split('.');
13642 var r = /(\d+)(\d{3})/;
13644 while (r.test(whole)) {
13645 whole = whole.replace(r, '$1' + ',' + '$2');
13651 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
13652 // does not have decimals
13653 (decimals ? ('.' + zero) : '');
13656 return whole + sub ;
13660 * Parse a value into a formatted date using the specified format pattern.
13661 * @param {Mixed} value The value to format
13662 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13663 * @return {String} The formatted date string
13665 date : function(v, format){
13669 if(!(v instanceof Date)){
13670 v = new Date(Date.parse(v));
13672 return v.dateFormat(format || Roo.util.Format.defaults.date);
13676 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13677 * @param {String} format Any valid date format string
13678 * @return {Function} The date formatting function
13680 dateRenderer : function(format){
13681 return function(v){
13682 return Roo.util.Format.date(v, format);
13687 stripTagsRE : /<\/?[^>]+>/gi,
13690 * Strips all HTML tags
13691 * @param {Mixed} value The text from which to strip tags
13692 * @return {String} The stripped text
13694 stripTags : function(v){
13695 return !v ? v : String(v).replace(this.stripTagsRE, "");
13699 Roo.util.Format.defaults = {
13703 * Ext JS Library 1.1.1
13704 * Copyright(c) 2006-2007, Ext JS, LLC.
13706 * Originally Released Under LGPL - original licence link has changed is not relivant.
13709 * <script type="text/javascript">
13716 * @class Roo.MasterTemplate
13717 * @extends Roo.Template
13718 * Provides a template that can have child templates. The syntax is:
13720 var t = new Roo.MasterTemplate(
13721 '<select name="{name}">',
13722 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13725 t.add('options', {value: 'foo', text: 'bar'});
13726 // or you can add multiple child elements in one shot
13727 t.addAll('options', [
13728 {value: 'foo', text: 'bar'},
13729 {value: 'foo2', text: 'bar2'},
13730 {value: 'foo3', text: 'bar3'}
13732 // then append, applying the master template values
13733 t.append('my-form', {name: 'my-select'});
13735 * A name attribute for the child template is not required if you have only one child
13736 * template or you want to refer to them by index.
13738 Roo.MasterTemplate = function(){
13739 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13740 this.originalHtml = this.html;
13742 var m, re = this.subTemplateRe;
13745 while(m = re.exec(this.html)){
13746 var name = m[1], content = m[2];
13751 tpl : new Roo.Template(content)
13754 st[name] = st[subIndex];
13756 st[subIndex].tpl.compile();
13757 st[subIndex].tpl.call = this.call.createDelegate(this);
13760 this.subCount = subIndex;
13763 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13765 * The regular expression used to match sub templates
13769 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13772 * Applies the passed values to a child template.
13773 * @param {String/Number} name (optional) The name or index of the child template
13774 * @param {Array/Object} values The values to be applied to the template
13775 * @return {MasterTemplate} this
13777 add : function(name, values){
13778 if(arguments.length == 1){
13779 values = arguments[0];
13782 var s = this.subs[name];
13783 s.buffer[s.buffer.length] = s.tpl.apply(values);
13788 * Applies all the passed values to a child template.
13789 * @param {String/Number} name (optional) The name or index of the child template
13790 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13791 * @param {Boolean} reset (optional) True to reset the template first
13792 * @return {MasterTemplate} this
13794 fill : function(name, values, reset){
13796 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13804 for(var i = 0, len = values.length; i < len; i++){
13805 this.add(name, values[i]);
13811 * Resets the template for reuse
13812 * @return {MasterTemplate} this
13814 reset : function(){
13816 for(var i = 0; i < this.subCount; i++){
13822 applyTemplate : function(values){
13824 var replaceIndex = -1;
13825 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13826 return s[++replaceIndex].buffer.join("");
13828 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13831 apply : function(){
13832 return this.applyTemplate.apply(this, arguments);
13835 compile : function(){return this;}
13839 * Alias for fill().
13842 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13844 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13845 * var tpl = Roo.MasterTemplate.from('element-id');
13846 * @param {String/HTMLElement} el
13847 * @param {Object} config
13850 Roo.MasterTemplate.from = function(el, config){
13851 el = Roo.getDom(el);
13852 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13855 * Ext JS Library 1.1.1
13856 * Copyright(c) 2006-2007, Ext JS, LLC.
13858 * Originally Released Under LGPL - original licence link has changed is not relivant.
13861 * <script type="text/javascript">
13866 * @class Roo.util.CSS
13867 * Utility class for manipulating CSS rules
13870 Roo.util.CSS = function(){
13872 var doc = document;
13874 var camelRe = /(-[a-z])/gi;
13875 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13879 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13880 * tag and appended to the HEAD of the document.
13881 * @param {String|Object} cssText The text containing the css rules
13882 * @param {String} id An id to add to the stylesheet for later removal
13883 * @return {StyleSheet}
13885 createStyleSheet : function(cssText, id){
13887 var head = doc.getElementsByTagName("head")[0];
13888 var nrules = doc.createElement("style");
13889 nrules.setAttribute("type", "text/css");
13891 nrules.setAttribute("id", id);
13893 if (typeof(cssText) != 'string') {
13894 // support object maps..
13895 // not sure if this a good idea..
13896 // perhaps it should be merged with the general css handling
13897 // and handle js style props.
13898 var cssTextNew = [];
13899 for(var n in cssText) {
13901 for(var k in cssText[n]) {
13902 citems.push( k + ' : ' +cssText[n][k] + ';' );
13904 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13907 cssText = cssTextNew.join("\n");
13913 head.appendChild(nrules);
13914 ss = nrules.styleSheet;
13915 ss.cssText = cssText;
13918 nrules.appendChild(doc.createTextNode(cssText));
13920 nrules.cssText = cssText;
13922 head.appendChild(nrules);
13923 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13925 this.cacheStyleSheet(ss);
13930 * Removes a style or link tag by id
13931 * @param {String} id The id of the tag
13933 removeStyleSheet : function(id){
13934 var existing = doc.getElementById(id);
13936 existing.parentNode.removeChild(existing);
13941 * Dynamically swaps an existing stylesheet reference for a new one
13942 * @param {String} id The id of an existing link tag to remove
13943 * @param {String} url The href of the new stylesheet to include
13945 swapStyleSheet : function(id, url){
13946 this.removeStyleSheet(id);
13947 var ss = doc.createElement("link");
13948 ss.setAttribute("rel", "stylesheet");
13949 ss.setAttribute("type", "text/css");
13950 ss.setAttribute("id", id);
13951 ss.setAttribute("href", url);
13952 doc.getElementsByTagName("head")[0].appendChild(ss);
13956 * Refresh the rule cache if you have dynamically added stylesheets
13957 * @return {Object} An object (hash) of rules indexed by selector
13959 refreshCache : function(){
13960 return this.getRules(true);
13964 cacheStyleSheet : function(stylesheet){
13968 try{// try catch for cross domain access issue
13969 var ssRules = stylesheet.cssRules || stylesheet.rules;
13970 for(var j = ssRules.length-1; j >= 0; --j){
13971 rules[ssRules[j].selectorText] = ssRules[j];
13977 * Gets all css rules for the document
13978 * @param {Boolean} refreshCache true to refresh the internal cache
13979 * @return {Object} An object (hash) of rules indexed by selector
13981 getRules : function(refreshCache){
13982 if(rules == null || refreshCache){
13984 var ds = doc.styleSheets;
13985 for(var i =0, len = ds.length; i < len; i++){
13987 this.cacheStyleSheet(ds[i]);
13995 * Gets an an individual CSS rule by selector(s)
13996 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
13997 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
13998 * @return {CSSRule} The CSS rule or null if one is not found
14000 getRule : function(selector, refreshCache){
14001 var rs = this.getRules(refreshCache);
14002 if(!(selector instanceof Array)){
14003 return rs[selector];
14005 for(var i = 0; i < selector.length; i++){
14006 if(rs[selector[i]]){
14007 return rs[selector[i]];
14015 * Updates a rule property
14016 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
14017 * @param {String} property The css property
14018 * @param {String} value The new value for the property
14019 * @return {Boolean} true If a rule was found and updated
14021 updateRule : function(selector, property, value){
14022 if(!(selector instanceof Array)){
14023 var rule = this.getRule(selector);
14025 rule.style[property.replace(camelRe, camelFn)] = value;
14029 for(var i = 0; i < selector.length; i++){
14030 if(this.updateRule(selector[i], property, value)){
14040 * Ext JS Library 1.1.1
14041 * Copyright(c) 2006-2007, Ext JS, LLC.
14043 * Originally Released Under LGPL - original licence link has changed is not relivant.
14046 * <script type="text/javascript">
14052 * @class Roo.util.ClickRepeater
14053 * @extends Roo.util.Observable
14055 * A wrapper class which can be applied to any element. Fires a "click" event while the
14056 * mouse is pressed. The interval between firings may be specified in the config but
14057 * defaults to 10 milliseconds.
14059 * Optionally, a CSS class may be applied to the element during the time it is pressed.
14061 * @cfg {String/HTMLElement/Element} el The element to act as a button.
14062 * @cfg {Number} delay The initial delay before the repeating event begins firing.
14063 * Similar to an autorepeat key delay.
14064 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
14065 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
14066 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
14067 * "interval" and "delay" are ignored. "immediate" is honored.
14068 * @cfg {Boolean} preventDefault True to prevent the default click event
14069 * @cfg {Boolean} stopDefault True to stop the default click event
14072 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
14073 * 2007-02-02 jvs Renamed to ClickRepeater
14074 * 2007-02-03 jvs Modifications for FF Mac and Safari
14077 * @param {String/HTMLElement/Element} el The element to listen on
14078 * @param {Object} config
14080 Roo.util.ClickRepeater = function(el, config)
14082 this.el = Roo.get(el);
14083 this.el.unselectable();
14085 Roo.apply(this, config);
14090 * Fires when the mouse button is depressed.
14091 * @param {Roo.util.ClickRepeater} this
14093 "mousedown" : true,
14096 * Fires on a specified interval during the time the element is pressed.
14097 * @param {Roo.util.ClickRepeater} this
14102 * Fires when the mouse key is released.
14103 * @param {Roo.util.ClickRepeater} this
14108 this.el.on("mousedown", this.handleMouseDown, this);
14109 if(this.preventDefault || this.stopDefault){
14110 this.el.on("click", function(e){
14111 if(this.preventDefault){
14112 e.preventDefault();
14114 if(this.stopDefault){
14120 // allow inline handler
14122 this.on("click", this.handler, this.scope || this);
14125 Roo.util.ClickRepeater.superclass.constructor.call(this);
14128 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
14131 preventDefault : true,
14132 stopDefault : false,
14136 handleMouseDown : function(){
14137 clearTimeout(this.timer);
14139 if(this.pressClass){
14140 this.el.addClass(this.pressClass);
14142 this.mousedownTime = new Date();
14144 Roo.get(document).on("mouseup", this.handleMouseUp, this);
14145 this.el.on("mouseout", this.handleMouseOut, this);
14147 this.fireEvent("mousedown", this);
14148 this.fireEvent("click", this);
14150 this.timer = this.click.defer(this.delay || this.interval, this);
14154 click : function(){
14155 this.fireEvent("click", this);
14156 this.timer = this.click.defer(this.getInterval(), this);
14160 getInterval: function(){
14161 if(!this.accelerate){
14162 return this.interval;
14164 var pressTime = this.mousedownTime.getElapsed();
14165 if(pressTime < 500){
14167 }else if(pressTime < 1700){
14169 }else if(pressTime < 2600){
14171 }else if(pressTime < 3500){
14173 }else if(pressTime < 4400){
14175 }else if(pressTime < 5300){
14177 }else if(pressTime < 6200){
14185 handleMouseOut : function(){
14186 clearTimeout(this.timer);
14187 if(this.pressClass){
14188 this.el.removeClass(this.pressClass);
14190 this.el.on("mouseover", this.handleMouseReturn, this);
14194 handleMouseReturn : function(){
14195 this.el.un("mouseover", this.handleMouseReturn);
14196 if(this.pressClass){
14197 this.el.addClass(this.pressClass);
14203 handleMouseUp : function(){
14204 clearTimeout(this.timer);
14205 this.el.un("mouseover", this.handleMouseReturn);
14206 this.el.un("mouseout", this.handleMouseOut);
14207 Roo.get(document).un("mouseup", this.handleMouseUp);
14208 this.el.removeClass(this.pressClass);
14209 this.fireEvent("mouseup", this);
14213 * Ext JS Library 1.1.1
14214 * Copyright(c) 2006-2007, Ext JS, LLC.
14216 * Originally Released Under LGPL - original licence link has changed is not relivant.
14219 * <script type="text/javascript">
14224 * @class Roo.KeyNav
14225 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
14226 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
14227 * way to implement custom navigation schemes for any UI component.</p>
14228 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
14229 * pageUp, pageDown, del, home, end. Usage:</p>
14231 var nav = new Roo.KeyNav("my-element", {
14232 "left" : function(e){
14233 this.moveLeft(e.ctrlKey);
14235 "right" : function(e){
14236 this.moveRight(e.ctrlKey);
14238 "enter" : function(e){
14245 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14246 * @param {Object} config The config
14248 Roo.KeyNav = function(el, config){
14249 this.el = Roo.get(el);
14250 Roo.apply(this, config);
14251 if(!this.disabled){
14252 this.disabled = true;
14257 Roo.KeyNav.prototype = {
14259 * @cfg {Boolean} disabled
14260 * True to disable this KeyNav instance (defaults to false)
14264 * @cfg {String} defaultEventAction
14265 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
14266 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
14267 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
14269 defaultEventAction: "stopEvent",
14271 * @cfg {Boolean} forceKeyDown
14272 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
14273 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
14274 * handle keydown instead of keypress.
14276 forceKeyDown : false,
14279 prepareEvent : function(e){
14280 var k = e.getKey();
14281 var h = this.keyToHandler[k];
14282 //if(h && this[h]){
14283 // e.stopPropagation();
14285 if(Roo.isSafari && h && k >= 37 && k <= 40){
14291 relay : function(e){
14292 var k = e.getKey();
14293 var h = this.keyToHandler[k];
14295 if(this.doRelay(e, this[h], h) !== true){
14296 e[this.defaultEventAction]();
14302 doRelay : function(e, h, hname){
14303 return h.call(this.scope || this, e);
14306 // possible handlers
14320 // quick lookup hash
14337 * Enable this KeyNav
14339 enable: function(){
14341 // ie won't do special keys on keypress, no one else will repeat keys with keydown
14342 // the EventObject will normalize Safari automatically
14343 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14344 this.el.on("keydown", this.relay, this);
14346 this.el.on("keydown", this.prepareEvent, this);
14347 this.el.on("keypress", this.relay, this);
14349 this.disabled = false;
14354 * Disable this KeyNav
14356 disable: function(){
14357 if(!this.disabled){
14358 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14359 this.el.un("keydown", this.relay);
14361 this.el.un("keydown", this.prepareEvent);
14362 this.el.un("keypress", this.relay);
14364 this.disabled = true;
14369 * Ext JS Library 1.1.1
14370 * Copyright(c) 2006-2007, Ext JS, LLC.
14372 * Originally Released Under LGPL - original licence link has changed is not relivant.
14375 * <script type="text/javascript">
14380 * @class Roo.KeyMap
14381 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
14382 * The constructor accepts the same config object as defined by {@link #addBinding}.
14383 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
14384 * combination it will call the function with this signature (if the match is a multi-key
14385 * combination the callback will still be called only once): (String key, Roo.EventObject e)
14386 * A KeyMap can also handle a string representation of keys.<br />
14389 // map one key by key code
14390 var map = new Roo.KeyMap("my-element", {
14391 key: 13, // or Roo.EventObject.ENTER
14396 // map multiple keys to one action by string
14397 var map = new Roo.KeyMap("my-element", {
14403 // map multiple keys to multiple actions by strings and array of codes
14404 var map = new Roo.KeyMap("my-element", [
14407 fn: function(){ alert("Return was pressed"); }
14410 fn: function(){ alert('a, b or c was pressed'); }
14415 fn: function(){ alert('Control + shift + tab was pressed.'); }
14419 * <b>Note: A KeyMap starts enabled</b>
14421 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14422 * @param {Object} config The config (see {@link #addBinding})
14423 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
14425 Roo.KeyMap = function(el, config, eventName){
14426 this.el = Roo.get(el);
14427 this.eventName = eventName || "keydown";
14428 this.bindings = [];
14430 this.addBinding(config);
14435 Roo.KeyMap.prototype = {
14437 * True to stop the event from bubbling and prevent the default browser action if the
14438 * key was handled by the KeyMap (defaults to false)
14444 * Add a new binding to this KeyMap. The following config object properties are supported:
14446 Property Type Description
14447 ---------- --------------- ----------------------------------------------------------------------
14448 key String/Array A single keycode or an array of keycodes to handle
14449 shift Boolean True to handle key only when shift is pressed (defaults to false)
14450 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
14451 alt Boolean True to handle key only when alt is pressed (defaults to false)
14452 fn Function The function to call when KeyMap finds the expected key combination
14453 scope Object The scope of the callback function
14459 var map = new Roo.KeyMap(document, {
14460 key: Roo.EventObject.ENTER,
14465 //Add a new binding to the existing KeyMap later
14473 * @param {Object/Array} config A single KeyMap config or an array of configs
14475 addBinding : function(config){
14476 if(config instanceof Array){
14477 for(var i = 0, len = config.length; i < len; i++){
14478 this.addBinding(config[i]);
14482 var keyCode = config.key,
14483 shift = config.shift,
14484 ctrl = config.ctrl,
14487 scope = config.scope;
14488 if(typeof keyCode == "string"){
14490 var keyString = keyCode.toUpperCase();
14491 for(var j = 0, len = keyString.length; j < len; j++){
14492 ks.push(keyString.charCodeAt(j));
14496 var keyArray = keyCode instanceof Array;
14497 var handler = function(e){
14498 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14499 var k = e.getKey();
14501 for(var i = 0, len = keyCode.length; i < len; i++){
14502 if(keyCode[i] == k){
14503 if(this.stopEvent){
14506 fn.call(scope || window, k, e);
14512 if(this.stopEvent){
14515 fn.call(scope || window, k, e);
14520 this.bindings.push(handler);
14524 * Shorthand for adding a single key listener
14525 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
14526 * following options:
14527 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14528 * @param {Function} fn The function to call
14529 * @param {Object} scope (optional) The scope of the function
14531 on : function(key, fn, scope){
14532 var keyCode, shift, ctrl, alt;
14533 if(typeof key == "object" && !(key instanceof Array)){
14552 handleKeyDown : function(e){
14553 if(this.enabled){ //just in case
14554 var b = this.bindings;
14555 for(var i = 0, len = b.length; i < len; i++){
14556 b[i].call(this, e);
14562 * Returns true if this KeyMap is enabled
14563 * @return {Boolean}
14565 isEnabled : function(){
14566 return this.enabled;
14570 * Enables this KeyMap
14572 enable: function(){
14574 this.el.on(this.eventName, this.handleKeyDown, this);
14575 this.enabled = true;
14580 * Disable this KeyMap
14582 disable: function(){
14584 this.el.removeListener(this.eventName, this.handleKeyDown, this);
14585 this.enabled = false;
14590 * Ext JS Library 1.1.1
14591 * Copyright(c) 2006-2007, Ext JS, LLC.
14593 * Originally Released Under LGPL - original licence link has changed is not relivant.
14596 * <script type="text/javascript">
14601 * @class Roo.util.TextMetrics
14602 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14603 * wide, in pixels, a given block of text will be.
14606 Roo.util.TextMetrics = function(){
14610 * Measures the size of the specified text
14611 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14612 * that can affect the size of the rendered text
14613 * @param {String} text The text to measure
14614 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14615 * in order to accurately measure the text height
14616 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14618 measure : function(el, text, fixedWidth){
14620 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14623 shared.setFixedWidth(fixedWidth || 'auto');
14624 return shared.getSize(text);
14628 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
14629 * the overhead of multiple calls to initialize the style properties on each measurement.
14630 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14631 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14632 * in order to accurately measure the text height
14633 * @return {Roo.util.TextMetrics.Instance} instance The new instance
14635 createInstance : function(el, fixedWidth){
14636 return Roo.util.TextMetrics.Instance(el, fixedWidth);
14643 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14644 var ml = new Roo.Element(document.createElement('div'));
14645 document.body.appendChild(ml.dom);
14646 ml.position('absolute');
14647 ml.setLeftTop(-1000, -1000);
14651 ml.setWidth(fixedWidth);
14656 * Returns the size of the specified text based on the internal element's style and width properties
14657 * @memberOf Roo.util.TextMetrics.Instance#
14658 * @param {String} text The text to measure
14659 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14661 getSize : function(text){
14663 var s = ml.getSize();
14669 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14670 * that can affect the size of the rendered text
14671 * @memberOf Roo.util.TextMetrics.Instance#
14672 * @param {String/HTMLElement} el The element, dom node or id
14674 bind : function(el){
14676 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14681 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
14682 * to set a fixed width in order to accurately measure the text height.
14683 * @memberOf Roo.util.TextMetrics.Instance#
14684 * @param {Number} width The width to set on the element
14686 setFixedWidth : function(width){
14687 ml.setWidth(width);
14691 * Returns the measured width of the specified text
14692 * @memberOf Roo.util.TextMetrics.Instance#
14693 * @param {String} text The text to measure
14694 * @return {Number} width The width in pixels
14696 getWidth : function(text){
14697 ml.dom.style.width = 'auto';
14698 return this.getSize(text).width;
14702 * Returns the measured height of the specified text. For multiline text, be sure to call
14703 * {@link #setFixedWidth} if necessary.
14704 * @memberOf Roo.util.TextMetrics.Instance#
14705 * @param {String} text The text to measure
14706 * @return {Number} height The height in pixels
14708 getHeight : function(text){
14709 return this.getSize(text).height;
14713 instance.bind(bindTo);
14718 // backwards compat
14719 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14721 * Ext JS Library 1.1.1
14722 * Copyright(c) 2006-2007, Ext JS, LLC.
14724 * Originally Released Under LGPL - original licence link has changed is not relivant.
14727 * <script type="text/javascript">
14731 * @class Roo.state.Provider
14732 * Abstract base class for state provider implementations. This class provides methods
14733 * for encoding and decoding <b>typed</b> variables including dates and defines the
14734 * Provider interface.
14736 Roo.state.Provider = function(){
14738 * @event statechange
14739 * Fires when a state change occurs.
14740 * @param {Provider} this This state provider
14741 * @param {String} key The state key which was changed
14742 * @param {String} value The encoded value for the state
14745 "statechange": true
14748 Roo.state.Provider.superclass.constructor.call(this);
14750 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14752 * Returns the current value for a key
14753 * @param {String} name The key name
14754 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14755 * @return {Mixed} The state data
14757 get : function(name, defaultValue){
14758 return typeof this.state[name] == "undefined" ?
14759 defaultValue : this.state[name];
14763 * Clears a value from the state
14764 * @param {String} name The key name
14766 clear : function(name){
14767 delete this.state[name];
14768 this.fireEvent("statechange", this, name, null);
14772 * Sets the value for a key
14773 * @param {String} name The key name
14774 * @param {Mixed} value The value to set
14776 set : function(name, value){
14777 this.state[name] = value;
14778 this.fireEvent("statechange", this, name, value);
14782 * Decodes a string previously encoded with {@link #encodeValue}.
14783 * @param {String} value The value to decode
14784 * @return {Mixed} The decoded value
14786 decodeValue : function(cookie){
14787 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14788 var matches = re.exec(unescape(cookie));
14789 if(!matches || !matches[1]) return; // non state cookie
14790 var type = matches[1];
14791 var v = matches[2];
14794 return parseFloat(v);
14796 return new Date(Date.parse(v));
14801 var values = v.split("^");
14802 for(var i = 0, len = values.length; i < len; i++){
14803 all.push(this.decodeValue(values[i]));
14808 var values = v.split("^");
14809 for(var i = 0, len = values.length; i < len; i++){
14810 var kv = values[i].split("=");
14811 all[kv[0]] = this.decodeValue(kv[1]);
14820 * Encodes a value including type information. Decode with {@link #decodeValue}.
14821 * @param {Mixed} value The value to encode
14822 * @return {String} The encoded value
14824 encodeValue : function(v){
14826 if(typeof v == "number"){
14828 }else if(typeof v == "boolean"){
14829 enc = "b:" + (v ? "1" : "0");
14830 }else if(v instanceof Date){
14831 enc = "d:" + v.toGMTString();
14832 }else if(v instanceof Array){
14834 for(var i = 0, len = v.length; i < len; i++){
14835 flat += this.encodeValue(v[i]);
14836 if(i != len-1) flat += "^";
14839 }else if(typeof v == "object"){
14842 if(typeof v[key] != "function"){
14843 flat += key + "=" + this.encodeValue(v[key]) + "^";
14846 enc = "o:" + flat.substring(0, flat.length-1);
14850 return escape(enc);
14856 * Ext JS Library 1.1.1
14857 * Copyright(c) 2006-2007, Ext JS, LLC.
14859 * Originally Released Under LGPL - original licence link has changed is not relivant.
14862 * <script type="text/javascript">
14865 * @class Roo.state.Manager
14866 * This is the global state manager. By default all components that are "state aware" check this class
14867 * for state information if you don't pass them a custom state provider. In order for this class
14868 * to be useful, it must be initialized with a provider when your application initializes.
14870 // in your initialization function
14872 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14874 // supposed you have a {@link Roo.BorderLayout}
14875 var layout = new Roo.BorderLayout(...);
14876 layout.restoreState();
14877 // or a {Roo.BasicDialog}
14878 var dialog = new Roo.BasicDialog(...);
14879 dialog.restoreState();
14883 Roo.state.Manager = function(){
14884 var provider = new Roo.state.Provider();
14888 * Configures the default state provider for your application
14889 * @param {Provider} stateProvider The state provider to set
14891 setProvider : function(stateProvider){
14892 provider = stateProvider;
14896 * Returns the current value for a key
14897 * @param {String} name The key name
14898 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14899 * @return {Mixed} The state data
14901 get : function(key, defaultValue){
14902 return provider.get(key, defaultValue);
14906 * Sets the value for a key
14907 * @param {String} name The key name
14908 * @param {Mixed} value The state data
14910 set : function(key, value){
14911 provider.set(key, value);
14915 * Clears a value from the state
14916 * @param {String} name The key name
14918 clear : function(key){
14919 provider.clear(key);
14923 * Gets the currently configured state provider
14924 * @return {Provider} The state provider
14926 getProvider : function(){
14933 * Ext JS Library 1.1.1
14934 * Copyright(c) 2006-2007, Ext JS, LLC.
14936 * Originally Released Under LGPL - original licence link has changed is not relivant.
14939 * <script type="text/javascript">
14942 * @class Roo.state.CookieProvider
14943 * @extends Roo.state.Provider
14944 * The default Provider implementation which saves state via cookies.
14947 var cp = new Roo.state.CookieProvider({
14949 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14950 domain: "roojs.com"
14952 Roo.state.Manager.setProvider(cp);
14954 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14955 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14956 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14957 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14958 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14959 * domain the page is running on including the 'www' like 'www.roojs.com')
14960 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14962 * Create a new CookieProvider
14963 * @param {Object} config The configuration object
14965 Roo.state.CookieProvider = function(config){
14966 Roo.state.CookieProvider.superclass.constructor.call(this);
14968 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14969 this.domain = null;
14970 this.secure = false;
14971 Roo.apply(this, config);
14972 this.state = this.readCookies();
14975 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14977 set : function(name, value){
14978 if(typeof value == "undefined" || value === null){
14982 this.setCookie(name, value);
14983 Roo.state.CookieProvider.superclass.set.call(this, name, value);
14987 clear : function(name){
14988 this.clearCookie(name);
14989 Roo.state.CookieProvider.superclass.clear.call(this, name);
14993 readCookies : function(){
14995 var c = document.cookie + ";";
14996 var re = /\s?(.*?)=(.*?);/g;
14998 while((matches = re.exec(c)) != null){
14999 var name = matches[1];
15000 var value = matches[2];
15001 if(name && name.substring(0,3) == "ys-"){
15002 cookies[name.substr(3)] = this.decodeValue(value);
15009 setCookie : function(name, value){
15010 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
15011 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
15012 ((this.path == null) ? "" : ("; path=" + this.path)) +
15013 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15014 ((this.secure == true) ? "; secure" : "");
15018 clearCookie : function(name){
15019 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
15020 ((this.path == null) ? "" : ("; path=" + this.path)) +
15021 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15022 ((this.secure == true) ? "; secure" : "");
15026 * Ext JS Library 1.1.1
15027 * Copyright(c) 2006-2007, Ext JS, LLC.
15029 * Originally Released Under LGPL - original licence link has changed is not relivant.
15032 * <script type="text/javascript">
15037 * @class Roo.ComponentMgr
15038 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
15041 Roo.ComponentMgr = function(){
15042 var all = new Roo.util.MixedCollection();
15046 * Registers a component.
15047 * @param {Roo.Component} c The component
15049 register : function(c){
15054 * Unregisters a component.
15055 * @param {Roo.Component} c The component
15057 unregister : function(c){
15062 * Returns a component by id
15063 * @param {String} id The component id
15065 get : function(id){
15066 return all.get(id);
15070 * Registers a function that will be called when a specified component is added to ComponentMgr
15071 * @param {String} id The component id
15072 * @param {Funtction} fn The callback function
15073 * @param {Object} scope The scope of the callback
15075 onAvailable : function(id, fn, scope){
15076 all.on("add", function(index, o){
15078 fn.call(scope || o, o);
15079 all.un("add", fn, scope);
15086 * Ext JS Library 1.1.1
15087 * Copyright(c) 2006-2007, Ext JS, LLC.
15089 * Originally Released Under LGPL - original licence link has changed is not relivant.
15092 * <script type="text/javascript">
15096 * @class Roo.Component
15097 * @extends Roo.util.Observable
15098 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
15099 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
15100 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
15101 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
15102 * All visual components (widgets) that require rendering into a layout should subclass Component.
15104 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
15105 * 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
15106 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
15108 Roo.Component = function(config){
15109 config = config || {};
15110 if(config.tagName || config.dom || typeof config == "string"){ // element object
15111 config = {el: config, id: config.id || config};
15113 this.initialConfig = config;
15115 Roo.apply(this, config);
15119 * Fires after the component is disabled.
15120 * @param {Roo.Component} this
15125 * Fires after the component is enabled.
15126 * @param {Roo.Component} this
15130 * @event beforeshow
15131 * Fires before the component is shown. Return false to stop the show.
15132 * @param {Roo.Component} this
15137 * Fires after the component is shown.
15138 * @param {Roo.Component} this
15142 * @event beforehide
15143 * Fires before the component is hidden. Return false to stop the hide.
15144 * @param {Roo.Component} this
15149 * Fires after the component is hidden.
15150 * @param {Roo.Component} this
15154 * @event beforerender
15155 * Fires before the component is rendered. Return false to stop the render.
15156 * @param {Roo.Component} this
15158 beforerender : true,
15161 * Fires after the component is rendered.
15162 * @param {Roo.Component} this
15166 * @event beforedestroy
15167 * Fires before the component is destroyed. Return false to stop the destroy.
15168 * @param {Roo.Component} this
15170 beforedestroy : true,
15173 * Fires after the component is destroyed.
15174 * @param {Roo.Component} this
15179 this.id = "ext-comp-" + (++Roo.Component.AUTO_ID);
15181 Roo.ComponentMgr.register(this);
15182 Roo.Component.superclass.constructor.call(this);
15183 this.initComponent();
15184 if(this.renderTo){ // not supported by all components yet. use at your own risk!
15185 this.render(this.renderTo);
15186 delete this.renderTo;
15191 Roo.Component.AUTO_ID = 1000;
15193 Roo.extend(Roo.Component, Roo.util.Observable, {
15195 * @scope Roo.Component.prototype
15197 * true if this component is hidden. Read-only.
15202 * true if this component is disabled. Read-only.
15207 * true if this component has been rendered. Read-only.
15211 /** @cfg {String} disableClass
15212 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
15214 disabledClass : "x-item-disabled",
15215 /** @cfg {Boolean} allowDomMove
15216 * Whether the component can move the Dom node when rendering (defaults to true).
15218 allowDomMove : true,
15219 /** @cfg {String} hideMode (display|visibility)
15220 * How this component should hidden. Supported values are
15221 * "visibility" (css visibility), "offsets" (negative offset position) and
15222 * "display" (css display) - defaults to "display".
15224 hideMode: 'display',
15227 ctype : "Roo.Component",
15230 * @cfg {String} actionMode
15231 * which property holds the element that used for hide() / show() / disable() / enable()
15237 getActionEl : function(){
15238 return this[this.actionMode];
15241 initComponent : Roo.emptyFn,
15243 * If this is a lazy rendering component, render it to its container element.
15244 * @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.
15246 render : function(container, position){
15247 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
15248 if(!container && this.el){
15249 this.el = Roo.get(this.el);
15250 container = this.el.dom.parentNode;
15251 this.allowDomMove = false;
15253 this.container = Roo.get(container);
15254 this.rendered = true;
15255 if(position !== undefined){
15256 if(typeof position == 'number'){
15257 position = this.container.dom.childNodes[position];
15259 position = Roo.getDom(position);
15262 this.onRender(this.container, position || null);
15264 this.el.addClass(this.cls);
15268 this.el.applyStyles(this.style);
15271 this.fireEvent("render", this);
15272 this.afterRender(this.container);
15284 // default function is not really useful
15285 onRender : function(ct, position){
15287 this.el = Roo.get(this.el);
15288 if(this.allowDomMove !== false){
15289 ct.dom.insertBefore(this.el.dom, position);
15295 getAutoCreate : function(){
15296 var cfg = typeof this.autoCreate == "object" ?
15297 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
15298 if(this.id && !cfg.id){
15305 afterRender : Roo.emptyFn,
15308 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
15309 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
15311 destroy : function(){
15312 if(this.fireEvent("beforedestroy", this) !== false){
15313 this.purgeListeners();
15314 this.beforeDestroy();
15316 this.el.removeAllListeners();
15318 if(this.actionMode == "container"){
15319 this.container.remove();
15323 Roo.ComponentMgr.unregister(this);
15324 this.fireEvent("destroy", this);
15329 beforeDestroy : function(){
15334 onDestroy : function(){
15339 * Returns the underlying {@link Roo.Element}.
15340 * @return {Roo.Element} The element
15342 getEl : function(){
15347 * Returns the id of this component.
15350 getId : function(){
15355 * Try to focus this component.
15356 * @param {Boolean} selectText True to also select the text in this component (if applicable)
15357 * @return {Roo.Component} this
15359 focus : function(selectText){
15362 if(selectText === true){
15363 this.el.dom.select();
15378 * Disable this component.
15379 * @return {Roo.Component} this
15381 disable : function(){
15385 this.disabled = true;
15386 this.fireEvent("disable", this);
15391 onDisable : function(){
15392 this.getActionEl().addClass(this.disabledClass);
15393 this.el.dom.disabled = true;
15397 * Enable this component.
15398 * @return {Roo.Component} this
15400 enable : function(){
15404 this.disabled = false;
15405 this.fireEvent("enable", this);
15410 onEnable : function(){
15411 this.getActionEl().removeClass(this.disabledClass);
15412 this.el.dom.disabled = false;
15416 * Convenience function for setting disabled/enabled by boolean.
15417 * @param {Boolean} disabled
15419 setDisabled : function(disabled){
15420 this[disabled ? "disable" : "enable"]();
15424 * Show this component.
15425 * @return {Roo.Component} this
15428 if(this.fireEvent("beforeshow", this) !== false){
15429 this.hidden = false;
15433 this.fireEvent("show", this);
15439 onShow : function(){
15440 var ae = this.getActionEl();
15441 if(this.hideMode == 'visibility'){
15442 ae.dom.style.visibility = "visible";
15443 }else if(this.hideMode == 'offsets'){
15444 ae.removeClass('x-hidden');
15446 ae.dom.style.display = "";
15451 * Hide this component.
15452 * @return {Roo.Component} this
15455 if(this.fireEvent("beforehide", this) !== false){
15456 this.hidden = true;
15460 this.fireEvent("hide", this);
15466 onHide : function(){
15467 var ae = this.getActionEl();
15468 if(this.hideMode == 'visibility'){
15469 ae.dom.style.visibility = "hidden";
15470 }else if(this.hideMode == 'offsets'){
15471 ae.addClass('x-hidden');
15473 ae.dom.style.display = "none";
15478 * Convenience function to hide or show this component by boolean.
15479 * @param {Boolean} visible True to show, false to hide
15480 * @return {Roo.Component} this
15482 setVisible: function(visible){
15492 * Returns true if this component is visible.
15494 isVisible : function(){
15495 return this.getActionEl().isVisible();
15498 cloneConfig : function(overrides){
15499 overrides = overrides || {};
15500 var id = overrides.id || Roo.id();
15501 var cfg = Roo.applyIf(overrides, this.initialConfig);
15502 cfg.id = id; // prevent dup id
15503 return new this.constructor(cfg);
15507 * Ext JS Library 1.1.1
15508 * Copyright(c) 2006-2007, Ext JS, LLC.
15510 * Originally Released Under LGPL - original licence link has changed is not relivant.
15513 * <script type="text/javascript">
15517 * @class Roo.BoxComponent
15518 * @extends Roo.Component
15519 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
15520 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
15521 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
15522 * layout containers.
15524 * @param {Roo.Element/String/Object} config The configuration options.
15526 Roo.BoxComponent = function(config){
15527 Roo.Component.call(this, config);
15531 * Fires after the component is resized.
15532 * @param {Roo.Component} this
15533 * @param {Number} adjWidth The box-adjusted width that was set
15534 * @param {Number} adjHeight The box-adjusted height that was set
15535 * @param {Number} rawWidth The width that was originally specified
15536 * @param {Number} rawHeight The height that was originally specified
15541 * Fires after the component is moved.
15542 * @param {Roo.Component} this
15543 * @param {Number} x The new x position
15544 * @param {Number} y The new y position
15550 Roo.extend(Roo.BoxComponent, Roo.Component, {
15551 // private, set in afterRender to signify that the component has been rendered
15553 // private, used to defer height settings to subclasses
15554 deferHeight: false,
15555 /** @cfg {Number} width
15556 * width (optional) size of component
15558 /** @cfg {Number} height
15559 * height (optional) size of component
15563 * Sets the width and height of the component. This method fires the resize event. This method can accept
15564 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
15565 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
15566 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
15567 * @return {Roo.BoxComponent} this
15569 setSize : function(w, h){
15570 // support for standard size objects
15571 if(typeof w == 'object'){
15576 if(!this.boxReady){
15582 // prevent recalcs when not needed
15583 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
15586 this.lastSize = {width: w, height: h};
15588 var adj = this.adjustSize(w, h);
15589 var aw = adj.width, ah = adj.height;
15590 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
15591 var rz = this.getResizeEl();
15592 if(!this.deferHeight && aw !== undefined && ah !== undefined){
15593 rz.setSize(aw, ah);
15594 }else if(!this.deferHeight && ah !== undefined){
15596 }else if(aw !== undefined){
15599 this.onResize(aw, ah, w, h);
15600 this.fireEvent('resize', this, aw, ah, w, h);
15606 * Gets the current size of the component's underlying element.
15607 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
15609 getSize : function(){
15610 return this.el.getSize();
15614 * Gets the current XY position of the component's underlying element.
15615 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15616 * @return {Array} The XY position of the element (e.g., [100, 200])
15618 getPosition : function(local){
15619 if(local === true){
15620 return [this.el.getLeft(true), this.el.getTop(true)];
15622 return this.xy || this.el.getXY();
15626 * Gets the current box measurements of the component's underlying element.
15627 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15628 * @returns {Object} box An object in the format {x, y, width, height}
15630 getBox : function(local){
15631 var s = this.el.getSize();
15633 s.x = this.el.getLeft(true);
15634 s.y = this.el.getTop(true);
15636 var xy = this.xy || this.el.getXY();
15644 * Sets the current box measurements of the component's underlying element.
15645 * @param {Object} box An object in the format {x, y, width, height}
15646 * @returns {Roo.BoxComponent} this
15648 updateBox : function(box){
15649 this.setSize(box.width, box.height);
15650 this.setPagePosition(box.x, box.y);
15655 getResizeEl : function(){
15656 return this.resizeEl || this.el;
15660 getPositionEl : function(){
15661 return this.positionEl || this.el;
15665 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
15666 * This method fires the move event.
15667 * @param {Number} left The new left
15668 * @param {Number} top The new top
15669 * @returns {Roo.BoxComponent} this
15671 setPosition : function(x, y){
15674 if(!this.boxReady){
15677 var adj = this.adjustPosition(x, y);
15678 var ax = adj.x, ay = adj.y;
15680 var el = this.getPositionEl();
15681 if(ax !== undefined || ay !== undefined){
15682 if(ax !== undefined && ay !== undefined){
15683 el.setLeftTop(ax, ay);
15684 }else if(ax !== undefined){
15686 }else if(ay !== undefined){
15689 this.onPosition(ax, ay);
15690 this.fireEvent('move', this, ax, ay);
15696 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
15697 * This method fires the move event.
15698 * @param {Number} x The new x position
15699 * @param {Number} y The new y position
15700 * @returns {Roo.BoxComponent} this
15702 setPagePosition : function(x, y){
15705 if(!this.boxReady){
15708 if(x === undefined || y === undefined){ // cannot translate undefined points
15711 var p = this.el.translatePoints(x, y);
15712 this.setPosition(p.left, p.top);
15717 onRender : function(ct, position){
15718 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
15720 this.resizeEl = Roo.get(this.resizeEl);
15722 if(this.positionEl){
15723 this.positionEl = Roo.get(this.positionEl);
15728 afterRender : function(){
15729 Roo.BoxComponent.superclass.afterRender.call(this);
15730 this.boxReady = true;
15731 this.setSize(this.width, this.height);
15732 if(this.x || this.y){
15733 this.setPosition(this.x, this.y);
15735 if(this.pageX || this.pageY){
15736 this.setPagePosition(this.pageX, this.pageY);
15741 * Force the component's size to recalculate based on the underlying element's current height and width.
15742 * @returns {Roo.BoxComponent} this
15744 syncSize : function(){
15745 delete this.lastSize;
15746 this.setSize(this.el.getWidth(), this.el.getHeight());
15751 * Called after the component is resized, this method is empty by default but can be implemented by any
15752 * subclass that needs to perform custom logic after a resize occurs.
15753 * @param {Number} adjWidth The box-adjusted width that was set
15754 * @param {Number} adjHeight The box-adjusted height that was set
15755 * @param {Number} rawWidth The width that was originally specified
15756 * @param {Number} rawHeight The height that was originally specified
15758 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
15763 * Called after the component is moved, this method is empty by default but can be implemented by any
15764 * subclass that needs to perform custom logic after a move occurs.
15765 * @param {Number} x The new x position
15766 * @param {Number} y The new y position
15768 onPosition : function(x, y){
15773 adjustSize : function(w, h){
15774 if(this.autoWidth){
15777 if(this.autoHeight){
15780 return {width : w, height: h};
15784 adjustPosition : function(x, y){
15785 return {x : x, y: y};
15788 * Original code for Roojs - LGPL
15789 * <script type="text/javascript">
15793 * @class Roo.XComponent
15794 * A delayed Element creator...
15795 * Or a way to group chunks of interface together.
15796 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
15797 * used in conjunction with XComponent.build() it will create an instance of each element,
15798 * then call addxtype() to build the User interface.
15800 * Mypart.xyx = new Roo.XComponent({
15802 parent : 'Mypart.xyz', // empty == document.element.!!
15806 disabled : function() {}
15808 tree : function() { // return an tree of xtype declared components
15812 xtype : 'NestedLayoutPanel',
15819 * It can be used to build a big heiracy, with parent etc.
15820 * or you can just use this to render a single compoent to a dom element
15821 * MYPART.render(Roo.Element | String(id) | dom_element )
15828 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
15829 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
15831 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
15833 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
15834 * - if mulitple topModules exist, the last one is defined as the top module.
15838 * When the top level or multiple modules are to embedded into a existing HTML page,
15839 * the parent element can container '#id' of the element where the module will be drawn.
15843 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
15844 * it relies more on a include mechanism, where sub modules are included into an outer page.
15845 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
15847 * Bootstrap Roo Included elements
15849 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
15850 * hence confusing the component builder as it thinks there are multiple top level elements.
15854 * @extends Roo.util.Observable
15856 * @param cfg {Object} configuration of component
15859 Roo.XComponent = function(cfg) {
15860 Roo.apply(this, cfg);
15864 * Fires when this the componnt is built
15865 * @param {Roo.XComponent} c the component
15870 this.region = this.region || 'center'; // default..
15871 Roo.XComponent.register(this);
15872 this.modules = false;
15873 this.el = false; // where the layout goes..
15877 Roo.extend(Roo.XComponent, Roo.util.Observable, {
15880 * The created element (with Roo.factory())
15881 * @type {Roo.Layout}
15887 * for BC - use el in new code
15888 * @type {Roo.Layout}
15894 * for BC - use el in new code
15895 * @type {Roo.Layout}
15900 * @cfg {Function|boolean} disabled
15901 * If this module is disabled by some rule, return true from the funtion
15906 * @cfg {String} parent
15907 * Name of parent element which it get xtype added to..
15912 * @cfg {String} order
15913 * Used to set the order in which elements are created (usefull for multiple tabs)
15918 * @cfg {String} name
15919 * String to display while loading.
15923 * @cfg {String} region
15924 * Region to render component to (defaults to center)
15929 * @cfg {Array} items
15930 * A single item array - the first element is the root of the tree..
15931 * It's done this way to stay compatible with the Xtype system...
15937 * The method that retuns the tree of parts that make up this compoennt
15944 * render element to dom or tree
15945 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
15948 render : function(el)
15952 var hp = this.parent ? 1 : 0;
15953 Roo.debug && Roo.log(this);
15955 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
15956 // if parent is a '#.....' string, then let's use that..
15957 var ename = this.parent.substr(1);
15958 this.parent = false;
15959 Roo.debug && Roo.log(ename);
15961 case 'bootstrap-body' :
15962 if (typeof(Roo.bootstrap.Body) != 'undefined') {
15963 this.parent = { el : new Roo.bootstrap.Body() };
15964 Roo.debug && Roo.log("setting el to doc body");
15967 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
15971 this.parent = { el : true};
15974 el = Roo.get(ename);
15979 if (!el && !this.parent) {
15980 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
15984 Roo.debug && Roo.log("EL:");
15985 Roo.debug && Roo.log(el);
15986 Roo.debug && Roo.log("this.parent.el:");
15987 Roo.debug && Roo.log(this.parent.el);
15989 var tree = this._tree ? this._tree() : this.tree();
15991 // altertive root elements ??? - we need a better way to indicate these.
15992 var is_alt = (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
15993 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
15995 if (!this.parent && is_alt) {
15996 //el = Roo.get(document.body);
15997 this.parent = { el : true };
16002 if (!this.parent) {
16004 Roo.debug && Roo.log("no parent - creating one");
16006 el = el ? Roo.get(el) : false;
16008 // it's a top level one..
16010 el : new Roo.BorderLayout(el || document.body, {
16016 tabPosition: 'top',
16017 //resizeTabs: true,
16018 alwaysShowTabs: el && hp? false : true,
16019 hideTabs: el || !hp ? true : false,
16026 if (!this.parent.el) {
16027 // probably an old style ctor, which has been disabled.
16031 // The 'tree' method is '_tree now'
16033 tree.region = tree.region || this.region;
16035 if (this.parent.el === true) {
16036 // bootstrap... - body..
16037 this.parent.el = Roo.factory(tree);
16040 this.el = this.parent.el.addxtype(tree);
16041 this.fireEvent('built', this);
16043 this.panel = this.el;
16044 this.layout = this.panel.layout;
16045 this.parentLayout = this.parent.layout || false;
16051 Roo.apply(Roo.XComponent, {
16053 * @property hideProgress
16054 * true to disable the building progress bar.. usefull on single page renders.
16057 hideProgress : false,
16059 * @property buildCompleted
16060 * True when the builder has completed building the interface.
16063 buildCompleted : false,
16066 * @property topModule
16067 * the upper most module - uses document.element as it's constructor.
16074 * @property modules
16075 * array of modules to be created by registration system.
16076 * @type {Array} of Roo.XComponent
16081 * @property elmodules
16082 * array of modules to be created by which use #ID
16083 * @type {Array} of Roo.XComponent
16089 * @property build_from_html
16090 * Build elements from html - used by bootstrap HTML stuff
16091 * - this is cleared after build is completed
16092 * @type {boolean} true (default false)
16095 build_from_html : false,
16098 * Register components to be built later.
16100 * This solves the following issues
16101 * - Building is not done on page load, but after an authentication process has occured.
16102 * - Interface elements are registered on page load
16103 * - Parent Interface elements may not be loaded before child, so this handles that..
16110 module : 'Pman.Tab.projectMgr',
16112 parent : 'Pman.layout',
16113 disabled : false, // or use a function..
16116 * * @param {Object} details about module
16118 register : function(obj) {
16120 Roo.XComponent.event.fireEvent('register', obj);
16121 switch(typeof(obj.disabled) ) {
16127 if ( obj.disabled() ) {
16133 if (obj.disabled) {
16139 this.modules.push(obj);
16143 * convert a string to an object..
16144 * eg. 'AAA.BBB' -> finds AAA.BBB
16148 toObject : function(str)
16150 if (!str || typeof(str) == 'object') {
16153 if (str.substring(0,1) == '#') {
16157 var ar = str.split('.');
16162 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
16164 throw "Module not found : " + str;
16168 throw "Module not found : " + str;
16170 Roo.each(ar, function(e) {
16171 if (typeof(o[e]) == 'undefined') {
16172 throw "Module not found : " + str;
16183 * move modules into their correct place in the tree..
16186 preBuild : function ()
16189 Roo.each(this.modules , function (obj)
16191 Roo.XComponent.event.fireEvent('beforebuild', obj);
16193 var opar = obj.parent;
16195 obj.parent = this.toObject(opar);
16197 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
16202 Roo.debug && Roo.log("GOT top level module");
16203 Roo.debug && Roo.log(obj);
16204 obj.modules = new Roo.util.MixedCollection(false,
16205 function(o) { return o.order + '' }
16207 this.topModule = obj;
16210 // parent is a string (usually a dom element name..)
16211 if (typeof(obj.parent) == 'string') {
16212 this.elmodules.push(obj);
16215 if (obj.parent.constructor != Roo.XComponent) {
16216 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
16218 if (!obj.parent.modules) {
16219 obj.parent.modules = new Roo.util.MixedCollection(false,
16220 function(o) { return o.order + '' }
16223 if (obj.parent.disabled) {
16224 obj.disabled = true;
16226 obj.parent.modules.add(obj);
16231 * make a list of modules to build.
16232 * @return {Array} list of modules.
16235 buildOrder : function()
16238 var cmp = function(a,b) {
16239 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
16241 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
16242 throw "No top level modules to build";
16245 // make a flat list in order of modules to build.
16246 var mods = this.topModule ? [ this.topModule ] : [];
16249 // elmodules (is a list of DOM based modules )
16250 Roo.each(this.elmodules, function(e) {
16252 if (!this.topModule &&
16253 typeof(e.parent) == 'string' &&
16254 e.parent.substring(0,1) == '#' &&
16255 Roo.get(e.parent.substr(1))
16258 _this.topModule = e;
16264 // add modules to their parents..
16265 var addMod = function(m) {
16266 Roo.debug && Roo.log("build Order: add: " + m.name);
16269 if (m.modules && !m.disabled) {
16270 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
16271 m.modules.keySort('ASC', cmp );
16272 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
16274 m.modules.each(addMod);
16276 Roo.debug && Roo.log("build Order: no child modules");
16278 // not sure if this is used any more..
16280 m.finalize.name = m.name + " (clean up) ";
16281 mods.push(m.finalize);
16285 if (this.topModule && this.topModule.modules) {
16286 this.topModule.modules.keySort('ASC', cmp );
16287 this.topModule.modules.each(addMod);
16293 * Build the registered modules.
16294 * @param {Object} parent element.
16295 * @param {Function} optional method to call after module has been added.
16299 build : function(opts)
16302 if (typeof(opts) != 'undefined') {
16303 Roo.apply(this,opts);
16307 var mods = this.buildOrder();
16309 //this.allmods = mods;
16310 //Roo.debug && Roo.log(mods);
16312 if (!mods.length) { // should not happen
16313 throw "NO modules!!!";
16317 var msg = "Building Interface...";
16318 // flash it up as modal - so we store the mask!?
16319 if (!this.hideProgress && Roo.MessageBox) {
16320 Roo.MessageBox.show({ title: 'loading' });
16321 Roo.MessageBox.show({
16322 title: "Please wait...",
16331 var total = mods.length;
16334 var progressRun = function() {
16335 if (!mods.length) {
16336 Roo.debug && Roo.log('hide?');
16337 if (!this.hideProgress && Roo.MessageBox) {
16338 Roo.MessageBox.hide();
16340 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
16342 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
16348 var m = mods.shift();
16351 Roo.debug && Roo.log(m);
16352 // not sure if this is supported any more.. - modules that are are just function
16353 if (typeof(m) == 'function') {
16355 return progressRun.defer(10, _this);
16359 msg = "Building Interface " + (total - mods.length) +
16361 (m.name ? (' - ' + m.name) : '');
16362 Roo.debug && Roo.log(msg);
16363 if (!this.hideProgress && Roo.MessageBox) {
16364 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
16368 // is the module disabled?
16369 var disabled = (typeof(m.disabled) == 'function') ?
16370 m.disabled.call(m.module.disabled) : m.disabled;
16374 return progressRun(); // we do not update the display!
16382 // it's 10 on top level, and 1 on others??? why...
16383 return progressRun.defer(10, _this);
16386 progressRun.defer(1, _this);
16400 * wrapper for event.on - aliased later..
16401 * Typically use to register a event handler for register:
16403 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
16412 Roo.XComponent.event = new Roo.util.Observable({
16416 * Fires when an Component is registered,
16417 * set the disable property on the Component to stop registration.
16418 * @param {Roo.XComponent} c the component being registerd.
16423 * @event beforebuild
16424 * Fires before each Component is built
16425 * can be used to apply permissions.
16426 * @param {Roo.XComponent} c the component being registerd.
16429 'beforebuild' : true,
16431 * @event buildcomplete
16432 * Fires on the top level element when all elements have been built
16433 * @param {Roo.XComponent} the top level component.
16435 'buildcomplete' : true
16440 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
16443 * Ext JS Library 1.1.1
16444 * Copyright(c) 2006-2007, Ext JS, LLC.
16446 * Originally Released Under LGPL - original licence link has changed is not relivant.
16449 * <script type="text/javascript">
16455 * These classes are derivatives of the similarly named classes in the YUI Library.
16456 * The original license:
16457 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
16458 * Code licensed under the BSD License:
16459 * http://developer.yahoo.net/yui/license.txt
16464 var Event=Roo.EventManager;
16465 var Dom=Roo.lib.Dom;
16468 * @class Roo.dd.DragDrop
16469 * @extends Roo.util.Observable
16470 * Defines the interface and base operation of items that that can be
16471 * dragged or can be drop targets. It was designed to be extended, overriding
16472 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
16473 * Up to three html elements can be associated with a DragDrop instance:
16475 * <li>linked element: the element that is passed into the constructor.
16476 * This is the element which defines the boundaries for interaction with
16477 * other DragDrop objects.</li>
16478 * <li>handle element(s): The drag operation only occurs if the element that
16479 * was clicked matches a handle element. By default this is the linked
16480 * element, but there are times that you will want only a portion of the
16481 * linked element to initiate the drag operation, and the setHandleElId()
16482 * method provides a way to define this.</li>
16483 * <li>drag element: this represents the element that would be moved along
16484 * with the cursor during a drag operation. By default, this is the linked
16485 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
16486 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
16489 * This class should not be instantiated until the onload event to ensure that
16490 * the associated elements are available.
16491 * The following would define a DragDrop obj that would interact with any
16492 * other DragDrop obj in the "group1" group:
16494 * dd = new Roo.dd.DragDrop("div1", "group1");
16496 * Since none of the event handlers have been implemented, nothing would
16497 * actually happen if you were to run the code above. Normally you would
16498 * override this class or one of the default implementations, but you can
16499 * also override the methods you want on an instance of the class...
16501 * dd.onDragDrop = function(e, id) {
16502 * alert("dd was dropped on " + id);
16506 * @param {String} id of the element that is linked to this instance
16507 * @param {String} sGroup the group of related DragDrop objects
16508 * @param {object} config an object containing configurable attributes
16509 * Valid properties for DragDrop:
16510 * padding, isTarget, maintainOffset, primaryButtonOnly
16512 Roo.dd.DragDrop = function(id, sGroup, config) {
16514 this.init(id, sGroup, config);
16519 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
16522 * The id of the element associated with this object. This is what we
16523 * refer to as the "linked element" because the size and position of
16524 * this element is used to determine when the drag and drop objects have
16532 * Configuration attributes passed into the constructor
16539 * The id of the element that will be dragged. By default this is same
16540 * as the linked element , but could be changed to another element. Ex:
16542 * @property dragElId
16549 * the id of the element that initiates the drag operation. By default
16550 * this is the linked element, but could be changed to be a child of this
16551 * element. This lets us do things like only starting the drag when the
16552 * header element within the linked html element is clicked.
16553 * @property handleElId
16560 * An associative array of HTML tags that will be ignored if clicked.
16561 * @property invalidHandleTypes
16562 * @type {string: string}
16564 invalidHandleTypes: null,
16567 * An associative array of ids for elements that will be ignored if clicked
16568 * @property invalidHandleIds
16569 * @type {string: string}
16571 invalidHandleIds: null,
16574 * An indexted array of css class names for elements that will be ignored
16576 * @property invalidHandleClasses
16579 invalidHandleClasses: null,
16582 * The linked element's absolute X position at the time the drag was
16584 * @property startPageX
16591 * The linked element's absolute X position at the time the drag was
16593 * @property startPageY
16600 * The group defines a logical collection of DragDrop objects that are
16601 * related. Instances only get events when interacting with other
16602 * DragDrop object in the same group. This lets us define multiple
16603 * groups using a single DragDrop subclass if we want.
16605 * @type {string: string}
16610 * Individual drag/drop instances can be locked. This will prevent
16611 * onmousedown start drag.
16619 * Lock this instance
16622 lock: function() { this.locked = true; },
16625 * Unlock this instace
16628 unlock: function() { this.locked = false; },
16631 * By default, all insances can be a drop target. This can be disabled by
16632 * setting isTarget to false.
16639 * The padding configured for this drag and drop object for calculating
16640 * the drop zone intersection with this object.
16647 * Cached reference to the linked element
16648 * @property _domRef
16654 * Internal typeof flag
16655 * @property __ygDragDrop
16658 __ygDragDrop: true,
16661 * Set to true when horizontal contraints are applied
16662 * @property constrainX
16669 * Set to true when vertical contraints are applied
16670 * @property constrainY
16677 * The left constraint
16685 * The right constraint
16693 * The up constraint
16702 * The down constraint
16710 * Maintain offsets when we resetconstraints. Set to true when you want
16711 * the position of the element relative to its parent to stay the same
16712 * when the page changes
16714 * @property maintainOffset
16717 maintainOffset: false,
16720 * Array of pixel locations the element will snap to if we specified a
16721 * horizontal graduation/interval. This array is generated automatically
16722 * when you define a tick interval.
16729 * Array of pixel locations the element will snap to if we specified a
16730 * vertical graduation/interval. This array is generated automatically
16731 * when you define a tick interval.
16738 * By default the drag and drop instance will only respond to the primary
16739 * button click (left button for a right-handed mouse). Set to true to
16740 * allow drag and drop to start with any mouse click that is propogated
16742 * @property primaryButtonOnly
16745 primaryButtonOnly: true,
16748 * The availabe property is false until the linked dom element is accessible.
16749 * @property available
16755 * By default, drags can only be initiated if the mousedown occurs in the
16756 * region the linked element is. This is done in part to work around a
16757 * bug in some browsers that mis-report the mousedown if the previous
16758 * mouseup happened outside of the window. This property is set to true
16759 * if outer handles are defined.
16761 * @property hasOuterHandles
16765 hasOuterHandles: false,
16768 * Code that executes immediately before the startDrag event
16769 * @method b4StartDrag
16772 b4StartDrag: function(x, y) { },
16775 * Abstract method called after a drag/drop object is clicked
16776 * and the drag or mousedown time thresholds have beeen met.
16777 * @method startDrag
16778 * @param {int} X click location
16779 * @param {int} Y click location
16781 startDrag: function(x, y) { /* override this */ },
16784 * Code that executes immediately before the onDrag event
16788 b4Drag: function(e) { },
16791 * Abstract method called during the onMouseMove event while dragging an
16794 * @param {Event} e the mousemove event
16796 onDrag: function(e) { /* override this */ },
16799 * Abstract method called when this element fist begins hovering over
16800 * another DragDrop obj
16801 * @method onDragEnter
16802 * @param {Event} e the mousemove event
16803 * @param {String|DragDrop[]} id In POINT mode, the element
16804 * id this is hovering over. In INTERSECT mode, an array of one or more
16805 * dragdrop items being hovered over.
16807 onDragEnter: function(e, id) { /* override this */ },
16810 * Code that executes immediately before the onDragOver event
16811 * @method b4DragOver
16814 b4DragOver: function(e) { },
16817 * Abstract method called when this element is hovering over another
16819 * @method onDragOver
16820 * @param {Event} e the mousemove event
16821 * @param {String|DragDrop[]} id In POINT mode, the element
16822 * id this is hovering over. In INTERSECT mode, an array of dd items
16823 * being hovered over.
16825 onDragOver: function(e, id) { /* override this */ },
16828 * Code that executes immediately before the onDragOut event
16829 * @method b4DragOut
16832 b4DragOut: function(e) { },
16835 * Abstract method called when we are no longer hovering over an element
16836 * @method onDragOut
16837 * @param {Event} e the mousemove event
16838 * @param {String|DragDrop[]} id In POINT mode, the element
16839 * id this was hovering over. In INTERSECT mode, an array of dd items
16840 * that the mouse is no longer over.
16842 onDragOut: function(e, id) { /* override this */ },
16845 * Code that executes immediately before the onDragDrop event
16846 * @method b4DragDrop
16849 b4DragDrop: function(e) { },
16852 * Abstract method called when this item is dropped on another DragDrop
16854 * @method onDragDrop
16855 * @param {Event} e the mouseup event
16856 * @param {String|DragDrop[]} id In POINT mode, the element
16857 * id this was dropped on. In INTERSECT mode, an array of dd items this
16860 onDragDrop: function(e, id) { /* override this */ },
16863 * Abstract method called when this item is dropped on an area with no
16865 * @method onInvalidDrop
16866 * @param {Event} e the mouseup event
16868 onInvalidDrop: function(e) { /* override this */ },
16871 * Code that executes immediately before the endDrag event
16872 * @method b4EndDrag
16875 b4EndDrag: function(e) { },
16878 * Fired when we are done dragging the object
16880 * @param {Event} e the mouseup event
16882 endDrag: function(e) { /* override this */ },
16885 * Code executed immediately before the onMouseDown event
16886 * @method b4MouseDown
16887 * @param {Event} e the mousedown event
16890 b4MouseDown: function(e) { },
16893 * Event handler that fires when a drag/drop obj gets a mousedown
16894 * @method onMouseDown
16895 * @param {Event} e the mousedown event
16897 onMouseDown: function(e) { /* override this */ },
16900 * Event handler that fires when a drag/drop obj gets a mouseup
16901 * @method onMouseUp
16902 * @param {Event} e the mouseup event
16904 onMouseUp: function(e) { /* override this */ },
16907 * Override the onAvailable method to do what is needed after the initial
16908 * position was determined.
16909 * @method onAvailable
16911 onAvailable: function () {
16915 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
16918 defaultPadding : {left:0, right:0, top:0, bottom:0},
16921 * Initializes the drag drop object's constraints to restrict movement to a certain element.
16925 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
16926 { dragElId: "existingProxyDiv" });
16927 dd.startDrag = function(){
16928 this.constrainTo("parent-id");
16931 * Or you can initalize it using the {@link Roo.Element} object:
16933 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
16934 startDrag : function(){
16935 this.constrainTo("parent-id");
16939 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
16940 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
16941 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
16942 * an object containing the sides to pad. For example: {right:10, bottom:10}
16943 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
16945 constrainTo : function(constrainTo, pad, inContent){
16946 if(typeof pad == "number"){
16947 pad = {left: pad, right:pad, top:pad, bottom:pad};
16949 pad = pad || this.defaultPadding;
16950 var b = Roo.get(this.getEl()).getBox();
16951 var ce = Roo.get(constrainTo);
16952 var s = ce.getScroll();
16953 var c, cd = ce.dom;
16954 if(cd == document.body){
16955 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
16958 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
16962 var topSpace = b.y - c.y;
16963 var leftSpace = b.x - c.x;
16965 this.resetConstraints();
16966 this.setXConstraint(leftSpace - (pad.left||0), // left
16967 c.width - leftSpace - b.width - (pad.right||0) //right
16969 this.setYConstraint(topSpace - (pad.top||0), //top
16970 c.height - topSpace - b.height - (pad.bottom||0) //bottom
16975 * Returns a reference to the linked element
16977 * @return {HTMLElement} the html element
16979 getEl: function() {
16980 if (!this._domRef) {
16981 this._domRef = Roo.getDom(this.id);
16984 return this._domRef;
16988 * Returns a reference to the actual element to drag. By default this is
16989 * the same as the html element, but it can be assigned to another
16990 * element. An example of this can be found in Roo.dd.DDProxy
16991 * @method getDragEl
16992 * @return {HTMLElement} the html element
16994 getDragEl: function() {
16995 return Roo.getDom(this.dragElId);
16999 * Sets up the DragDrop object. Must be called in the constructor of any
17000 * Roo.dd.DragDrop subclass
17002 * @param id the id of the linked element
17003 * @param {String} sGroup the group of related items
17004 * @param {object} config configuration attributes
17006 init: function(id, sGroup, config) {
17007 this.initTarget(id, sGroup, config);
17008 if (!Roo.isTouch) {
17009 Event.on(this.id, "mousedown", this.handleMouseDown, this);
17011 Event.on(this.id, "touchstart", this.handleMouseDown, this);
17012 // Event.on(this.id, "selectstart", Event.preventDefault);
17016 * Initializes Targeting functionality only... the object does not
17017 * get a mousedown handler.
17018 * @method initTarget
17019 * @param id the id of the linked element
17020 * @param {String} sGroup the group of related items
17021 * @param {object} config configuration attributes
17023 initTarget: function(id, sGroup, config) {
17025 // configuration attributes
17026 this.config = config || {};
17028 // create a local reference to the drag and drop manager
17029 this.DDM = Roo.dd.DDM;
17030 // initialize the groups array
17033 // assume that we have an element reference instead of an id if the
17034 // parameter is not a string
17035 if (typeof id !== "string") {
17042 // add to an interaction group
17043 this.addToGroup((sGroup) ? sGroup : "default");
17045 // We don't want to register this as the handle with the manager
17046 // so we just set the id rather than calling the setter.
17047 this.handleElId = id;
17049 // the linked element is the element that gets dragged by default
17050 this.setDragElId(id);
17052 // by default, clicked anchors will not start drag operations.
17053 this.invalidHandleTypes = { A: "A" };
17054 this.invalidHandleIds = {};
17055 this.invalidHandleClasses = [];
17057 this.applyConfig();
17059 this.handleOnAvailable();
17063 * Applies the configuration parameters that were passed into the constructor.
17064 * This is supposed to happen at each level through the inheritance chain. So
17065 * a DDProxy implentation will execute apply config on DDProxy, DD, and
17066 * DragDrop in order to get all of the parameters that are available in
17068 * @method applyConfig
17070 applyConfig: function() {
17072 // configurable properties:
17073 // padding, isTarget, maintainOffset, primaryButtonOnly
17074 this.padding = this.config.padding || [0, 0, 0, 0];
17075 this.isTarget = (this.config.isTarget !== false);
17076 this.maintainOffset = (this.config.maintainOffset);
17077 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
17082 * Executed when the linked element is available
17083 * @method handleOnAvailable
17086 handleOnAvailable: function() {
17087 this.available = true;
17088 this.resetConstraints();
17089 this.onAvailable();
17093 * Configures the padding for the target zone in px. Effectively expands
17094 * (or reduces) the virtual object size for targeting calculations.
17095 * Supports css-style shorthand; if only one parameter is passed, all sides
17096 * will have that padding, and if only two are passed, the top and bottom
17097 * will have the first param, the left and right the second.
17098 * @method setPadding
17099 * @param {int} iTop Top pad
17100 * @param {int} iRight Right pad
17101 * @param {int} iBot Bot pad
17102 * @param {int} iLeft Left pad
17104 setPadding: function(iTop, iRight, iBot, iLeft) {
17105 // this.padding = [iLeft, iRight, iTop, iBot];
17106 if (!iRight && 0 !== iRight) {
17107 this.padding = [iTop, iTop, iTop, iTop];
17108 } else if (!iBot && 0 !== iBot) {
17109 this.padding = [iTop, iRight, iTop, iRight];
17111 this.padding = [iTop, iRight, iBot, iLeft];
17116 * Stores the initial placement of the linked element.
17117 * @method setInitialPosition
17118 * @param {int} diffX the X offset, default 0
17119 * @param {int} diffY the Y offset, default 0
17121 setInitPosition: function(diffX, diffY) {
17122 var el = this.getEl();
17124 if (!this.DDM.verifyEl(el)) {
17128 var dx = diffX || 0;
17129 var dy = diffY || 0;
17131 var p = Dom.getXY( el );
17133 this.initPageX = p[0] - dx;
17134 this.initPageY = p[1] - dy;
17136 this.lastPageX = p[0];
17137 this.lastPageY = p[1];
17140 this.setStartPosition(p);
17144 * Sets the start position of the element. This is set when the obj
17145 * is initialized, the reset when a drag is started.
17146 * @method setStartPosition
17147 * @param pos current position (from previous lookup)
17150 setStartPosition: function(pos) {
17151 var p = pos || Dom.getXY( this.getEl() );
17152 this.deltaSetXY = null;
17154 this.startPageX = p[0];
17155 this.startPageY = p[1];
17159 * Add this instance to a group of related drag/drop objects. All
17160 * instances belong to at least one group, and can belong to as many
17161 * groups as needed.
17162 * @method addToGroup
17163 * @param sGroup {string} the name of the group
17165 addToGroup: function(sGroup) {
17166 this.groups[sGroup] = true;
17167 this.DDM.regDragDrop(this, sGroup);
17171 * Remove's this instance from the supplied interaction group
17172 * @method removeFromGroup
17173 * @param {string} sGroup The group to drop
17175 removeFromGroup: function(sGroup) {
17176 if (this.groups[sGroup]) {
17177 delete this.groups[sGroup];
17180 this.DDM.removeDDFromGroup(this, sGroup);
17184 * Allows you to specify that an element other than the linked element
17185 * will be moved with the cursor during a drag
17186 * @method setDragElId
17187 * @param id {string} the id of the element that will be used to initiate the drag
17189 setDragElId: function(id) {
17190 this.dragElId = id;
17194 * Allows you to specify a child of the linked element that should be
17195 * used to initiate the drag operation. An example of this would be if
17196 * you have a content div with text and links. Clicking anywhere in the
17197 * content area would normally start the drag operation. Use this method
17198 * to specify that an element inside of the content div is the element
17199 * that starts the drag operation.
17200 * @method setHandleElId
17201 * @param id {string} the id of the element that will be used to
17202 * initiate the drag.
17204 setHandleElId: function(id) {
17205 if (typeof id !== "string") {
17208 this.handleElId = id;
17209 this.DDM.regHandle(this.id, id);
17213 * Allows you to set an element outside of the linked element as a drag
17215 * @method setOuterHandleElId
17216 * @param id the id of the element that will be used to initiate the drag
17218 setOuterHandleElId: function(id) {
17219 if (typeof id !== "string") {
17222 Event.on(id, "mousedown",
17223 this.handleMouseDown, this);
17224 this.setHandleElId(id);
17226 this.hasOuterHandles = true;
17230 * Remove all drag and drop hooks for this element
17233 unreg: function() {
17234 Event.un(this.id, "mousedown",
17235 this.handleMouseDown);
17236 Event.un(this.id, "touchstart",
17237 this.handleMouseDown);
17238 this._domRef = null;
17239 this.DDM._remove(this);
17242 destroy : function(){
17247 * Returns true if this instance is locked, or the drag drop mgr is locked
17248 * (meaning that all drag/drop is disabled on the page.)
17250 * @return {boolean} true if this obj or all drag/drop is locked, else
17253 isLocked: function() {
17254 return (this.DDM.isLocked() || this.locked);
17258 * Fired when this object is clicked
17259 * @method handleMouseDown
17261 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
17264 handleMouseDown: function(e, oDD){
17266 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
17267 //Roo.log('not touch/ button !=0');
17270 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
17271 return; // double touch..
17275 if (this.isLocked()) {
17276 //Roo.log('locked');
17280 this.DDM.refreshCache(this.groups);
17281 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
17282 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
17283 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
17284 //Roo.log('no outer handes or not over target');
17287 // Roo.log('check validator');
17288 if (this.clickValidator(e)) {
17289 // Roo.log('validate success');
17290 // set the initial element position
17291 this.setStartPosition();
17294 this.b4MouseDown(e);
17295 this.onMouseDown(e);
17297 this.DDM.handleMouseDown(e, this);
17299 this.DDM.stopEvent(e);
17307 clickValidator: function(e) {
17308 var target = e.getTarget();
17309 return ( this.isValidHandleChild(target) &&
17310 (this.id == this.handleElId ||
17311 this.DDM.handleWasClicked(target, this.id)) );
17315 * Allows you to specify a tag name that should not start a drag operation
17316 * when clicked. This is designed to facilitate embedding links within a
17317 * drag handle that do something other than start the drag.
17318 * @method addInvalidHandleType
17319 * @param {string} tagName the type of element to exclude
17321 addInvalidHandleType: function(tagName) {
17322 var type = tagName.toUpperCase();
17323 this.invalidHandleTypes[type] = type;
17327 * Lets you to specify an element id for a child of a drag handle
17328 * that should not initiate a drag
17329 * @method addInvalidHandleId
17330 * @param {string} id the element id of the element you wish to ignore
17332 addInvalidHandleId: function(id) {
17333 if (typeof id !== "string") {
17336 this.invalidHandleIds[id] = id;
17340 * Lets you specify a css class of elements that will not initiate a drag
17341 * @method addInvalidHandleClass
17342 * @param {string} cssClass the class of the elements you wish to ignore
17344 addInvalidHandleClass: function(cssClass) {
17345 this.invalidHandleClasses.push(cssClass);
17349 * Unsets an excluded tag name set by addInvalidHandleType
17350 * @method removeInvalidHandleType
17351 * @param {string} tagName the type of element to unexclude
17353 removeInvalidHandleType: function(tagName) {
17354 var type = tagName.toUpperCase();
17355 // this.invalidHandleTypes[type] = null;
17356 delete this.invalidHandleTypes[type];
17360 * Unsets an invalid handle id
17361 * @method removeInvalidHandleId
17362 * @param {string} id the id of the element to re-enable
17364 removeInvalidHandleId: function(id) {
17365 if (typeof id !== "string") {
17368 delete this.invalidHandleIds[id];
17372 * Unsets an invalid css class
17373 * @method removeInvalidHandleClass
17374 * @param {string} cssClass the class of the element(s) you wish to
17377 removeInvalidHandleClass: function(cssClass) {
17378 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
17379 if (this.invalidHandleClasses[i] == cssClass) {
17380 delete this.invalidHandleClasses[i];
17386 * Checks the tag exclusion list to see if this click should be ignored
17387 * @method isValidHandleChild
17388 * @param {HTMLElement} node the HTMLElement to evaluate
17389 * @return {boolean} true if this is a valid tag type, false if not
17391 isValidHandleChild: function(node) {
17394 // var n = (node.nodeName == "#text") ? node.parentNode : node;
17397 nodeName = node.nodeName.toUpperCase();
17399 nodeName = node.nodeName;
17401 valid = valid && !this.invalidHandleTypes[nodeName];
17402 valid = valid && !this.invalidHandleIds[node.id];
17404 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
17405 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
17414 * Create the array of horizontal tick marks if an interval was specified
17415 * in setXConstraint().
17416 * @method setXTicks
17419 setXTicks: function(iStartX, iTickSize) {
17421 this.xTickSize = iTickSize;
17425 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
17427 this.xTicks[this.xTicks.length] = i;
17432 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
17434 this.xTicks[this.xTicks.length] = i;
17439 this.xTicks.sort(this.DDM.numericSort) ;
17443 * Create the array of vertical tick marks if an interval was specified in
17444 * setYConstraint().
17445 * @method setYTicks
17448 setYTicks: function(iStartY, iTickSize) {
17450 this.yTickSize = iTickSize;
17454 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
17456 this.yTicks[this.yTicks.length] = i;
17461 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
17463 this.yTicks[this.yTicks.length] = i;
17468 this.yTicks.sort(this.DDM.numericSort) ;
17472 * By default, the element can be dragged any place on the screen. Use
17473 * this method to limit the horizontal travel of the element. Pass in
17474 * 0,0 for the parameters if you want to lock the drag to the y axis.
17475 * @method setXConstraint
17476 * @param {int} iLeft the number of pixels the element can move to the left
17477 * @param {int} iRight the number of pixels the element can move to the
17479 * @param {int} iTickSize optional parameter for specifying that the
17481 * should move iTickSize pixels at a time.
17483 setXConstraint: function(iLeft, iRight, iTickSize) {
17484 this.leftConstraint = iLeft;
17485 this.rightConstraint = iRight;
17487 this.minX = this.initPageX - iLeft;
17488 this.maxX = this.initPageX + iRight;
17489 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
17491 this.constrainX = true;
17495 * Clears any constraints applied to this instance. Also clears ticks
17496 * since they can't exist independent of a constraint at this time.
17497 * @method clearConstraints
17499 clearConstraints: function() {
17500 this.constrainX = false;
17501 this.constrainY = false;
17506 * Clears any tick interval defined for this instance
17507 * @method clearTicks
17509 clearTicks: function() {
17510 this.xTicks = null;
17511 this.yTicks = null;
17512 this.xTickSize = 0;
17513 this.yTickSize = 0;
17517 * By default, the element can be dragged any place on the screen. Set
17518 * this to limit the vertical travel of the element. Pass in 0,0 for the
17519 * parameters if you want to lock the drag to the x axis.
17520 * @method setYConstraint
17521 * @param {int} iUp the number of pixels the element can move up
17522 * @param {int} iDown the number of pixels the element can move down
17523 * @param {int} iTickSize optional parameter for specifying that the
17524 * element should move iTickSize pixels at a time.
17526 setYConstraint: function(iUp, iDown, iTickSize) {
17527 this.topConstraint = iUp;
17528 this.bottomConstraint = iDown;
17530 this.minY = this.initPageY - iUp;
17531 this.maxY = this.initPageY + iDown;
17532 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
17534 this.constrainY = true;
17539 * resetConstraints must be called if you manually reposition a dd element.
17540 * @method resetConstraints
17541 * @param {boolean} maintainOffset
17543 resetConstraints: function() {
17546 // Maintain offsets if necessary
17547 if (this.initPageX || this.initPageX === 0) {
17548 // figure out how much this thing has moved
17549 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
17550 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
17552 this.setInitPosition(dx, dy);
17554 // This is the first time we have detected the element's position
17556 this.setInitPosition();
17559 if (this.constrainX) {
17560 this.setXConstraint( this.leftConstraint,
17561 this.rightConstraint,
17565 if (this.constrainY) {
17566 this.setYConstraint( this.topConstraint,
17567 this.bottomConstraint,
17573 * Normally the drag element is moved pixel by pixel, but we can specify
17574 * that it move a number of pixels at a time. This method resolves the
17575 * location when we have it set up like this.
17577 * @param {int} val where we want to place the object
17578 * @param {int[]} tickArray sorted array of valid points
17579 * @return {int} the closest tick
17582 getTick: function(val, tickArray) {
17585 // If tick interval is not defined, it is effectively 1 pixel,
17586 // so we return the value passed to us.
17588 } else if (tickArray[0] >= val) {
17589 // The value is lower than the first tick, so we return the first
17591 return tickArray[0];
17593 for (var i=0, len=tickArray.length; i<len; ++i) {
17595 if (tickArray[next] && tickArray[next] >= val) {
17596 var diff1 = val - tickArray[i];
17597 var diff2 = tickArray[next] - val;
17598 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
17602 // The value is larger than the last tick, so we return the last
17604 return tickArray[tickArray.length - 1];
17611 * @return {string} string representation of the dd obj
17613 toString: function() {
17614 return ("DragDrop " + this.id);
17622 * Ext JS Library 1.1.1
17623 * Copyright(c) 2006-2007, Ext JS, LLC.
17625 * Originally Released Under LGPL - original licence link has changed is not relivant.
17628 * <script type="text/javascript">
17633 * The drag and drop utility provides a framework for building drag and drop
17634 * applications. In addition to enabling drag and drop for specific elements,
17635 * the drag and drop elements are tracked by the manager class, and the
17636 * interactions between the various elements are tracked during the drag and
17637 * the implementing code is notified about these important moments.
17640 // Only load the library once. Rewriting the manager class would orphan
17641 // existing drag and drop instances.
17642 if (!Roo.dd.DragDropMgr) {
17645 * @class Roo.dd.DragDropMgr
17646 * DragDropMgr is a singleton that tracks the element interaction for
17647 * all DragDrop items in the window. Generally, you will not call
17648 * this class directly, but it does have helper methods that could
17649 * be useful in your DragDrop implementations.
17652 Roo.dd.DragDropMgr = function() {
17654 var Event = Roo.EventManager;
17659 * Two dimensional Array of registered DragDrop objects. The first
17660 * dimension is the DragDrop item group, the second the DragDrop
17663 * @type {string: string}
17670 * Array of element ids defined as drag handles. Used to determine
17671 * if the element that generated the mousedown event is actually the
17672 * handle and not the html element itself.
17673 * @property handleIds
17674 * @type {string: string}
17681 * the DragDrop object that is currently being dragged
17682 * @property dragCurrent
17690 * the DragDrop object(s) that are being hovered over
17691 * @property dragOvers
17699 * the X distance between the cursor and the object being dragged
17708 * the Y distance between the cursor and the object being dragged
17717 * Flag to determine if we should prevent the default behavior of the
17718 * events we define. By default this is true, but this can be set to
17719 * false if you need the default behavior (not recommended)
17720 * @property preventDefault
17724 preventDefault: true,
17727 * Flag to determine if we should stop the propagation of the events
17728 * we generate. This is true by default but you may want to set it to
17729 * false if the html element contains other features that require the
17731 * @property stopPropagation
17735 stopPropagation: true,
17738 * Internal flag that is set to true when drag and drop has been
17740 * @property initialized
17747 * All drag and drop can be disabled.
17755 * Called the first time an element is registered.
17761 this.initialized = true;
17765 * In point mode, drag and drop interaction is defined by the
17766 * location of the cursor during the drag/drop
17774 * In intersect mode, drag and drop interactio nis defined by the
17775 * overlap of two or more drag and drop objects.
17776 * @property INTERSECT
17783 * The current drag and drop mode. Default: POINT
17791 * Runs method on all drag and drop objects
17792 * @method _execOnAll
17796 _execOnAll: function(sMethod, args) {
17797 for (var i in this.ids) {
17798 for (var j in this.ids[i]) {
17799 var oDD = this.ids[i][j];
17800 if (! this.isTypeOfDD(oDD)) {
17803 oDD[sMethod].apply(oDD, args);
17809 * Drag and drop initialization. Sets up the global event handlers
17814 _onLoad: function() {
17818 if (!Roo.isTouch) {
17819 Event.on(document, "mouseup", this.handleMouseUp, this, true);
17820 Event.on(document, "mousemove", this.handleMouseMove, this, true);
17822 Event.on(document, "touchend", this.handleMouseUp, this, true);
17823 Event.on(document, "touchmove", this.handleMouseMove, this, true);
17825 Event.on(window, "unload", this._onUnload, this, true);
17826 Event.on(window, "resize", this._onResize, this, true);
17827 // Event.on(window, "mouseout", this._test);
17832 * Reset constraints on all drag and drop objs
17833 * @method _onResize
17837 _onResize: function(e) {
17838 this._execOnAll("resetConstraints", []);
17842 * Lock all drag and drop functionality
17846 lock: function() { this.locked = true; },
17849 * Unlock all drag and drop functionality
17853 unlock: function() { this.locked = false; },
17856 * Is drag and drop locked?
17858 * @return {boolean} True if drag and drop is locked, false otherwise.
17861 isLocked: function() { return this.locked; },
17864 * Location cache that is set for all drag drop objects when a drag is
17865 * initiated, cleared when the drag is finished.
17866 * @property locationCache
17873 * Set useCache to false if you want to force object the lookup of each
17874 * drag and drop linked element constantly during a drag.
17875 * @property useCache
17882 * The number of pixels that the mouse needs to move after the
17883 * mousedown before the drag is initiated. Default=3;
17884 * @property clickPixelThresh
17888 clickPixelThresh: 3,
17891 * The number of milliseconds after the mousedown event to initiate the
17892 * drag if we don't get a mouseup event. Default=1000
17893 * @property clickTimeThresh
17897 clickTimeThresh: 350,
17900 * Flag that indicates that either the drag pixel threshold or the
17901 * mousdown time threshold has been met
17902 * @property dragThreshMet
17907 dragThreshMet: false,
17910 * Timeout used for the click time threshold
17911 * @property clickTimeout
17916 clickTimeout: null,
17919 * The X position of the mousedown event stored for later use when a
17920 * drag threshold is met.
17929 * The Y position of the mousedown event stored for later use when a
17930 * drag threshold is met.
17939 * Each DragDrop instance must be registered with the DragDropMgr.
17940 * This is executed in DragDrop.init()
17941 * @method regDragDrop
17942 * @param {DragDrop} oDD the DragDrop object to register
17943 * @param {String} sGroup the name of the group this element belongs to
17946 regDragDrop: function(oDD, sGroup) {
17947 if (!this.initialized) { this.init(); }
17949 if (!this.ids[sGroup]) {
17950 this.ids[sGroup] = {};
17952 this.ids[sGroup][oDD.id] = oDD;
17956 * Removes the supplied dd instance from the supplied group. Executed
17957 * by DragDrop.removeFromGroup, so don't call this function directly.
17958 * @method removeDDFromGroup
17962 removeDDFromGroup: function(oDD, sGroup) {
17963 if (!this.ids[sGroup]) {
17964 this.ids[sGroup] = {};
17967 var obj = this.ids[sGroup];
17968 if (obj && obj[oDD.id]) {
17969 delete obj[oDD.id];
17974 * Unregisters a drag and drop item. This is executed in
17975 * DragDrop.unreg, use that method instead of calling this directly.
17980 _remove: function(oDD) {
17981 for (var g in oDD.groups) {
17982 if (g && this.ids[g][oDD.id]) {
17983 delete this.ids[g][oDD.id];
17986 delete this.handleIds[oDD.id];
17990 * Each DragDrop handle element must be registered. This is done
17991 * automatically when executing DragDrop.setHandleElId()
17992 * @method regHandle
17993 * @param {String} sDDId the DragDrop id this element is a handle for
17994 * @param {String} sHandleId the id of the element that is the drag
17998 regHandle: function(sDDId, sHandleId) {
17999 if (!this.handleIds[sDDId]) {
18000 this.handleIds[sDDId] = {};
18002 this.handleIds[sDDId][sHandleId] = sHandleId;
18006 * Utility function to determine if a given element has been
18007 * registered as a drag drop item.
18008 * @method isDragDrop
18009 * @param {String} id the element id to check
18010 * @return {boolean} true if this element is a DragDrop item,
18014 isDragDrop: function(id) {
18015 return ( this.getDDById(id) ) ? true : false;
18019 * Returns the drag and drop instances that are in all groups the
18020 * passed in instance belongs to.
18021 * @method getRelated
18022 * @param {DragDrop} p_oDD the obj to get related data for
18023 * @param {boolean} bTargetsOnly if true, only return targetable objs
18024 * @return {DragDrop[]} the related instances
18027 getRelated: function(p_oDD, bTargetsOnly) {
18029 for (var i in p_oDD.groups) {
18030 for (j in this.ids[i]) {
18031 var dd = this.ids[i][j];
18032 if (! this.isTypeOfDD(dd)) {
18035 if (!bTargetsOnly || dd.isTarget) {
18036 oDDs[oDDs.length] = dd;
18045 * Returns true if the specified dd target is a legal target for
18046 * the specifice drag obj
18047 * @method isLegalTarget
18048 * @param {DragDrop} the drag obj
18049 * @param {DragDrop} the target
18050 * @return {boolean} true if the target is a legal target for the
18054 isLegalTarget: function (oDD, oTargetDD) {
18055 var targets = this.getRelated(oDD, true);
18056 for (var i=0, len=targets.length;i<len;++i) {
18057 if (targets[i].id == oTargetDD.id) {
18066 * My goal is to be able to transparently determine if an object is
18067 * typeof DragDrop, and the exact subclass of DragDrop. typeof
18068 * returns "object", oDD.constructor.toString() always returns
18069 * "DragDrop" and not the name of the subclass. So for now it just
18070 * evaluates a well-known variable in DragDrop.
18071 * @method isTypeOfDD
18072 * @param {Object} the object to evaluate
18073 * @return {boolean} true if typeof oDD = DragDrop
18076 isTypeOfDD: function (oDD) {
18077 return (oDD && oDD.__ygDragDrop);
18081 * Utility function to determine if a given element has been
18082 * registered as a drag drop handle for the given Drag Drop object.
18084 * @param {String} id the element id to check
18085 * @return {boolean} true if this element is a DragDrop handle, false
18089 isHandle: function(sDDId, sHandleId) {
18090 return ( this.handleIds[sDDId] &&
18091 this.handleIds[sDDId][sHandleId] );
18095 * Returns the DragDrop instance for a given id
18096 * @method getDDById
18097 * @param {String} id the id of the DragDrop object
18098 * @return {DragDrop} the drag drop object, null if it is not found
18101 getDDById: function(id) {
18102 for (var i in this.ids) {
18103 if (this.ids[i][id]) {
18104 return this.ids[i][id];
18111 * Fired after a registered DragDrop object gets the mousedown event.
18112 * Sets up the events required to track the object being dragged
18113 * @method handleMouseDown
18114 * @param {Event} e the event
18115 * @param oDD the DragDrop object being dragged
18119 handleMouseDown: function(e, oDD) {
18121 Roo.QuickTips.disable();
18123 this.currentTarget = e.getTarget();
18125 this.dragCurrent = oDD;
18127 var el = oDD.getEl();
18129 // track start position
18130 this.startX = e.getPageX();
18131 this.startY = e.getPageY();
18133 this.deltaX = this.startX - el.offsetLeft;
18134 this.deltaY = this.startY - el.offsetTop;
18136 this.dragThreshMet = false;
18138 this.clickTimeout = setTimeout(
18140 var DDM = Roo.dd.DDM;
18141 DDM.startDrag(DDM.startX, DDM.startY);
18143 this.clickTimeThresh );
18147 * Fired when either the drag pixel threshol or the mousedown hold
18148 * time threshold has been met.
18149 * @method startDrag
18150 * @param x {int} the X position of the original mousedown
18151 * @param y {int} the Y position of the original mousedown
18154 startDrag: function(x, y) {
18155 clearTimeout(this.clickTimeout);
18156 if (this.dragCurrent) {
18157 this.dragCurrent.b4StartDrag(x, y);
18158 this.dragCurrent.startDrag(x, y);
18160 this.dragThreshMet = true;
18164 * Internal function to handle the mouseup event. Will be invoked
18165 * from the context of the document.
18166 * @method handleMouseUp
18167 * @param {Event} e the event
18171 handleMouseUp: function(e) {
18174 Roo.QuickTips.enable();
18176 if (! this.dragCurrent) {
18180 clearTimeout(this.clickTimeout);
18182 if (this.dragThreshMet) {
18183 this.fireEvents(e, true);
18193 * Utility to stop event propagation and event default, if these
18194 * features are turned on.
18195 * @method stopEvent
18196 * @param {Event} e the event as returned by this.getEvent()
18199 stopEvent: function(e){
18200 if(this.stopPropagation) {
18201 e.stopPropagation();
18204 if (this.preventDefault) {
18205 e.preventDefault();
18210 * Internal function to clean up event handlers after the drag
18211 * operation is complete
18213 * @param {Event} e the event
18217 stopDrag: function(e) {
18218 // Fire the drag end event for the item that was dragged
18219 if (this.dragCurrent) {
18220 if (this.dragThreshMet) {
18221 this.dragCurrent.b4EndDrag(e);
18222 this.dragCurrent.endDrag(e);
18225 this.dragCurrent.onMouseUp(e);
18228 this.dragCurrent = null;
18229 this.dragOvers = {};
18233 * Internal function to handle the mousemove event. Will be invoked
18234 * from the context of the html element.
18236 * @TODO figure out what we can do about mouse events lost when the
18237 * user drags objects beyond the window boundary. Currently we can
18238 * detect this in internet explorer by verifying that the mouse is
18239 * down during the mousemove event. Firefox doesn't give us the
18240 * button state on the mousemove event.
18241 * @method handleMouseMove
18242 * @param {Event} e the event
18246 handleMouseMove: function(e) {
18247 if (! this.dragCurrent) {
18251 // var button = e.which || e.button;
18253 // check for IE mouseup outside of page boundary
18254 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
18256 return this.handleMouseUp(e);
18259 if (!this.dragThreshMet) {
18260 var diffX = Math.abs(this.startX - e.getPageX());
18261 var diffY = Math.abs(this.startY - e.getPageY());
18262 if (diffX > this.clickPixelThresh ||
18263 diffY > this.clickPixelThresh) {
18264 this.startDrag(this.startX, this.startY);
18268 if (this.dragThreshMet) {
18269 this.dragCurrent.b4Drag(e);
18270 this.dragCurrent.onDrag(e);
18271 if(!this.dragCurrent.moveOnly){
18272 this.fireEvents(e, false);
18282 * Iterates over all of the DragDrop elements to find ones we are
18283 * hovering over or dropping on
18284 * @method fireEvents
18285 * @param {Event} e the event
18286 * @param {boolean} isDrop is this a drop op or a mouseover op?
18290 fireEvents: function(e, isDrop) {
18291 var dc = this.dragCurrent;
18293 // If the user did the mouse up outside of the window, we could
18294 // get here even though we have ended the drag.
18295 if (!dc || dc.isLocked()) {
18299 var pt = e.getPoint();
18301 // cache the previous dragOver array
18307 var enterEvts = [];
18309 // Check to see if the object(s) we were hovering over is no longer
18310 // being hovered over so we can fire the onDragOut event
18311 for (var i in this.dragOvers) {
18313 var ddo = this.dragOvers[i];
18315 if (! this.isTypeOfDD(ddo)) {
18319 if (! this.isOverTarget(pt, ddo, this.mode)) {
18320 outEvts.push( ddo );
18323 oldOvers[i] = true;
18324 delete this.dragOvers[i];
18327 for (var sGroup in dc.groups) {
18329 if ("string" != typeof sGroup) {
18333 for (i in this.ids[sGroup]) {
18334 var oDD = this.ids[sGroup][i];
18335 if (! this.isTypeOfDD(oDD)) {
18339 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
18340 if (this.isOverTarget(pt, oDD, this.mode)) {
18341 // look for drop interactions
18343 dropEvts.push( oDD );
18344 // look for drag enter and drag over interactions
18347 // initial drag over: dragEnter fires
18348 if (!oldOvers[oDD.id]) {
18349 enterEvts.push( oDD );
18350 // subsequent drag overs: dragOver fires
18352 overEvts.push( oDD );
18355 this.dragOvers[oDD.id] = oDD;
18363 if (outEvts.length) {
18364 dc.b4DragOut(e, outEvts);
18365 dc.onDragOut(e, outEvts);
18368 if (enterEvts.length) {
18369 dc.onDragEnter(e, enterEvts);
18372 if (overEvts.length) {
18373 dc.b4DragOver(e, overEvts);
18374 dc.onDragOver(e, overEvts);
18377 if (dropEvts.length) {
18378 dc.b4DragDrop(e, dropEvts);
18379 dc.onDragDrop(e, dropEvts);
18383 // fire dragout events
18385 for (i=0, len=outEvts.length; i<len; ++i) {
18386 dc.b4DragOut(e, outEvts[i].id);
18387 dc.onDragOut(e, outEvts[i].id);
18390 // fire enter events
18391 for (i=0,len=enterEvts.length; i<len; ++i) {
18392 // dc.b4DragEnter(e, oDD.id);
18393 dc.onDragEnter(e, enterEvts[i].id);
18396 // fire over events
18397 for (i=0,len=overEvts.length; i<len; ++i) {
18398 dc.b4DragOver(e, overEvts[i].id);
18399 dc.onDragOver(e, overEvts[i].id);
18402 // fire drop events
18403 for (i=0, len=dropEvts.length; i<len; ++i) {
18404 dc.b4DragDrop(e, dropEvts[i].id);
18405 dc.onDragDrop(e, dropEvts[i].id);
18410 // notify about a drop that did not find a target
18411 if (isDrop && !dropEvts.length) {
18412 dc.onInvalidDrop(e);
18418 * Helper function for getting the best match from the list of drag
18419 * and drop objects returned by the drag and drop events when we are
18420 * in INTERSECT mode. It returns either the first object that the
18421 * cursor is over, or the object that has the greatest overlap with
18422 * the dragged element.
18423 * @method getBestMatch
18424 * @param {DragDrop[]} dds The array of drag and drop objects
18426 * @return {DragDrop} The best single match
18429 getBestMatch: function(dds) {
18431 // Return null if the input is not what we expect
18432 //if (!dds || !dds.length || dds.length == 0) {
18434 // If there is only one item, it wins
18435 //} else if (dds.length == 1) {
18437 var len = dds.length;
18442 // Loop through the targeted items
18443 for (var i=0; i<len; ++i) {
18445 // If the cursor is over the object, it wins. If the
18446 // cursor is over multiple matches, the first one we come
18448 if (dd.cursorIsOver) {
18451 // Otherwise the object with the most overlap wins
18454 winner.overlap.getArea() < dd.overlap.getArea()) {
18465 * Refreshes the cache of the top-left and bottom-right points of the
18466 * drag and drop objects in the specified group(s). This is in the
18467 * format that is stored in the drag and drop instance, so typical
18470 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
18474 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
18476 * @TODO this really should be an indexed array. Alternatively this
18477 * method could accept both.
18478 * @method refreshCache
18479 * @param {Object} groups an associative array of groups to refresh
18482 refreshCache: function(groups) {
18483 for (var sGroup in groups) {
18484 if ("string" != typeof sGroup) {
18487 for (var i in this.ids[sGroup]) {
18488 var oDD = this.ids[sGroup][i];
18490 if (this.isTypeOfDD(oDD)) {
18491 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
18492 var loc = this.getLocation(oDD);
18494 this.locationCache[oDD.id] = loc;
18496 delete this.locationCache[oDD.id];
18497 // this will unregister the drag and drop object if
18498 // the element is not in a usable state
18507 * This checks to make sure an element exists and is in the DOM. The
18508 * main purpose is to handle cases where innerHTML is used to remove
18509 * drag and drop objects from the DOM. IE provides an 'unspecified
18510 * error' when trying to access the offsetParent of such an element
18512 * @param {HTMLElement} el the element to check
18513 * @return {boolean} true if the element looks usable
18516 verifyEl: function(el) {
18521 parent = el.offsetParent;
18524 parent = el.offsetParent;
18535 * Returns a Region object containing the drag and drop element's position
18536 * and size, including the padding configured for it
18537 * @method getLocation
18538 * @param {DragDrop} oDD the drag and drop object to get the
18540 * @return {Roo.lib.Region} a Region object representing the total area
18541 * the element occupies, including any padding
18542 * the instance is configured for.
18545 getLocation: function(oDD) {
18546 if (! this.isTypeOfDD(oDD)) {
18550 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
18553 pos= Roo.lib.Dom.getXY(el);
18561 x2 = x1 + el.offsetWidth;
18563 y2 = y1 + el.offsetHeight;
18565 t = y1 - oDD.padding[0];
18566 r = x2 + oDD.padding[1];
18567 b = y2 + oDD.padding[2];
18568 l = x1 - oDD.padding[3];
18570 return new Roo.lib.Region( t, r, b, l );
18574 * Checks the cursor location to see if it over the target
18575 * @method isOverTarget
18576 * @param {Roo.lib.Point} pt The point to evaluate
18577 * @param {DragDrop} oTarget the DragDrop object we are inspecting
18578 * @return {boolean} true if the mouse is over the target
18582 isOverTarget: function(pt, oTarget, intersect) {
18583 // use cache if available
18584 var loc = this.locationCache[oTarget.id];
18585 if (!loc || !this.useCache) {
18586 loc = this.getLocation(oTarget);
18587 this.locationCache[oTarget.id] = loc;
18595 oTarget.cursorIsOver = loc.contains( pt );
18597 // DragDrop is using this as a sanity check for the initial mousedown
18598 // in this case we are done. In POINT mode, if the drag obj has no
18599 // contraints, we are also done. Otherwise we need to evaluate the
18600 // location of the target as related to the actual location of the
18601 // dragged element.
18602 var dc = this.dragCurrent;
18603 if (!dc || !dc.getTargetCoord ||
18604 (!intersect && !dc.constrainX && !dc.constrainY)) {
18605 return oTarget.cursorIsOver;
18608 oTarget.overlap = null;
18610 // Get the current location of the drag element, this is the
18611 // location of the mouse event less the delta that represents
18612 // where the original mousedown happened on the element. We
18613 // need to consider constraints and ticks as well.
18614 var pos = dc.getTargetCoord(pt.x, pt.y);
18616 var el = dc.getDragEl();
18617 var curRegion = new Roo.lib.Region( pos.y,
18618 pos.x + el.offsetWidth,
18619 pos.y + el.offsetHeight,
18622 var overlap = curRegion.intersect(loc);
18625 oTarget.overlap = overlap;
18626 return (intersect) ? true : oTarget.cursorIsOver;
18633 * unload event handler
18634 * @method _onUnload
18638 _onUnload: function(e, me) {
18639 Roo.dd.DragDropMgr.unregAll();
18643 * Cleans up the drag and drop events and objects.
18648 unregAll: function() {
18650 if (this.dragCurrent) {
18652 this.dragCurrent = null;
18655 this._execOnAll("unreg", []);
18657 for (i in this.elementCache) {
18658 delete this.elementCache[i];
18661 this.elementCache = {};
18666 * A cache of DOM elements
18667 * @property elementCache
18674 * Get the wrapper for the DOM element specified
18675 * @method getElWrapper
18676 * @param {String} id the id of the element to get
18677 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
18679 * @deprecated This wrapper isn't that useful
18682 getElWrapper: function(id) {
18683 var oWrapper = this.elementCache[id];
18684 if (!oWrapper || !oWrapper.el) {
18685 oWrapper = this.elementCache[id] =
18686 new this.ElementWrapper(Roo.getDom(id));
18692 * Returns the actual DOM element
18693 * @method getElement
18694 * @param {String} id the id of the elment to get
18695 * @return {Object} The element
18696 * @deprecated use Roo.getDom instead
18699 getElement: function(id) {
18700 return Roo.getDom(id);
18704 * Returns the style property for the DOM element (i.e.,
18705 * document.getElById(id).style)
18707 * @param {String} id the id of the elment to get
18708 * @return {Object} The style property of the element
18709 * @deprecated use Roo.getDom instead
18712 getCss: function(id) {
18713 var el = Roo.getDom(id);
18714 return (el) ? el.style : null;
18718 * Inner class for cached elements
18719 * @class DragDropMgr.ElementWrapper
18724 ElementWrapper: function(el) {
18729 this.el = el || null;
18734 this.id = this.el && el.id;
18736 * A reference to the style property
18739 this.css = this.el && el.style;
18743 * Returns the X position of an html element
18745 * @param el the element for which to get the position
18746 * @return {int} the X coordinate
18748 * @deprecated use Roo.lib.Dom.getX instead
18751 getPosX: function(el) {
18752 return Roo.lib.Dom.getX(el);
18756 * Returns the Y position of an html element
18758 * @param el the element for which to get the position
18759 * @return {int} the Y coordinate
18760 * @deprecated use Roo.lib.Dom.getY instead
18763 getPosY: function(el) {
18764 return Roo.lib.Dom.getY(el);
18768 * Swap two nodes. In IE, we use the native method, for others we
18769 * emulate the IE behavior
18771 * @param n1 the first node to swap
18772 * @param n2 the other node to swap
18775 swapNode: function(n1, n2) {
18779 var p = n2.parentNode;
18780 var s = n2.nextSibling;
18783 p.insertBefore(n1, n2);
18784 } else if (n2 == n1.nextSibling) {
18785 p.insertBefore(n2, n1);
18787 n1.parentNode.replaceChild(n2, n1);
18788 p.insertBefore(n1, s);
18794 * Returns the current scroll position
18795 * @method getScroll
18799 getScroll: function () {
18800 var t, l, dde=document.documentElement, db=document.body;
18801 if (dde && (dde.scrollTop || dde.scrollLeft)) {
18803 l = dde.scrollLeft;
18810 return { top: t, left: l };
18814 * Returns the specified element style property
18816 * @param {HTMLElement} el the element
18817 * @param {string} styleProp the style property
18818 * @return {string} The value of the style property
18819 * @deprecated use Roo.lib.Dom.getStyle
18822 getStyle: function(el, styleProp) {
18823 return Roo.fly(el).getStyle(styleProp);
18827 * Gets the scrollTop
18828 * @method getScrollTop
18829 * @return {int} the document's scrollTop
18832 getScrollTop: function () { return this.getScroll().top; },
18835 * Gets the scrollLeft
18836 * @method getScrollLeft
18837 * @return {int} the document's scrollTop
18840 getScrollLeft: function () { return this.getScroll().left; },
18843 * Sets the x/y position of an element to the location of the
18846 * @param {HTMLElement} moveEl The element to move
18847 * @param {HTMLElement} targetEl The position reference element
18850 moveToEl: function (moveEl, targetEl) {
18851 var aCoord = Roo.lib.Dom.getXY(targetEl);
18852 Roo.lib.Dom.setXY(moveEl, aCoord);
18856 * Numeric array sort function
18857 * @method numericSort
18860 numericSort: function(a, b) { return (a - b); },
18864 * @property _timeoutCount
18871 * Trying to make the load order less important. Without this we get
18872 * an error if this file is loaded before the Event Utility.
18873 * @method _addListeners
18877 _addListeners: function() {
18878 var DDM = Roo.dd.DDM;
18879 if ( Roo.lib.Event && document ) {
18882 if (DDM._timeoutCount > 2000) {
18884 setTimeout(DDM._addListeners, 10);
18885 if (document && document.body) {
18886 DDM._timeoutCount += 1;
18893 * Recursively searches the immediate parent and all child nodes for
18894 * the handle element in order to determine wheter or not it was
18896 * @method handleWasClicked
18897 * @param node the html element to inspect
18900 handleWasClicked: function(node, id) {
18901 if (this.isHandle(id, node.id)) {
18904 // check to see if this is a text node child of the one we want
18905 var p = node.parentNode;
18908 if (this.isHandle(id, p.id)) {
18923 // shorter alias, save a few bytes
18924 Roo.dd.DDM = Roo.dd.DragDropMgr;
18925 Roo.dd.DDM._addListeners();
18929 * Ext JS Library 1.1.1
18930 * Copyright(c) 2006-2007, Ext JS, LLC.
18932 * Originally Released Under LGPL - original licence link has changed is not relivant.
18935 * <script type="text/javascript">
18940 * A DragDrop implementation where the linked element follows the
18941 * mouse cursor during a drag.
18942 * @extends Roo.dd.DragDrop
18944 * @param {String} id the id of the linked element
18945 * @param {String} sGroup the group of related DragDrop items
18946 * @param {object} config an object containing configurable attributes
18947 * Valid properties for DD:
18950 Roo.dd.DD = function(id, sGroup, config) {
18952 this.init(id, sGroup, config);
18956 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
18959 * When set to true, the utility automatically tries to scroll the browser
18960 * window wehn a drag and drop element is dragged near the viewport boundary.
18961 * Defaults to true.
18968 * Sets the pointer offset to the distance between the linked element's top
18969 * left corner and the location the element was clicked
18970 * @method autoOffset
18971 * @param {int} iPageX the X coordinate of the click
18972 * @param {int} iPageY the Y coordinate of the click
18974 autoOffset: function(iPageX, iPageY) {
18975 var x = iPageX - this.startPageX;
18976 var y = iPageY - this.startPageY;
18977 this.setDelta(x, y);
18981 * Sets the pointer offset. You can call this directly to force the
18982 * offset to be in a particular location (e.g., pass in 0,0 to set it
18983 * to the center of the object)
18985 * @param {int} iDeltaX the distance from the left
18986 * @param {int} iDeltaY the distance from the top
18988 setDelta: function(iDeltaX, iDeltaY) {
18989 this.deltaX = iDeltaX;
18990 this.deltaY = iDeltaY;
18994 * Sets the drag element to the location of the mousedown or click event,
18995 * maintaining the cursor location relative to the location on the element
18996 * that was clicked. Override this if you want to place the element in a
18997 * location other than where the cursor is.
18998 * @method setDragElPos
18999 * @param {int} iPageX the X coordinate of the mousedown or drag event
19000 * @param {int} iPageY the Y coordinate of the mousedown or drag event
19002 setDragElPos: function(iPageX, iPageY) {
19003 // the first time we do this, we are going to check to make sure
19004 // the element has css positioning
19006 var el = this.getDragEl();
19007 this.alignElWithMouse(el, iPageX, iPageY);
19011 * Sets the element to the location of the mousedown or click event,
19012 * maintaining the cursor location relative to the location on the element
19013 * that was clicked. Override this if you want to place the element in a
19014 * location other than where the cursor is.
19015 * @method alignElWithMouse
19016 * @param {HTMLElement} el the element to move
19017 * @param {int} iPageX the X coordinate of the mousedown or drag event
19018 * @param {int} iPageY the Y coordinate of the mousedown or drag event
19020 alignElWithMouse: function(el, iPageX, iPageY) {
19021 var oCoord = this.getTargetCoord(iPageX, iPageY);
19022 var fly = el.dom ? el : Roo.fly(el);
19023 if (!this.deltaSetXY) {
19024 var aCoord = [oCoord.x, oCoord.y];
19026 var newLeft = fly.getLeft(true);
19027 var newTop = fly.getTop(true);
19028 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
19030 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
19033 this.cachePosition(oCoord.x, oCoord.y);
19034 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
19039 * Saves the most recent position so that we can reset the constraints and
19040 * tick marks on-demand. We need to know this so that we can calculate the
19041 * number of pixels the element is offset from its original position.
19042 * @method cachePosition
19043 * @param iPageX the current x position (optional, this just makes it so we
19044 * don't have to look it up again)
19045 * @param iPageY the current y position (optional, this just makes it so we
19046 * don't have to look it up again)
19048 cachePosition: function(iPageX, iPageY) {
19050 this.lastPageX = iPageX;
19051 this.lastPageY = iPageY;
19053 var aCoord = Roo.lib.Dom.getXY(this.getEl());
19054 this.lastPageX = aCoord[0];
19055 this.lastPageY = aCoord[1];
19060 * Auto-scroll the window if the dragged object has been moved beyond the
19061 * visible window boundary.
19062 * @method autoScroll
19063 * @param {int} x the drag element's x position
19064 * @param {int} y the drag element's y position
19065 * @param {int} h the height of the drag element
19066 * @param {int} w the width of the drag element
19069 autoScroll: function(x, y, h, w) {
19072 // The client height
19073 var clientH = Roo.lib.Dom.getViewWidth();
19075 // The client width
19076 var clientW = Roo.lib.Dom.getViewHeight();
19078 // The amt scrolled down
19079 var st = this.DDM.getScrollTop();
19081 // The amt scrolled right
19082 var sl = this.DDM.getScrollLeft();
19084 // Location of the bottom of the element
19087 // Location of the right of the element
19090 // The distance from the cursor to the bottom of the visible area,
19091 // adjusted so that we don't scroll if the cursor is beyond the
19092 // element drag constraints
19093 var toBot = (clientH + st - y - this.deltaY);
19095 // The distance from the cursor to the right of the visible area
19096 var toRight = (clientW + sl - x - this.deltaX);
19099 // How close to the edge the cursor must be before we scroll
19100 // var thresh = (document.all) ? 100 : 40;
19103 // How many pixels to scroll per autoscroll op. This helps to reduce
19104 // clunky scrolling. IE is more sensitive about this ... it needs this
19105 // value to be higher.
19106 var scrAmt = (document.all) ? 80 : 30;
19108 // Scroll down if we are near the bottom of the visible page and the
19109 // obj extends below the crease
19110 if ( bot > clientH && toBot < thresh ) {
19111 window.scrollTo(sl, st + scrAmt);
19114 // Scroll up if the window is scrolled down and the top of the object
19115 // goes above the top border
19116 if ( y < st && st > 0 && y - st < thresh ) {
19117 window.scrollTo(sl, st - scrAmt);
19120 // Scroll right if the obj is beyond the right border and the cursor is
19121 // near the border.
19122 if ( right > clientW && toRight < thresh ) {
19123 window.scrollTo(sl + scrAmt, st);
19126 // Scroll left if the window has been scrolled to the right and the obj
19127 // extends past the left border
19128 if ( x < sl && sl > 0 && x - sl < thresh ) {
19129 window.scrollTo(sl - scrAmt, st);
19135 * Finds the location the element should be placed if we want to move
19136 * it to where the mouse location less the click offset would place us.
19137 * @method getTargetCoord
19138 * @param {int} iPageX the X coordinate of the click
19139 * @param {int} iPageY the Y coordinate of the click
19140 * @return an object that contains the coordinates (Object.x and Object.y)
19143 getTargetCoord: function(iPageX, iPageY) {
19146 var x = iPageX - this.deltaX;
19147 var y = iPageY - this.deltaY;
19149 if (this.constrainX) {
19150 if (x < this.minX) { x = this.minX; }
19151 if (x > this.maxX) { x = this.maxX; }
19154 if (this.constrainY) {
19155 if (y < this.minY) { y = this.minY; }
19156 if (y > this.maxY) { y = this.maxY; }
19159 x = this.getTick(x, this.xTicks);
19160 y = this.getTick(y, this.yTicks);
19167 * Sets up config options specific to this class. Overrides
19168 * Roo.dd.DragDrop, but all versions of this method through the
19169 * inheritance chain are called
19171 applyConfig: function() {
19172 Roo.dd.DD.superclass.applyConfig.call(this);
19173 this.scroll = (this.config.scroll !== false);
19177 * Event that fires prior to the onMouseDown event. Overrides
19180 b4MouseDown: function(e) {
19181 // this.resetConstraints();
19182 this.autoOffset(e.getPageX(),
19187 * Event that fires prior to the onDrag event. Overrides
19190 b4Drag: function(e) {
19191 this.setDragElPos(e.getPageX(),
19195 toString: function() {
19196 return ("DD " + this.id);
19199 //////////////////////////////////////////////////////////////////////////
19200 // Debugging ygDragDrop events that can be overridden
19201 //////////////////////////////////////////////////////////////////////////
19203 startDrag: function(x, y) {
19206 onDrag: function(e) {
19209 onDragEnter: function(e, id) {
19212 onDragOver: function(e, id) {
19215 onDragOut: function(e, id) {
19218 onDragDrop: function(e, id) {
19221 endDrag: function(e) {
19228 * Ext JS Library 1.1.1
19229 * Copyright(c) 2006-2007, Ext JS, LLC.
19231 * Originally Released Under LGPL - original licence link has changed is not relivant.
19234 * <script type="text/javascript">
19238 * @class Roo.dd.DDProxy
19239 * A DragDrop implementation that inserts an empty, bordered div into
19240 * the document that follows the cursor during drag operations. At the time of
19241 * the click, the frame div is resized to the dimensions of the linked html
19242 * element, and moved to the exact location of the linked element.
19244 * References to the "frame" element refer to the single proxy element that
19245 * was created to be dragged in place of all DDProxy elements on the
19248 * @extends Roo.dd.DD
19250 * @param {String} id the id of the linked html element
19251 * @param {String} sGroup the group of related DragDrop objects
19252 * @param {object} config an object containing configurable attributes
19253 * Valid properties for DDProxy in addition to those in DragDrop:
19254 * resizeFrame, centerFrame, dragElId
19256 Roo.dd.DDProxy = function(id, sGroup, config) {
19258 this.init(id, sGroup, config);
19264 * The default drag frame div id
19265 * @property Roo.dd.DDProxy.dragElId
19269 Roo.dd.DDProxy.dragElId = "ygddfdiv";
19271 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
19274 * By default we resize the drag frame to be the same size as the element
19275 * we want to drag (this is to get the frame effect). We can turn it off
19276 * if we want a different behavior.
19277 * @property resizeFrame
19283 * By default the frame is positioned exactly where the drag element is, so
19284 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
19285 * you do not have constraints on the obj is to have the drag frame centered
19286 * around the cursor. Set centerFrame to true for this effect.
19287 * @property centerFrame
19290 centerFrame: false,
19293 * Creates the proxy element if it does not yet exist
19294 * @method createFrame
19296 createFrame: function() {
19298 var body = document.body;
19300 if (!body || !body.firstChild) {
19301 setTimeout( function() { self.createFrame(); }, 50 );
19305 var div = this.getDragEl();
19308 div = document.createElement("div");
19309 div.id = this.dragElId;
19312 s.position = "absolute";
19313 s.visibility = "hidden";
19315 s.border = "2px solid #aaa";
19318 // appendChild can blow up IE if invoked prior to the window load event
19319 // while rendering a table. It is possible there are other scenarios
19320 // that would cause this to happen as well.
19321 body.insertBefore(div, body.firstChild);
19326 * Initialization for the drag frame element. Must be called in the
19327 * constructor of all subclasses
19328 * @method initFrame
19330 initFrame: function() {
19331 this.createFrame();
19334 applyConfig: function() {
19335 Roo.dd.DDProxy.superclass.applyConfig.call(this);
19337 this.resizeFrame = (this.config.resizeFrame !== false);
19338 this.centerFrame = (this.config.centerFrame);
19339 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
19343 * Resizes the drag frame to the dimensions of the clicked object, positions
19344 * it over the object, and finally displays it
19345 * @method showFrame
19346 * @param {int} iPageX X click position
19347 * @param {int} iPageY Y click position
19350 showFrame: function(iPageX, iPageY) {
19351 var el = this.getEl();
19352 var dragEl = this.getDragEl();
19353 var s = dragEl.style;
19355 this._resizeProxy();
19357 if (this.centerFrame) {
19358 this.setDelta( Math.round(parseInt(s.width, 10)/2),
19359 Math.round(parseInt(s.height, 10)/2) );
19362 this.setDragElPos(iPageX, iPageY);
19364 Roo.fly(dragEl).show();
19368 * The proxy is automatically resized to the dimensions of the linked
19369 * element when a drag is initiated, unless resizeFrame is set to false
19370 * @method _resizeProxy
19373 _resizeProxy: function() {
19374 if (this.resizeFrame) {
19375 var el = this.getEl();
19376 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
19380 // overrides Roo.dd.DragDrop
19381 b4MouseDown: function(e) {
19382 var x = e.getPageX();
19383 var y = e.getPageY();
19384 this.autoOffset(x, y);
19385 this.setDragElPos(x, y);
19388 // overrides Roo.dd.DragDrop
19389 b4StartDrag: function(x, y) {
19390 // show the drag frame
19391 this.showFrame(x, y);
19394 // overrides Roo.dd.DragDrop
19395 b4EndDrag: function(e) {
19396 Roo.fly(this.getDragEl()).hide();
19399 // overrides Roo.dd.DragDrop
19400 // By default we try to move the element to the last location of the frame.
19401 // This is so that the default behavior mirrors that of Roo.dd.DD.
19402 endDrag: function(e) {
19404 var lel = this.getEl();
19405 var del = this.getDragEl();
19407 // Show the drag frame briefly so we can get its position
19408 del.style.visibility = "";
19411 // Hide the linked element before the move to get around a Safari
19413 lel.style.visibility = "hidden";
19414 Roo.dd.DDM.moveToEl(lel, del);
19415 del.style.visibility = "hidden";
19416 lel.style.visibility = "";
19421 beforeMove : function(){
19425 afterDrag : function(){
19429 toString: function() {
19430 return ("DDProxy " + this.id);
19436 * Ext JS Library 1.1.1
19437 * Copyright(c) 2006-2007, Ext JS, LLC.
19439 * Originally Released Under LGPL - original licence link has changed is not relivant.
19442 * <script type="text/javascript">
19446 * @class Roo.dd.DDTarget
19447 * A DragDrop implementation that does not move, but can be a drop
19448 * target. You would get the same result by simply omitting implementation
19449 * for the event callbacks, but this way we reduce the processing cost of the
19450 * event listener and the callbacks.
19451 * @extends Roo.dd.DragDrop
19453 * @param {String} id the id of the element that is a drop target
19454 * @param {String} sGroup the group of related DragDrop objects
19455 * @param {object} config an object containing configurable attributes
19456 * Valid properties for DDTarget in addition to those in
19460 Roo.dd.DDTarget = function(id, sGroup, config) {
19462 this.initTarget(id, sGroup, config);
19464 if (config.listeners || config.events) {
19465 Roo.dd.DragDrop.superclass.constructor.call(this, {
19466 listeners : config.listeners || {},
19467 events : config.events || {}
19472 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
19473 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
19474 toString: function() {
19475 return ("DDTarget " + this.id);
19480 * Ext JS Library 1.1.1
19481 * Copyright(c) 2006-2007, Ext JS, LLC.
19483 * Originally Released Under LGPL - original licence link has changed is not relivant.
19486 * <script type="text/javascript">
19491 * @class Roo.dd.ScrollManager
19492 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
19493 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
19496 Roo.dd.ScrollManager = function(){
19497 var ddm = Roo.dd.DragDropMgr;
19504 var onStop = function(e){
19509 var triggerRefresh = function(){
19510 if(ddm.dragCurrent){
19511 ddm.refreshCache(ddm.dragCurrent.groups);
19515 var doScroll = function(){
19516 if(ddm.dragCurrent){
19517 var dds = Roo.dd.ScrollManager;
19519 if(proc.el.scroll(proc.dir, dds.increment)){
19523 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
19528 var clearProc = function(){
19530 clearInterval(proc.id);
19537 var startProc = function(el, dir){
19538 Roo.log('scroll startproc');
19542 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
19545 var onFire = function(e, isDrop){
19547 if(isDrop || !ddm.dragCurrent){ return; }
19548 var dds = Roo.dd.ScrollManager;
19549 if(!dragEl || dragEl != ddm.dragCurrent){
19550 dragEl = ddm.dragCurrent;
19551 // refresh regions on drag start
19552 dds.refreshCache();
19555 var xy = Roo.lib.Event.getXY(e);
19556 var pt = new Roo.lib.Point(xy[0], xy[1]);
19557 for(var id in els){
19558 var el = els[id], r = el._region;
19559 if(r && r.contains(pt) && el.isScrollable()){
19560 if(r.bottom - pt.y <= dds.thresh){
19562 startProc(el, "down");
19565 }else if(r.right - pt.x <= dds.thresh){
19567 startProc(el, "left");
19570 }else if(pt.y - r.top <= dds.thresh){
19572 startProc(el, "up");
19575 }else if(pt.x - r.left <= dds.thresh){
19577 startProc(el, "right");
19586 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
19587 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
19591 * Registers new overflow element(s) to auto scroll
19592 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
19594 register : function(el){
19595 if(el instanceof Array){
19596 for(var i = 0, len = el.length; i < len; i++) {
19597 this.register(el[i]);
19603 Roo.dd.ScrollManager.els = els;
19607 * Unregisters overflow element(s) so they are no longer scrolled
19608 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
19610 unregister : function(el){
19611 if(el instanceof Array){
19612 for(var i = 0, len = el.length; i < len; i++) {
19613 this.unregister(el[i]);
19622 * The number of pixels from the edge of a container the pointer needs to be to
19623 * trigger scrolling (defaults to 25)
19629 * The number of pixels to scroll in each scroll increment (defaults to 50)
19635 * The frequency of scrolls in milliseconds (defaults to 500)
19641 * True to animate the scroll (defaults to true)
19647 * The animation duration in seconds -
19648 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
19654 * Manually trigger a cache refresh.
19656 refreshCache : function(){
19657 for(var id in els){
19658 if(typeof els[id] == 'object'){ // for people extending the object prototype
19659 els[id]._region = els[id].getRegion();
19666 * Ext JS Library 1.1.1
19667 * Copyright(c) 2006-2007, Ext JS, LLC.
19669 * Originally Released Under LGPL - original licence link has changed is not relivant.
19672 * <script type="text/javascript">
19677 * @class Roo.dd.Registry
19678 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
19679 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
19682 Roo.dd.Registry = function(){
19685 var autoIdSeed = 0;
19687 var getId = function(el, autogen){
19688 if(typeof el == "string"){
19692 if(!id && autogen !== false){
19693 id = "roodd-" + (++autoIdSeed);
19701 * Register a drag drop element
19702 * @param {String|HTMLElement} element The id or DOM node to register
19703 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
19704 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
19705 * knows how to interpret, plus there are some specific properties known to the Registry that should be
19706 * populated in the data object (if applicable):
19708 Value Description<br />
19709 --------- ------------------------------------------<br />
19710 handles Array of DOM nodes that trigger dragging<br />
19711 for the element being registered<br />
19712 isHandle True if the element passed in triggers<br />
19713 dragging itself, else false
19716 register : function(el, data){
19718 if(typeof el == "string"){
19719 el = document.getElementById(el);
19722 elements[getId(el)] = data;
19723 if(data.isHandle !== false){
19724 handles[data.ddel.id] = data;
19727 var hs = data.handles;
19728 for(var i = 0, len = hs.length; i < len; i++){
19729 handles[getId(hs[i])] = data;
19735 * Unregister a drag drop element
19736 * @param {String|HTMLElement} element The id or DOM node to unregister
19738 unregister : function(el){
19739 var id = getId(el, false);
19740 var data = elements[id];
19742 delete elements[id];
19744 var hs = data.handles;
19745 for(var i = 0, len = hs.length; i < len; i++){
19746 delete handles[getId(hs[i], false)];
19753 * Returns the handle registered for a DOM Node by id
19754 * @param {String|HTMLElement} id The DOM node or id to look up
19755 * @return {Object} handle The custom handle data
19757 getHandle : function(id){
19758 if(typeof id != "string"){ // must be element?
19761 return handles[id];
19765 * Returns the handle that is registered for the DOM node that is the target of the event
19766 * @param {Event} e The event
19767 * @return {Object} handle The custom handle data
19769 getHandleFromEvent : function(e){
19770 var t = Roo.lib.Event.getTarget(e);
19771 return t ? handles[t.id] : null;
19775 * Returns a custom data object that is registered for a DOM node by id
19776 * @param {String|HTMLElement} id The DOM node or id to look up
19777 * @return {Object} data The custom data
19779 getTarget : function(id){
19780 if(typeof id != "string"){ // must be element?
19783 return elements[id];
19787 * Returns a custom data object that is registered for the DOM node that is the target of the event
19788 * @param {Event} e The event
19789 * @return {Object} data The custom data
19791 getTargetFromEvent : function(e){
19792 var t = Roo.lib.Event.getTarget(e);
19793 return t ? elements[t.id] || handles[t.id] : null;
19798 * Ext JS Library 1.1.1
19799 * Copyright(c) 2006-2007, Ext JS, LLC.
19801 * Originally Released Under LGPL - original licence link has changed is not relivant.
19804 * <script type="text/javascript">
19809 * @class Roo.dd.StatusProxy
19810 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
19811 * default drag proxy used by all Roo.dd components.
19813 * @param {Object} config
19815 Roo.dd.StatusProxy = function(config){
19816 Roo.apply(this, config);
19817 this.id = this.id || Roo.id();
19818 this.el = new Roo.Layer({
19820 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
19821 {tag: "div", cls: "x-dd-drop-icon"},
19822 {tag: "div", cls: "x-dd-drag-ghost"}
19825 shadow: !config || config.shadow !== false
19827 this.ghost = Roo.get(this.el.dom.childNodes[1]);
19828 this.dropStatus = this.dropNotAllowed;
19831 Roo.dd.StatusProxy.prototype = {
19833 * @cfg {String} dropAllowed
19834 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
19836 dropAllowed : "x-dd-drop-ok",
19838 * @cfg {String} dropNotAllowed
19839 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
19841 dropNotAllowed : "x-dd-drop-nodrop",
19844 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
19845 * over the current target element.
19846 * @param {String} cssClass The css class for the new drop status indicator image
19848 setStatus : function(cssClass){
19849 cssClass = cssClass || this.dropNotAllowed;
19850 if(this.dropStatus != cssClass){
19851 this.el.replaceClass(this.dropStatus, cssClass);
19852 this.dropStatus = cssClass;
19857 * Resets the status indicator to the default dropNotAllowed value
19858 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
19860 reset : function(clearGhost){
19861 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
19862 this.dropStatus = this.dropNotAllowed;
19864 this.ghost.update("");
19869 * Updates the contents of the ghost element
19870 * @param {String} html The html that will replace the current innerHTML of the ghost element
19872 update : function(html){
19873 if(typeof html == "string"){
19874 this.ghost.update(html);
19876 this.ghost.update("");
19877 html.style.margin = "0";
19878 this.ghost.dom.appendChild(html);
19880 // ensure float = none set?? cant remember why though.
19881 var el = this.ghost.dom.firstChild;
19883 Roo.fly(el).setStyle('float', 'none');
19888 * Returns the underlying proxy {@link Roo.Layer}
19889 * @return {Roo.Layer} el
19891 getEl : function(){
19896 * Returns the ghost element
19897 * @return {Roo.Element} el
19899 getGhost : function(){
19905 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
19907 hide : function(clear){
19915 * Stops the repair animation if it's currently running
19918 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
19924 * Displays this proxy
19931 * Force the Layer to sync its shadow and shim positions to the element
19938 * Causes the proxy to return to its position of origin via an animation. Should be called after an
19939 * invalid drop operation by the item being dragged.
19940 * @param {Array} xy The XY position of the element ([x, y])
19941 * @param {Function} callback The function to call after the repair is complete
19942 * @param {Object} scope The scope in which to execute the callback
19944 repair : function(xy, callback, scope){
19945 this.callback = callback;
19946 this.scope = scope;
19947 if(xy && this.animRepair !== false){
19948 this.el.addClass("x-dd-drag-repair");
19949 this.el.hideUnders(true);
19950 this.anim = this.el.shift({
19951 duration: this.repairDuration || .5,
19955 callback: this.afterRepair,
19959 this.afterRepair();
19964 afterRepair : function(){
19966 if(typeof this.callback == "function"){
19967 this.callback.call(this.scope || this);
19969 this.callback = null;
19974 * Ext JS Library 1.1.1
19975 * Copyright(c) 2006-2007, Ext JS, LLC.
19977 * Originally Released Under LGPL - original licence link has changed is not relivant.
19980 * <script type="text/javascript">
19984 * @class Roo.dd.DragSource
19985 * @extends Roo.dd.DDProxy
19986 * A simple class that provides the basic implementation needed to make any element draggable.
19988 * @param {String/HTMLElement/Element} el The container element
19989 * @param {Object} config
19991 Roo.dd.DragSource = function(el, config){
19992 this.el = Roo.get(el);
19993 this.dragData = {};
19995 Roo.apply(this, config);
19998 this.proxy = new Roo.dd.StatusProxy();
20001 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
20002 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
20004 this.dragging = false;
20007 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
20009 * @cfg {String} dropAllowed
20010 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
20012 dropAllowed : "x-dd-drop-ok",
20014 * @cfg {String} dropNotAllowed
20015 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
20017 dropNotAllowed : "x-dd-drop-nodrop",
20020 * Returns the data object associated with this drag source
20021 * @return {Object} data An object containing arbitrary data
20023 getDragData : function(e){
20024 return this.dragData;
20028 onDragEnter : function(e, id){
20029 var target = Roo.dd.DragDropMgr.getDDById(id);
20030 this.cachedTarget = target;
20031 if(this.beforeDragEnter(target, e, id) !== false){
20032 if(target.isNotifyTarget){
20033 var status = target.notifyEnter(this, e, this.dragData);
20034 this.proxy.setStatus(status);
20036 this.proxy.setStatus(this.dropAllowed);
20039 if(this.afterDragEnter){
20041 * An empty function by default, but provided so that you can perform a custom action
20042 * when the dragged item enters the drop target by providing an implementation.
20043 * @param {Roo.dd.DragDrop} target The drop target
20044 * @param {Event} e The event object
20045 * @param {String} id The id of the dragged element
20046 * @method afterDragEnter
20048 this.afterDragEnter(target, e, id);
20054 * An empty function by default, but provided so that you can perform a custom action
20055 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
20056 * @param {Roo.dd.DragDrop} target The drop target
20057 * @param {Event} e The event object
20058 * @param {String} id The id of the dragged element
20059 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20061 beforeDragEnter : function(target, e, id){
20066 alignElWithMouse: function() {
20067 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
20072 onDragOver : function(e, id){
20073 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20074 if(this.beforeDragOver(target, e, id) !== false){
20075 if(target.isNotifyTarget){
20076 var status = target.notifyOver(this, e, this.dragData);
20077 this.proxy.setStatus(status);
20080 if(this.afterDragOver){
20082 * An empty function by default, but provided so that you can perform a custom action
20083 * while the dragged item is over the drop target by providing an implementation.
20084 * @param {Roo.dd.DragDrop} target The drop target
20085 * @param {Event} e The event object
20086 * @param {String} id The id of the dragged element
20087 * @method afterDragOver
20089 this.afterDragOver(target, e, id);
20095 * An empty function by default, but provided so that you can perform a custom action
20096 * while the dragged item is over the drop target and optionally cancel the onDragOver.
20097 * @param {Roo.dd.DragDrop} target The drop target
20098 * @param {Event} e The event object
20099 * @param {String} id The id of the dragged element
20100 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20102 beforeDragOver : function(target, e, id){
20107 onDragOut : function(e, id){
20108 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20109 if(this.beforeDragOut(target, e, id) !== false){
20110 if(target.isNotifyTarget){
20111 target.notifyOut(this, e, this.dragData);
20113 this.proxy.reset();
20114 if(this.afterDragOut){
20116 * An empty function by default, but provided so that you can perform a custom action
20117 * after the dragged item is dragged out of the target without dropping.
20118 * @param {Roo.dd.DragDrop} target The drop target
20119 * @param {Event} e The event object
20120 * @param {String} id The id of the dragged element
20121 * @method afterDragOut
20123 this.afterDragOut(target, e, id);
20126 this.cachedTarget = null;
20130 * An empty function by default, but provided so that you can perform a custom action before the dragged
20131 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
20132 * @param {Roo.dd.DragDrop} target The drop target
20133 * @param {Event} e The event object
20134 * @param {String} id The id of the dragged element
20135 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20137 beforeDragOut : function(target, e, id){
20142 onDragDrop : function(e, id){
20143 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20144 if(this.beforeDragDrop(target, e, id) !== false){
20145 if(target.isNotifyTarget){
20146 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
20147 this.onValidDrop(target, e, id);
20149 this.onInvalidDrop(target, e, id);
20152 this.onValidDrop(target, e, id);
20155 if(this.afterDragDrop){
20157 * An empty function by default, but provided so that you can perform a custom action
20158 * after a valid drag drop has occurred by providing an implementation.
20159 * @param {Roo.dd.DragDrop} target The drop target
20160 * @param {Event} e The event object
20161 * @param {String} id The id of the dropped element
20162 * @method afterDragDrop
20164 this.afterDragDrop(target, e, id);
20167 delete this.cachedTarget;
20171 * An empty function by default, but provided so that you can perform a custom action before the dragged
20172 * item is dropped onto the target and optionally cancel the onDragDrop.
20173 * @param {Roo.dd.DragDrop} target The drop target
20174 * @param {Event} e The event object
20175 * @param {String} id The id of the dragged element
20176 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
20178 beforeDragDrop : function(target, e, id){
20183 onValidDrop : function(target, e, id){
20185 if(this.afterValidDrop){
20187 * An empty function by default, but provided so that you can perform a custom action
20188 * after a valid drop has occurred by providing an implementation.
20189 * @param {Object} target The target DD
20190 * @param {Event} e The event object
20191 * @param {String} id The id of the dropped element
20192 * @method afterInvalidDrop
20194 this.afterValidDrop(target, e, id);
20199 getRepairXY : function(e, data){
20200 return this.el.getXY();
20204 onInvalidDrop : function(target, e, id){
20205 this.beforeInvalidDrop(target, e, id);
20206 if(this.cachedTarget){
20207 if(this.cachedTarget.isNotifyTarget){
20208 this.cachedTarget.notifyOut(this, e, this.dragData);
20210 this.cacheTarget = null;
20212 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
20214 if(this.afterInvalidDrop){
20216 * An empty function by default, but provided so that you can perform a custom action
20217 * after an invalid drop has occurred by providing an implementation.
20218 * @param {Event} e The event object
20219 * @param {String} id The id of the dropped element
20220 * @method afterInvalidDrop
20222 this.afterInvalidDrop(e, id);
20227 afterRepair : function(){
20229 this.el.highlight(this.hlColor || "c3daf9");
20231 this.dragging = false;
20235 * An empty function by default, but provided so that you can perform a custom action after an invalid
20236 * drop has occurred.
20237 * @param {Roo.dd.DragDrop} target The drop target
20238 * @param {Event} e The event object
20239 * @param {String} id The id of the dragged element
20240 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
20242 beforeInvalidDrop : function(target, e, id){
20247 handleMouseDown : function(e){
20248 if(this.dragging) {
20251 var data = this.getDragData(e);
20252 if(data && this.onBeforeDrag(data, e) !== false){
20253 this.dragData = data;
20255 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
20260 * An empty function by default, but provided so that you can perform a custom action before the initial
20261 * drag event begins and optionally cancel it.
20262 * @param {Object} data An object containing arbitrary data to be shared with drop targets
20263 * @param {Event} e The event object
20264 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20266 onBeforeDrag : function(data, e){
20271 * An empty function by default, but provided so that you can perform a custom action once the initial
20272 * drag event has begun. The drag cannot be canceled from this function.
20273 * @param {Number} x The x position of the click on the dragged object
20274 * @param {Number} y The y position of the click on the dragged object
20276 onStartDrag : Roo.emptyFn,
20278 // private - YUI override
20279 startDrag : function(x, y){
20280 this.proxy.reset();
20281 this.dragging = true;
20282 this.proxy.update("");
20283 this.onInitDrag(x, y);
20288 onInitDrag : function(x, y){
20289 var clone = this.el.dom.cloneNode(true);
20290 clone.id = Roo.id(); // prevent duplicate ids
20291 this.proxy.update(clone);
20292 this.onStartDrag(x, y);
20297 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
20298 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
20300 getProxy : function(){
20305 * Hides the drag source's {@link Roo.dd.StatusProxy}
20307 hideProxy : function(){
20309 this.proxy.reset(true);
20310 this.dragging = false;
20314 triggerCacheRefresh : function(){
20315 Roo.dd.DDM.refreshCache(this.groups);
20318 // private - override to prevent hiding
20319 b4EndDrag: function(e) {
20322 // private - override to prevent moving
20323 endDrag : function(e){
20324 this.onEndDrag(this.dragData, e);
20328 onEndDrag : function(data, e){
20331 // private - pin to cursor
20332 autoOffset : function(x, y) {
20333 this.setDelta(-12, -20);
20337 * Ext JS Library 1.1.1
20338 * Copyright(c) 2006-2007, Ext JS, LLC.
20340 * Originally Released Under LGPL - original licence link has changed is not relivant.
20343 * <script type="text/javascript">
20348 * @class Roo.dd.DropTarget
20349 * @extends Roo.dd.DDTarget
20350 * A simple class that provides the basic implementation needed to make any element a drop target that can have
20351 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
20353 * @param {String/HTMLElement/Element} el The container element
20354 * @param {Object} config
20356 Roo.dd.DropTarget = function(el, config){
20357 this.el = Roo.get(el);
20359 var listeners = false; ;
20360 if (config && config.listeners) {
20361 listeners= config.listeners;
20362 delete config.listeners;
20364 Roo.apply(this, config);
20366 if(this.containerScroll){
20367 Roo.dd.ScrollManager.register(this.el);
20371 * @scope Roo.dd.DropTarget
20376 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
20377 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
20378 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
20380 * IMPORTANT : it should set this.overClass and this.dropAllowed
20382 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20383 * @param {Event} e The event
20384 * @param {Object} data An object containing arbitrary data supplied by the drag source
20390 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
20391 * This method will be called on every mouse movement while the drag source is over the drop target.
20392 * This default implementation simply returns the dropAllowed config value.
20394 * IMPORTANT : it should set this.dropAllowed
20396 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20397 * @param {Event} e The event
20398 * @param {Object} data An object containing arbitrary data supplied by the drag source
20404 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
20405 * out of the target without dropping. This default implementation simply removes the CSS class specified by
20406 * overClass (if any) from the drop element.
20408 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20409 * @param {Event} e The event
20410 * @param {Object} data An object containing arbitrary data supplied by the drag source
20416 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
20417 * been dropped on it. This method has no default implementation and returns false, so you must provide an
20418 * implementation that does something to process the drop event and returns true so that the drag source's
20419 * repair action does not run.
20421 * IMPORTANT : it should set this.success
20423 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20424 * @param {Event} e The event
20425 * @param {Object} data An object containing arbitrary data supplied by the drag source
20431 Roo.dd.DropTarget.superclass.constructor.call( this,
20433 this.ddGroup || this.group,
20436 listeners : listeners || {}
20444 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
20446 * @cfg {String} overClass
20447 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
20450 * @cfg {String} ddGroup
20451 * The drag drop group to handle drop events for
20455 * @cfg {String} dropAllowed
20456 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
20458 dropAllowed : "x-dd-drop-ok",
20460 * @cfg {String} dropNotAllowed
20461 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
20463 dropNotAllowed : "x-dd-drop-nodrop",
20465 * @cfg {boolean} success
20466 * set this after drop listener..
20470 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
20471 * if the drop point is valid for over/enter..
20478 isNotifyTarget : true,
20483 notifyEnter : function(dd, e, data)
20486 this.fireEvent('enter', dd, e, data);
20487 if(this.overClass){
20488 this.el.addClass(this.overClass);
20490 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
20491 this.valid ? this.dropAllowed : this.dropNotAllowed
20498 notifyOver : function(dd, e, data)
20501 this.fireEvent('over', dd, e, data);
20502 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
20503 this.valid ? this.dropAllowed : this.dropNotAllowed
20510 notifyOut : function(dd, e, data)
20512 this.fireEvent('out', dd, e, data);
20513 if(this.overClass){
20514 this.el.removeClass(this.overClass);
20521 notifyDrop : function(dd, e, data)
20523 this.success = false;
20524 this.fireEvent('drop', dd, e, data);
20525 return this.success;
20529 * Ext JS Library 1.1.1
20530 * Copyright(c) 2006-2007, Ext JS, LLC.
20532 * Originally Released Under LGPL - original licence link has changed is not relivant.
20535 * <script type="text/javascript">
20540 * @class Roo.dd.DragZone
20541 * @extends Roo.dd.DragSource
20542 * This class provides a container DD instance that proxies for multiple child node sources.<br />
20543 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
20545 * @param {String/HTMLElement/Element} el The container element
20546 * @param {Object} config
20548 Roo.dd.DragZone = function(el, config){
20549 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
20550 if(this.containerScroll){
20551 Roo.dd.ScrollManager.register(this.el);
20555 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
20557 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
20558 * for auto scrolling during drag operations.
20561 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
20562 * method after a failed drop (defaults to "c3daf9" - light blue)
20566 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
20567 * for a valid target to drag based on the mouse down. Override this method
20568 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
20569 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
20570 * @param {EventObject} e The mouse down event
20571 * @return {Object} The dragData
20573 getDragData : function(e){
20574 return Roo.dd.Registry.getHandleFromEvent(e);
20578 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
20579 * this.dragData.ddel
20580 * @param {Number} x The x position of the click on the dragged object
20581 * @param {Number} y The y position of the click on the dragged object
20582 * @return {Boolean} true to continue the drag, false to cancel
20584 onInitDrag : function(x, y){
20585 this.proxy.update(this.dragData.ddel.cloneNode(true));
20586 this.onStartDrag(x, y);
20591 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
20593 afterRepair : function(){
20595 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
20597 this.dragging = false;
20601 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
20602 * the XY of this.dragData.ddel
20603 * @param {EventObject} e The mouse up event
20604 * @return {Array} The xy location (e.g. [100, 200])
20606 getRepairXY : function(e){
20607 return Roo.Element.fly(this.dragData.ddel).getXY();
20611 * Ext JS Library 1.1.1
20612 * Copyright(c) 2006-2007, Ext JS, LLC.
20614 * Originally Released Under LGPL - original licence link has changed is not relivant.
20617 * <script type="text/javascript">
20620 * @class Roo.dd.DropZone
20621 * @extends Roo.dd.DropTarget
20622 * This class provides a container DD instance that proxies for multiple child node targets.<br />
20623 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
20625 * @param {String/HTMLElement/Element} el The container element
20626 * @param {Object} config
20628 Roo.dd.DropZone = function(el, config){
20629 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
20632 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
20634 * Returns a custom data object associated with the DOM node that is the target of the event. By default
20635 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
20636 * provide your own custom lookup.
20637 * @param {Event} e The event
20638 * @return {Object} data The custom data
20640 getTargetFromEvent : function(e){
20641 return Roo.dd.Registry.getTargetFromEvent(e);
20645 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
20646 * that it has registered. This method has no default implementation and should be overridden to provide
20647 * node-specific processing if necessary.
20648 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20649 * {@link #getTargetFromEvent} for this node)
20650 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20651 * @param {Event} e The event
20652 * @param {Object} data An object containing arbitrary data supplied by the drag source
20654 onNodeEnter : function(n, dd, e, data){
20659 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
20660 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
20661 * overridden to provide the proper feedback.
20662 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20663 * {@link #getTargetFromEvent} for this node)
20664 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20665 * @param {Event} e The event
20666 * @param {Object} data An object containing arbitrary data supplied by the drag source
20667 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20668 * underlying {@link Roo.dd.StatusProxy} can be updated
20670 onNodeOver : function(n, dd, e, data){
20671 return this.dropAllowed;
20675 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
20676 * the drop node without dropping. This method has no default implementation and should be overridden to provide
20677 * node-specific processing if necessary.
20678 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20679 * {@link #getTargetFromEvent} for this node)
20680 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20681 * @param {Event} e The event
20682 * @param {Object} data An object containing arbitrary data supplied by the drag source
20684 onNodeOut : function(n, dd, e, data){
20689 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
20690 * the drop node. The default implementation returns false, so it should be overridden to provide the
20691 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
20692 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20693 * {@link #getTargetFromEvent} for this node)
20694 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20695 * @param {Event} e The event
20696 * @param {Object} data An object containing arbitrary data supplied by the drag source
20697 * @return {Boolean} True if the drop was valid, else false
20699 onNodeDrop : function(n, dd, e, data){
20704 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
20705 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
20706 * it should be overridden to provide the proper feedback if necessary.
20707 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20708 * @param {Event} e The event
20709 * @param {Object} data An object containing arbitrary data supplied by the drag source
20710 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20711 * underlying {@link Roo.dd.StatusProxy} can be updated
20713 onContainerOver : function(dd, e, data){
20714 return this.dropNotAllowed;
20718 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
20719 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
20720 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
20721 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
20722 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20723 * @param {Event} e The event
20724 * @param {Object} data An object containing arbitrary data supplied by the drag source
20725 * @return {Boolean} True if the drop was valid, else false
20727 onContainerDrop : function(dd, e, data){
20732 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
20733 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
20734 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
20735 * you should override this method and provide a custom implementation.
20736 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20737 * @param {Event} e The event
20738 * @param {Object} data An object containing arbitrary data supplied by the drag source
20739 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20740 * underlying {@link Roo.dd.StatusProxy} can be updated
20742 notifyEnter : function(dd, e, data){
20743 return this.dropNotAllowed;
20747 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
20748 * This method will be called on every mouse movement while the drag source is over the drop zone.
20749 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
20750 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
20751 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
20752 * registered node, it will call {@link #onContainerOver}.
20753 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20754 * @param {Event} e The event
20755 * @param {Object} data An object containing arbitrary data supplied by the drag source
20756 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20757 * underlying {@link Roo.dd.StatusProxy} can be updated
20759 notifyOver : function(dd, e, data){
20760 var n = this.getTargetFromEvent(e);
20761 if(!n){ // not over valid drop target
20762 if(this.lastOverNode){
20763 this.onNodeOut(this.lastOverNode, dd, e, data);
20764 this.lastOverNode = null;
20766 return this.onContainerOver(dd, e, data);
20768 if(this.lastOverNode != n){
20769 if(this.lastOverNode){
20770 this.onNodeOut(this.lastOverNode, dd, e, data);
20772 this.onNodeEnter(n, dd, e, data);
20773 this.lastOverNode = n;
20775 return this.onNodeOver(n, dd, e, data);
20779 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
20780 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
20781 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
20782 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20783 * @param {Event} e The event
20784 * @param {Object} data An object containing arbitrary data supplied by the drag zone
20786 notifyOut : function(dd, e, data){
20787 if(this.lastOverNode){
20788 this.onNodeOut(this.lastOverNode, dd, e, data);
20789 this.lastOverNode = null;
20794 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
20795 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
20796 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
20797 * otherwise it will call {@link #onContainerDrop}.
20798 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20799 * @param {Event} e The event
20800 * @param {Object} data An object containing arbitrary data supplied by the drag source
20801 * @return {Boolean} True if the drop was valid, else false
20803 notifyDrop : function(dd, e, data){
20804 if(this.lastOverNode){
20805 this.onNodeOut(this.lastOverNode, dd, e, data);
20806 this.lastOverNode = null;
20808 var n = this.getTargetFromEvent(e);
20810 this.onNodeDrop(n, dd, e, data) :
20811 this.onContainerDrop(dd, e, data);
20815 triggerCacheRefresh : function(){
20816 Roo.dd.DDM.refreshCache(this.groups);
20820 * Ext JS Library 1.1.1
20821 * Copyright(c) 2006-2007, Ext JS, LLC.
20823 * Originally Released Under LGPL - original licence link has changed is not relivant.
20826 * <script type="text/javascript">
20831 * @class Roo.data.SortTypes
20833 * Defines the default sorting (casting?) comparison functions used when sorting data.
20835 Roo.data.SortTypes = {
20837 * Default sort that does nothing
20838 * @param {Mixed} s The value being converted
20839 * @return {Mixed} The comparison value
20841 none : function(s){
20846 * The regular expression used to strip tags
20850 stripTagsRE : /<\/?[^>]+>/gi,
20853 * Strips all HTML tags to sort on text only
20854 * @param {Mixed} s The value being converted
20855 * @return {String} The comparison value
20857 asText : function(s){
20858 return String(s).replace(this.stripTagsRE, "");
20862 * Strips all HTML tags to sort on text only - Case insensitive
20863 * @param {Mixed} s The value being converted
20864 * @return {String} The comparison value
20866 asUCText : function(s){
20867 return String(s).toUpperCase().replace(this.stripTagsRE, "");
20871 * Case insensitive string
20872 * @param {Mixed} s The value being converted
20873 * @return {String} The comparison value
20875 asUCString : function(s) {
20876 return String(s).toUpperCase();
20881 * @param {Mixed} s The value being converted
20882 * @return {Number} The comparison value
20884 asDate : function(s) {
20888 if(s instanceof Date){
20889 return s.getTime();
20891 return Date.parse(String(s));
20896 * @param {Mixed} s The value being converted
20897 * @return {Float} The comparison value
20899 asFloat : function(s) {
20900 var val = parseFloat(String(s).replace(/,/g, ""));
20901 if(isNaN(val)) val = 0;
20907 * @param {Mixed} s The value being converted
20908 * @return {Number} The comparison value
20910 asInt : function(s) {
20911 var val = parseInt(String(s).replace(/,/g, ""));
20912 if(isNaN(val)) val = 0;
20917 * Ext JS Library 1.1.1
20918 * Copyright(c) 2006-2007, Ext JS, LLC.
20920 * Originally Released Under LGPL - original licence link has changed is not relivant.
20923 * <script type="text/javascript">
20927 * @class Roo.data.Record
20928 * Instances of this class encapsulate both record <em>definition</em> information, and record
20929 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
20930 * to access Records cached in an {@link Roo.data.Store} object.<br>
20932 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
20933 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
20936 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
20938 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
20939 * {@link #create}. The parameters are the same.
20940 * @param {Array} data An associative Array of data values keyed by the field name.
20941 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
20942 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
20943 * not specified an integer id is generated.
20945 Roo.data.Record = function(data, id){
20946 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
20951 * Generate a constructor for a specific record layout.
20952 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
20953 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
20954 * Each field definition object may contain the following properties: <ul>
20955 * <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
20956 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
20957 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
20958 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
20959 * is being used, then this is a string containing the javascript expression to reference the data relative to
20960 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
20961 * to the data item relative to the record element. If the mapping expression is the same as the field name,
20962 * this may be omitted.</p></li>
20963 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
20964 * <ul><li>auto (Default, implies no conversion)</li>
20969 * <li>date</li></ul></p></li>
20970 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
20971 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
20972 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
20973 * by the Reader into an object that will be stored in the Record. It is passed the
20974 * following parameters:<ul>
20975 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
20977 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
20979 * <br>usage:<br><pre><code>
20980 var TopicRecord = Roo.data.Record.create(
20981 {name: 'title', mapping: 'topic_title'},
20982 {name: 'author', mapping: 'username'},
20983 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
20984 {name: 'lastPost', mapping: 'post_time', type: 'date'},
20985 {name: 'lastPoster', mapping: 'user2'},
20986 {name: 'excerpt', mapping: 'post_text'}
20989 var myNewRecord = new TopicRecord({
20990 title: 'Do my job please',
20993 lastPost: new Date(),
20994 lastPoster: 'Animal',
20995 excerpt: 'No way dude!'
20997 myStore.add(myNewRecord);
21002 Roo.data.Record.create = function(o){
21003 var f = function(){
21004 f.superclass.constructor.apply(this, arguments);
21006 Roo.extend(f, Roo.data.Record);
21007 var p = f.prototype;
21008 p.fields = new Roo.util.MixedCollection(false, function(field){
21011 for(var i = 0, len = o.length; i < len; i++){
21012 p.fields.add(new Roo.data.Field(o[i]));
21014 f.getField = function(name){
21015 return p.fields.get(name);
21020 Roo.data.Record.AUTO_ID = 1000;
21021 Roo.data.Record.EDIT = 'edit';
21022 Roo.data.Record.REJECT = 'reject';
21023 Roo.data.Record.COMMIT = 'commit';
21025 Roo.data.Record.prototype = {
21027 * Readonly flag - true if this record has been modified.
21036 join : function(store){
21037 this.store = store;
21041 * Set the named field to the specified value.
21042 * @param {String} name The name of the field to set.
21043 * @param {Object} value The value to set the field to.
21045 set : function(name, value){
21046 if(this.data[name] == value){
21050 if(!this.modified){
21051 this.modified = {};
21053 if(typeof this.modified[name] == 'undefined'){
21054 this.modified[name] = this.data[name];
21056 this.data[name] = value;
21057 if(!this.editing && this.store){
21058 this.store.afterEdit(this);
21063 * Get the value of the named field.
21064 * @param {String} name The name of the field to get the value of.
21065 * @return {Object} The value of the field.
21067 get : function(name){
21068 return this.data[name];
21072 beginEdit : function(){
21073 this.editing = true;
21074 this.modified = {};
21078 cancelEdit : function(){
21079 this.editing = false;
21080 delete this.modified;
21084 endEdit : function(){
21085 this.editing = false;
21086 if(this.dirty && this.store){
21087 this.store.afterEdit(this);
21092 * Usually called by the {@link Roo.data.Store} which owns the Record.
21093 * Rejects all changes made to the Record since either creation, or the last commit operation.
21094 * Modified fields are reverted to their original values.
21096 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
21097 * of reject operations.
21099 reject : function(){
21100 var m = this.modified;
21102 if(typeof m[n] != "function"){
21103 this.data[n] = m[n];
21106 this.dirty = false;
21107 delete this.modified;
21108 this.editing = false;
21110 this.store.afterReject(this);
21115 * Usually called by the {@link Roo.data.Store} which owns the Record.
21116 * Commits all changes made to the Record since either creation, or the last commit operation.
21118 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
21119 * of commit operations.
21121 commit : function(){
21122 this.dirty = false;
21123 delete this.modified;
21124 this.editing = false;
21126 this.store.afterCommit(this);
21131 hasError : function(){
21132 return this.error != null;
21136 clearError : function(){
21141 * Creates a copy of this record.
21142 * @param {String} id (optional) A new record id if you don't want to use this record's id
21145 copy : function(newId) {
21146 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
21150 * Ext JS Library 1.1.1
21151 * Copyright(c) 2006-2007, Ext JS, LLC.
21153 * Originally Released Under LGPL - original licence link has changed is not relivant.
21156 * <script type="text/javascript">
21162 * @class Roo.data.Store
21163 * @extends Roo.util.Observable
21164 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
21165 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
21167 * A Store object uses an implementation of {@link Roo.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
21168 * has no knowledge of the format of the data returned by the Proxy.<br>
21170 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
21171 * instances from the data object. These records are cached and made available through accessor functions.
21173 * Creates a new Store.
21174 * @param {Object} config A config object containing the objects needed for the Store to access data,
21175 * and read the data into Records.
21177 Roo.data.Store = function(config){
21178 this.data = new Roo.util.MixedCollection(false);
21179 this.data.getKey = function(o){
21182 this.baseParams = {};
21184 this.paramNames = {
21189 "multisort" : "_multisort"
21192 if(config && config.data){
21193 this.inlineData = config.data;
21194 delete config.data;
21197 Roo.apply(this, config);
21199 if(this.reader){ // reader passed
21200 this.reader = Roo.factory(this.reader, Roo.data);
21201 this.reader.xmodule = this.xmodule || false;
21202 if(!this.recordType){
21203 this.recordType = this.reader.recordType;
21205 if(this.reader.onMetaChange){
21206 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
21210 if(this.recordType){
21211 this.fields = this.recordType.prototype.fields;
21213 this.modified = [];
21217 * @event datachanged
21218 * Fires when the data cache has changed, and a widget which is using this Store
21219 * as a Record cache should refresh its view.
21220 * @param {Store} this
21222 datachanged : true,
21224 * @event metachange
21225 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
21226 * @param {Store} this
21227 * @param {Object} meta The JSON metadata
21232 * Fires when Records have been added to the Store
21233 * @param {Store} this
21234 * @param {Roo.data.Record[]} records The array of Records added
21235 * @param {Number} index The index at which the record(s) were added
21240 * Fires when a Record has been removed from the Store
21241 * @param {Store} this
21242 * @param {Roo.data.Record} record The Record that was removed
21243 * @param {Number} index The index at which the record was removed
21248 * Fires when a Record has been updated
21249 * @param {Store} this
21250 * @param {Roo.data.Record} record The Record that was updated
21251 * @param {String} operation The update operation being performed. Value may be one of:
21253 Roo.data.Record.EDIT
21254 Roo.data.Record.REJECT
21255 Roo.data.Record.COMMIT
21261 * Fires when the data cache has been cleared.
21262 * @param {Store} this
21266 * @event beforeload
21267 * Fires before a request is made for a new data object. If the beforeload handler returns false
21268 * the load action will be canceled.
21269 * @param {Store} this
21270 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21274 * @event beforeloadadd
21275 * Fires after a new set of Records has been loaded.
21276 * @param {Store} this
21277 * @param {Roo.data.Record[]} records The Records that were loaded
21278 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21280 beforeloadadd : true,
21283 * Fires after a new set of Records has been loaded, before they are added to the store.
21284 * @param {Store} this
21285 * @param {Roo.data.Record[]} records The Records that were loaded
21286 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21287 * @params {Object} return from reader
21291 * @event loadexception
21292 * Fires if an exception occurs in the Proxy during loading.
21293 * Called with the signature of the Proxy's "loadexception" event.
21294 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
21297 * @param {Object} return from JsonData.reader() - success, totalRecords, records
21298 * @param {Object} load options
21299 * @param {Object} jsonData from your request (normally this contains the Exception)
21301 loadexception : true
21305 this.proxy = Roo.factory(this.proxy, Roo.data);
21306 this.proxy.xmodule = this.xmodule || false;
21307 this.relayEvents(this.proxy, ["loadexception"]);
21309 this.sortToggle = {};
21310 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
21312 Roo.data.Store.superclass.constructor.call(this);
21314 if(this.inlineData){
21315 this.loadData(this.inlineData);
21316 delete this.inlineData;
21320 Roo.extend(Roo.data.Store, Roo.util.Observable, {
21322 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
21323 * without a remote query - used by combo/forms at present.
21327 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
21330 * @cfg {Array} data Inline data to be loaded when the store is initialized.
21333 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
21334 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
21337 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
21338 * on any HTTP request
21341 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
21344 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
21348 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
21349 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
21351 remoteSort : false,
21354 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
21355 * loaded or when a record is removed. (defaults to false).
21357 pruneModifiedRecords : false,
21360 lastOptions : null,
21363 * Add Records to the Store and fires the add event.
21364 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
21366 add : function(records){
21367 records = [].concat(records);
21368 for(var i = 0, len = records.length; i < len; i++){
21369 records[i].join(this);
21371 var index = this.data.length;
21372 this.data.addAll(records);
21373 this.fireEvent("add", this, records, index);
21377 * Remove a Record from the Store and fires the remove event.
21378 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
21380 remove : function(record){
21381 var index = this.data.indexOf(record);
21382 this.data.removeAt(index);
21383 if(this.pruneModifiedRecords){
21384 this.modified.remove(record);
21386 this.fireEvent("remove", this, record, index);
21390 * Remove all Records from the Store and fires the clear event.
21392 removeAll : function(){
21394 if(this.pruneModifiedRecords){
21395 this.modified = [];
21397 this.fireEvent("clear", this);
21401 * Inserts Records to the Store at the given index and fires the add event.
21402 * @param {Number} index The start index at which to insert the passed Records.
21403 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
21405 insert : function(index, records){
21406 records = [].concat(records);
21407 for(var i = 0, len = records.length; i < len; i++){
21408 this.data.insert(index, records[i]);
21409 records[i].join(this);
21411 this.fireEvent("add", this, records, index);
21415 * Get the index within the cache of the passed Record.
21416 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
21417 * @return {Number} The index of the passed Record. Returns -1 if not found.
21419 indexOf : function(record){
21420 return this.data.indexOf(record);
21424 * Get the index within the cache of the Record with the passed id.
21425 * @param {String} id The id of the Record to find.
21426 * @return {Number} The index of the Record. Returns -1 if not found.
21428 indexOfId : function(id){
21429 return this.data.indexOfKey(id);
21433 * Get the Record with the specified id.
21434 * @param {String} id The id of the Record to find.
21435 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
21437 getById : function(id){
21438 return this.data.key(id);
21442 * Get the Record at the specified index.
21443 * @param {Number} index The index of the Record to find.
21444 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
21446 getAt : function(index){
21447 return this.data.itemAt(index);
21451 * Returns a range of Records between specified indices.
21452 * @param {Number} startIndex (optional) The starting index (defaults to 0)
21453 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
21454 * @return {Roo.data.Record[]} An array of Records
21456 getRange : function(start, end){
21457 return this.data.getRange(start, end);
21461 storeOptions : function(o){
21462 o = Roo.apply({}, o);
21465 this.lastOptions = o;
21469 * Loads the Record cache from the configured Proxy using the configured Reader.
21471 * If using remote paging, then the first load call must specify the <em>start</em>
21472 * and <em>limit</em> properties in the options.params property to establish the initial
21473 * position within the dataset, and the number of Records to cache on each read from the Proxy.
21475 * <strong>It is important to note that for remote data sources, loading is asynchronous,
21476 * and this call will return before the new data has been loaded. Perform any post-processing
21477 * in a callback function, or in a "load" event handler.</strong>
21479 * @param {Object} options An object containing properties which control loading options:<ul>
21480 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
21481 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
21482 * passed the following arguments:<ul>
21483 * <li>r : Roo.data.Record[]</li>
21484 * <li>options: Options object from the load call</li>
21485 * <li>success: Boolean success indicator</li></ul></li>
21486 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
21487 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
21490 load : function(options){
21491 options = options || {};
21492 if(this.fireEvent("beforeload", this, options) !== false){
21493 this.storeOptions(options);
21494 var p = Roo.apply(options.params || {}, this.baseParams);
21495 // if meta was not loaded from remote source.. try requesting it.
21496 if (!this.reader.metaFromRemote) {
21497 p._requestMeta = 1;
21499 if(this.sortInfo && this.remoteSort){
21500 var pn = this.paramNames;
21501 p[pn["sort"]] = this.sortInfo.field;
21502 p[pn["dir"]] = this.sortInfo.direction;
21504 if (this.multiSort) {
21505 var pn = this.paramNames;
21506 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
21509 this.proxy.load(p, this.reader, this.loadRecords, this, options);
21514 * Reloads the Record cache from the configured Proxy using the configured Reader and
21515 * the options from the last load operation performed.
21516 * @param {Object} options (optional) An object containing properties which may override the options
21517 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
21518 * the most recently used options are reused).
21520 reload : function(options){
21521 this.load(Roo.applyIf(options||{}, this.lastOptions));
21525 // Called as a callback by the Reader during a load operation.
21526 loadRecords : function(o, options, success){
21527 if(!o || success === false){
21528 if(success !== false){
21529 this.fireEvent("load", this, [], options, o);
21531 if(options.callback){
21532 options.callback.call(options.scope || this, [], options, false);
21536 // if data returned failure - throw an exception.
21537 if (o.success === false) {
21538 // show a message if no listener is registered.
21539 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
21540 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
21542 // loadmask wil be hooked into this..
21543 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
21546 var r = o.records, t = o.totalRecords || r.length;
21548 this.fireEvent("beforeloadadd", this, r, options, o);
21550 if(!options || options.add !== true){
21551 if(this.pruneModifiedRecords){
21552 this.modified = [];
21554 for(var i = 0, len = r.length; i < len; i++){
21558 this.data = this.snapshot;
21559 delete this.snapshot;
21562 this.data.addAll(r);
21563 this.totalLength = t;
21565 this.fireEvent("datachanged", this);
21567 this.totalLength = Math.max(t, this.data.length+r.length);
21570 this.fireEvent("load", this, r, options, o);
21571 if(options.callback){
21572 options.callback.call(options.scope || this, r, options, true);
21578 * Loads data from a passed data block. A Reader which understands the format of the data
21579 * must have been configured in the constructor.
21580 * @param {Object} data The data block from which to read the Records. The format of the data expected
21581 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
21582 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
21584 loadData : function(o, append){
21585 var r = this.reader.readRecords(o);
21586 this.loadRecords(r, {add: append}, true);
21590 * Gets the number of cached records.
21592 * <em>If using paging, this may not be the total size of the dataset. If the data object
21593 * used by the Reader contains the dataset size, then the getTotalCount() function returns
21594 * the data set size</em>
21596 getCount : function(){
21597 return this.data.length || 0;
21601 * Gets the total number of records in the dataset as returned by the server.
21603 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
21604 * the dataset size</em>
21606 getTotalCount : function(){
21607 return this.totalLength || 0;
21611 * Returns the sort state of the Store as an object with two properties:
21613 field {String} The name of the field by which the Records are sorted
21614 direction {String} The sort order, "ASC" or "DESC"
21617 getSortState : function(){
21618 return this.sortInfo;
21622 applySort : function(){
21623 if(this.sortInfo && !this.remoteSort){
21624 var s = this.sortInfo, f = s.field;
21625 var st = this.fields.get(f).sortType;
21626 var fn = function(r1, r2){
21627 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
21628 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
21630 this.data.sort(s.direction, fn);
21631 if(this.snapshot && this.snapshot != this.data){
21632 this.snapshot.sort(s.direction, fn);
21638 * Sets the default sort column and order to be used by the next load operation.
21639 * @param {String} fieldName The name of the field to sort by.
21640 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
21642 setDefaultSort : function(field, dir){
21643 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
21647 * Sort the Records.
21648 * If remote sorting is used, the sort is performed on the server, and the cache is
21649 * reloaded. If local sorting is used, the cache is sorted internally.
21650 * @param {String} fieldName The name of the field to sort by.
21651 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
21653 sort : function(fieldName, dir){
21654 var f = this.fields.get(fieldName);
21656 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
21658 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
21659 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
21664 this.sortToggle[f.name] = dir;
21665 this.sortInfo = {field: f.name, direction: dir};
21666 if(!this.remoteSort){
21668 this.fireEvent("datachanged", this);
21670 this.load(this.lastOptions);
21675 * Calls the specified function for each of the Records in the cache.
21676 * @param {Function} fn The function to call. The Record is passed as the first parameter.
21677 * Returning <em>false</em> aborts and exits the iteration.
21678 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
21680 each : function(fn, scope){
21681 this.data.each(fn, scope);
21685 * Gets all records modified since the last commit. Modified records are persisted across load operations
21686 * (e.g., during paging).
21687 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
21689 getModifiedRecords : function(){
21690 return this.modified;
21694 createFilterFn : function(property, value, anyMatch){
21695 if(!value.exec){ // not a regex
21696 value = String(value);
21697 if(value.length == 0){
21700 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
21703 return function(r){
21704 return value.test(r.data[property]);
21709 * Sums the value of <i>property</i> for each record between start and end and returns the result.
21710 * @param {String} property A field on your records
21711 * @param {Number} start The record index to start at (defaults to 0)
21712 * @param {Number} end The last record index to include (defaults to length - 1)
21713 * @return {Number} The sum
21715 sum : function(property, start, end){
21716 var rs = this.data.items, v = 0;
21717 start = start || 0;
21718 end = (end || end === 0) ? end : rs.length-1;
21720 for(var i = start; i <= end; i++){
21721 v += (rs[i].data[property] || 0);
21727 * Filter the records by a specified property.
21728 * @param {String} field A field on your records
21729 * @param {String/RegExp} value Either a string that the field
21730 * should start with or a RegExp to test against the field
21731 * @param {Boolean} anyMatch True to match any part not just the beginning
21733 filter : function(property, value, anyMatch){
21735 if(typeof(property) == 'string'){
21736 var fn = this.createFilterFn(property, value, anyMatch);
21737 return fn ? this.filterBy(fn) : this.clearFilter();
21745 Roo.each(property, function(p){
21746 if(anyMatch == true){
21747 afn.push(_this.createFilterFn(p, value, true));
21750 fn.push(_this.createFilterFn(p, value, false));
21753 if(!fn.length && !afn.length){
21754 return this.clearFilter();
21757 this.snapshot = this.snapshot || this.data;
21759 var filterData = [];
21761 Roo.each(fn, function(f){
21762 filterData.push(_this.queryBy(f, _this));
21765 Roo.each(afn, function(f){
21766 filterData.push(_this.queryBy(f, _this));
21769 var data = this.snapshot || this.data;
21771 var r = new Roo.util.MixedCollection();
21772 r.getKey = data.getKey;
21776 Roo.each(filterData, function(d){
21777 var k = d.keys, it = d.items;
21778 for(var i = 0, len = it.length; i < len; i++){
21779 if(keys.indexOf(k[i]) == -1){
21780 r.add(k[i], it[i]);
21786 this.fireEvent("datachanged", this);
21790 * Filter by a function. The specified function will be called with each
21791 * record in this data source. If the function returns true the record is included,
21792 * otherwise it is filtered.
21793 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
21794 * @param {Object} scope (optional) The scope of the function (defaults to this)
21796 filterBy : function(fn, scope){
21797 this.snapshot = this.snapshot || this.data;
21798 this.data = this.queryBy(fn, scope||this);
21799 this.fireEvent("datachanged", this);
21803 * Query the records by a specified property.
21804 * @param {String} field A field on your records
21805 * @param {String/RegExp} value Either a string that the field
21806 * should start with or a RegExp to test against the field
21807 * @param {Boolean} anyMatch True to match any part not just the beginning
21808 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
21810 query : function(property, value, anyMatch){
21811 var fn = this.createFilterFn(property, value, anyMatch);
21812 return fn ? this.queryBy(fn) : this.data.clone();
21816 * Query by a function. The specified function will be called with each
21817 * record in this data source. If the function returns true the record is included
21819 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
21820 * @param {Object} scope (optional) The scope of the function (defaults to this)
21821 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
21823 queryBy : function(fn, scope){
21824 var data = this.snapshot || this.data;
21825 return data.filterBy(fn, scope||this);
21829 * Collects unique values for a particular dataIndex from this store.
21830 * @param {String} dataIndex The property to collect
21831 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
21832 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
21833 * @return {Array} An array of the unique values
21835 collect : function(dataIndex, allowNull, bypassFilter){
21836 var d = (bypassFilter === true && this.snapshot) ?
21837 this.snapshot.items : this.data.items;
21838 var v, sv, r = [], l = {};
21839 for(var i = 0, len = d.length; i < len; i++){
21840 v = d[i].data[dataIndex];
21842 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
21851 * Revert to a view of the Record cache with no filtering applied.
21852 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
21854 clearFilter : function(suppressEvent){
21855 if(this.snapshot && this.snapshot != this.data){
21856 this.data = this.snapshot;
21857 delete this.snapshot;
21858 if(suppressEvent !== true){
21859 this.fireEvent("datachanged", this);
21865 afterEdit : function(record){
21866 if(this.modified.indexOf(record) == -1){
21867 this.modified.push(record);
21869 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
21873 afterReject : function(record){
21874 this.modified.remove(record);
21875 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
21879 afterCommit : function(record){
21880 this.modified.remove(record);
21881 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
21885 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
21886 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
21888 commitChanges : function(){
21889 var m = this.modified.slice(0);
21890 this.modified = [];
21891 for(var i = 0, len = m.length; i < len; i++){
21897 * Cancel outstanding changes on all changed records.
21899 rejectChanges : function(){
21900 var m = this.modified.slice(0);
21901 this.modified = [];
21902 for(var i = 0, len = m.length; i < len; i++){
21907 onMetaChange : function(meta, rtype, o){
21908 this.recordType = rtype;
21909 this.fields = rtype.prototype.fields;
21910 delete this.snapshot;
21911 this.sortInfo = meta.sortInfo || this.sortInfo;
21912 this.modified = [];
21913 this.fireEvent('metachange', this, this.reader.meta);
21916 moveIndex : function(data, type)
21918 var index = this.indexOf(data);
21920 var newIndex = index + type;
21924 this.insert(newIndex, data);
21929 * Ext JS Library 1.1.1
21930 * Copyright(c) 2006-2007, Ext JS, LLC.
21932 * Originally Released Under LGPL - original licence link has changed is not relivant.
21935 * <script type="text/javascript">
21939 * @class Roo.data.SimpleStore
21940 * @extends Roo.data.Store
21941 * Small helper class to make creating Stores from Array data easier.
21942 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
21943 * @cfg {Array} fields An array of field definition objects, or field name strings.
21944 * @cfg {Array} data The multi-dimensional array of data
21946 * @param {Object} config
21948 Roo.data.SimpleStore = function(config){
21949 Roo.data.SimpleStore.superclass.constructor.call(this, {
21951 reader: new Roo.data.ArrayReader({
21954 Roo.data.Record.create(config.fields)
21956 proxy : new Roo.data.MemoryProxy(config.data)
21960 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
21962 * Ext JS Library 1.1.1
21963 * Copyright(c) 2006-2007, Ext JS, LLC.
21965 * Originally Released Under LGPL - original licence link has changed is not relivant.
21968 * <script type="text/javascript">
21973 * @extends Roo.data.Store
21974 * @class Roo.data.JsonStore
21975 * Small helper class to make creating Stores for JSON data easier. <br/>
21977 var store = new Roo.data.JsonStore({
21978 url: 'get-images.php',
21980 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
21983 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
21984 * JsonReader and HttpProxy (unless inline data is provided).</b>
21985 * @cfg {Array} fields An array of field definition objects, or field name strings.
21987 * @param {Object} config
21989 Roo.data.JsonStore = function(c){
21990 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
21991 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
21992 reader: new Roo.data.JsonReader(c, c.fields)
21995 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
21997 * Ext JS Library 1.1.1
21998 * Copyright(c) 2006-2007, Ext JS, LLC.
22000 * Originally Released Under LGPL - original licence link has changed is not relivant.
22003 * <script type="text/javascript">
22007 Roo.data.Field = function(config){
22008 if(typeof config == "string"){
22009 config = {name: config};
22011 Roo.apply(this, config);
22014 this.type = "auto";
22017 var st = Roo.data.SortTypes;
22018 // named sortTypes are supported, here we look them up
22019 if(typeof this.sortType == "string"){
22020 this.sortType = st[this.sortType];
22023 // set default sortType for strings and dates
22024 if(!this.sortType){
22027 this.sortType = st.asUCString;
22030 this.sortType = st.asDate;
22033 this.sortType = st.none;
22038 var stripRe = /[\$,%]/g;
22040 // prebuilt conversion function for this field, instead of
22041 // switching every time we're reading a value
22043 var cv, dateFormat = this.dateFormat;
22048 cv = function(v){ return v; };
22051 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
22055 return v !== undefined && v !== null && v !== '' ?
22056 parseInt(String(v).replace(stripRe, ""), 10) : '';
22061 return v !== undefined && v !== null && v !== '' ?
22062 parseFloat(String(v).replace(stripRe, ""), 10) : '';
22067 cv = function(v){ return v === true || v === "true" || v == 1; };
22074 if(v instanceof Date){
22078 if(dateFormat == "timestamp"){
22079 return new Date(v*1000);
22081 return Date.parseDate(v, dateFormat);
22083 var parsed = Date.parse(v);
22084 return parsed ? new Date(parsed) : null;
22093 Roo.data.Field.prototype = {
22101 * Ext JS Library 1.1.1
22102 * Copyright(c) 2006-2007, Ext JS, LLC.
22104 * Originally Released Under LGPL - original licence link has changed is not relivant.
22107 * <script type="text/javascript">
22110 // Base class for reading structured data from a data source. This class is intended to be
22111 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
22114 * @class Roo.data.DataReader
22115 * Base class for reading structured data from a data source. This class is intended to be
22116 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
22119 Roo.data.DataReader = function(meta, recordType){
22123 this.recordType = recordType instanceof Array ?
22124 Roo.data.Record.create(recordType) : recordType;
22127 Roo.data.DataReader.prototype = {
22129 * Create an empty record
22130 * @param {Object} data (optional) - overlay some values
22131 * @return {Roo.data.Record} record created.
22133 newRow : function(d) {
22135 this.recordType.prototype.fields.each(function(c) {
22137 case 'int' : da[c.name] = 0; break;
22138 case 'date' : da[c.name] = new Date(); break;
22139 case 'float' : da[c.name] = 0.0; break;
22140 case 'boolean' : da[c.name] = false; break;
22141 default : da[c.name] = ""; break;
22145 return new this.recordType(Roo.apply(da, d));
22150 * Ext JS Library 1.1.1
22151 * Copyright(c) 2006-2007, Ext JS, LLC.
22153 * Originally Released Under LGPL - original licence link has changed is not relivant.
22156 * <script type="text/javascript">
22160 * @class Roo.data.DataProxy
22161 * @extends Roo.data.Observable
22162 * This class is an abstract base class for implementations which provide retrieval of
22163 * unformatted data objects.<br>
22165 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
22166 * (of the appropriate type which knows how to parse the data object) to provide a block of
22167 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
22169 * Custom implementations must implement the load method as described in
22170 * {@link Roo.data.HttpProxy#load}.
22172 Roo.data.DataProxy = function(){
22175 * @event beforeload
22176 * Fires before a network request is made to retrieve a data object.
22177 * @param {Object} This DataProxy object.
22178 * @param {Object} params The params parameter to the load function.
22183 * Fires before the load method's callback is called.
22184 * @param {Object} This DataProxy object.
22185 * @param {Object} o The data object.
22186 * @param {Object} arg The callback argument object passed to the load function.
22190 * @event loadexception
22191 * Fires if an Exception occurs during data retrieval.
22192 * @param {Object} This DataProxy object.
22193 * @param {Object} o The data object.
22194 * @param {Object} arg The callback argument object passed to the load function.
22195 * @param {Object} e The Exception.
22197 loadexception : true
22199 Roo.data.DataProxy.superclass.constructor.call(this);
22202 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
22205 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
22209 * Ext JS Library 1.1.1
22210 * Copyright(c) 2006-2007, Ext JS, LLC.
22212 * Originally Released Under LGPL - original licence link has changed is not relivant.
22215 * <script type="text/javascript">
22218 * @class Roo.data.MemoryProxy
22219 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
22220 * to the Reader when its load method is called.
22222 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
22224 Roo.data.MemoryProxy = function(data){
22228 Roo.data.MemoryProxy.superclass.constructor.call(this);
22232 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
22234 * Load data from the requested source (in this case an in-memory
22235 * data object passed to the constructor), read the data object into
22236 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
22237 * process that block using the passed callback.
22238 * @param {Object} params This parameter is not used by the MemoryProxy class.
22239 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22240 * object into a block of Roo.data.Records.
22241 * @param {Function} callback The function into which to pass the block of Roo.data.records.
22242 * The function must be passed <ul>
22243 * <li>The Record block object</li>
22244 * <li>The "arg" argument from the load function</li>
22245 * <li>A boolean success indicator</li>
22247 * @param {Object} scope The scope in which to call the callback
22248 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22250 load : function(params, reader, callback, scope, arg){
22251 params = params || {};
22254 result = reader.readRecords(this.data);
22256 this.fireEvent("loadexception", this, arg, null, e);
22257 callback.call(scope, null, arg, false);
22260 callback.call(scope, result, arg, true);
22264 update : function(params, records){
22269 * Ext JS Library 1.1.1
22270 * Copyright(c) 2006-2007, Ext JS, LLC.
22272 * Originally Released Under LGPL - original licence link has changed is not relivant.
22275 * <script type="text/javascript">
22278 * @class Roo.data.HttpProxy
22279 * @extends Roo.data.DataProxy
22280 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
22281 * configured to reference a certain URL.<br><br>
22283 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
22284 * from which the running page was served.<br><br>
22286 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
22288 * Be aware that to enable the browser to parse an XML document, the server must set
22289 * the Content-Type header in the HTTP response to "text/xml".
22291 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
22292 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
22293 * will be used to make the request.
22295 Roo.data.HttpProxy = function(conn){
22296 Roo.data.HttpProxy.superclass.constructor.call(this);
22297 // is conn a conn config or a real conn?
22299 this.useAjax = !conn || !conn.events;
22303 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
22304 // thse are take from connection...
22307 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
22310 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
22311 * extra parameters to each request made by this object. (defaults to undefined)
22314 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
22315 * to each request made by this object. (defaults to undefined)
22318 * @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)
22321 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
22324 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
22330 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
22334 * Return the {@link Roo.data.Connection} object being used by this Proxy.
22335 * @return {Connection} The Connection object. This object may be used to subscribe to events on
22336 * a finer-grained basis than the DataProxy events.
22338 getConnection : function(){
22339 return this.useAjax ? Roo.Ajax : this.conn;
22343 * Load data from the configured {@link Roo.data.Connection}, read the data object into
22344 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
22345 * process that block using the passed callback.
22346 * @param {Object} params An object containing properties which are to be used as HTTP parameters
22347 * for the request to the remote server.
22348 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22349 * object into a block of Roo.data.Records.
22350 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
22351 * The function must be passed <ul>
22352 * <li>The Record block object</li>
22353 * <li>The "arg" argument from the load function</li>
22354 * <li>A boolean success indicator</li>
22356 * @param {Object} scope The scope in which to call the callback
22357 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22359 load : function(params, reader, callback, scope, arg){
22360 if(this.fireEvent("beforeload", this, params) !== false){
22362 params : params || {},
22364 callback : callback,
22369 callback : this.loadResponse,
22373 Roo.applyIf(o, this.conn);
22374 if(this.activeRequest){
22375 Roo.Ajax.abort(this.activeRequest);
22377 this.activeRequest = Roo.Ajax.request(o);
22379 this.conn.request(o);
22382 callback.call(scope||this, null, arg, false);
22387 loadResponse : function(o, success, response){
22388 delete this.activeRequest;
22390 this.fireEvent("loadexception", this, o, response);
22391 o.request.callback.call(o.request.scope, null, o.request.arg, false);
22396 result = o.reader.read(response);
22398 this.fireEvent("loadexception", this, o, response, e);
22399 o.request.callback.call(o.request.scope, null, o.request.arg, false);
22403 this.fireEvent("load", this, o, o.request.arg);
22404 o.request.callback.call(o.request.scope, result, o.request.arg, true);
22408 update : function(dataSet){
22413 updateResponse : function(dataSet){
22418 * Ext JS Library 1.1.1
22419 * Copyright(c) 2006-2007, Ext JS, LLC.
22421 * Originally Released Under LGPL - original licence link has changed is not relivant.
22424 * <script type="text/javascript">
22428 * @class Roo.data.ScriptTagProxy
22429 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
22430 * other than the originating domain of the running page.<br><br>
22432 * <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
22433 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
22435 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
22436 * source code that is used as the source inside a <script> tag.<br><br>
22438 * In order for the browser to process the returned data, the server must wrap the data object
22439 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
22440 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
22441 * depending on whether the callback name was passed:
22444 boolean scriptTag = false;
22445 String cb = request.getParameter("callback");
22448 response.setContentType("text/javascript");
22450 response.setContentType("application/x-json");
22452 Writer out = response.getWriter();
22454 out.write(cb + "(");
22456 out.print(dataBlock.toJsonString());
22463 * @param {Object} config A configuration object.
22465 Roo.data.ScriptTagProxy = function(config){
22466 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
22467 Roo.apply(this, config);
22468 this.head = document.getElementsByTagName("head")[0];
22471 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
22473 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
22475 * @cfg {String} url The URL from which to request the data object.
22478 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
22482 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
22483 * the server the name of the callback function set up by the load call to process the returned data object.
22484 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
22485 * javascript output which calls this named function passing the data object as its only parameter.
22487 callbackParam : "callback",
22489 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
22490 * name to the request.
22495 * Load data from the configured URL, read the data object into
22496 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
22497 * process that block using the passed callback.
22498 * @param {Object} params An object containing properties which are to be used as HTTP parameters
22499 * for the request to the remote server.
22500 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22501 * object into a block of Roo.data.Records.
22502 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
22503 * The function must be passed <ul>
22504 * <li>The Record block object</li>
22505 * <li>The "arg" argument from the load function</li>
22506 * <li>A boolean success indicator</li>
22508 * @param {Object} scope The scope in which to call the callback
22509 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22511 load : function(params, reader, callback, scope, arg){
22512 if(this.fireEvent("beforeload", this, params) !== false){
22514 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
22516 var url = this.url;
22517 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
22519 url += "&_dc=" + (new Date().getTime());
22521 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
22524 cb : "stcCallback"+transId,
22525 scriptId : "stcScript"+transId,
22529 callback : callback,
22535 window[trans.cb] = function(o){
22536 conn.handleResponse(o, trans);
22539 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
22541 if(this.autoAbort !== false){
22545 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
22547 var script = document.createElement("script");
22548 script.setAttribute("src", url);
22549 script.setAttribute("type", "text/javascript");
22550 script.setAttribute("id", trans.scriptId);
22551 this.head.appendChild(script);
22553 this.trans = trans;
22555 callback.call(scope||this, null, arg, false);
22560 isLoading : function(){
22561 return this.trans ? true : false;
22565 * Abort the current server request.
22567 abort : function(){
22568 if(this.isLoading()){
22569 this.destroyTrans(this.trans);
22574 destroyTrans : function(trans, isLoaded){
22575 this.head.removeChild(document.getElementById(trans.scriptId));
22576 clearTimeout(trans.timeoutId);
22578 window[trans.cb] = undefined;
22580 delete window[trans.cb];
22583 // if hasn't been loaded, wait for load to remove it to prevent script error
22584 window[trans.cb] = function(){
22585 window[trans.cb] = undefined;
22587 delete window[trans.cb];
22594 handleResponse : function(o, trans){
22595 this.trans = false;
22596 this.destroyTrans(trans, true);
22599 result = trans.reader.readRecords(o);
22601 this.fireEvent("loadexception", this, o, trans.arg, e);
22602 trans.callback.call(trans.scope||window, null, trans.arg, false);
22605 this.fireEvent("load", this, o, trans.arg);
22606 trans.callback.call(trans.scope||window, result, trans.arg, true);
22610 handleFailure : function(trans){
22611 this.trans = false;
22612 this.destroyTrans(trans, false);
22613 this.fireEvent("loadexception", this, null, trans.arg);
22614 trans.callback.call(trans.scope||window, null, trans.arg, false);
22618 * Ext JS Library 1.1.1
22619 * Copyright(c) 2006-2007, Ext JS, LLC.
22621 * Originally Released Under LGPL - original licence link has changed is not relivant.
22624 * <script type="text/javascript">
22628 * @class Roo.data.JsonReader
22629 * @extends Roo.data.DataReader
22630 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
22631 * based on mappings in a provided Roo.data.Record constructor.
22633 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
22634 * in the reply previously.
22639 var RecordDef = Roo.data.Record.create([
22640 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
22641 {name: 'occupation'} // This field will use "occupation" as the mapping.
22643 var myReader = new Roo.data.JsonReader({
22644 totalProperty: "results", // The property which contains the total dataset size (optional)
22645 root: "rows", // The property which contains an Array of row objects
22646 id: "id" // The property within each row object that provides an ID for the record (optional)
22650 * This would consume a JSON file like this:
22652 { 'results': 2, 'rows': [
22653 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
22654 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
22657 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
22658 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
22659 * paged from the remote server.
22660 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
22661 * @cfg {String} root name of the property which contains the Array of row objects.
22662 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
22664 * Create a new JsonReader
22665 * @param {Object} meta Metadata configuration options
22666 * @param {Object} recordType Either an Array of field definition objects,
22667 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
22669 Roo.data.JsonReader = function(meta, recordType){
22672 // set some defaults:
22673 Roo.applyIf(meta, {
22674 totalProperty: 'total',
22675 successProperty : 'success',
22680 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
22682 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
22685 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
22686 * Used by Store query builder to append _requestMeta to params.
22689 metaFromRemote : false,
22691 * This method is only used by a DataProxy which has retrieved data from a remote server.
22692 * @param {Object} response The XHR object which contains the JSON data in its responseText.
22693 * @return {Object} data A data block which is used by an Roo.data.Store object as
22694 * a cache of Roo.data.Records.
22696 read : function(response){
22697 var json = response.responseText;
22699 var o = /* eval:var:o */ eval("("+json+")");
22701 throw {message: "JsonReader.read: Json object not found"};
22707 this.metaFromRemote = true;
22708 this.meta = o.metaData;
22709 this.recordType = Roo.data.Record.create(o.metaData.fields);
22710 this.onMetaChange(this.meta, this.recordType, o);
22712 return this.readRecords(o);
22715 // private function a store will implement
22716 onMetaChange : function(meta, recordType, o){
22723 simpleAccess: function(obj, subsc) {
22730 getJsonAccessor: function(){
22732 return function(expr) {
22734 return(re.test(expr))
22735 ? new Function("obj", "return obj." + expr)
22740 return Roo.emptyFn;
22745 * Create a data block containing Roo.data.Records from an XML document.
22746 * @param {Object} o An object which contains an Array of row objects in the property specified
22747 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
22748 * which contains the total size of the dataset.
22749 * @return {Object} data A data block which is used by an Roo.data.Store object as
22750 * a cache of Roo.data.Records.
22752 readRecords : function(o){
22754 * After any data loads, the raw JSON data is available for further custom processing.
22758 var s = this.meta, Record = this.recordType,
22759 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
22761 // Generate extraction functions for the totalProperty, the root, the id, and for each field
22763 if(s.totalProperty) {
22764 this.getTotal = this.getJsonAccessor(s.totalProperty);
22766 if(s.successProperty) {
22767 this.getSuccess = this.getJsonAccessor(s.successProperty);
22769 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
22771 var g = this.getJsonAccessor(s.id);
22772 this.getId = function(rec) {
22774 return (r === undefined || r === "") ? null : r;
22777 this.getId = function(){return null;};
22780 for(var jj = 0; jj < fl; jj++){
22782 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
22783 this.ef[jj] = this.getJsonAccessor(map);
22787 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
22788 if(s.totalProperty){
22789 var vt = parseInt(this.getTotal(o), 10);
22794 if(s.successProperty){
22795 var vs = this.getSuccess(o);
22796 if(vs === false || vs === 'false'){
22801 for(var i = 0; i < c; i++){
22804 var id = this.getId(n);
22805 for(var j = 0; j < fl; j++){
22807 var v = this.ef[j](n);
22809 Roo.log('missing convert for ' + f.name);
22813 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
22815 var record = new Record(values, id);
22817 records[i] = record;
22823 totalRecords : totalRecords
22828 * Ext JS Library 1.1.1
22829 * Copyright(c) 2006-2007, Ext JS, LLC.
22831 * Originally Released Under LGPL - original licence link has changed is not relivant.
22834 * <script type="text/javascript">
22838 * @class Roo.data.XmlReader
22839 * @extends Roo.data.DataReader
22840 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
22841 * based on mappings in a provided Roo.data.Record constructor.<br><br>
22843 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
22844 * header in the HTTP response must be set to "text/xml".</em>
22848 var RecordDef = Roo.data.Record.create([
22849 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
22850 {name: 'occupation'} // This field will use "occupation" as the mapping.
22852 var myReader = new Roo.data.XmlReader({
22853 totalRecords: "results", // The element which contains the total dataset size (optional)
22854 record: "row", // The repeated element which contains row information
22855 id: "id" // The element within the row that provides an ID for the record (optional)
22859 * This would consume an XML file like this:
22863 <results>2</results>
22866 <name>Bill</name>
22867 <occupation>Gardener</occupation>
22871 <name>Ben</name>
22872 <occupation>Horticulturalist</occupation>
22876 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
22877 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
22878 * paged from the remote server.
22879 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
22880 * @cfg {String} success The DomQuery path to the success attribute used by forms.
22881 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
22882 * a record identifier value.
22884 * Create a new XmlReader
22885 * @param {Object} meta Metadata configuration options
22886 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
22887 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
22888 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
22890 Roo.data.XmlReader = function(meta, recordType){
22892 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
22894 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
22896 * This method is only used by a DataProxy which has retrieved data from a remote server.
22897 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
22898 * to contain a method called 'responseXML' that returns an XML document object.
22899 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
22900 * a cache of Roo.data.Records.
22902 read : function(response){
22903 var doc = response.responseXML;
22905 throw {message: "XmlReader.read: XML Document not available"};
22907 return this.readRecords(doc);
22911 * Create a data block containing Roo.data.Records from an XML document.
22912 * @param {Object} doc A parsed XML document.
22913 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
22914 * a cache of Roo.data.Records.
22916 readRecords : function(doc){
22918 * After any data loads/reads, the raw XML Document is available for further custom processing.
22919 * @type XMLDocument
22921 this.xmlData = doc;
22922 var root = doc.documentElement || doc;
22923 var q = Roo.DomQuery;
22924 var recordType = this.recordType, fields = recordType.prototype.fields;
22925 var sid = this.meta.id;
22926 var totalRecords = 0, success = true;
22927 if(this.meta.totalRecords){
22928 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
22931 if(this.meta.success){
22932 var sv = q.selectValue(this.meta.success, root, true);
22933 success = sv !== false && sv !== 'false';
22936 var ns = q.select(this.meta.record, root);
22937 for(var i = 0, len = ns.length; i < len; i++) {
22940 var id = sid ? q.selectValue(sid, n) : undefined;
22941 for(var j = 0, jlen = fields.length; j < jlen; j++){
22942 var f = fields.items[j];
22943 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
22945 values[f.name] = v;
22947 var record = new recordType(values, id);
22949 records[records.length] = record;
22955 totalRecords : totalRecords || records.length
22960 * Ext JS Library 1.1.1
22961 * Copyright(c) 2006-2007, Ext JS, LLC.
22963 * Originally Released Under LGPL - original licence link has changed is not relivant.
22966 * <script type="text/javascript">
22970 * @class Roo.data.ArrayReader
22971 * @extends Roo.data.DataReader
22972 * Data reader class to create an Array of Roo.data.Record objects from an Array.
22973 * Each element of that Array represents a row of data fields. The
22974 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
22975 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
22979 var RecordDef = Roo.data.Record.create([
22980 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
22981 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
22983 var myReader = new Roo.data.ArrayReader({
22984 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
22988 * This would consume an Array like this:
22990 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
22992 * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
22994 * Create a new JsonReader
22995 * @param {Object} meta Metadata configuration options.
22996 * @param {Object} recordType Either an Array of field definition objects
22997 * as specified to {@link Roo.data.Record#create},
22998 * or an {@link Roo.data.Record} object
22999 * created using {@link Roo.data.Record#create}.
23001 Roo.data.ArrayReader = function(meta, recordType){
23002 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
23005 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
23007 * Create a data block containing Roo.data.Records from an XML document.
23008 * @param {Object} o An Array of row objects which represents the dataset.
23009 * @return {Object} data A data block which is used by an Roo.data.Store object as
23010 * a cache of Roo.data.Records.
23012 readRecords : function(o){
23013 var sid = this.meta ? this.meta.id : null;
23014 var recordType = this.recordType, fields = recordType.prototype.fields;
23017 for(var i = 0; i < root.length; i++){
23020 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
23021 for(var j = 0, jlen = fields.length; j < jlen; j++){
23022 var f = fields.items[j];
23023 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
23024 var v = n[k] !== undefined ? n[k] : f.defaultValue;
23026 values[f.name] = v;
23028 var record = new recordType(values, id);
23030 records[records.length] = record;
23034 totalRecords : records.length
23039 * Ext JS Library 1.1.1
23040 * Copyright(c) 2006-2007, Ext JS, LLC.
23042 * Originally Released Under LGPL - original licence link has changed is not relivant.
23045 * <script type="text/javascript">
23050 * @class Roo.data.Tree
23051 * @extends Roo.util.Observable
23052 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
23053 * in the tree have most standard DOM functionality.
23055 * @param {Node} root (optional) The root node
23057 Roo.data.Tree = function(root){
23058 this.nodeHash = {};
23060 * The root node for this tree
23065 this.setRootNode(root);
23070 * Fires when a new child node is appended to a node in this tree.
23071 * @param {Tree} tree The owner tree
23072 * @param {Node} parent The parent node
23073 * @param {Node} node The newly appended node
23074 * @param {Number} index The index of the newly appended node
23079 * Fires when a child node is removed from a node in this tree.
23080 * @param {Tree} tree The owner tree
23081 * @param {Node} parent The parent node
23082 * @param {Node} node The child node removed
23087 * Fires when a node is moved to a new location in the tree
23088 * @param {Tree} tree The owner tree
23089 * @param {Node} node The node moved
23090 * @param {Node} oldParent The old parent of this node
23091 * @param {Node} newParent The new parent of this node
23092 * @param {Number} index The index it was moved to
23097 * Fires when a new child node is inserted in a node in this tree.
23098 * @param {Tree} tree The owner tree
23099 * @param {Node} parent The parent node
23100 * @param {Node} node The child node inserted
23101 * @param {Node} refNode The child node the node was inserted before
23105 * @event beforeappend
23106 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
23107 * @param {Tree} tree The owner tree
23108 * @param {Node} parent The parent node
23109 * @param {Node} node The child node to be appended
23111 "beforeappend" : true,
23113 * @event beforeremove
23114 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
23115 * @param {Tree} tree The owner tree
23116 * @param {Node} parent The parent node
23117 * @param {Node} node The child node to be removed
23119 "beforeremove" : true,
23121 * @event beforemove
23122 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
23123 * @param {Tree} tree The owner tree
23124 * @param {Node} node The node being moved
23125 * @param {Node} oldParent The parent of the node
23126 * @param {Node} newParent The new parent the node is moving to
23127 * @param {Number} index The index it is being moved to
23129 "beforemove" : true,
23131 * @event beforeinsert
23132 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
23133 * @param {Tree} tree The owner tree
23134 * @param {Node} parent The parent node
23135 * @param {Node} node The child node to be inserted
23136 * @param {Node} refNode The child node the node is being inserted before
23138 "beforeinsert" : true
23141 Roo.data.Tree.superclass.constructor.call(this);
23144 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
23145 pathSeparator: "/",
23147 proxyNodeEvent : function(){
23148 return this.fireEvent.apply(this, arguments);
23152 * Returns the root node for this tree.
23155 getRootNode : function(){
23160 * Sets the root node for this tree.
23161 * @param {Node} node
23164 setRootNode : function(node){
23166 node.ownerTree = this;
23167 node.isRoot = true;
23168 this.registerNode(node);
23173 * Gets a node in this tree by its id.
23174 * @param {String} id
23177 getNodeById : function(id){
23178 return this.nodeHash[id];
23181 registerNode : function(node){
23182 this.nodeHash[node.id] = node;
23185 unregisterNode : function(node){
23186 delete this.nodeHash[node.id];
23189 toString : function(){
23190 return "[Tree"+(this.id?" "+this.id:"")+"]";
23195 * @class Roo.data.Node
23196 * @extends Roo.util.Observable
23197 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
23198 * @cfg {String} id The id for this node. If one is not specified, one is generated.
23200 * @param {Object} attributes The attributes/config for the node
23202 Roo.data.Node = function(attributes){
23204 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
23207 this.attributes = attributes || {};
23208 this.leaf = this.attributes.leaf;
23210 * The node id. @type String
23212 this.id = this.attributes.id;
23214 this.id = Roo.id(null, "ynode-");
23215 this.attributes.id = this.id;
23220 * All child nodes of this node. @type Array
23222 this.childNodes = [];
23223 if(!this.childNodes.indexOf){ // indexOf is a must
23224 this.childNodes.indexOf = function(o){
23225 for(var i = 0, len = this.length; i < len; i++){
23234 * The parent node for this node. @type Node
23236 this.parentNode = null;
23238 * The first direct child node of this node, or null if this node has no child nodes. @type Node
23240 this.firstChild = null;
23242 * The last direct child node of this node, or null if this node has no child nodes. @type Node
23244 this.lastChild = null;
23246 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
23248 this.previousSibling = null;
23250 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
23252 this.nextSibling = null;
23257 * Fires when a new child node is appended
23258 * @param {Tree} tree The owner tree
23259 * @param {Node} this This node
23260 * @param {Node} node The newly appended node
23261 * @param {Number} index The index of the newly appended node
23266 * Fires when a child node is removed
23267 * @param {Tree} tree The owner tree
23268 * @param {Node} this This node
23269 * @param {Node} node The removed node
23274 * Fires when this node is moved to a new location in the tree
23275 * @param {Tree} tree The owner tree
23276 * @param {Node} this This node
23277 * @param {Node} oldParent The old parent of this node
23278 * @param {Node} newParent The new parent of this node
23279 * @param {Number} index The index it was moved to
23284 * Fires when a new child node is inserted.
23285 * @param {Tree} tree The owner tree
23286 * @param {Node} this This node
23287 * @param {Node} node The child node inserted
23288 * @param {Node} refNode The child node the node was inserted before
23292 * @event beforeappend
23293 * Fires before a new child is appended, return false to cancel the append.
23294 * @param {Tree} tree The owner tree
23295 * @param {Node} this This node
23296 * @param {Node} node The child node to be appended
23298 "beforeappend" : true,
23300 * @event beforeremove
23301 * Fires before a child is removed, return false to cancel the remove.
23302 * @param {Tree} tree The owner tree
23303 * @param {Node} this This node
23304 * @param {Node} node The child node to be removed
23306 "beforeremove" : true,
23308 * @event beforemove
23309 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
23310 * @param {Tree} tree The owner tree
23311 * @param {Node} this This node
23312 * @param {Node} oldParent The parent of this node
23313 * @param {Node} newParent The new parent this node is moving to
23314 * @param {Number} index The index it is being moved to
23316 "beforemove" : true,
23318 * @event beforeinsert
23319 * Fires before a new child is inserted, return false to cancel the insert.
23320 * @param {Tree} tree The owner tree
23321 * @param {Node} this This node
23322 * @param {Node} node The child node to be inserted
23323 * @param {Node} refNode The child node the node is being inserted before
23325 "beforeinsert" : true
23327 this.listeners = this.attributes.listeners;
23328 Roo.data.Node.superclass.constructor.call(this);
23331 Roo.extend(Roo.data.Node, Roo.util.Observable, {
23332 fireEvent : function(evtName){
23333 // first do standard event for this node
23334 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
23337 // then bubble it up to the tree if the event wasn't cancelled
23338 var ot = this.getOwnerTree();
23340 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
23348 * Returns true if this node is a leaf
23349 * @return {Boolean}
23351 isLeaf : function(){
23352 return this.leaf === true;
23356 setFirstChild : function(node){
23357 this.firstChild = node;
23361 setLastChild : function(node){
23362 this.lastChild = node;
23367 * Returns true if this node is the last child of its parent
23368 * @return {Boolean}
23370 isLast : function(){
23371 return (!this.parentNode ? true : this.parentNode.lastChild == this);
23375 * Returns true if this node is the first child of its parent
23376 * @return {Boolean}
23378 isFirst : function(){
23379 return (!this.parentNode ? true : this.parentNode.firstChild == this);
23382 hasChildNodes : function(){
23383 return !this.isLeaf() && this.childNodes.length > 0;
23387 * Insert node(s) as the last child node of this node.
23388 * @param {Node/Array} node The node or Array of nodes to append
23389 * @return {Node} The appended node if single append, or null if an array was passed
23391 appendChild : function(node){
23393 if(node instanceof Array){
23395 }else if(arguments.length > 1){
23398 // if passed an array or multiple args do them one by one
23400 for(var i = 0, len = multi.length; i < len; i++) {
23401 this.appendChild(multi[i]);
23404 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
23407 var index = this.childNodes.length;
23408 var oldParent = node.parentNode;
23409 // it's a move, make sure we move it cleanly
23411 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
23414 oldParent.removeChild(node);
23416 index = this.childNodes.length;
23418 this.setFirstChild(node);
23420 this.childNodes.push(node);
23421 node.parentNode = this;
23422 var ps = this.childNodes[index-1];
23424 node.previousSibling = ps;
23425 ps.nextSibling = node;
23427 node.previousSibling = null;
23429 node.nextSibling = null;
23430 this.setLastChild(node);
23431 node.setOwnerTree(this.getOwnerTree());
23432 this.fireEvent("append", this.ownerTree, this, node, index);
23434 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
23441 * Removes a child node from this node.
23442 * @param {Node} node The node to remove
23443 * @return {Node} The removed node
23445 removeChild : function(node){
23446 var index = this.childNodes.indexOf(node);
23450 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
23454 // remove it from childNodes collection
23455 this.childNodes.splice(index, 1);
23458 if(node.previousSibling){
23459 node.previousSibling.nextSibling = node.nextSibling;
23461 if(node.nextSibling){
23462 node.nextSibling.previousSibling = node.previousSibling;
23465 // update child refs
23466 if(this.firstChild == node){
23467 this.setFirstChild(node.nextSibling);
23469 if(this.lastChild == node){
23470 this.setLastChild(node.previousSibling);
23473 node.setOwnerTree(null);
23474 // clear any references from the node
23475 node.parentNode = null;
23476 node.previousSibling = null;
23477 node.nextSibling = null;
23478 this.fireEvent("remove", this.ownerTree, this, node);
23483 * Inserts the first node before the second node in this nodes childNodes collection.
23484 * @param {Node} node The node to insert
23485 * @param {Node} refNode The node to insert before (if null the node is appended)
23486 * @return {Node} The inserted node
23488 insertBefore : function(node, refNode){
23489 if(!refNode){ // like standard Dom, refNode can be null for append
23490 return this.appendChild(node);
23493 if(node == refNode){
23497 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
23500 var index = this.childNodes.indexOf(refNode);
23501 var oldParent = node.parentNode;
23502 var refIndex = index;
23504 // when moving internally, indexes will change after remove
23505 if(oldParent == this && this.childNodes.indexOf(node) < index){
23509 // it's a move, make sure we move it cleanly
23511 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
23514 oldParent.removeChild(node);
23517 this.setFirstChild(node);
23519 this.childNodes.splice(refIndex, 0, node);
23520 node.parentNode = this;
23521 var ps = this.childNodes[refIndex-1];
23523 node.previousSibling = ps;
23524 ps.nextSibling = node;
23526 node.previousSibling = null;
23528 node.nextSibling = refNode;
23529 refNode.previousSibling = node;
23530 node.setOwnerTree(this.getOwnerTree());
23531 this.fireEvent("insert", this.ownerTree, this, node, refNode);
23533 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
23539 * Returns the child node at the specified index.
23540 * @param {Number} index
23543 item : function(index){
23544 return this.childNodes[index];
23548 * Replaces one child node in this node with another.
23549 * @param {Node} newChild The replacement node
23550 * @param {Node} oldChild The node to replace
23551 * @return {Node} The replaced node
23553 replaceChild : function(newChild, oldChild){
23554 this.insertBefore(newChild, oldChild);
23555 this.removeChild(oldChild);
23560 * Returns the index of a child node
23561 * @param {Node} node
23562 * @return {Number} The index of the node or -1 if it was not found
23564 indexOf : function(child){
23565 return this.childNodes.indexOf(child);
23569 * Returns the tree this node is in.
23572 getOwnerTree : function(){
23573 // if it doesn't have one, look for one
23574 if(!this.ownerTree){
23578 this.ownerTree = p.ownerTree;
23584 return this.ownerTree;
23588 * Returns depth of this node (the root node has a depth of 0)
23591 getDepth : function(){
23594 while(p.parentNode){
23602 setOwnerTree : function(tree){
23603 // if it's move, we need to update everyone
23604 if(tree != this.ownerTree){
23605 if(this.ownerTree){
23606 this.ownerTree.unregisterNode(this);
23608 this.ownerTree = tree;
23609 var cs = this.childNodes;
23610 for(var i = 0, len = cs.length; i < len; i++) {
23611 cs[i].setOwnerTree(tree);
23614 tree.registerNode(this);
23620 * Returns the path for this node. The path can be used to expand or select this node programmatically.
23621 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
23622 * @return {String} The path
23624 getPath : function(attr){
23625 attr = attr || "id";
23626 var p = this.parentNode;
23627 var b = [this.attributes[attr]];
23629 b.unshift(p.attributes[attr]);
23632 var sep = this.getOwnerTree().pathSeparator;
23633 return sep + b.join(sep);
23637 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
23638 * function call will be the scope provided or the current node. The arguments to the function
23639 * will be the args provided or the current node. If the function returns false at any point,
23640 * the bubble is stopped.
23641 * @param {Function} fn The function to call
23642 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23643 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23645 bubble : function(fn, scope, args){
23648 if(fn.call(scope || p, args || p) === false){
23656 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
23657 * function call will be the scope provided or the current node. The arguments to the function
23658 * will be the args provided or the current node. If the function returns false at any point,
23659 * the cascade is stopped on that branch.
23660 * @param {Function} fn The function to call
23661 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23662 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23664 cascade : function(fn, scope, args){
23665 if(fn.call(scope || this, args || this) !== false){
23666 var cs = this.childNodes;
23667 for(var i = 0, len = cs.length; i < len; i++) {
23668 cs[i].cascade(fn, scope, args);
23674 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
23675 * function call will be the scope provided or the current node. The arguments to the function
23676 * will be the args provided or the current node. If the function returns false at any point,
23677 * the iteration stops.
23678 * @param {Function} fn The function to call
23679 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23680 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23682 eachChild : function(fn, scope, args){
23683 var cs = this.childNodes;
23684 for(var i = 0, len = cs.length; i < len; i++) {
23685 if(fn.call(scope || this, args || cs[i]) === false){
23692 * Finds the first child that has the attribute with the specified value.
23693 * @param {String} attribute The attribute name
23694 * @param {Mixed} value The value to search for
23695 * @return {Node} The found child or null if none was found
23697 findChild : function(attribute, value){
23698 var cs = this.childNodes;
23699 for(var i = 0, len = cs.length; i < len; i++) {
23700 if(cs[i].attributes[attribute] == value){
23708 * Finds the first child by a custom function. The child matches if the function passed
23710 * @param {Function} fn
23711 * @param {Object} scope (optional)
23712 * @return {Node} The found child or null if none was found
23714 findChildBy : function(fn, scope){
23715 var cs = this.childNodes;
23716 for(var i = 0, len = cs.length; i < len; i++) {
23717 if(fn.call(scope||cs[i], cs[i]) === true){
23725 * Sorts this nodes children using the supplied sort function
23726 * @param {Function} fn
23727 * @param {Object} scope (optional)
23729 sort : function(fn, scope){
23730 var cs = this.childNodes;
23731 var len = cs.length;
23733 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
23735 for(var i = 0; i < len; i++){
23737 n.previousSibling = cs[i-1];
23738 n.nextSibling = cs[i+1];
23740 this.setFirstChild(n);
23743 this.setLastChild(n);
23750 * Returns true if this node is an ancestor (at any point) of the passed node.
23751 * @param {Node} node
23752 * @return {Boolean}
23754 contains : function(node){
23755 return node.isAncestor(this);
23759 * Returns true if the passed node is an ancestor (at any point) of this node.
23760 * @param {Node} node
23761 * @return {Boolean}
23763 isAncestor : function(node){
23764 var p = this.parentNode;
23774 toString : function(){
23775 return "[Node"+(this.id?" "+this.id:"")+"]";
23779 * Ext JS Library 1.1.1
23780 * Copyright(c) 2006-2007, Ext JS, LLC.
23782 * Originally Released Under LGPL - original licence link has changed is not relivant.
23785 * <script type="text/javascript">
23790 * @extends Roo.Element
23791 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
23792 * automatic maintaining of shadow/shim positions.
23793 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
23794 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
23795 * you can pass a string with a CSS class name. False turns off the shadow.
23796 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
23797 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
23798 * @cfg {String} cls CSS class to add to the element
23799 * @cfg {Number} zindex Starting z-index (defaults to 11000)
23800 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
23802 * @param {Object} config An object with config options.
23803 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
23806 Roo.Layer = function(config, existingEl){
23807 config = config || {};
23808 var dh = Roo.DomHelper;
23809 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
23811 this.dom = Roo.getDom(existingEl);
23814 var o = config.dh || {tag: "div", cls: "x-layer"};
23815 this.dom = dh.append(pel, o);
23818 this.addClass(config.cls);
23820 this.constrain = config.constrain !== false;
23821 this.visibilityMode = Roo.Element.VISIBILITY;
23823 this.id = this.dom.id = config.id;
23825 this.id = Roo.id(this.dom);
23827 this.zindex = config.zindex || this.getZIndex();
23828 this.position("absolute", this.zindex);
23830 this.shadowOffset = config.shadowOffset || 4;
23831 this.shadow = new Roo.Shadow({
23832 offset : this.shadowOffset,
23833 mode : config.shadow
23836 this.shadowOffset = 0;
23838 this.useShim = config.shim !== false && Roo.useShims;
23839 this.useDisplay = config.useDisplay;
23843 var supr = Roo.Element.prototype;
23845 // shims are shared among layer to keep from having 100 iframes
23848 Roo.extend(Roo.Layer, Roo.Element, {
23850 getZIndex : function(){
23851 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
23854 getShim : function(){
23861 var shim = shims.shift();
23863 shim = this.createShim();
23864 shim.enableDisplayMode('block');
23865 shim.dom.style.display = 'none';
23866 shim.dom.style.visibility = 'visible';
23868 var pn = this.dom.parentNode;
23869 if(shim.dom.parentNode != pn){
23870 pn.insertBefore(shim.dom, this.dom);
23872 shim.setStyle('z-index', this.getZIndex()-2);
23877 hideShim : function(){
23879 this.shim.setDisplayed(false);
23880 shims.push(this.shim);
23885 disableShadow : function(){
23887 this.shadowDisabled = true;
23888 this.shadow.hide();
23889 this.lastShadowOffset = this.shadowOffset;
23890 this.shadowOffset = 0;
23894 enableShadow : function(show){
23896 this.shadowDisabled = false;
23897 this.shadowOffset = this.lastShadowOffset;
23898 delete this.lastShadowOffset;
23906 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
23907 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
23908 sync : function(doShow){
23909 var sw = this.shadow;
23910 if(!this.updating && this.isVisible() && (sw || this.useShim)){
23911 var sh = this.getShim();
23913 var w = this.getWidth(),
23914 h = this.getHeight();
23916 var l = this.getLeft(true),
23917 t = this.getTop(true);
23919 if(sw && !this.shadowDisabled){
23920 if(doShow && !sw.isVisible()){
23923 sw.realign(l, t, w, h);
23929 // fit the shim behind the shadow, so it is shimmed too
23930 var a = sw.adjusts, s = sh.dom.style;
23931 s.left = (Math.min(l, l+a.l))+"px";
23932 s.top = (Math.min(t, t+a.t))+"px";
23933 s.width = (w+a.w)+"px";
23934 s.height = (h+a.h)+"px";
23941 sh.setLeftTop(l, t);
23948 destroy : function(){
23951 this.shadow.hide();
23953 this.removeAllListeners();
23954 var pn = this.dom.parentNode;
23956 pn.removeChild(this.dom);
23958 Roo.Element.uncache(this.id);
23961 remove : function(){
23966 beginUpdate : function(){
23967 this.updating = true;
23971 endUpdate : function(){
23972 this.updating = false;
23977 hideUnders : function(negOffset){
23979 this.shadow.hide();
23985 constrainXY : function(){
23986 if(this.constrain){
23987 var vw = Roo.lib.Dom.getViewWidth(),
23988 vh = Roo.lib.Dom.getViewHeight();
23989 var s = Roo.get(document).getScroll();
23991 var xy = this.getXY();
23992 var x = xy[0], y = xy[1];
23993 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
23994 // only move it if it needs it
23996 // first validate right/bottom
23997 if((x + w) > vw+s.left){
23998 x = vw - w - this.shadowOffset;
24001 if((y + h) > vh+s.top){
24002 y = vh - h - this.shadowOffset;
24005 // then make sure top/left isn't negative
24016 var ay = this.avoidY;
24017 if(y <= ay && (y+h) >= ay){
24023 supr.setXY.call(this, xy);
24029 isVisible : function(){
24030 return this.visible;
24034 showAction : function(){
24035 this.visible = true; // track visibility to prevent getStyle calls
24036 if(this.useDisplay === true){
24037 this.setDisplayed("");
24038 }else if(this.lastXY){
24039 supr.setXY.call(this, this.lastXY);
24040 }else if(this.lastLT){
24041 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
24046 hideAction : function(){
24047 this.visible = false;
24048 if(this.useDisplay === true){
24049 this.setDisplayed(false);
24051 this.setLeftTop(-10000,-10000);
24055 // overridden Element method
24056 setVisible : function(v, a, d, c, e){
24061 var cb = function(){
24066 }.createDelegate(this);
24067 supr.setVisible.call(this, true, true, d, cb, e);
24070 this.hideUnders(true);
24079 }.createDelegate(this);
24081 supr.setVisible.call(this, v, a, d, cb, e);
24090 storeXY : function(xy){
24091 delete this.lastLT;
24095 storeLeftTop : function(left, top){
24096 delete this.lastXY;
24097 this.lastLT = [left, top];
24101 beforeFx : function(){
24102 this.beforeAction();
24103 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
24107 afterFx : function(){
24108 Roo.Layer.superclass.afterFx.apply(this, arguments);
24109 this.sync(this.isVisible());
24113 beforeAction : function(){
24114 if(!this.updating && this.shadow){
24115 this.shadow.hide();
24119 // overridden Element method
24120 setLeft : function(left){
24121 this.storeLeftTop(left, this.getTop(true));
24122 supr.setLeft.apply(this, arguments);
24126 setTop : function(top){
24127 this.storeLeftTop(this.getLeft(true), top);
24128 supr.setTop.apply(this, arguments);
24132 setLeftTop : function(left, top){
24133 this.storeLeftTop(left, top);
24134 supr.setLeftTop.apply(this, arguments);
24138 setXY : function(xy, a, d, c, e){
24140 this.beforeAction();
24142 var cb = this.createCB(c);
24143 supr.setXY.call(this, xy, a, d, cb, e);
24150 createCB : function(c){
24161 // overridden Element method
24162 setX : function(x, a, d, c, e){
24163 this.setXY([x, this.getY()], a, d, c, e);
24166 // overridden Element method
24167 setY : function(y, a, d, c, e){
24168 this.setXY([this.getX(), y], a, d, c, e);
24171 // overridden Element method
24172 setSize : function(w, h, a, d, c, e){
24173 this.beforeAction();
24174 var cb = this.createCB(c);
24175 supr.setSize.call(this, w, h, a, d, cb, e);
24181 // overridden Element method
24182 setWidth : function(w, a, d, c, e){
24183 this.beforeAction();
24184 var cb = this.createCB(c);
24185 supr.setWidth.call(this, w, a, d, cb, e);
24191 // overridden Element method
24192 setHeight : function(h, a, d, c, e){
24193 this.beforeAction();
24194 var cb = this.createCB(c);
24195 supr.setHeight.call(this, h, a, d, cb, e);
24201 // overridden Element method
24202 setBounds : function(x, y, w, h, a, d, c, e){
24203 this.beforeAction();
24204 var cb = this.createCB(c);
24206 this.storeXY([x, y]);
24207 supr.setXY.call(this, [x, y]);
24208 supr.setSize.call(this, w, h, a, d, cb, e);
24211 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
24217 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
24218 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
24219 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
24220 * @param {Number} zindex The new z-index to set
24221 * @return {this} The Layer
24223 setZIndex : function(zindex){
24224 this.zindex = zindex;
24225 this.setStyle("z-index", zindex + 2);
24227 this.shadow.setZIndex(zindex + 1);
24230 this.shim.setStyle("z-index", zindex);
24236 * Ext JS Library 1.1.1
24237 * Copyright(c) 2006-2007, Ext JS, LLC.
24239 * Originally Released Under LGPL - original licence link has changed is not relivant.
24242 * <script type="text/javascript">
24247 * @class Roo.Shadow
24248 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
24249 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
24250 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
24252 * Create a new Shadow
24253 * @param {Object} config The config object
24255 Roo.Shadow = function(config){
24256 Roo.apply(this, config);
24257 if(typeof this.mode != "string"){
24258 this.mode = this.defaultMode;
24260 var o = this.offset, a = {h: 0};
24261 var rad = Math.floor(this.offset/2);
24262 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
24268 a.l -= this.offset + rad;
24269 a.t -= this.offset + rad;
24280 a.l -= (this.offset - rad);
24281 a.t -= this.offset + rad;
24283 a.w -= (this.offset - rad)*2;
24294 a.l -= (this.offset - rad);
24295 a.t -= (this.offset - rad);
24297 a.w -= (this.offset + rad + 1);
24298 a.h -= (this.offset + rad);
24307 Roo.Shadow.prototype = {
24309 * @cfg {String} mode
24310 * The shadow display mode. Supports the following options:<br />
24311 * sides: Shadow displays on both sides and bottom only<br />
24312 * frame: Shadow displays equally on all four sides<br />
24313 * drop: Traditional bottom-right drop shadow (default)
24316 * @cfg {String} offset
24317 * The number of pixels to offset the shadow from the element (defaults to 4)
24322 defaultMode: "drop",
24325 * Displays the shadow under the target element
24326 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
24328 show : function(target){
24329 target = Roo.get(target);
24331 this.el = Roo.Shadow.Pool.pull();
24332 if(this.el.dom.nextSibling != target.dom){
24333 this.el.insertBefore(target);
24336 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
24338 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
24341 target.getLeft(true),
24342 target.getTop(true),
24346 this.el.dom.style.display = "block";
24350 * Returns true if the shadow is visible, else false
24352 isVisible : function(){
24353 return this.el ? true : false;
24357 * Direct alignment when values are already available. Show must be called at least once before
24358 * calling this method to ensure it is initialized.
24359 * @param {Number} left The target element left position
24360 * @param {Number} top The target element top position
24361 * @param {Number} width The target element width
24362 * @param {Number} height The target element height
24364 realign : function(l, t, w, h){
24368 var a = this.adjusts, d = this.el.dom, s = d.style;
24370 s.left = (l+a.l)+"px";
24371 s.top = (t+a.t)+"px";
24372 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
24374 if(s.width != sws || s.height != shs){
24378 var cn = d.childNodes;
24379 var sww = Math.max(0, (sw-12))+"px";
24380 cn[0].childNodes[1].style.width = sww;
24381 cn[1].childNodes[1].style.width = sww;
24382 cn[2].childNodes[1].style.width = sww;
24383 cn[1].style.height = Math.max(0, (sh-12))+"px";
24389 * Hides this shadow
24393 this.el.dom.style.display = "none";
24394 Roo.Shadow.Pool.push(this.el);
24400 * Adjust the z-index of this shadow
24401 * @param {Number} zindex The new z-index
24403 setZIndex : function(z){
24406 this.el.setStyle("z-index", z);
24411 // Private utility class that manages the internal Shadow cache
24412 Roo.Shadow.Pool = function(){
24414 var markup = Roo.isIE ?
24415 '<div class="x-ie-shadow"></div>' :
24416 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
24419 var sh = p.shift();
24421 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
24422 sh.autoBoxAdjust = false;
24427 push : function(sh){
24433 * Ext JS Library 1.1.1
24434 * Copyright(c) 2006-2007, Ext JS, LLC.
24436 * Originally Released Under LGPL - original licence link has changed is not relivant.
24439 * <script type="text/javascript">
24444 * @class Roo.SplitBar
24445 * @extends Roo.util.Observable
24446 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
24450 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
24451 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
24452 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
24453 split.minSize = 100;
24454 split.maxSize = 600;
24455 split.animate = true;
24456 split.on('moved', splitterMoved);
24459 * Create a new SplitBar
24460 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
24461 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
24462 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
24463 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
24464 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
24465 position of the SplitBar).
24467 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
24470 this.el = Roo.get(dragElement, true);
24471 this.el.dom.unselectable = "on";
24473 this.resizingEl = Roo.get(resizingElement, true);
24477 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
24478 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
24481 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
24484 * The minimum size of the resizing element. (Defaults to 0)
24490 * The maximum size of the resizing element. (Defaults to 2000)
24493 this.maxSize = 2000;
24496 * Whether to animate the transition to the new size
24499 this.animate = false;
24502 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
24505 this.useShim = false;
24510 if(!existingProxy){
24512 this.proxy = Roo.SplitBar.createProxy(this.orientation);
24514 this.proxy = Roo.get(existingProxy).dom;
24517 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
24520 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
24523 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
24526 this.dragSpecs = {};
24529 * @private The adapter to use to positon and resize elements
24531 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
24532 this.adapter.init(this);
24534 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24536 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
24537 this.el.addClass("x-splitbar-h");
24540 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
24541 this.el.addClass("x-splitbar-v");
24547 * Fires when the splitter is moved (alias for {@link #event-moved})
24548 * @param {Roo.SplitBar} this
24549 * @param {Number} newSize the new width or height
24554 * Fires when the splitter is moved
24555 * @param {Roo.SplitBar} this
24556 * @param {Number} newSize the new width or height
24560 * @event beforeresize
24561 * Fires before the splitter is dragged
24562 * @param {Roo.SplitBar} this
24564 "beforeresize" : true,
24566 "beforeapply" : true
24569 Roo.util.Observable.call(this);
24572 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
24573 onStartProxyDrag : function(x, y){
24574 this.fireEvent("beforeresize", this);
24576 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
24578 o.enableDisplayMode("block");
24579 // all splitbars share the same overlay
24580 Roo.SplitBar.prototype.overlay = o;
24582 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
24583 this.overlay.show();
24584 Roo.get(this.proxy).setDisplayed("block");
24585 var size = this.adapter.getElementSize(this);
24586 this.activeMinSize = this.getMinimumSize();;
24587 this.activeMaxSize = this.getMaximumSize();;
24588 var c1 = size - this.activeMinSize;
24589 var c2 = Math.max(this.activeMaxSize - size, 0);
24590 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24591 this.dd.resetConstraints();
24592 this.dd.setXConstraint(
24593 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
24594 this.placement == Roo.SplitBar.LEFT ? c2 : c1
24596 this.dd.setYConstraint(0, 0);
24598 this.dd.resetConstraints();
24599 this.dd.setXConstraint(0, 0);
24600 this.dd.setYConstraint(
24601 this.placement == Roo.SplitBar.TOP ? c1 : c2,
24602 this.placement == Roo.SplitBar.TOP ? c2 : c1
24605 this.dragSpecs.startSize = size;
24606 this.dragSpecs.startPoint = [x, y];
24607 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
24611 * @private Called after the drag operation by the DDProxy
24613 onEndProxyDrag : function(e){
24614 Roo.get(this.proxy).setDisplayed(false);
24615 var endPoint = Roo.lib.Event.getXY(e);
24617 this.overlay.hide();
24620 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24621 newSize = this.dragSpecs.startSize +
24622 (this.placement == Roo.SplitBar.LEFT ?
24623 endPoint[0] - this.dragSpecs.startPoint[0] :
24624 this.dragSpecs.startPoint[0] - endPoint[0]
24627 newSize = this.dragSpecs.startSize +
24628 (this.placement == Roo.SplitBar.TOP ?
24629 endPoint[1] - this.dragSpecs.startPoint[1] :
24630 this.dragSpecs.startPoint[1] - endPoint[1]
24633 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
24634 if(newSize != this.dragSpecs.startSize){
24635 if(this.fireEvent('beforeapply', this, newSize) !== false){
24636 this.adapter.setElementSize(this, newSize);
24637 this.fireEvent("moved", this, newSize);
24638 this.fireEvent("resize", this, newSize);
24644 * Get the adapter this SplitBar uses
24645 * @return The adapter object
24647 getAdapter : function(){
24648 return this.adapter;
24652 * Set the adapter this SplitBar uses
24653 * @param {Object} adapter A SplitBar adapter object
24655 setAdapter : function(adapter){
24656 this.adapter = adapter;
24657 this.adapter.init(this);
24661 * Gets the minimum size for the resizing element
24662 * @return {Number} The minimum size
24664 getMinimumSize : function(){
24665 return this.minSize;
24669 * Sets the minimum size for the resizing element
24670 * @param {Number} minSize The minimum size
24672 setMinimumSize : function(minSize){
24673 this.minSize = minSize;
24677 * Gets the maximum size for the resizing element
24678 * @return {Number} The maximum size
24680 getMaximumSize : function(){
24681 return this.maxSize;
24685 * Sets the maximum size for the resizing element
24686 * @param {Number} maxSize The maximum size
24688 setMaximumSize : function(maxSize){
24689 this.maxSize = maxSize;
24693 * Sets the initialize size for the resizing element
24694 * @param {Number} size The initial size
24696 setCurrentSize : function(size){
24697 var oldAnimate = this.animate;
24698 this.animate = false;
24699 this.adapter.setElementSize(this, size);
24700 this.animate = oldAnimate;
24704 * Destroy this splitbar.
24705 * @param {Boolean} removeEl True to remove the element
24707 destroy : function(removeEl){
24709 this.shim.remove();
24712 this.proxy.parentNode.removeChild(this.proxy);
24720 * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
24722 Roo.SplitBar.createProxy = function(dir){
24723 var proxy = new Roo.Element(document.createElement("div"));
24724 proxy.unselectable();
24725 var cls = 'x-splitbar-proxy';
24726 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
24727 document.body.appendChild(proxy.dom);
24732 * @class Roo.SplitBar.BasicLayoutAdapter
24733 * Default Adapter. It assumes the splitter and resizing element are not positioned
24734 * elements and only gets/sets the width of the element. Generally used for table based layouts.
24736 Roo.SplitBar.BasicLayoutAdapter = function(){
24739 Roo.SplitBar.BasicLayoutAdapter.prototype = {
24740 // do nothing for now
24741 init : function(s){
24745 * Called before drag operations to get the current size of the resizing element.
24746 * @param {Roo.SplitBar} s The SplitBar using this adapter
24748 getElementSize : function(s){
24749 if(s.orientation == Roo.SplitBar.HORIZONTAL){
24750 return s.resizingEl.getWidth();
24752 return s.resizingEl.getHeight();
24757 * Called after drag operations to set the size of the resizing element.
24758 * @param {Roo.SplitBar} s The SplitBar using this adapter
24759 * @param {Number} newSize The new size to set
24760 * @param {Function} onComplete A function to be invoked when resizing is complete
24762 setElementSize : function(s, newSize, onComplete){
24763 if(s.orientation == Roo.SplitBar.HORIZONTAL){
24765 s.resizingEl.setWidth(newSize);
24767 onComplete(s, newSize);
24770 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
24775 s.resizingEl.setHeight(newSize);
24777 onComplete(s, newSize);
24780 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
24787 *@class Roo.SplitBar.AbsoluteLayoutAdapter
24788 * @extends Roo.SplitBar.BasicLayoutAdapter
24789 * Adapter that moves the splitter element to align with the resized sizing element.
24790 * Used with an absolute positioned SplitBar.
24791 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
24792 * document.body, make sure you assign an id to the body element.
24794 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
24795 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
24796 this.container = Roo.get(container);
24799 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
24800 init : function(s){
24801 this.basic.init(s);
24804 getElementSize : function(s){
24805 return this.basic.getElementSize(s);
24808 setElementSize : function(s, newSize, onComplete){
24809 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
24812 moveSplitter : function(s){
24813 var yes = Roo.SplitBar;
24814 switch(s.placement){
24816 s.el.setX(s.resizingEl.getRight());
24819 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
24822 s.el.setY(s.resizingEl.getBottom());
24825 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
24832 * Orientation constant - Create a vertical SplitBar
24836 Roo.SplitBar.VERTICAL = 1;
24839 * Orientation constant - Create a horizontal SplitBar
24843 Roo.SplitBar.HORIZONTAL = 2;
24846 * Placement constant - The resizing element is to the left of the splitter element
24850 Roo.SplitBar.LEFT = 1;
24853 * Placement constant - The resizing element is to the right of the splitter element
24857 Roo.SplitBar.RIGHT = 2;
24860 * Placement constant - The resizing element is positioned above the splitter element
24864 Roo.SplitBar.TOP = 3;
24867 * Placement constant - The resizing element is positioned under splitter element
24871 Roo.SplitBar.BOTTOM = 4;
24874 * Ext JS Library 1.1.1
24875 * Copyright(c) 2006-2007, Ext JS, LLC.
24877 * Originally Released Under LGPL - original licence link has changed is not relivant.
24880 * <script type="text/javascript">
24885 * @extends Roo.util.Observable
24886 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
24887 * This class also supports single and multi selection modes. <br>
24888 * Create a data model bound view:
24890 var store = new Roo.data.Store(...);
24892 var view = new Roo.View({
24894 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
24896 singleSelect: true,
24897 selectedClass: "ydataview-selected",
24901 // listen for node click?
24902 view.on("click", function(vw, index, node, e){
24903 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
24907 dataModel.load("foobar.xml");
24909 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
24911 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
24912 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
24914 * Note: old style constructor is still suported (container, template, config)
24917 * Create a new View
24918 * @param {Object} config The config object
24921 Roo.View = function(config, depreciated_tpl, depreciated_config){
24923 this.parent = false;
24925 if (typeof(depreciated_tpl) == 'undefined') {
24926 // new way.. - universal constructor.
24927 Roo.apply(this, config);
24928 this.el = Roo.get(this.el);
24931 this.el = Roo.get(config);
24932 this.tpl = depreciated_tpl;
24933 Roo.apply(this, depreciated_config);
24935 this.wrapEl = this.el.wrap().wrap();
24936 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
24939 if(typeof(this.tpl) == "string"){
24940 this.tpl = new Roo.Template(this.tpl);
24942 // support xtype ctors..
24943 this.tpl = new Roo.factory(this.tpl, Roo);
24947 this.tpl.compile();
24952 * @event beforeclick
24953 * Fires before a click is processed. Returns false to cancel the default action.
24954 * @param {Roo.View} this
24955 * @param {Number} index The index of the target node
24956 * @param {HTMLElement} node The target node
24957 * @param {Roo.EventObject} e The raw event object
24959 "beforeclick" : true,
24962 * Fires when a template node is clicked.
24963 * @param {Roo.View} this
24964 * @param {Number} index The index of the target node
24965 * @param {HTMLElement} node The target node
24966 * @param {Roo.EventObject} e The raw event object
24971 * Fires when a template node is double clicked.
24972 * @param {Roo.View} this
24973 * @param {Number} index The index of the target node
24974 * @param {HTMLElement} node The target node
24975 * @param {Roo.EventObject} e The raw event object
24979 * @event contextmenu
24980 * Fires when a template node is right clicked.
24981 * @param {Roo.View} this
24982 * @param {Number} index The index of the target node
24983 * @param {HTMLElement} node The target node
24984 * @param {Roo.EventObject} e The raw event object
24986 "contextmenu" : true,
24988 * @event selectionchange
24989 * Fires when the selected nodes change.
24990 * @param {Roo.View} this
24991 * @param {Array} selections Array of the selected nodes
24993 "selectionchange" : true,
24996 * @event beforeselect
24997 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
24998 * @param {Roo.View} this
24999 * @param {HTMLElement} node The node to be selected
25000 * @param {Array} selections Array of currently selected nodes
25002 "beforeselect" : true,
25004 * @event preparedata
25005 * Fires on every row to render, to allow you to change the data.
25006 * @param {Roo.View} this
25007 * @param {Object} data to be rendered (change this)
25009 "preparedata" : true
25017 "click": this.onClick,
25018 "dblclick": this.onDblClick,
25019 "contextmenu": this.onContextMenu,
25023 this.selections = [];
25025 this.cmp = new Roo.CompositeElementLite([]);
25027 this.store = Roo.factory(this.store, Roo.data);
25028 this.setStore(this.store, true);
25031 if ( this.footer && this.footer.xtype) {
25033 var fctr = this.wrapEl.appendChild(document.createElement("div"));
25035 this.footer.dataSource = this.store
25036 this.footer.container = fctr;
25037 this.footer = Roo.factory(this.footer, Roo);
25038 fctr.insertFirst(this.el);
25040 // this is a bit insane - as the paging toolbar seems to detach the el..
25041 // dom.parentNode.parentNode.parentNode
25042 // they get detached?
25046 Roo.View.superclass.constructor.call(this);
25051 Roo.extend(Roo.View, Roo.util.Observable, {
25054 * @cfg {Roo.data.Store} store Data store to load data from.
25059 * @cfg {String|Roo.Element} el The container element.
25064 * @cfg {String|Roo.Template} tpl The template used by this View
25068 * @cfg {String} dataName the named area of the template to use as the data area
25069 * Works with domtemplates roo-name="name"
25073 * @cfg {String} selectedClass The css class to add to selected nodes
25075 selectedClass : "x-view-selected",
25077 * @cfg {String} emptyText The empty text to show when nothing is loaded.
25082 * @cfg {String} text to display on mask (default Loading)
25086 * @cfg {Boolean} multiSelect Allow multiple selection
25088 multiSelect : false,
25090 * @cfg {Boolean} singleSelect Allow single selection
25092 singleSelect: false,
25095 * @cfg {Boolean} toggleSelect - selecting
25097 toggleSelect : false,
25100 * @cfg {Boolean} tickable - selecting
25105 * Returns the element this view is bound to.
25106 * @return {Roo.Element}
25108 getEl : function(){
25109 return this.wrapEl;
25115 * Refreshes the view. - called by datachanged on the store. - do not call directly.
25117 refresh : function(){
25118 //Roo.log('refresh');
25121 // if we are using something like 'domtemplate', then
25122 // the what gets used is:
25123 // t.applySubtemplate(NAME, data, wrapping data..)
25124 // the outer template then get' applied with
25125 // the store 'extra data'
25126 // and the body get's added to the
25127 // roo-name="data" node?
25128 // <span class='roo-tpl-{name}'></span> ?????
25132 this.clearSelections();
25133 this.el.update("");
25135 var records = this.store.getRange();
25136 if(records.length < 1) {
25138 // is this valid?? = should it render a template??
25140 this.el.update(this.emptyText);
25144 if (this.dataName) {
25145 this.el.update(t.apply(this.store.meta)); //????
25146 el = this.el.child('.roo-tpl-' + this.dataName);
25149 for(var i = 0, len = records.length; i < len; i++){
25150 var data = this.prepareData(records[i].data, i, records[i]);
25151 this.fireEvent("preparedata", this, data, i, records[i]);
25153 var d = Roo.apply({}, data);
25156 Roo.apply(d, {'roo-id' : Roo.id()});
25160 Roo.each(this.parent.item, function(item){
25161 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
25164 Roo.apply(d, {'roo-data-checked' : 'checked'});
25168 html[html.length] = Roo.util.Format.trim(
25170 t.applySubtemplate(this.dataName, d, this.store.meta) :
25177 el.update(html.join(""));
25178 this.nodes = el.dom.childNodes;
25179 this.updateIndexes(0);
25184 * Function to override to reformat the data that is sent to
25185 * the template for each node.
25186 * DEPRICATED - use the preparedata event handler.
25187 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
25188 * a JSON object for an UpdateManager bound view).
25190 prepareData : function(data, index, record)
25192 this.fireEvent("preparedata", this, data, index, record);
25196 onUpdate : function(ds, record){
25197 // Roo.log('on update');
25198 this.clearSelections();
25199 var index = this.store.indexOf(record);
25200 var n = this.nodes[index];
25201 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
25202 n.parentNode.removeChild(n);
25203 this.updateIndexes(index, index);
25209 onAdd : function(ds, records, index)
25211 //Roo.log(['on Add', ds, records, index] );
25212 this.clearSelections();
25213 if(this.nodes.length == 0){
25217 var n = this.nodes[index];
25218 for(var i = 0, len = records.length; i < len; i++){
25219 var d = this.prepareData(records[i].data, i, records[i]);
25221 this.tpl.insertBefore(n, d);
25224 this.tpl.append(this.el, d);
25227 this.updateIndexes(index);
25230 onRemove : function(ds, record, index){
25231 // Roo.log('onRemove');
25232 this.clearSelections();
25233 var el = this.dataName ?
25234 this.el.child('.roo-tpl-' + this.dataName) :
25237 el.dom.removeChild(this.nodes[index]);
25238 this.updateIndexes(index);
25242 * Refresh an individual node.
25243 * @param {Number} index
25245 refreshNode : function(index){
25246 this.onUpdate(this.store, this.store.getAt(index));
25249 updateIndexes : function(startIndex, endIndex){
25250 var ns = this.nodes;
25251 startIndex = startIndex || 0;
25252 endIndex = endIndex || ns.length - 1;
25253 for(var i = startIndex; i <= endIndex; i++){
25254 ns[i].nodeIndex = i;
25259 * Changes the data store this view uses and refresh the view.
25260 * @param {Store} store
25262 setStore : function(store, initial){
25263 if(!initial && this.store){
25264 this.store.un("datachanged", this.refresh);
25265 this.store.un("add", this.onAdd);
25266 this.store.un("remove", this.onRemove);
25267 this.store.un("update", this.onUpdate);
25268 this.store.un("clear", this.refresh);
25269 this.store.un("beforeload", this.onBeforeLoad);
25270 this.store.un("load", this.onLoad);
25271 this.store.un("loadexception", this.onLoad);
25275 store.on("datachanged", this.refresh, this);
25276 store.on("add", this.onAdd, this);
25277 store.on("remove", this.onRemove, this);
25278 store.on("update", this.onUpdate, this);
25279 store.on("clear", this.refresh, this);
25280 store.on("beforeload", this.onBeforeLoad, this);
25281 store.on("load", this.onLoad, this);
25282 store.on("loadexception", this.onLoad, this);
25290 * onbeforeLoad - masks the loading area.
25293 onBeforeLoad : function(store,opts)
25295 //Roo.log('onBeforeLoad');
25297 this.el.update("");
25299 this.el.mask(this.mask ? this.mask : "Loading" );
25301 onLoad : function ()
25308 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
25309 * @param {HTMLElement} node
25310 * @return {HTMLElement} The template node
25312 findItemFromChild : function(node){
25313 var el = this.dataName ?
25314 this.el.child('.roo-tpl-' + this.dataName,true) :
25317 if(!node || node.parentNode == el){
25320 var p = node.parentNode;
25321 while(p && p != el){
25322 if(p.parentNode == el){
25331 onClick : function(e){
25332 var item = this.findItemFromChild(e.getTarget());
25334 var index = this.indexOf(item);
25335 if(this.onItemClick(item, index, e) !== false){
25336 this.fireEvent("click", this, index, item, e);
25339 this.clearSelections();
25344 onContextMenu : function(e){
25345 var item = this.findItemFromChild(e.getTarget());
25347 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
25352 onDblClick : function(e){
25353 var item = this.findItemFromChild(e.getTarget());
25355 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
25359 onItemClick : function(item, index, e)
25361 if(this.fireEvent("beforeclick", this, index, item, e) === false){
25364 if (this.toggleSelect) {
25365 var m = this.isSelected(item) ? 'unselect' : 'select';
25368 _t[m](item, true, false);
25371 if(this.multiSelect || this.singleSelect){
25372 if(this.multiSelect && e.shiftKey && this.lastSelection){
25373 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
25375 this.select(item, this.multiSelect && e.ctrlKey);
25376 this.lastSelection = item;
25379 if(!this.tickable){
25380 e.preventDefault();
25388 * Get the number of selected nodes.
25391 getSelectionCount : function(){
25392 return this.selections.length;
25396 * Get the currently selected nodes.
25397 * @return {Array} An array of HTMLElements
25399 getSelectedNodes : function(){
25400 return this.selections;
25404 * Get the indexes of the selected nodes.
25407 getSelectedIndexes : function(){
25408 var indexes = [], s = this.selections;
25409 for(var i = 0, len = s.length; i < len; i++){
25410 indexes.push(s[i].nodeIndex);
25416 * Clear all selections
25417 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
25419 clearSelections : function(suppressEvent){
25420 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
25421 this.cmp.elements = this.selections;
25422 this.cmp.removeClass(this.selectedClass);
25423 this.selections = [];
25424 if(!suppressEvent){
25425 this.fireEvent("selectionchange", this, this.selections);
25431 * Returns true if the passed node is selected
25432 * @param {HTMLElement/Number} node The node or node index
25433 * @return {Boolean}
25435 isSelected : function(node){
25436 var s = this.selections;
25440 node = this.getNode(node);
25441 return s.indexOf(node) !== -1;
25446 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
25447 * @param {Boolean} keepExisting (optional) true to keep existing selections
25448 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
25450 select : function(nodeInfo, keepExisting, suppressEvent){
25451 if(nodeInfo instanceof Array){
25453 this.clearSelections(true);
25455 for(var i = 0, len = nodeInfo.length; i < len; i++){
25456 this.select(nodeInfo[i], true, true);
25460 var node = this.getNode(nodeInfo);
25461 if(!node || this.isSelected(node)){
25462 return; // already selected.
25465 this.clearSelections(true);
25468 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
25469 Roo.fly(node).addClass(this.selectedClass);
25470 this.selections.push(node);
25471 if(!suppressEvent){
25472 this.fireEvent("selectionchange", this, this.selections);
25480 * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
25481 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
25482 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
25484 unselect : function(nodeInfo, keepExisting, suppressEvent)
25486 if(nodeInfo instanceof Array){
25487 Roo.each(this.selections, function(s) {
25488 this.unselect(s, nodeInfo);
25492 var node = this.getNode(nodeInfo);
25493 if(!node || !this.isSelected(node)){
25494 //Roo.log("not selected");
25495 return; // not selected.
25499 Roo.each(this.selections, function(s) {
25501 Roo.fly(node).removeClass(this.selectedClass);
25508 this.selections= ns;
25509 this.fireEvent("selectionchange", this, this.selections);
25513 * Gets a template node.
25514 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
25515 * @return {HTMLElement} The node or null if it wasn't found
25517 getNode : function(nodeInfo){
25518 if(typeof nodeInfo == "string"){
25519 return document.getElementById(nodeInfo);
25520 }else if(typeof nodeInfo == "number"){
25521 return this.nodes[nodeInfo];
25527 * Gets a range template nodes.
25528 * @param {Number} startIndex
25529 * @param {Number} endIndex
25530 * @return {Array} An array of nodes
25532 getNodes : function(start, end){
25533 var ns = this.nodes;
25534 start = start || 0;
25535 end = typeof end == "undefined" ? ns.length - 1 : end;
25538 for(var i = start; i <= end; i++){
25542 for(var i = start; i >= end; i--){
25550 * Finds the index of the passed node
25551 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
25552 * @return {Number} The index of the node or -1
25554 indexOf : function(node){
25555 node = this.getNode(node);
25556 if(typeof node.nodeIndex == "number"){
25557 return node.nodeIndex;
25559 var ns = this.nodes;
25560 for(var i = 0, len = ns.length; i < len; i++){
25570 * Ext JS Library 1.1.1
25571 * Copyright(c) 2006-2007, Ext JS, LLC.
25573 * Originally Released Under LGPL - original licence link has changed is not relivant.
25576 * <script type="text/javascript">
25580 * @class Roo.JsonView
25581 * @extends Roo.View
25582 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
25584 var view = new Roo.JsonView({
25585 container: "my-element",
25586 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
25591 // listen for node click?
25592 view.on("click", function(vw, index, node, e){
25593 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
25596 // direct load of JSON data
25597 view.load("foobar.php");
25599 // Example from my blog list
25600 var tpl = new Roo.Template(
25601 '<div class="entry">' +
25602 '<a class="entry-title" href="{link}">{title}</a>' +
25603 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
25604 "</div><hr />"
25607 var moreView = new Roo.JsonView({
25608 container : "entry-list",
25612 moreView.on("beforerender", this.sortEntries, this);
25614 url: "/blog/get-posts.php",
25615 params: "allposts=true",
25616 text: "Loading Blog Entries..."
25620 * Note: old code is supported with arguments : (container, template, config)
25624 * Create a new JsonView
25626 * @param {Object} config The config object
25629 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
25632 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
25634 var um = this.el.getUpdateManager();
25635 um.setRenderer(this);
25636 um.on("update", this.onLoad, this);
25637 um.on("failure", this.onLoadException, this);
25640 * @event beforerender
25641 * Fires before rendering of the downloaded JSON data.
25642 * @param {Roo.JsonView} this
25643 * @param {Object} data The JSON data loaded
25647 * Fires when data is loaded.
25648 * @param {Roo.JsonView} this
25649 * @param {Object} data The JSON data loaded
25650 * @param {Object} response The raw Connect response object
25653 * @event loadexception
25654 * Fires when loading fails.
25655 * @param {Roo.JsonView} this
25656 * @param {Object} response The raw Connect response object
25659 'beforerender' : true,
25661 'loadexception' : true
25664 Roo.extend(Roo.JsonView, Roo.View, {
25666 * @type {String} The root property in the loaded JSON object that contains the data
25671 * Refreshes the view.
25673 refresh : function(){
25674 this.clearSelections();
25675 this.el.update("");
25677 var o = this.jsonData;
25678 if(o && o.length > 0){
25679 for(var i = 0, len = o.length; i < len; i++){
25680 var data = this.prepareData(o[i], i, o);
25681 html[html.length] = this.tpl.apply(data);
25684 html.push(this.emptyText);
25686 this.el.update(html.join(""));
25687 this.nodes = this.el.dom.childNodes;
25688 this.updateIndexes(0);
25692 * Performs an async HTTP request, and loads the JSON from the response. If <i>params</i> are specified it uses POST, otherwise it uses GET.
25693 * @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:
25696 url: "your-url.php",
25697 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
25698 callback: yourFunction,
25699 scope: yourObject, //(optional scope)
25702 text: "Loading...",
25707 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
25708 * are respectively shorthand for <i>disableCaching</i>, <i>indicatorText</i>, and <i>loadScripts</i> and are used to set their associated property on this UpdateManager instance.
25709 * @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}
25710 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
25711 * @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.
25714 var um = this.el.getUpdateManager();
25715 um.update.apply(um, arguments);
25718 render : function(el, response){
25719 this.clearSelections();
25720 this.el.update("");
25723 o = Roo.util.JSON.decode(response.responseText);
25726 o = o[this.jsonRoot];
25731 * The current JSON data or null
25734 this.beforeRender();
25739 * Get the number of records in the current JSON dataset
25742 getCount : function(){
25743 return this.jsonData ? this.jsonData.length : 0;
25747 * Returns the JSON object for the specified node(s)
25748 * @param {HTMLElement/Array} node The node or an array of nodes
25749 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
25750 * you get the JSON object for the node
25752 getNodeData : function(node){
25753 if(node instanceof Array){
25755 for(var i = 0, len = node.length; i < len; i++){
25756 data.push(this.getNodeData(node[i]));
25760 return this.jsonData[this.indexOf(node)] || null;
25763 beforeRender : function(){
25764 this.snapshot = this.jsonData;
25766 this.sort.apply(this, this.sortInfo);
25768 this.fireEvent("beforerender", this, this.jsonData);
25771 onLoad : function(el, o){
25772 this.fireEvent("load", this, this.jsonData, o);
25775 onLoadException : function(el, o){
25776 this.fireEvent("loadexception", this, o);
25780 * Filter the data by a specific property.
25781 * @param {String} property A property on your JSON objects
25782 * @param {String/RegExp} value Either string that the property values
25783 * should start with, or a RegExp to test against the property
25785 filter : function(property, value){
25788 var ss = this.snapshot;
25789 if(typeof value == "string"){
25790 var vlen = value.length;
25792 this.clearFilter();
25795 value = value.toLowerCase();
25796 for(var i = 0, len = ss.length; i < len; i++){
25798 if(o[property].substr(0, vlen).toLowerCase() == value){
25802 } else if(value.exec){ // regex?
25803 for(var i = 0, len = ss.length; i < len; i++){
25805 if(value.test(o[property])){
25812 this.jsonData = data;
25818 * Filter by a function. The passed function will be called with each
25819 * object in the current dataset. If the function returns true the value is kept,
25820 * otherwise it is filtered.
25821 * @param {Function} fn
25822 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
25824 filterBy : function(fn, scope){
25827 var ss = this.snapshot;
25828 for(var i = 0, len = ss.length; i < len; i++){
25830 if(fn.call(scope || this, o)){
25834 this.jsonData = data;
25840 * Clears the current filter.
25842 clearFilter : function(){
25843 if(this.snapshot && this.jsonData != this.snapshot){
25844 this.jsonData = this.snapshot;
25851 * Sorts the data for this view and refreshes it.
25852 * @param {String} property A property on your JSON objects to sort on
25853 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
25854 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
25856 sort : function(property, dir, sortType){
25857 this.sortInfo = Array.prototype.slice.call(arguments, 0);
25860 var dsc = dir && dir.toLowerCase() == "desc";
25861 var f = function(o1, o2){
25862 var v1 = sortType ? sortType(o1[p]) : o1[p];
25863 var v2 = sortType ? sortType(o2[p]) : o2[p];
25866 return dsc ? +1 : -1;
25867 } else if(v1 > v2){
25868 return dsc ? -1 : +1;
25873 this.jsonData.sort(f);
25875 if(this.jsonData != this.snapshot){
25876 this.snapshot.sort(f);
25882 * Ext JS Library 1.1.1
25883 * Copyright(c) 2006-2007, Ext JS, LLC.
25885 * Originally Released Under LGPL - original licence link has changed is not relivant.
25888 * <script type="text/javascript">
25893 * @class Roo.ColorPalette
25894 * @extends Roo.Component
25895 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
25896 * Here's an example of typical usage:
25898 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
25899 cp.render('my-div');
25901 cp.on('select', function(palette, selColor){
25902 // do something with selColor
25906 * Create a new ColorPalette
25907 * @param {Object} config The config object
25909 Roo.ColorPalette = function(config){
25910 Roo.ColorPalette.superclass.constructor.call(this, config);
25914 * Fires when a color is selected
25915 * @param {ColorPalette} this
25916 * @param {String} color The 6-digit color hex code (without the # symbol)
25922 this.on("select", this.handler, this.scope, true);
25925 Roo.extend(Roo.ColorPalette, Roo.Component, {
25927 * @cfg {String} itemCls
25928 * The CSS class to apply to the containing element (defaults to "x-color-palette")
25930 itemCls : "x-color-palette",
25932 * @cfg {String} value
25933 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
25934 * the hex codes are case-sensitive.
25937 clickEvent:'click',
25939 ctype: "Roo.ColorPalette",
25942 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
25944 allowReselect : false,
25947 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
25948 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
25949 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
25950 * of colors with the width setting until the box is symmetrical.</p>
25951 * <p>You can override individual colors if needed:</p>
25953 var cp = new Roo.ColorPalette();
25954 cp.colors[0] = "FF0000"; // change the first box to red
25957 Or you can provide a custom array of your own for complete control:
25959 var cp = new Roo.ColorPalette();
25960 cp.colors = ["000000", "993300", "333300"];
25965 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
25966 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
25967 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
25968 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
25969 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
25973 onRender : function(container, position){
25974 var t = new Roo.MasterTemplate(
25975 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
25977 var c = this.colors;
25978 for(var i = 0, len = c.length; i < len; i++){
25981 var el = document.createElement("div");
25982 el.className = this.itemCls;
25984 container.dom.insertBefore(el, position);
25985 this.el = Roo.get(el);
25986 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
25987 if(this.clickEvent != 'click'){
25988 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
25993 afterRender : function(){
25994 Roo.ColorPalette.superclass.afterRender.call(this);
25996 var s = this.value;
26003 handleClick : function(e, t){
26004 e.preventDefault();
26005 if(!this.disabled){
26006 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
26007 this.select(c.toUpperCase());
26012 * Selects the specified color in the palette (fires the select event)
26013 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
26015 select : function(color){
26016 color = color.replace("#", "");
26017 if(color != this.value || this.allowReselect){
26020 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
26022 el.child("a.color-"+color).addClass("x-color-palette-sel");
26023 this.value = color;
26024 this.fireEvent("select", this, color);
26029 * Ext JS Library 1.1.1
26030 * Copyright(c) 2006-2007, Ext JS, LLC.
26032 * Originally Released Under LGPL - original licence link has changed is not relivant.
26035 * <script type="text/javascript">
26039 * @class Roo.DatePicker
26040 * @extends Roo.Component
26041 * Simple date picker class.
26043 * Create a new DatePicker
26044 * @param {Object} config The config object
26046 Roo.DatePicker = function(config){
26047 Roo.DatePicker.superclass.constructor.call(this, config);
26049 this.value = config && config.value ?
26050 config.value.clearTime() : new Date().clearTime();
26055 * Fires when a date is selected
26056 * @param {DatePicker} this
26057 * @param {Date} date The selected date
26061 * @event monthchange
26062 * Fires when the displayed month changes
26063 * @param {DatePicker} this
26064 * @param {Date} date The selected month
26066 'monthchange': true
26070 this.on("select", this.handler, this.scope || this);
26072 // build the disabledDatesRE
26073 if(!this.disabledDatesRE && this.disabledDates){
26074 var dd = this.disabledDates;
26076 for(var i = 0; i < dd.length; i++){
26078 if(i != dd.length-1) re += "|";
26080 this.disabledDatesRE = new RegExp(re + ")");
26084 Roo.extend(Roo.DatePicker, Roo.Component, {
26086 * @cfg {String} todayText
26087 * The text to display on the button that selects the current date (defaults to "Today")
26089 todayText : "Today",
26091 * @cfg {String} okText
26092 * The text to display on the ok button
26094 okText : " OK ", //   to give the user extra clicking room
26096 * @cfg {String} cancelText
26097 * The text to display on the cancel button
26099 cancelText : "Cancel",
26101 * @cfg {String} todayTip
26102 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
26104 todayTip : "{0} (Spacebar)",
26106 * @cfg {Date} minDate
26107 * Minimum allowable date (JavaScript date object, defaults to null)
26111 * @cfg {Date} maxDate
26112 * Maximum allowable date (JavaScript date object, defaults to null)
26116 * @cfg {String} minText
26117 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
26119 minText : "This date is before the minimum date",
26121 * @cfg {String} maxText
26122 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
26124 maxText : "This date is after the maximum date",
26126 * @cfg {String} format
26127 * The default date format string which can be overriden for localization support. The format must be
26128 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
26132 * @cfg {Array} disabledDays
26133 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
26135 disabledDays : null,
26137 * @cfg {String} disabledDaysText
26138 * The tooltip to display when the date falls on a disabled day (defaults to "")
26140 disabledDaysText : "",
26142 * @cfg {RegExp} disabledDatesRE
26143 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
26145 disabledDatesRE : null,
26147 * @cfg {String} disabledDatesText
26148 * The tooltip text to display when the date falls on a disabled date (defaults to "")
26150 disabledDatesText : "",
26152 * @cfg {Boolean} constrainToViewport
26153 * True to constrain the date picker to the viewport (defaults to true)
26155 constrainToViewport : true,
26157 * @cfg {Array} monthNames
26158 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
26160 monthNames : Date.monthNames,
26162 * @cfg {Array} dayNames
26163 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
26165 dayNames : Date.dayNames,
26167 * @cfg {String} nextText
26168 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
26170 nextText: 'Next Month (Control+Right)',
26172 * @cfg {String} prevText
26173 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
26175 prevText: 'Previous Month (Control+Left)',
26177 * @cfg {String} monthYearText
26178 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
26180 monthYearText: 'Choose a month (Control+Up/Down to move years)',
26182 * @cfg {Number} startDay
26183 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
26187 * @cfg {Bool} showClear
26188 * Show a clear button (usefull for date form elements that can be blank.)
26194 * Sets the value of the date field
26195 * @param {Date} value The date to set
26197 setValue : function(value){
26198 var old = this.value;
26200 if (typeof(value) == 'string') {
26202 value = Date.parseDate(value, this.format);
26205 value = new Date();
26208 this.value = value.clearTime(true);
26210 this.update(this.value);
26215 * Gets the current selected value of the date field
26216 * @return {Date} The selected date
26218 getValue : function(){
26223 focus : function(){
26225 this.update(this.activeDate);
26230 onRender : function(container, position){
26233 '<table cellspacing="0">',
26234 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
26235 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
26236 var dn = this.dayNames;
26237 for(var i = 0; i < 7; i++){
26238 var d = this.startDay+i;
26242 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
26244 m[m.length] = "</tr></thead><tbody><tr>";
26245 for(var i = 0; i < 42; i++) {
26246 if(i % 7 == 0 && i != 0){
26247 m[m.length] = "</tr><tr>";
26249 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
26251 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
26252 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
26254 var el = document.createElement("div");
26255 el.className = "x-date-picker";
26256 el.innerHTML = m.join("");
26258 container.dom.insertBefore(el, position);
26260 this.el = Roo.get(el);
26261 this.eventEl = Roo.get(el.firstChild);
26263 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
26264 handler: this.showPrevMonth,
26266 preventDefault:true,
26270 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
26271 handler: this.showNextMonth,
26273 preventDefault:true,
26277 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
26279 this.monthPicker = this.el.down('div.x-date-mp');
26280 this.monthPicker.enableDisplayMode('block');
26282 var kn = new Roo.KeyNav(this.eventEl, {
26283 "left" : function(e){
26285 this.showPrevMonth() :
26286 this.update(this.activeDate.add("d", -1));
26289 "right" : function(e){
26291 this.showNextMonth() :
26292 this.update(this.activeDate.add("d", 1));
26295 "up" : function(e){
26297 this.showNextYear() :
26298 this.update(this.activeDate.add("d", -7));
26301 "down" : function(e){
26303 this.showPrevYear() :
26304 this.update(this.activeDate.add("d", 7));
26307 "pageUp" : function(e){
26308 this.showNextMonth();
26311 "pageDown" : function(e){
26312 this.showPrevMonth();
26315 "enter" : function(e){
26316 e.stopPropagation();
26323 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
26325 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
26327 this.el.unselectable();
26329 this.cells = this.el.select("table.x-date-inner tbody td");
26330 this.textNodes = this.el.query("table.x-date-inner tbody span");
26332 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
26334 tooltip: this.monthYearText
26337 this.mbtn.on('click', this.showMonthPicker, this);
26338 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
26341 var today = (new Date()).dateFormat(this.format);
26343 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
26344 if (this.showClear) {
26345 baseTb.add( new Roo.Toolbar.Fill());
26348 text: String.format(this.todayText, today),
26349 tooltip: String.format(this.todayTip, today),
26350 handler: this.selectToday,
26354 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
26357 if (this.showClear) {
26359 baseTb.add( new Roo.Toolbar.Fill());
26362 cls: 'x-btn-icon x-btn-clear',
26363 handler: function() {
26365 this.fireEvent("select", this, '');
26375 this.update(this.value);
26378 createMonthPicker : function(){
26379 if(!this.monthPicker.dom.firstChild){
26380 var buf = ['<table border="0" cellspacing="0">'];
26381 for(var i = 0; i < 6; i++){
26383 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
26384 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
26386 '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
26387 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
26391 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
26393 '</button><button type="button" class="x-date-mp-cancel">',
26395 '</button></td></tr>',
26398 this.monthPicker.update(buf.join(''));
26399 this.monthPicker.on('click', this.onMonthClick, this);
26400 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
26402 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
26403 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
26405 this.mpMonths.each(function(m, a, i){
26408 m.dom.xmonth = 5 + Math.round(i * .5);
26410 m.dom.xmonth = Math.round((i-1) * .5);
26416 showMonthPicker : function(){
26417 this.createMonthPicker();
26418 var size = this.el.getSize();
26419 this.monthPicker.setSize(size);
26420 this.monthPicker.child('table').setSize(size);
26422 this.mpSelMonth = (this.activeDate || this.value).getMonth();
26423 this.updateMPMonth(this.mpSelMonth);
26424 this.mpSelYear = (this.activeDate || this.value).getFullYear();
26425 this.updateMPYear(this.mpSelYear);
26427 this.monthPicker.slideIn('t', {duration:.2});
26430 updateMPYear : function(y){
26432 var ys = this.mpYears.elements;
26433 for(var i = 1; i <= 10; i++){
26434 var td = ys[i-1], y2;
26436 y2 = y + Math.round(i * .5);
26437 td.firstChild.innerHTML = y2;
26440 y2 = y - (5-Math.round(i * .5));
26441 td.firstChild.innerHTML = y2;
26444 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
26448 updateMPMonth : function(sm){
26449 this.mpMonths.each(function(m, a, i){
26450 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
26454 selectMPMonth: function(m){
26458 onMonthClick : function(e, t){
26460 var el = new Roo.Element(t), pn;
26461 if(el.is('button.x-date-mp-cancel')){
26462 this.hideMonthPicker();
26464 else if(el.is('button.x-date-mp-ok')){
26465 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
26466 this.hideMonthPicker();
26468 else if(pn = el.up('td.x-date-mp-month', 2)){
26469 this.mpMonths.removeClass('x-date-mp-sel');
26470 pn.addClass('x-date-mp-sel');
26471 this.mpSelMonth = pn.dom.xmonth;
26473 else if(pn = el.up('td.x-date-mp-year', 2)){
26474 this.mpYears.removeClass('x-date-mp-sel');
26475 pn.addClass('x-date-mp-sel');
26476 this.mpSelYear = pn.dom.xyear;
26478 else if(el.is('a.x-date-mp-prev')){
26479 this.updateMPYear(this.mpyear-10);
26481 else if(el.is('a.x-date-mp-next')){
26482 this.updateMPYear(this.mpyear+10);
26486 onMonthDblClick : function(e, t){
26488 var el = new Roo.Element(t), pn;
26489 if(pn = el.up('td.x-date-mp-month', 2)){
26490 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
26491 this.hideMonthPicker();
26493 else if(pn = el.up('td.x-date-mp-year', 2)){
26494 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
26495 this.hideMonthPicker();
26499 hideMonthPicker : function(disableAnim){
26500 if(this.monthPicker){
26501 if(disableAnim === true){
26502 this.monthPicker.hide();
26504 this.monthPicker.slideOut('t', {duration:.2});
26510 showPrevMonth : function(e){
26511 this.update(this.activeDate.add("mo", -1));
26515 showNextMonth : function(e){
26516 this.update(this.activeDate.add("mo", 1));
26520 showPrevYear : function(){
26521 this.update(this.activeDate.add("y", -1));
26525 showNextYear : function(){
26526 this.update(this.activeDate.add("y", 1));
26530 handleMouseWheel : function(e){
26531 var delta = e.getWheelDelta();
26533 this.showPrevMonth();
26535 } else if(delta < 0){
26536 this.showNextMonth();
26542 handleDateClick : function(e, t){
26544 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
26545 this.setValue(new Date(t.dateValue));
26546 this.fireEvent("select", this, this.value);
26551 selectToday : function(){
26552 this.setValue(new Date().clearTime());
26553 this.fireEvent("select", this, this.value);
26557 update : function(date)
26559 var vd = this.activeDate;
26560 this.activeDate = date;
26562 var t = date.getTime();
26563 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
26564 this.cells.removeClass("x-date-selected");
26565 this.cells.each(function(c){
26566 if(c.dom.firstChild.dateValue == t){
26567 c.addClass("x-date-selected");
26568 setTimeout(function(){
26569 try{c.dom.firstChild.focus();}catch(e){}
26578 var days = date.getDaysInMonth();
26579 var firstOfMonth = date.getFirstDateOfMonth();
26580 var startingPos = firstOfMonth.getDay()-this.startDay;
26582 if(startingPos <= this.startDay){
26586 var pm = date.add("mo", -1);
26587 var prevStart = pm.getDaysInMonth()-startingPos;
26589 var cells = this.cells.elements;
26590 var textEls = this.textNodes;
26591 days += startingPos;
26593 // convert everything to numbers so it's fast
26594 var day = 86400000;
26595 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
26596 var today = new Date().clearTime().getTime();
26597 var sel = date.clearTime().getTime();
26598 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
26599 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
26600 var ddMatch = this.disabledDatesRE;
26601 var ddText = this.disabledDatesText;
26602 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
26603 var ddaysText = this.disabledDaysText;
26604 var format = this.format;
26606 var setCellClass = function(cal, cell){
26608 var t = d.getTime();
26609 cell.firstChild.dateValue = t;
26611 cell.className += " x-date-today";
26612 cell.title = cal.todayText;
26615 cell.className += " x-date-selected";
26616 setTimeout(function(){
26617 try{cell.firstChild.focus();}catch(e){}
26622 cell.className = " x-date-disabled";
26623 cell.title = cal.minText;
26627 cell.className = " x-date-disabled";
26628 cell.title = cal.maxText;
26632 if(ddays.indexOf(d.getDay()) != -1){
26633 cell.title = ddaysText;
26634 cell.className = " x-date-disabled";
26637 if(ddMatch && format){
26638 var fvalue = d.dateFormat(format);
26639 if(ddMatch.test(fvalue)){
26640 cell.title = ddText.replace("%0", fvalue);
26641 cell.className = " x-date-disabled";
26647 for(; i < startingPos; i++) {
26648 textEls[i].innerHTML = (++prevStart);
26649 d.setDate(d.getDate()+1);
26650 cells[i].className = "x-date-prevday";
26651 setCellClass(this, cells[i]);
26653 for(; i < days; i++){
26654 intDay = i - startingPos + 1;
26655 textEls[i].innerHTML = (intDay);
26656 d.setDate(d.getDate()+1);
26657 cells[i].className = "x-date-active";
26658 setCellClass(this, cells[i]);
26661 for(; i < 42; i++) {
26662 textEls[i].innerHTML = (++extraDays);
26663 d.setDate(d.getDate()+1);
26664 cells[i].className = "x-date-nextday";
26665 setCellClass(this, cells[i]);
26668 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
26669 this.fireEvent('monthchange', this, date);
26671 if(!this.internalRender){
26672 var main = this.el.dom.firstChild;
26673 var w = main.offsetWidth;
26674 this.el.setWidth(w + this.el.getBorderWidth("lr"));
26675 Roo.fly(main).setWidth(w);
26676 this.internalRender = true;
26677 // opera does not respect the auto grow header center column
26678 // then, after it gets a width opera refuses to recalculate
26679 // without a second pass
26680 if(Roo.isOpera && !this.secondPass){
26681 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
26682 this.secondPass = true;
26683 this.update.defer(10, this, [date]);
26691 * Ext JS Library 1.1.1
26692 * Copyright(c) 2006-2007, Ext JS, LLC.
26694 * Originally Released Under LGPL - original licence link has changed is not relivant.
26697 * <script type="text/javascript">
26700 * @class Roo.TabPanel
26701 * @extends Roo.util.Observable
26702 * A lightweight tab container.
26706 // basic tabs 1, built from existing content
26707 var tabs = new Roo.TabPanel("tabs1");
26708 tabs.addTab("script", "View Script");
26709 tabs.addTab("markup", "View Markup");
26710 tabs.activate("script");
26712 // more advanced tabs, built from javascript
26713 var jtabs = new Roo.TabPanel("jtabs");
26714 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
26716 // set up the UpdateManager
26717 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
26718 var updater = tab2.getUpdateManager();
26719 updater.setDefaultUrl("ajax1.htm");
26720 tab2.on('activate', updater.refresh, updater, true);
26722 // Use setUrl for Ajax loading
26723 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
26724 tab3.setUrl("ajax2.htm", null, true);
26727 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
26730 jtabs.activate("jtabs-1");
26733 * Create a new TabPanel.
26734 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
26735 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
26737 Roo.TabPanel = function(container, config){
26739 * The container element for this TabPanel.
26740 * @type Roo.Element
26742 this.el = Roo.get(container, true);
26744 if(typeof config == "boolean"){
26745 this.tabPosition = config ? "bottom" : "top";
26747 Roo.apply(this, config);
26750 if(this.tabPosition == "bottom"){
26751 this.bodyEl = Roo.get(this.createBody(this.el.dom));
26752 this.el.addClass("x-tabs-bottom");
26754 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
26755 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
26756 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
26758 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
26760 if(this.tabPosition != "bottom"){
26761 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
26762 * @type Roo.Element
26764 this.bodyEl = Roo.get(this.createBody(this.el.dom));
26765 this.el.addClass("x-tabs-top");
26769 this.bodyEl.setStyle("position", "relative");
26771 this.active = null;
26772 this.activateDelegate = this.activate.createDelegate(this);
26777 * Fires when the active tab changes
26778 * @param {Roo.TabPanel} this
26779 * @param {Roo.TabPanelItem} activePanel The new active tab
26783 * @event beforetabchange
26784 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
26785 * @param {Roo.TabPanel} this
26786 * @param {Object} e Set cancel to true on this object to cancel the tab change
26787 * @param {Roo.TabPanelItem} tab The tab being changed to
26789 "beforetabchange" : true
26792 Roo.EventManager.onWindowResize(this.onResize, this);
26793 this.cpad = this.el.getPadding("lr");
26794 this.hiddenCount = 0;
26797 // toolbar on the tabbar support...
26798 if (this.toolbar) {
26799 var tcfg = this.toolbar;
26800 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
26801 this.toolbar = new Roo.Toolbar(tcfg);
26802 if (Roo.isSafari) {
26803 var tbl = tcfg.container.child('table', true);
26804 tbl.setAttribute('width', '100%');
26811 Roo.TabPanel.superclass.constructor.call(this);
26814 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
26816 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
26818 tabPosition : "top",
26820 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
26822 currentTabWidth : 0,
26824 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
26828 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
26832 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
26834 preferredTabWidth : 175,
26836 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
26838 resizeTabs : false,
26840 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
26842 monitorResize : true,
26844 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
26849 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
26850 * @param {String} id The id of the div to use <b>or create</b>
26851 * @param {String} text The text for the tab
26852 * @param {String} content (optional) Content to put in the TabPanelItem body
26853 * @param {Boolean} closable (optional) True to create a close icon on the tab
26854 * @return {Roo.TabPanelItem} The created TabPanelItem
26856 addTab : function(id, text, content, closable){
26857 var item = new Roo.TabPanelItem(this, id, text, closable);
26858 this.addTabItem(item);
26860 item.setContent(content);
26866 * Returns the {@link Roo.TabPanelItem} with the specified id/index
26867 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
26868 * @return {Roo.TabPanelItem}
26870 getTab : function(id){
26871 return this.items[id];
26875 * Hides the {@link Roo.TabPanelItem} with the specified id/index
26876 * @param {String/Number} id The id or index of the TabPanelItem to hide.
26878 hideTab : function(id){
26879 var t = this.items[id];
26882 this.hiddenCount++;
26883 this.autoSizeTabs();
26888 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
26889 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
26891 unhideTab : function(id){
26892 var t = this.items[id];
26894 t.setHidden(false);
26895 this.hiddenCount--;
26896 this.autoSizeTabs();
26901 * Adds an existing {@link Roo.TabPanelItem}.
26902 * @param {Roo.TabPanelItem} item The TabPanelItem to add
26904 addTabItem : function(item){
26905 this.items[item.id] = item;
26906 this.items.push(item);
26907 if(this.resizeTabs){
26908 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
26909 this.autoSizeTabs();
26916 * Removes a {@link Roo.TabPanelItem}.
26917 * @param {String/Number} id The id or index of the TabPanelItem to remove.
26919 removeTab : function(id){
26920 var items = this.items;
26921 var tab = items[id];
26922 if(!tab) { return; }
26923 var index = items.indexOf(tab);
26924 if(this.active == tab && items.length > 1){
26925 var newTab = this.getNextAvailable(index);
26930 this.stripEl.dom.removeChild(tab.pnode.dom);
26931 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
26932 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
26934 items.splice(index, 1);
26935 delete this.items[tab.id];
26936 tab.fireEvent("close", tab);
26937 tab.purgeListeners();
26938 this.autoSizeTabs();
26941 getNextAvailable : function(start){
26942 var items = this.items;
26944 // look for a next tab that will slide over to
26945 // replace the one being removed
26946 while(index < items.length){
26947 var item = items[++index];
26948 if(item && !item.isHidden()){
26952 // if one isn't found select the previous tab (on the left)
26955 var item = items[--index];
26956 if(item && !item.isHidden()){
26964 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
26965 * @param {String/Number} id The id or index of the TabPanelItem to disable.
26967 disableTab : function(id){
26968 var tab = this.items[id];
26969 if(tab && this.active != tab){
26975 * Enables a {@link Roo.TabPanelItem} that is disabled.
26976 * @param {String/Number} id The id or index of the TabPanelItem to enable.
26978 enableTab : function(id){
26979 var tab = this.items[id];
26984 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
26985 * @param {String/Number} id The id or index of the TabPanelItem to activate.
26986 * @return {Roo.TabPanelItem} The TabPanelItem.
26988 activate : function(id){
26989 var tab = this.items[id];
26993 if(tab == this.active || tab.disabled){
26997 this.fireEvent("beforetabchange", this, e, tab);
26998 if(e.cancel !== true && !tab.disabled){
27000 this.active.hide();
27002 this.active = this.items[id];
27003 this.active.show();
27004 this.fireEvent("tabchange", this, this.active);
27010 * Gets the active {@link Roo.TabPanelItem}.
27011 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
27013 getActiveTab : function(){
27014 return this.active;
27018 * Updates the tab body element to fit the height of the container element
27019 * for overflow scrolling
27020 * @param {Number} targetHeight (optional) Override the starting height from the elements height
27022 syncHeight : function(targetHeight){
27023 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
27024 var bm = this.bodyEl.getMargins();
27025 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
27026 this.bodyEl.setHeight(newHeight);
27030 onResize : function(){
27031 if(this.monitorResize){
27032 this.autoSizeTabs();
27037 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
27039 beginUpdate : function(){
27040 this.updating = true;
27044 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
27046 endUpdate : function(){
27047 this.updating = false;
27048 this.autoSizeTabs();
27052 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
27054 autoSizeTabs : function(){
27055 var count = this.items.length;
27056 var vcount = count - this.hiddenCount;
27057 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
27058 var w = Math.max(this.el.getWidth() - this.cpad, 10);
27059 var availWidth = Math.floor(w / vcount);
27060 var b = this.stripBody;
27061 if(b.getWidth() > w){
27062 var tabs = this.items;
27063 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
27064 if(availWidth < this.minTabWidth){
27065 /*if(!this.sleft){ // incomplete scrolling code
27066 this.createScrollButtons();
27069 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
27072 if(this.currentTabWidth < this.preferredTabWidth){
27073 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
27079 * Returns the number of tabs in this TabPanel.
27082 getCount : function(){
27083 return this.items.length;
27087 * Resizes all the tabs to the passed width
27088 * @param {Number} The new width
27090 setTabWidth : function(width){
27091 this.currentTabWidth = width;
27092 for(var i = 0, len = this.items.length; i < len; i++) {
27093 if(!this.items[i].isHidden())this.items[i].setWidth(width);
27098 * Destroys this TabPanel
27099 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
27101 destroy : function(removeEl){
27102 Roo.EventManager.removeResizeListener(this.onResize, this);
27103 for(var i = 0, len = this.items.length; i < len; i++){
27104 this.items[i].purgeListeners();
27106 if(removeEl === true){
27107 this.el.update("");
27114 * @class Roo.TabPanelItem
27115 * @extends Roo.util.Observable
27116 * Represents an individual item (tab plus body) in a TabPanel.
27117 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
27118 * @param {String} id The id of this TabPanelItem
27119 * @param {String} text The text for the tab of this TabPanelItem
27120 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
27122 Roo.TabPanelItem = function(tabPanel, id, text, closable){
27124 * The {@link Roo.TabPanel} this TabPanelItem belongs to
27125 * @type Roo.TabPanel
27127 this.tabPanel = tabPanel;
27129 * The id for this TabPanelItem
27134 this.disabled = false;
27138 this.loaded = false;
27139 this.closable = closable;
27142 * The body element for this TabPanelItem.
27143 * @type Roo.Element
27145 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
27146 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
27147 this.bodyEl.setStyle("display", "block");
27148 this.bodyEl.setStyle("zoom", "1");
27151 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
27153 this.el = Roo.get(els.el, true);
27154 this.inner = Roo.get(els.inner, true);
27155 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
27156 this.pnode = Roo.get(els.el.parentNode, true);
27157 this.el.on("mousedown", this.onTabMouseDown, this);
27158 this.el.on("click", this.onTabClick, this);
27161 var c = Roo.get(els.close, true);
27162 c.dom.title = this.closeText;
27163 c.addClassOnOver("close-over");
27164 c.on("click", this.closeClick, this);
27170 * Fires when this tab becomes the active tab.
27171 * @param {Roo.TabPanel} tabPanel The parent TabPanel
27172 * @param {Roo.TabPanelItem} this
27176 * @event beforeclose
27177 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
27178 * @param {Roo.TabPanelItem} this
27179 * @param {Object} e Set cancel to true on this object to cancel the close.
27181 "beforeclose": true,
27184 * Fires when this tab is closed.
27185 * @param {Roo.TabPanelItem} this
27189 * @event deactivate
27190 * Fires when this tab is no longer the active tab.
27191 * @param {Roo.TabPanel} tabPanel The parent TabPanel
27192 * @param {Roo.TabPanelItem} this
27194 "deactivate" : true
27196 this.hidden = false;
27198 Roo.TabPanelItem.superclass.constructor.call(this);
27201 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
27202 purgeListeners : function(){
27203 Roo.util.Observable.prototype.purgeListeners.call(this);
27204 this.el.removeAllListeners();
27207 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
27210 this.pnode.addClass("on");
27213 this.tabPanel.stripWrap.repaint();
27215 this.fireEvent("activate", this.tabPanel, this);
27219 * Returns true if this tab is the active tab.
27220 * @return {Boolean}
27222 isActive : function(){
27223 return this.tabPanel.getActiveTab() == this;
27227 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
27230 this.pnode.removeClass("on");
27232 this.fireEvent("deactivate", this.tabPanel, this);
27235 hideAction : function(){
27236 this.bodyEl.hide();
27237 this.bodyEl.setStyle("position", "absolute");
27238 this.bodyEl.setLeft("-20000px");
27239 this.bodyEl.setTop("-20000px");
27242 showAction : function(){
27243 this.bodyEl.setStyle("position", "relative");
27244 this.bodyEl.setTop("");
27245 this.bodyEl.setLeft("");
27246 this.bodyEl.show();
27250 * Set the tooltip for the tab.
27251 * @param {String} tooltip The tab's tooltip
27253 setTooltip : function(text){
27254 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
27255 this.textEl.dom.qtip = text;
27256 this.textEl.dom.removeAttribute('title');
27258 this.textEl.dom.title = text;
27262 onTabClick : function(e){
27263 e.preventDefault();
27264 this.tabPanel.activate(this.id);
27267 onTabMouseDown : function(e){
27268 e.preventDefault();
27269 this.tabPanel.activate(this.id);
27272 getWidth : function(){
27273 return this.inner.getWidth();
27276 setWidth : function(width){
27277 var iwidth = width - this.pnode.getPadding("lr");
27278 this.inner.setWidth(iwidth);
27279 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
27280 this.pnode.setWidth(width);
27284 * Show or hide the tab
27285 * @param {Boolean} hidden True to hide or false to show.
27287 setHidden : function(hidden){
27288 this.hidden = hidden;
27289 this.pnode.setStyle("display", hidden ? "none" : "");
27293 * Returns true if this tab is "hidden"
27294 * @return {Boolean}
27296 isHidden : function(){
27297 return this.hidden;
27301 * Returns the text for this tab
27304 getText : function(){
27308 autoSize : function(){
27309 //this.el.beginMeasure();
27310 this.textEl.setWidth(1);
27312 * #2804 [new] Tabs in Roojs
27313 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
27315 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
27316 //this.el.endMeasure();
27320 * Sets the text for the tab (Note: this also sets the tooltip text)
27321 * @param {String} text The tab's text and tooltip
27323 setText : function(text){
27325 this.textEl.update(text);
27326 this.setTooltip(text);
27327 if(!this.tabPanel.resizeTabs){
27332 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
27334 activate : function(){
27335 this.tabPanel.activate(this.id);
27339 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
27341 disable : function(){
27342 if(this.tabPanel.active != this){
27343 this.disabled = true;
27344 this.pnode.addClass("disabled");
27349 * Enables this TabPanelItem if it was previously disabled.
27351 enable : function(){
27352 this.disabled = false;
27353 this.pnode.removeClass("disabled");
27357 * Sets the content for this TabPanelItem.
27358 * @param {String} content The content
27359 * @param {Boolean} loadScripts true to look for and load scripts
27361 setContent : function(content, loadScripts){
27362 this.bodyEl.update(content, loadScripts);
27366 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
27367 * @return {Roo.UpdateManager} The UpdateManager
27369 getUpdateManager : function(){
27370 return this.bodyEl.getUpdateManager();
27374 * Set a URL to be used to load the content for this TabPanelItem.
27375 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
27376 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
27377 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
27378 * @return {Roo.UpdateManager} The UpdateManager
27380 setUrl : function(url, params, loadOnce){
27381 if(this.refreshDelegate){
27382 this.un('activate', this.refreshDelegate);
27384 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
27385 this.on("activate", this.refreshDelegate);
27386 return this.bodyEl.getUpdateManager();
27390 _handleRefresh : function(url, params, loadOnce){
27391 if(!loadOnce || !this.loaded){
27392 var updater = this.bodyEl.getUpdateManager();
27393 updater.update(url, params, this._setLoaded.createDelegate(this));
27398 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
27399 * Will fail silently if the setUrl method has not been called.
27400 * This does not activate the panel, just updates its content.
27402 refresh : function(){
27403 if(this.refreshDelegate){
27404 this.loaded = false;
27405 this.refreshDelegate();
27410 _setLoaded : function(){
27411 this.loaded = true;
27415 closeClick : function(e){
27418 this.fireEvent("beforeclose", this, o);
27419 if(o.cancel !== true){
27420 this.tabPanel.removeTab(this.id);
27424 * The text displayed in the tooltip for the close icon.
27427 closeText : "Close this tab"
27431 Roo.TabPanel.prototype.createStrip = function(container){
27432 var strip = document.createElement("div");
27433 strip.className = "x-tabs-wrap";
27434 container.appendChild(strip);
27438 Roo.TabPanel.prototype.createStripList = function(strip){
27439 // div wrapper for retard IE
27440 // returns the "tr" element.
27441 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
27442 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
27443 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
27444 return strip.firstChild.firstChild.firstChild.firstChild;
27447 Roo.TabPanel.prototype.createBody = function(container){
27448 var body = document.createElement("div");
27449 Roo.id(body, "tab-body");
27450 Roo.fly(body).addClass("x-tabs-body");
27451 container.appendChild(body);
27455 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
27456 var body = Roo.getDom(id);
27458 body = document.createElement("div");
27461 Roo.fly(body).addClass("x-tabs-item-body");
27462 bodyEl.insertBefore(body, bodyEl.firstChild);
27466 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
27467 var td = document.createElement("td");
27468 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
27469 //stripEl.appendChild(td);
27471 td.className = "x-tabs-closable";
27472 if(!this.closeTpl){
27473 this.closeTpl = new Roo.Template(
27474 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
27475 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
27476 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
27479 var el = this.closeTpl.overwrite(td, {"text": text});
27480 var close = el.getElementsByTagName("div")[0];
27481 var inner = el.getElementsByTagName("em")[0];
27482 return {"el": el, "close": close, "inner": inner};
27485 this.tabTpl = new Roo.Template(
27486 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
27487 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
27490 var el = this.tabTpl.overwrite(td, {"text": text});
27491 var inner = el.getElementsByTagName("em")[0];
27492 return {"el": el, "inner": inner};
27496 * Ext JS Library 1.1.1
27497 * Copyright(c) 2006-2007, Ext JS, LLC.
27499 * Originally Released Under LGPL - original licence link has changed is not relivant.
27502 * <script type="text/javascript">
27506 * @class Roo.Button
27507 * @extends Roo.util.Observable
27508 * Simple Button class
27509 * @cfg {String} text The button text
27510 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
27511 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
27512 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
27513 * @cfg {Object} scope The scope of the handler
27514 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
27515 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
27516 * @cfg {Boolean} hidden True to start hidden (defaults to false)
27517 * @cfg {Boolean} disabled True to start disabled (defaults to false)
27518 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
27519 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
27520 applies if enableToggle = true)
27521 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
27522 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
27523 an {@link Roo.util.ClickRepeater} config object (defaults to false).
27525 * Create a new button
27526 * @param {Object} config The config object
27528 Roo.Button = function(renderTo, config)
27532 renderTo = config.renderTo || false;
27535 Roo.apply(this, config);
27539 * Fires when this button is clicked
27540 * @param {Button} this
27541 * @param {EventObject} e The click event
27546 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
27547 * @param {Button} this
27548 * @param {Boolean} pressed
27553 * Fires when the mouse hovers over the button
27554 * @param {Button} this
27555 * @param {Event} e The event object
27557 'mouseover' : true,
27560 * Fires when the mouse exits the button
27561 * @param {Button} this
27562 * @param {Event} e The event object
27567 * Fires when the button is rendered
27568 * @param {Button} this
27573 this.menu = Roo.menu.MenuMgr.get(this.menu);
27575 // register listeners first!! - so render can be captured..
27576 Roo.util.Observable.call(this);
27578 this.render(renderTo);
27584 Roo.extend(Roo.Button, Roo.util.Observable, {
27590 * Read-only. True if this button is hidden
27595 * Read-only. True if this button is disabled
27600 * Read-only. True if this button is pressed (only if enableToggle = true)
27606 * @cfg {Number} tabIndex
27607 * The DOM tabIndex for this button (defaults to undefined)
27609 tabIndex : undefined,
27612 * @cfg {Boolean} enableToggle
27613 * True to enable pressed/not pressed toggling (defaults to false)
27615 enableToggle: false,
27617 * @cfg {Mixed} menu
27618 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
27622 * @cfg {String} menuAlign
27623 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
27625 menuAlign : "tl-bl?",
27628 * @cfg {String} iconCls
27629 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
27631 iconCls : undefined,
27633 * @cfg {String} type
27634 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
27639 menuClassTarget: 'tr',
27642 * @cfg {String} clickEvent
27643 * The type of event to map to the button's event handler (defaults to 'click')
27645 clickEvent : 'click',
27648 * @cfg {Boolean} handleMouseEvents
27649 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
27651 handleMouseEvents : true,
27654 * @cfg {String} tooltipType
27655 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
27657 tooltipType : 'qtip',
27660 * @cfg {String} cls
27661 * A CSS class to apply to the button's main element.
27665 * @cfg {Roo.Template} template (Optional)
27666 * An {@link Roo.Template} with which to create the Button's main element. This Template must
27667 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
27668 * require code modifications if required elements (e.g. a button) aren't present.
27672 render : function(renderTo){
27674 if(this.hideParent){
27675 this.parentEl = Roo.get(renderTo);
27677 if(!this.dhconfig){
27678 if(!this.template){
27679 if(!Roo.Button.buttonTemplate){
27680 // hideous table template
27681 Roo.Button.buttonTemplate = new Roo.Template(
27682 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
27683 '<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
27684 "</tr></tbody></table>");
27686 this.template = Roo.Button.buttonTemplate;
27688 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
27689 var btnEl = btn.child("button:first");
27690 btnEl.on('focus', this.onFocus, this);
27691 btnEl.on('blur', this.onBlur, this);
27693 btn.addClass(this.cls);
27696 btnEl.setStyle('background-image', 'url(' +this.icon +')');
27699 btnEl.addClass(this.iconCls);
27701 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
27704 if(this.tabIndex !== undefined){
27705 btnEl.dom.tabIndex = this.tabIndex;
27708 if(typeof this.tooltip == 'object'){
27709 Roo.QuickTips.tips(Roo.apply({
27713 btnEl.dom[this.tooltipType] = this.tooltip;
27717 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
27721 this.el.dom.id = this.el.id = this.id;
27724 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
27725 this.menu.on("show", this.onMenuShow, this);
27726 this.menu.on("hide", this.onMenuHide, this);
27728 btn.addClass("x-btn");
27729 if(Roo.isIE && !Roo.isIE7){
27730 this.autoWidth.defer(1, this);
27734 if(this.handleMouseEvents){
27735 btn.on("mouseover", this.onMouseOver, this);
27736 btn.on("mouseout", this.onMouseOut, this);
27737 btn.on("mousedown", this.onMouseDown, this);
27739 btn.on(this.clickEvent, this.onClick, this);
27740 //btn.on("mouseup", this.onMouseUp, this);
27747 Roo.ButtonToggleMgr.register(this);
27749 this.el.addClass("x-btn-pressed");
27752 var repeater = new Roo.util.ClickRepeater(btn,
27753 typeof this.repeat == "object" ? this.repeat : {}
27755 repeater.on("click", this.onClick, this);
27758 this.fireEvent('render', this);
27762 * Returns the button's underlying element
27763 * @return {Roo.Element} The element
27765 getEl : function(){
27770 * Destroys this Button and removes any listeners.
27772 destroy : function(){
27773 Roo.ButtonToggleMgr.unregister(this);
27774 this.el.removeAllListeners();
27775 this.purgeListeners();
27780 autoWidth : function(){
27782 this.el.setWidth("auto");
27783 if(Roo.isIE7 && Roo.isStrict){
27784 var ib = this.el.child('button');
27785 if(ib && ib.getWidth() > 20){
27787 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
27792 this.el.beginMeasure();
27794 if(this.el.getWidth() < this.minWidth){
27795 this.el.setWidth(this.minWidth);
27798 this.el.endMeasure();
27805 * Assigns this button's click handler
27806 * @param {Function} handler The function to call when the button is clicked
27807 * @param {Object} scope (optional) Scope for the function passed in
27809 setHandler : function(handler, scope){
27810 this.handler = handler;
27811 this.scope = scope;
27815 * Sets this button's text
27816 * @param {String} text The button text
27818 setText : function(text){
27821 this.el.child("td.x-btn-center button.x-btn-text").update(text);
27827 * Gets the text for this button
27828 * @return {String} The button text
27830 getText : function(){
27838 this.hidden = false;
27840 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
27848 this.hidden = true;
27850 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
27855 * Convenience function for boolean show/hide
27856 * @param {Boolean} visible True to show, false to hide
27858 setVisible: function(visible){
27867 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
27868 * @param {Boolean} state (optional) Force a particular state
27870 toggle : function(state){
27871 state = state === undefined ? !this.pressed : state;
27872 if(state != this.pressed){
27874 this.el.addClass("x-btn-pressed");
27875 this.pressed = true;
27876 this.fireEvent("toggle", this, true);
27878 this.el.removeClass("x-btn-pressed");
27879 this.pressed = false;
27880 this.fireEvent("toggle", this, false);
27882 if(this.toggleHandler){
27883 this.toggleHandler.call(this.scope || this, this, state);
27891 focus : function(){
27892 this.el.child('button:first').focus();
27896 * Disable this button
27898 disable : function(){
27900 this.el.addClass("x-btn-disabled");
27902 this.disabled = true;
27906 * Enable this button
27908 enable : function(){
27910 this.el.removeClass("x-btn-disabled");
27912 this.disabled = false;
27916 * Convenience function for boolean enable/disable
27917 * @param {Boolean} enabled True to enable, false to disable
27919 setDisabled : function(v){
27920 this[v !== true ? "enable" : "disable"]();
27924 onClick : function(e)
27927 e.preventDefault();
27932 if(!this.disabled){
27933 if(this.enableToggle){
27936 if(this.menu && !this.menu.isVisible()){
27937 this.menu.show(this.el, this.menuAlign);
27939 this.fireEvent("click", this, e);
27941 this.el.removeClass("x-btn-over");
27942 this.handler.call(this.scope || this, this, e);
27947 onMouseOver : function(e){
27948 if(!this.disabled){
27949 this.el.addClass("x-btn-over");
27950 this.fireEvent('mouseover', this, e);
27954 onMouseOut : function(e){
27955 if(!e.within(this.el, true)){
27956 this.el.removeClass("x-btn-over");
27957 this.fireEvent('mouseout', this, e);
27961 onFocus : function(e){
27962 if(!this.disabled){
27963 this.el.addClass("x-btn-focus");
27967 onBlur : function(e){
27968 this.el.removeClass("x-btn-focus");
27971 onMouseDown : function(e){
27972 if(!this.disabled && e.button == 0){
27973 this.el.addClass("x-btn-click");
27974 Roo.get(document).on('mouseup', this.onMouseUp, this);
27978 onMouseUp : function(e){
27980 this.el.removeClass("x-btn-click");
27981 Roo.get(document).un('mouseup', this.onMouseUp, this);
27985 onMenuShow : function(e){
27986 this.el.addClass("x-btn-menu-active");
27989 onMenuHide : function(e){
27990 this.el.removeClass("x-btn-menu-active");
27994 // Private utility class used by Button
27995 Roo.ButtonToggleMgr = function(){
27998 function toggleGroup(btn, state){
28000 var g = groups[btn.toggleGroup];
28001 for(var i = 0, l = g.length; i < l; i++){
28003 g[i].toggle(false);
28010 register : function(btn){
28011 if(!btn.toggleGroup){
28014 var g = groups[btn.toggleGroup];
28016 g = groups[btn.toggleGroup] = [];
28019 btn.on("toggle", toggleGroup);
28022 unregister : function(btn){
28023 if(!btn.toggleGroup){
28026 var g = groups[btn.toggleGroup];
28029 btn.un("toggle", toggleGroup);
28035 * Ext JS Library 1.1.1
28036 * Copyright(c) 2006-2007, Ext JS, LLC.
28038 * Originally Released Under LGPL - original licence link has changed is not relivant.
28041 * <script type="text/javascript">
28045 * @class Roo.SplitButton
28046 * @extends Roo.Button
28047 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
28048 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
28049 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
28050 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
28051 * @cfg {String} arrowTooltip The title attribute of the arrow
28053 * Create a new menu button
28054 * @param {String/HTMLElement/Element} renderTo The element to append the button to
28055 * @param {Object} config The config object
28057 Roo.SplitButton = function(renderTo, config){
28058 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
28060 * @event arrowclick
28061 * Fires when this button's arrow is clicked
28062 * @param {SplitButton} this
28063 * @param {EventObject} e The click event
28065 this.addEvents({"arrowclick":true});
28068 Roo.extend(Roo.SplitButton, Roo.Button, {
28069 render : function(renderTo){
28070 // this is one sweet looking template!
28071 var tpl = new Roo.Template(
28072 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
28073 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
28074 '<tr><td class="x-btn-left"><i> </i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
28075 "</tbody></table></td><td>",
28076 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
28077 '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button"> </button></td><td class="x-btn-right"><i> </i></td></tr>',
28078 "</tbody></table></td></tr></table>"
28080 var btn = tpl.append(renderTo, [this.text, this.type], true);
28081 var btnEl = btn.child("button");
28083 btn.addClass(this.cls);
28086 btnEl.setStyle('background-image', 'url(' +this.icon +')');
28089 btnEl.addClass(this.iconCls);
28091 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
28095 if(this.handleMouseEvents){
28096 btn.on("mouseover", this.onMouseOver, this);
28097 btn.on("mouseout", this.onMouseOut, this);
28098 btn.on("mousedown", this.onMouseDown, this);
28099 btn.on("mouseup", this.onMouseUp, this);
28101 btn.on(this.clickEvent, this.onClick, this);
28103 if(typeof this.tooltip == 'object'){
28104 Roo.QuickTips.tips(Roo.apply({
28108 btnEl.dom[this.tooltipType] = this.tooltip;
28111 if(this.arrowTooltip){
28112 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
28121 this.el.addClass("x-btn-pressed");
28123 if(Roo.isIE && !Roo.isIE7){
28124 this.autoWidth.defer(1, this);
28129 this.menu.on("show", this.onMenuShow, this);
28130 this.menu.on("hide", this.onMenuHide, this);
28132 this.fireEvent('render', this);
28136 autoWidth : function(){
28138 var tbl = this.el.child("table:first");
28139 var tbl2 = this.el.child("table:last");
28140 this.el.setWidth("auto");
28141 tbl.setWidth("auto");
28142 if(Roo.isIE7 && Roo.isStrict){
28143 var ib = this.el.child('button:first');
28144 if(ib && ib.getWidth() > 20){
28146 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
28151 this.el.beginMeasure();
28153 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
28154 tbl.setWidth(this.minWidth-tbl2.getWidth());
28157 this.el.endMeasure();
28160 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
28164 * Sets this button's click handler
28165 * @param {Function} handler The function to call when the button is clicked
28166 * @param {Object} scope (optional) Scope for the function passed above
28168 setHandler : function(handler, scope){
28169 this.handler = handler;
28170 this.scope = scope;
28174 * Sets this button's arrow click handler
28175 * @param {Function} handler The function to call when the arrow is clicked
28176 * @param {Object} scope (optional) Scope for the function passed above
28178 setArrowHandler : function(handler, scope){
28179 this.arrowHandler = handler;
28180 this.scope = scope;
28186 focus : function(){
28188 this.el.child("button:first").focus();
28193 onClick : function(e){
28194 e.preventDefault();
28195 if(!this.disabled){
28196 if(e.getTarget(".x-btn-menu-arrow-wrap")){
28197 if(this.menu && !this.menu.isVisible()){
28198 this.menu.show(this.el, this.menuAlign);
28200 this.fireEvent("arrowclick", this, e);
28201 if(this.arrowHandler){
28202 this.arrowHandler.call(this.scope || this, this, e);
28205 this.fireEvent("click", this, e);
28207 this.handler.call(this.scope || this, this, e);
28213 onMouseDown : function(e){
28214 if(!this.disabled){
28215 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
28219 onMouseUp : function(e){
28220 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
28225 // backwards compat
28226 Roo.MenuButton = Roo.SplitButton;/*
28228 * Ext JS Library 1.1.1
28229 * Copyright(c) 2006-2007, Ext JS, LLC.
28231 * Originally Released Under LGPL - original licence link has changed is not relivant.
28234 * <script type="text/javascript">
28238 * @class Roo.Toolbar
28239 * Basic Toolbar class.
28241 * Creates a new Toolbar
28242 * @param {Object} container The config object
28244 Roo.Toolbar = function(container, buttons, config)
28246 /// old consturctor format still supported..
28247 if(container instanceof Array){ // omit the container for later rendering
28248 buttons = container;
28252 if (typeof(container) == 'object' && container.xtype) {
28253 config = container;
28254 container = config.container;
28255 buttons = config.buttons || []; // not really - use items!!
28258 if (config && config.items) {
28259 xitems = config.items;
28260 delete config.items;
28262 Roo.apply(this, config);
28263 this.buttons = buttons;
28266 this.render(container);
28268 this.xitems = xitems;
28269 Roo.each(xitems, function(b) {
28275 Roo.Toolbar.prototype = {
28277 * @cfg {Array} items
28278 * array of button configs or elements to add (will be converted to a MixedCollection)
28282 * @cfg {String/HTMLElement/Element} container
28283 * The id or element that will contain the toolbar
28286 render : function(ct){
28287 this.el = Roo.get(ct);
28289 this.el.addClass(this.cls);
28291 // using a table allows for vertical alignment
28292 // 100% width is needed by Safari...
28293 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
28294 this.tr = this.el.child("tr", true);
28296 this.items = new Roo.util.MixedCollection(false, function(o){
28297 return o.id || ("item" + (++autoId));
28300 this.add.apply(this, this.buttons);
28301 delete this.buttons;
28306 * Adds element(s) to the toolbar -- this function takes a variable number of
28307 * arguments of mixed type and adds them to the toolbar.
28308 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
28310 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
28311 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
28312 * <li>Field: Any form field (equivalent to {@link #addField})</li>
28313 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
28314 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
28315 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
28316 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
28317 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
28318 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
28320 * @param {Mixed} arg2
28321 * @param {Mixed} etc.
28324 var a = arguments, l = a.length;
28325 for(var i = 0; i < l; i++){
28330 _add : function(el) {
28333 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
28336 if (el.applyTo){ // some kind of form field
28337 return this.addField(el);
28339 if (el.render){ // some kind of Toolbar.Item
28340 return this.addItem(el);
28342 if (typeof el == "string"){ // string
28343 if(el == "separator" || el == "-"){
28344 return this.addSeparator();
28347 return this.addSpacer();
28350 return this.addFill();
28352 return this.addText(el);
28355 if(el.tagName){ // element
28356 return this.addElement(el);
28358 if(typeof el == "object"){ // must be button config?
28359 return this.addButton(el);
28361 // and now what?!?!
28367 * Add an Xtype element
28368 * @param {Object} xtype Xtype Object
28369 * @return {Object} created Object
28371 addxtype : function(e){
28372 return this.add(e);
28376 * Returns the Element for this toolbar.
28377 * @return {Roo.Element}
28379 getEl : function(){
28385 * @return {Roo.Toolbar.Item} The separator item
28387 addSeparator : function(){
28388 return this.addItem(new Roo.Toolbar.Separator());
28392 * Adds a spacer element
28393 * @return {Roo.Toolbar.Spacer} The spacer item
28395 addSpacer : function(){
28396 return this.addItem(new Roo.Toolbar.Spacer());
28400 * Adds a fill element that forces subsequent additions to the right side of the toolbar
28401 * @return {Roo.Toolbar.Fill} The fill item
28403 addFill : function(){
28404 return this.addItem(new Roo.Toolbar.Fill());
28408 * Adds any standard HTML element to the toolbar
28409 * @param {String/HTMLElement/Element} el The element or id of the element to add
28410 * @return {Roo.Toolbar.Item} The element's item
28412 addElement : function(el){
28413 return this.addItem(new Roo.Toolbar.Item(el));
28416 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
28417 * @type Roo.util.MixedCollection
28422 * Adds any Toolbar.Item or subclass
28423 * @param {Roo.Toolbar.Item} item
28424 * @return {Roo.Toolbar.Item} The item
28426 addItem : function(item){
28427 var td = this.nextBlock();
28429 this.items.add(item);
28434 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
28435 * @param {Object/Array} config A button config or array of configs
28436 * @return {Roo.Toolbar.Button/Array}
28438 addButton : function(config){
28439 if(config instanceof Array){
28441 for(var i = 0, len = config.length; i < len; i++) {
28442 buttons.push(this.addButton(config[i]));
28447 if(!(config instanceof Roo.Toolbar.Button)){
28449 new Roo.Toolbar.SplitButton(config) :
28450 new Roo.Toolbar.Button(config);
28452 var td = this.nextBlock();
28459 * Adds text to the toolbar
28460 * @param {String} text The text to add
28461 * @return {Roo.Toolbar.Item} The element's item
28463 addText : function(text){
28464 return this.addItem(new Roo.Toolbar.TextItem(text));
28468 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
28469 * @param {Number} index The index where the item is to be inserted
28470 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
28471 * @return {Roo.Toolbar.Button/Item}
28473 insertButton : function(index, item){
28474 if(item instanceof Array){
28476 for(var i = 0, len = item.length; i < len; i++) {
28477 buttons.push(this.insertButton(index + i, item[i]));
28481 if (!(item instanceof Roo.Toolbar.Button)){
28482 item = new Roo.Toolbar.Button(item);
28484 var td = document.createElement("td");
28485 this.tr.insertBefore(td, this.tr.childNodes[index]);
28487 this.items.insert(index, item);
28492 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
28493 * @param {Object} config
28494 * @return {Roo.Toolbar.Item} The element's item
28496 addDom : function(config, returnEl){
28497 var td = this.nextBlock();
28498 Roo.DomHelper.overwrite(td, config);
28499 var ti = new Roo.Toolbar.Item(td.firstChild);
28501 this.items.add(ti);
28506 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
28507 * @type Roo.util.MixedCollection
28512 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
28513 * Note: the field should not have been rendered yet. For a field that has already been
28514 * rendered, use {@link #addElement}.
28515 * @param {Roo.form.Field} field
28516 * @return {Roo.ToolbarItem}
28520 addField : function(field) {
28521 if (!this.fields) {
28523 this.fields = new Roo.util.MixedCollection(false, function(o){
28524 return o.id || ("item" + (++autoId));
28529 var td = this.nextBlock();
28531 var ti = new Roo.Toolbar.Item(td.firstChild);
28533 this.items.add(ti);
28534 this.fields.add(field);
28545 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
28546 this.el.child('div').hide();
28554 this.el.child('div').show();
28558 nextBlock : function(){
28559 var td = document.createElement("td");
28560 this.tr.appendChild(td);
28565 destroy : function(){
28566 if(this.items){ // rendered?
28567 Roo.destroy.apply(Roo, this.items.items);
28569 if(this.fields){ // rendered?
28570 Roo.destroy.apply(Roo, this.fields.items);
28572 Roo.Element.uncache(this.el, this.tr);
28577 * @class Roo.Toolbar.Item
28578 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
28580 * Creates a new Item
28581 * @param {HTMLElement} el
28583 Roo.Toolbar.Item = function(el){
28585 if (typeof (el.xtype) != 'undefined') {
28590 this.el = Roo.getDom(el);
28591 this.id = Roo.id(this.el);
28592 this.hidden = false;
28597 * Fires when the button is rendered
28598 * @param {Button} this
28602 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
28604 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
28605 //Roo.Toolbar.Item.prototype = {
28608 * Get this item's HTML Element
28609 * @return {HTMLElement}
28611 getEl : function(){
28616 render : function(td){
28619 td.appendChild(this.el);
28621 this.fireEvent('render', this);
28625 * Removes and destroys this item.
28627 destroy : function(){
28628 this.td.parentNode.removeChild(this.td);
28635 this.hidden = false;
28636 this.td.style.display = "";
28643 this.hidden = true;
28644 this.td.style.display = "none";
28648 * Convenience function for boolean show/hide.
28649 * @param {Boolean} visible true to show/false to hide
28651 setVisible: function(visible){
28660 * Try to focus this item.
28662 focus : function(){
28663 Roo.fly(this.el).focus();
28667 * Disables this item.
28669 disable : function(){
28670 Roo.fly(this.td).addClass("x-item-disabled");
28671 this.disabled = true;
28672 this.el.disabled = true;
28676 * Enables this item.
28678 enable : function(){
28679 Roo.fly(this.td).removeClass("x-item-disabled");
28680 this.disabled = false;
28681 this.el.disabled = false;
28687 * @class Roo.Toolbar.Separator
28688 * @extends Roo.Toolbar.Item
28689 * A simple toolbar separator class
28691 * Creates a new Separator
28693 Roo.Toolbar.Separator = function(cfg){
28695 var s = document.createElement("span");
28696 s.className = "ytb-sep";
28701 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
28703 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
28704 enable:Roo.emptyFn,
28705 disable:Roo.emptyFn,
28710 * @class Roo.Toolbar.Spacer
28711 * @extends Roo.Toolbar.Item
28712 * A simple element that adds extra horizontal space to a toolbar.
28714 * Creates a new Spacer
28716 Roo.Toolbar.Spacer = function(cfg){
28717 var s = document.createElement("div");
28718 s.className = "ytb-spacer";
28722 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
28724 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
28725 enable:Roo.emptyFn,
28726 disable:Roo.emptyFn,
28731 * @class Roo.Toolbar.Fill
28732 * @extends Roo.Toolbar.Spacer
28733 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
28735 * Creates a new Spacer
28737 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
28739 render : function(td){
28740 td.style.width = '100%';
28741 Roo.Toolbar.Fill.superclass.render.call(this, td);
28746 * @class Roo.Toolbar.TextItem
28747 * @extends Roo.Toolbar.Item
28748 * A simple class that renders text directly into a toolbar.
28750 * Creates a new TextItem
28751 * @param {String} text
28753 Roo.Toolbar.TextItem = function(cfg){
28754 var text = cfg || "";
28755 if (typeof(cfg) == 'object') {
28756 text = cfg.text || "";
28760 var s = document.createElement("span");
28761 s.className = "ytb-text";
28762 s.innerHTML = text;
28767 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
28769 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
28772 enable:Roo.emptyFn,
28773 disable:Roo.emptyFn,
28778 * @class Roo.Toolbar.Button
28779 * @extends Roo.Button
28780 * A button that renders into a toolbar.
28782 * Creates a new Button
28783 * @param {Object} config A standard {@link Roo.Button} config object
28785 Roo.Toolbar.Button = function(config){
28786 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
28788 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
28789 render : function(td){
28791 Roo.Toolbar.Button.superclass.render.call(this, td);
28795 * Removes and destroys this button
28797 destroy : function(){
28798 Roo.Toolbar.Button.superclass.destroy.call(this);
28799 this.td.parentNode.removeChild(this.td);
28803 * Shows this button
28806 this.hidden = false;
28807 this.td.style.display = "";
28811 * Hides this button
28814 this.hidden = true;
28815 this.td.style.display = "none";
28819 * Disables this item
28821 disable : function(){
28822 Roo.fly(this.td).addClass("x-item-disabled");
28823 this.disabled = true;
28827 * Enables this item
28829 enable : function(){
28830 Roo.fly(this.td).removeClass("x-item-disabled");
28831 this.disabled = false;
28834 // backwards compat
28835 Roo.ToolbarButton = Roo.Toolbar.Button;
28838 * @class Roo.Toolbar.SplitButton
28839 * @extends Roo.SplitButton
28840 * A menu button that renders into a toolbar.
28842 * Creates a new SplitButton
28843 * @param {Object} config A standard {@link Roo.SplitButton} config object
28845 Roo.Toolbar.SplitButton = function(config){
28846 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
28848 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
28849 render : function(td){
28851 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
28855 * Removes and destroys this button
28857 destroy : function(){
28858 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
28859 this.td.parentNode.removeChild(this.td);
28863 * Shows this button
28866 this.hidden = false;
28867 this.td.style.display = "";
28871 * Hides this button
28874 this.hidden = true;
28875 this.td.style.display = "none";
28879 // backwards compat
28880 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
28882 * Ext JS Library 1.1.1
28883 * Copyright(c) 2006-2007, Ext JS, LLC.
28885 * Originally Released Under LGPL - original licence link has changed is not relivant.
28888 * <script type="text/javascript">
28892 * @class Roo.PagingToolbar
28893 * @extends Roo.Toolbar
28894 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
28896 * Create a new PagingToolbar
28897 * @param {Object} config The config object
28899 Roo.PagingToolbar = function(el, ds, config)
28901 // old args format still supported... - xtype is prefered..
28902 if (typeof(el) == 'object' && el.xtype) {
28903 // created from xtype...
28905 ds = el.dataSource;
28906 el = config.container;
28909 if (config.items) {
28910 items = config.items;
28914 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
28917 this.renderButtons(this.el);
28920 // supprot items array.
28922 Roo.each(items, function(e) {
28923 this.add(Roo.factory(e));
28928 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
28930 * @cfg {Roo.data.Store} dataSource
28931 * The underlying data store providing the paged data
28934 * @cfg {String/HTMLElement/Element} container
28935 * container The id or element that will contain the toolbar
28938 * @cfg {Boolean} displayInfo
28939 * True to display the displayMsg (defaults to false)
28942 * @cfg {Number} pageSize
28943 * The number of records to display per page (defaults to 20)
28947 * @cfg {String} displayMsg
28948 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
28950 displayMsg : 'Displaying {0} - {1} of {2}',
28952 * @cfg {String} emptyMsg
28953 * The message to display when no records are found (defaults to "No data to display")
28955 emptyMsg : 'No data to display',
28957 * Customizable piece of the default paging text (defaults to "Page")
28960 beforePageText : "Page",
28962 * Customizable piece of the default paging text (defaults to "of %0")
28965 afterPageText : "of {0}",
28967 * Customizable piece of the default paging text (defaults to "First Page")
28970 firstText : "First Page",
28972 * Customizable piece of the default paging text (defaults to "Previous Page")
28975 prevText : "Previous Page",
28977 * Customizable piece of the default paging text (defaults to "Next Page")
28980 nextText : "Next Page",
28982 * Customizable piece of the default paging text (defaults to "Last Page")
28985 lastText : "Last Page",
28987 * Customizable piece of the default paging text (defaults to "Refresh")
28990 refreshText : "Refresh",
28993 renderButtons : function(el){
28994 Roo.PagingToolbar.superclass.render.call(this, el);
28995 this.first = this.addButton({
28996 tooltip: this.firstText,
28997 cls: "x-btn-icon x-grid-page-first",
28999 handler: this.onClick.createDelegate(this, ["first"])
29001 this.prev = this.addButton({
29002 tooltip: this.prevText,
29003 cls: "x-btn-icon x-grid-page-prev",
29005 handler: this.onClick.createDelegate(this, ["prev"])
29007 //this.addSeparator();
29008 this.add(this.beforePageText);
29009 this.field = Roo.get(this.addDom({
29014 cls: "x-grid-page-number"
29016 this.field.on("keydown", this.onPagingKeydown, this);
29017 this.field.on("focus", function(){this.dom.select();});
29018 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
29019 this.field.setHeight(18);
29020 //this.addSeparator();
29021 this.next = this.addButton({
29022 tooltip: this.nextText,
29023 cls: "x-btn-icon x-grid-page-next",
29025 handler: this.onClick.createDelegate(this, ["next"])
29027 this.last = this.addButton({
29028 tooltip: this.lastText,
29029 cls: "x-btn-icon x-grid-page-last",
29031 handler: this.onClick.createDelegate(this, ["last"])
29033 //this.addSeparator();
29034 this.loading = this.addButton({
29035 tooltip: this.refreshText,
29036 cls: "x-btn-icon x-grid-loading",
29037 handler: this.onClick.createDelegate(this, ["refresh"])
29040 if(this.displayInfo){
29041 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
29046 updateInfo : function(){
29047 if(this.displayEl){
29048 var count = this.ds.getCount();
29049 var msg = count == 0 ?
29053 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
29055 this.displayEl.update(msg);
29060 onLoad : function(ds, r, o){
29061 this.cursor = o.params ? o.params.start : 0;
29062 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
29064 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
29065 this.field.dom.value = ap;
29066 this.first.setDisabled(ap == 1);
29067 this.prev.setDisabled(ap == 1);
29068 this.next.setDisabled(ap == ps);
29069 this.last.setDisabled(ap == ps);
29070 this.loading.enable();
29075 getPageData : function(){
29076 var total = this.ds.getTotalCount();
29079 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
29080 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
29085 onLoadError : function(){
29086 this.loading.enable();
29090 onPagingKeydown : function(e){
29091 var k = e.getKey();
29092 var d = this.getPageData();
29094 var v = this.field.dom.value, pageNum;
29095 if(!v || isNaN(pageNum = parseInt(v, 10))){
29096 this.field.dom.value = d.activePage;
29099 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
29100 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
29103 else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
29105 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
29106 this.field.dom.value = pageNum;
29107 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
29110 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
29112 var v = this.field.dom.value, pageNum;
29113 var increment = (e.shiftKey) ? 10 : 1;
29114 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
29116 if(!v || isNaN(pageNum = parseInt(v, 10))) {
29117 this.field.dom.value = d.activePage;
29120 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
29122 this.field.dom.value = parseInt(v, 10) + increment;
29123 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
29124 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
29131 beforeLoad : function(){
29133 this.loading.disable();
29138 onClick : function(which){
29142 ds.load({params:{start: 0, limit: this.pageSize}});
29145 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
29148 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
29151 var total = ds.getTotalCount();
29152 var extra = total % this.pageSize;
29153 var lastStart = extra ? (total - extra) : total-this.pageSize;
29154 ds.load({params:{start: lastStart, limit: this.pageSize}});
29157 ds.load({params:{start: this.cursor, limit: this.pageSize}});
29163 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
29164 * @param {Roo.data.Store} store The data store to unbind
29166 unbind : function(ds){
29167 ds.un("beforeload", this.beforeLoad, this);
29168 ds.un("load", this.onLoad, this);
29169 ds.un("loadexception", this.onLoadError, this);
29170 ds.un("remove", this.updateInfo, this);
29171 ds.un("add", this.updateInfo, this);
29172 this.ds = undefined;
29176 * Binds the paging toolbar to the specified {@link Roo.data.Store}
29177 * @param {Roo.data.Store} store The data store to bind
29179 bind : function(ds){
29180 ds.on("beforeload", this.beforeLoad, this);
29181 ds.on("load", this.onLoad, this);
29182 ds.on("loadexception", this.onLoadError, this);
29183 ds.on("remove", this.updateInfo, this);
29184 ds.on("add", this.updateInfo, this);
29189 * Ext JS Library 1.1.1
29190 * Copyright(c) 2006-2007, Ext JS, LLC.
29192 * Originally Released Under LGPL - original licence link has changed is not relivant.
29195 * <script type="text/javascript">
29199 * @class Roo.Resizable
29200 * @extends Roo.util.Observable
29201 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
29202 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
29203 * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
29204 * the element will be wrapped for you automatically.</p>
29205 * <p>Here is the list of valid resize handles:</p>
29208 ------ -------------------
29217 'hd' horizontal drag
29220 * <p>Here's an example showing the creation of a typical Resizable:</p>
29222 var resizer = new Roo.Resizable("element-id", {
29230 resizer.on("resize", myHandler);
29232 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
29233 * resizer.east.setDisplayed(false);</p>
29234 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
29235 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
29236 * resize operation's new size (defaults to [0, 0])
29237 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
29238 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
29239 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
29240 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
29241 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
29242 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
29243 * @cfg {Number} width The width of the element in pixels (defaults to null)
29244 * @cfg {Number} height The height of the element in pixels (defaults to null)
29245 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
29246 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
29247 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
29248 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
29249 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
29250 * in favor of the handles config option (defaults to false)
29251 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
29252 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
29253 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
29254 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
29255 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
29256 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
29257 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
29258 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
29259 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
29260 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
29261 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
29263 * Create a new resizable component
29264 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
29265 * @param {Object} config configuration options
29267 Roo.Resizable = function(el, config)
29269 this.el = Roo.get(el);
29271 if(config && config.wrap){
29272 config.resizeChild = this.el;
29273 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
29274 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
29275 this.el.setStyle("overflow", "hidden");
29276 this.el.setPositioning(config.resizeChild.getPositioning());
29277 config.resizeChild.clearPositioning();
29278 if(!config.width || !config.height){
29279 var csize = config.resizeChild.getSize();
29280 this.el.setSize(csize.width, csize.height);
29282 if(config.pinned && !config.adjustments){
29283 config.adjustments = "auto";
29287 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
29288 this.proxy.unselectable();
29289 this.proxy.enableDisplayMode('block');
29291 Roo.apply(this, config);
29294 this.disableTrackOver = true;
29295 this.el.addClass("x-resizable-pinned");
29297 // if the element isn't positioned, make it relative
29298 var position = this.el.getStyle("position");
29299 if(position != "absolute" && position != "fixed"){
29300 this.el.setStyle("position", "relative");
29302 if(!this.handles){ // no handles passed, must be legacy style
29303 this.handles = 's,e,se';
29304 if(this.multiDirectional){
29305 this.handles += ',n,w';
29308 if(this.handles == "all"){
29309 this.handles = "n s e w ne nw se sw";
29311 var hs = this.handles.split(/\s*?[,;]\s*?| /);
29312 var ps = Roo.Resizable.positions;
29313 for(var i = 0, len = hs.length; i < len; i++){
29314 if(hs[i] && ps[hs[i]]){
29315 var pos = ps[hs[i]];
29316 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
29320 this.corner = this.southeast;
29322 // updateBox = the box can move..
29323 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
29324 this.updateBox = true;
29327 this.activeHandle = null;
29329 if(this.resizeChild){
29330 if(typeof this.resizeChild == "boolean"){
29331 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
29333 this.resizeChild = Roo.get(this.resizeChild, true);
29337 if(this.adjustments == "auto"){
29338 var rc = this.resizeChild;
29339 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
29340 if(rc && (hw || hn)){
29341 rc.position("relative");
29342 rc.setLeft(hw ? hw.el.getWidth() : 0);
29343 rc.setTop(hn ? hn.el.getHeight() : 0);
29345 this.adjustments = [
29346 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
29347 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
29351 if(this.draggable){
29352 this.dd = this.dynamic ?
29353 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
29354 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
29360 * @event beforeresize
29361 * Fired before resize is allowed. Set enabled to false to cancel resize.
29362 * @param {Roo.Resizable} this
29363 * @param {Roo.EventObject} e The mousedown event
29365 "beforeresize" : true,
29368 * Fired a resizing.
29369 * @param {Roo.Resizable} this
29370 * @param {Number} x The new x position
29371 * @param {Number} y The new y position
29372 * @param {Number} w The new w width
29373 * @param {Number} h The new h hight
29374 * @param {Roo.EventObject} e The mouseup event
29379 * Fired after a resize.
29380 * @param {Roo.Resizable} this
29381 * @param {Number} width The new width
29382 * @param {Number} height The new height
29383 * @param {Roo.EventObject} e The mouseup event
29388 if(this.width !== null && this.height !== null){
29389 this.resizeTo(this.width, this.height);
29391 this.updateChildSize();
29394 this.el.dom.style.zoom = 1;
29396 Roo.Resizable.superclass.constructor.call(this);
29399 Roo.extend(Roo.Resizable, Roo.util.Observable, {
29400 resizeChild : false,
29401 adjustments : [0, 0],
29411 multiDirectional : false,
29412 disableTrackOver : false,
29413 easing : 'easeOutStrong',
29414 widthIncrement : 0,
29415 heightIncrement : 0,
29419 preserveRatio : false,
29420 transparent: false,
29426 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
29428 constrainTo: undefined,
29430 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
29432 resizeRegion: undefined,
29436 * Perform a manual resize
29437 * @param {Number} width
29438 * @param {Number} height
29440 resizeTo : function(width, height){
29441 this.el.setSize(width, height);
29442 this.updateChildSize();
29443 this.fireEvent("resize", this, width, height, null);
29447 startSizing : function(e, handle){
29448 this.fireEvent("beforeresize", this, e);
29449 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
29452 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
29453 this.overlay.unselectable();
29454 this.overlay.enableDisplayMode("block");
29455 this.overlay.on("mousemove", this.onMouseMove, this);
29456 this.overlay.on("mouseup", this.onMouseUp, this);
29458 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
29460 this.resizing = true;
29461 this.startBox = this.el.getBox();
29462 this.startPoint = e.getXY();
29463 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
29464 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
29466 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
29467 this.overlay.show();
29469 if(this.constrainTo) {
29470 var ct = Roo.get(this.constrainTo);
29471 this.resizeRegion = ct.getRegion().adjust(
29472 ct.getFrameWidth('t'),
29473 ct.getFrameWidth('l'),
29474 -ct.getFrameWidth('b'),
29475 -ct.getFrameWidth('r')
29479 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
29481 this.proxy.setBox(this.startBox);
29483 this.proxy.setStyle('visibility', 'visible');
29489 onMouseDown : function(handle, e){
29492 this.activeHandle = handle;
29493 this.startSizing(e, handle);
29498 onMouseUp : function(e){
29499 var size = this.resizeElement();
29500 this.resizing = false;
29502 this.overlay.hide();
29504 this.fireEvent("resize", this, size.width, size.height, e);
29508 updateChildSize : function(){
29510 if(this.resizeChild){
29512 var child = this.resizeChild;
29513 var adj = this.adjustments;
29514 if(el.dom.offsetWidth){
29515 var b = el.getSize(true);
29516 child.setSize(b.width+adj[0], b.height+adj[1]);
29518 // Second call here for IE
29519 // The first call enables instant resizing and
29520 // the second call corrects scroll bars if they
29523 setTimeout(function(){
29524 if(el.dom.offsetWidth){
29525 var b = el.getSize(true);
29526 child.setSize(b.width+adj[0], b.height+adj[1]);
29534 snap : function(value, inc, min){
29535 if(!inc || !value) return value;
29536 var newValue = value;
29537 var m = value % inc;
29540 newValue = value + (inc-m);
29542 newValue = value - m;
29545 return Math.max(min, newValue);
29549 resizeElement : function(){
29550 var box = this.proxy.getBox();
29551 if(this.updateBox){
29552 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
29554 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
29556 this.updateChildSize();
29564 constrain : function(v, diff, m, mx){
29567 }else if(v - diff > mx){
29574 onMouseMove : function(e){
29577 try{// try catch so if something goes wrong the user doesn't get hung
29579 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
29583 //var curXY = this.startPoint;
29584 var curSize = this.curSize || this.startBox;
29585 var x = this.startBox.x, y = this.startBox.y;
29586 var ox = x, oy = y;
29587 var w = curSize.width, h = curSize.height;
29588 var ow = w, oh = h;
29589 var mw = this.minWidth, mh = this.minHeight;
29590 var mxw = this.maxWidth, mxh = this.maxHeight;
29591 var wi = this.widthIncrement;
29592 var hi = this.heightIncrement;
29594 var eventXY = e.getXY();
29595 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
29596 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
29598 var pos = this.activeHandle.position;
29603 w = Math.min(Math.max(mw, w), mxw);
29608 h = Math.min(Math.max(mh, h), mxh);
29613 w = Math.min(Math.max(mw, w), mxw);
29614 h = Math.min(Math.max(mh, h), mxh);
29617 diffY = this.constrain(h, diffY, mh, mxh);
29624 var adiffX = Math.abs(diffX);
29625 var sub = (adiffX % wi); // how much
29626 if (sub > (wi/2)) { // far enough to snap
29627 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
29629 // remove difference..
29630 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
29634 x = Math.max(this.minX, x);
29637 diffX = this.constrain(w, diffX, mw, mxw);
29643 w = Math.min(Math.max(mw, w), mxw);
29644 diffY = this.constrain(h, diffY, mh, mxh);
29649 diffX = this.constrain(w, diffX, mw, mxw);
29650 diffY = this.constrain(h, diffY, mh, mxh);
29657 diffX = this.constrain(w, diffX, mw, mxw);
29659 h = Math.min(Math.max(mh, h), mxh);
29665 var sw = this.snap(w, wi, mw);
29666 var sh = this.snap(h, hi, mh);
29667 if(sw != w || sh != h){
29690 if(this.preserveRatio){
29695 h = Math.min(Math.max(mh, h), mxh);
29700 w = Math.min(Math.max(mw, w), mxw);
29705 w = Math.min(Math.max(mw, w), mxw);
29711 w = Math.min(Math.max(mw, w), mxw);
29717 h = Math.min(Math.max(mh, h), mxh);
29725 h = Math.min(Math.max(mh, h), mxh);
29735 h = Math.min(Math.max(mh, h), mxh);
29743 if (pos == 'hdrag') {
29746 this.proxy.setBounds(x, y, w, h);
29748 this.resizeElement();
29752 this.fireEvent("resizing", this, x, y, w, h, e);
29756 handleOver : function(){
29758 this.el.addClass("x-resizable-over");
29763 handleOut : function(){
29764 if(!this.resizing){
29765 this.el.removeClass("x-resizable-over");
29770 * Returns the element this component is bound to.
29771 * @return {Roo.Element}
29773 getEl : function(){
29778 * Returns the resizeChild element (or null).
29779 * @return {Roo.Element}
29781 getResizeChild : function(){
29782 return this.resizeChild;
29784 groupHandler : function()
29789 * Destroys this resizable. If the element was wrapped and
29790 * removeEl is not true then the element remains.
29791 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
29793 destroy : function(removeEl){
29794 this.proxy.remove();
29796 this.overlay.removeAllListeners();
29797 this.overlay.remove();
29799 var ps = Roo.Resizable.positions;
29801 if(typeof ps[k] != "function" && this[ps[k]]){
29802 var h = this[ps[k]];
29803 h.el.removeAllListeners();
29808 this.el.update("");
29815 // hash to map config positions to true positions
29816 Roo.Resizable.positions = {
29817 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
29822 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
29824 // only initialize the template if resizable is used
29825 var tpl = Roo.DomHelper.createTemplate(
29826 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
29829 Roo.Resizable.Handle.prototype.tpl = tpl;
29831 this.position = pos;
29833 // show north drag fro topdra
29834 var handlepos = pos == 'hdrag' ? 'north' : pos;
29836 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
29837 if (pos == 'hdrag') {
29838 this.el.setStyle('cursor', 'pointer');
29840 this.el.unselectable();
29842 this.el.setOpacity(0);
29844 this.el.on("mousedown", this.onMouseDown, this);
29845 if(!disableTrackOver){
29846 this.el.on("mouseover", this.onMouseOver, this);
29847 this.el.on("mouseout", this.onMouseOut, this);
29852 Roo.Resizable.Handle.prototype = {
29853 afterResize : function(rz){
29858 onMouseDown : function(e){
29859 this.rz.onMouseDown(this, e);
29862 onMouseOver : function(e){
29863 this.rz.handleOver(this, e);
29866 onMouseOut : function(e){
29867 this.rz.handleOut(this, e);
29871 * Ext JS Library 1.1.1
29872 * Copyright(c) 2006-2007, Ext JS, LLC.
29874 * Originally Released Under LGPL - original licence link has changed is not relivant.
29877 * <script type="text/javascript">
29881 * @class Roo.Editor
29882 * @extends Roo.Component
29883 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
29885 * Create a new Editor
29886 * @param {Roo.form.Field} field The Field object (or descendant)
29887 * @param {Object} config The config object
29889 Roo.Editor = function(field, config){
29890 Roo.Editor.superclass.constructor.call(this, config);
29891 this.field = field;
29894 * @event beforestartedit
29895 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
29896 * false from the handler of this event.
29897 * @param {Editor} this
29898 * @param {Roo.Element} boundEl The underlying element bound to this editor
29899 * @param {Mixed} value The field value being set
29901 "beforestartedit" : true,
29904 * Fires when this editor is displayed
29905 * @param {Roo.Element} boundEl The underlying element bound to this editor
29906 * @param {Mixed} value The starting field value
29908 "startedit" : true,
29910 * @event beforecomplete
29911 * Fires after a change has been made to the field, but before the change is reflected in the underlying
29912 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
29913 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
29914 * event will not fire since no edit actually occurred.
29915 * @param {Editor} this
29916 * @param {Mixed} value The current field value
29917 * @param {Mixed} startValue The original field value
29919 "beforecomplete" : true,
29922 * Fires after editing is complete and any changed value has been written to the underlying field.
29923 * @param {Editor} this
29924 * @param {Mixed} value The current field value
29925 * @param {Mixed} startValue The original field value
29929 * @event specialkey
29930 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
29931 * {@link Roo.EventObject#getKey} to determine which key was pressed.
29932 * @param {Roo.form.Field} this
29933 * @param {Roo.EventObject} e The event object
29935 "specialkey" : true
29939 Roo.extend(Roo.Editor, Roo.Component, {
29941 * @cfg {Boolean/String} autosize
29942 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
29943 * or "height" to adopt the height only (defaults to false)
29946 * @cfg {Boolean} revertInvalid
29947 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
29948 * validation fails (defaults to true)
29951 * @cfg {Boolean} ignoreNoChange
29952 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
29953 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
29954 * will never be ignored.
29957 * @cfg {Boolean} hideEl
29958 * False to keep the bound element visible while the editor is displayed (defaults to true)
29961 * @cfg {Mixed} value
29962 * The data value of the underlying field (defaults to "")
29966 * @cfg {String} alignment
29967 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
29971 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
29972 * for bottom-right shadow (defaults to "frame")
29976 * @cfg {Boolean} constrain True to constrain the editor to the viewport
29980 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
29982 completeOnEnter : false,
29984 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
29986 cancelOnEsc : false,
29988 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
29993 onRender : function(ct, position){
29994 this.el = new Roo.Layer({
29995 shadow: this.shadow,
30001 constrain: this.constrain
30003 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
30004 if(this.field.msgTarget != 'title'){
30005 this.field.msgTarget = 'qtip';
30007 this.field.render(this.el);
30009 this.field.el.dom.setAttribute('autocomplete', 'off');
30011 this.field.on("specialkey", this.onSpecialKey, this);
30012 if(this.swallowKeys){
30013 this.field.el.swallowEvent(['keydown','keypress']);
30016 this.field.on("blur", this.onBlur, this);
30017 if(this.field.grow){
30018 this.field.on("autosize", this.el.sync, this.el, {delay:1});
30022 onSpecialKey : function(field, e)
30024 //Roo.log('editor onSpecialKey');
30025 if(this.completeOnEnter && e.getKey() == e.ENTER){
30027 this.completeEdit();
30030 // do not fire special key otherwise it might hide close the editor...
30031 if(e.getKey() == e.ENTER){
30034 if(this.cancelOnEsc && e.getKey() == e.ESC){
30038 this.fireEvent('specialkey', field, e);
30043 * Starts the editing process and shows the editor.
30044 * @param {String/HTMLElement/Element} el The element to edit
30045 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
30046 * to the innerHTML of el.
30048 startEdit : function(el, value){
30050 this.completeEdit();
30052 this.boundEl = Roo.get(el);
30053 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
30054 if(!this.rendered){
30055 this.render(this.parentEl || document.body);
30057 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
30060 this.startValue = v;
30061 this.field.setValue(v);
30063 var sz = this.boundEl.getSize();
30064 switch(this.autoSize){
30066 this.setSize(sz.width, "");
30069 this.setSize("", sz.height);
30072 this.setSize(sz.width, sz.height);
30075 this.el.alignTo(this.boundEl, this.alignment);
30076 this.editing = true;
30078 Roo.QuickTips.disable();
30084 * Sets the height and width of this editor.
30085 * @param {Number} width The new width
30086 * @param {Number} height The new height
30088 setSize : function(w, h){
30089 this.field.setSize(w, h);
30096 * Realigns the editor to the bound field based on the current alignment config value.
30098 realign : function(){
30099 this.el.alignTo(this.boundEl, this.alignment);
30103 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
30104 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
30106 completeEdit : function(remainVisible){
30110 var v = this.getValue();
30111 if(this.revertInvalid !== false && !this.field.isValid()){
30112 v = this.startValue;
30113 this.cancelEdit(true);
30115 if(String(v) === String(this.startValue) && this.ignoreNoChange){
30116 this.editing = false;
30120 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
30121 this.editing = false;
30122 if(this.updateEl && this.boundEl){
30123 this.boundEl.update(v);
30125 if(remainVisible !== true){
30128 this.fireEvent("complete", this, v, this.startValue);
30133 onShow : function(){
30135 if(this.hideEl !== false){
30136 this.boundEl.hide();
30139 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
30140 this.fixIEFocus = true;
30141 this.deferredFocus.defer(50, this);
30143 this.field.focus();
30145 this.fireEvent("startedit", this.boundEl, this.startValue);
30148 deferredFocus : function(){
30150 this.field.focus();
30155 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
30156 * reverted to the original starting value.
30157 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
30158 * cancel (defaults to false)
30160 cancelEdit : function(remainVisible){
30162 this.setValue(this.startValue);
30163 if(remainVisible !== true){
30170 onBlur : function(){
30171 if(this.allowBlur !== true && this.editing){
30172 this.completeEdit();
30177 onHide : function(){
30179 this.completeEdit();
30183 if(this.field.collapse){
30184 this.field.collapse();
30187 if(this.hideEl !== false){
30188 this.boundEl.show();
30191 Roo.QuickTips.enable();
30196 * Sets the data value of the editor
30197 * @param {Mixed} value Any valid value supported by the underlying field
30199 setValue : function(v){
30200 this.field.setValue(v);
30204 * Gets the data value of the editor
30205 * @return {Mixed} The data value
30207 getValue : function(){
30208 return this.field.getValue();
30212 * Ext JS Library 1.1.1
30213 * Copyright(c) 2006-2007, Ext JS, LLC.
30215 * Originally Released Under LGPL - original licence link has changed is not relivant.
30218 * <script type="text/javascript">
30222 * @class Roo.BasicDialog
30223 * @extends Roo.util.Observable
30224 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
30226 var dlg = new Roo.BasicDialog("my-dlg", {
30235 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
30236 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
30237 dlg.addButton('Cancel', dlg.hide, dlg);
30240 <b>A Dialog should always be a direct child of the body element.</b>
30241 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
30242 * @cfg {String} title Default text to display in the title bar (defaults to null)
30243 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
30244 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
30245 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
30246 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
30247 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
30248 * (defaults to null with no animation)
30249 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
30250 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
30251 * property for valid values (defaults to 'all')
30252 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
30253 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
30254 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
30255 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
30256 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
30257 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
30258 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
30259 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
30260 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
30261 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
30262 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
30263 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
30264 * draggable = true (defaults to false)
30265 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
30266 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
30267 * shadow (defaults to false)
30268 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
30269 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
30270 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
30271 * @cfg {Array} buttons Array of buttons
30272 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
30274 * Create a new BasicDialog.
30275 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
30276 * @param {Object} config Configuration options
30278 Roo.BasicDialog = function(el, config){
30279 this.el = Roo.get(el);
30280 var dh = Roo.DomHelper;
30281 if(!this.el && config && config.autoCreate){
30282 if(typeof config.autoCreate == "object"){
30283 if(!config.autoCreate.id){
30284 config.autoCreate.id = el;
30286 this.el = dh.append(document.body,
30287 config.autoCreate, true);
30289 this.el = dh.append(document.body,
30290 {tag: "div", id: el, style:'visibility:hidden;'}, true);
30294 el.setDisplayed(true);
30295 el.hide = this.hideAction;
30297 el.addClass("x-dlg");
30299 Roo.apply(this, config);
30301 this.proxy = el.createProxy("x-dlg-proxy");
30302 this.proxy.hide = this.hideAction;
30303 this.proxy.setOpacity(.5);
30307 el.setWidth(config.width);
30310 el.setHeight(config.height);
30312 this.size = el.getSize();
30313 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
30314 this.xy = [config.x,config.y];
30316 this.xy = el.getCenterXY(true);
30318 /** The header element @type Roo.Element */
30319 this.header = el.child("> .x-dlg-hd");
30320 /** The body element @type Roo.Element */
30321 this.body = el.child("> .x-dlg-bd");
30322 /** The footer element @type Roo.Element */
30323 this.footer = el.child("> .x-dlg-ft");
30326 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
30329 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
30332 this.header.unselectable();
30334 this.header.update(this.title);
30336 // this element allows the dialog to be focused for keyboard event
30337 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
30338 this.focusEl.swallowEvent("click", true);
30340 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
30342 // wrap the body and footer for special rendering
30343 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
30345 this.bwrap.dom.appendChild(this.footer.dom);
30348 this.bg = this.el.createChild({
30349 tag: "div", cls:"x-dlg-bg",
30350 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
30352 this.centerBg = this.bg.child("div.x-dlg-bg-center");
30355 if(this.autoScroll !== false && !this.autoTabs){
30356 this.body.setStyle("overflow", "auto");
30359 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
30361 if(this.closable !== false){
30362 this.el.addClass("x-dlg-closable");
30363 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
30364 this.close.on("click", this.closeClick, this);
30365 this.close.addClassOnOver("x-dlg-close-over");
30367 if(this.collapsible !== false){
30368 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
30369 this.collapseBtn.on("click", this.collapseClick, this);
30370 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
30371 this.header.on("dblclick", this.collapseClick, this);
30373 if(this.resizable !== false){
30374 this.el.addClass("x-dlg-resizable");
30375 this.resizer = new Roo.Resizable(el, {
30376 minWidth: this.minWidth || 80,
30377 minHeight:this.minHeight || 80,
30378 handles: this.resizeHandles || "all",
30381 this.resizer.on("beforeresize", this.beforeResize, this);
30382 this.resizer.on("resize", this.onResize, this);
30384 if(this.draggable !== false){
30385 el.addClass("x-dlg-draggable");
30386 if (!this.proxyDrag) {
30387 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
30390 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
30392 dd.setHandleElId(this.header.id);
30393 dd.endDrag = this.endMove.createDelegate(this);
30394 dd.startDrag = this.startMove.createDelegate(this);
30395 dd.onDrag = this.onDrag.createDelegate(this);
30400 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
30401 this.mask.enableDisplayMode("block");
30403 this.el.addClass("x-dlg-modal");
30406 this.shadow = new Roo.Shadow({
30407 mode : typeof this.shadow == "string" ? this.shadow : "sides",
30408 offset : this.shadowOffset
30411 this.shadowOffset = 0;
30413 if(Roo.useShims && this.shim !== false){
30414 this.shim = this.el.createShim();
30415 this.shim.hide = this.hideAction;
30423 if (this.buttons) {
30424 var bts= this.buttons;
30426 Roo.each(bts, function(b) {
30435 * Fires when a key is pressed
30436 * @param {Roo.BasicDialog} this
30437 * @param {Roo.EventObject} e
30442 * Fires when this dialog is moved by the user.
30443 * @param {Roo.BasicDialog} this
30444 * @param {Number} x The new page X
30445 * @param {Number} y The new page Y
30450 * Fires when this dialog is resized by the user.
30451 * @param {Roo.BasicDialog} this
30452 * @param {Number} width The new width
30453 * @param {Number} height The new height
30457 * @event beforehide
30458 * Fires before this dialog is hidden.
30459 * @param {Roo.BasicDialog} this
30461 "beforehide" : true,
30464 * Fires when this dialog is hidden.
30465 * @param {Roo.BasicDialog} this
30469 * @event beforeshow
30470 * Fires before this dialog is shown.
30471 * @param {Roo.BasicDialog} this
30473 "beforeshow" : true,
30476 * Fires when this dialog is shown.
30477 * @param {Roo.BasicDialog} this
30481 el.on("keydown", this.onKeyDown, this);
30482 el.on("mousedown", this.toFront, this);
30483 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
30485 Roo.DialogManager.register(this);
30486 Roo.BasicDialog.superclass.constructor.call(this);
30489 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
30490 shadowOffset: Roo.isIE ? 6 : 5,
30493 minButtonWidth: 75,
30494 defaultButton: null,
30495 buttonAlign: "right",
30500 * Sets the dialog title text
30501 * @param {String} text The title text to display
30502 * @return {Roo.BasicDialog} this
30504 setTitle : function(text){
30505 this.header.update(text);
30510 closeClick : function(){
30515 collapseClick : function(){
30516 this[this.collapsed ? "expand" : "collapse"]();
30520 * Collapses the dialog to its minimized state (only the title bar is visible).
30521 * Equivalent to the user clicking the collapse dialog button.
30523 collapse : function(){
30524 if(!this.collapsed){
30525 this.collapsed = true;
30526 this.el.addClass("x-dlg-collapsed");
30527 this.restoreHeight = this.el.getHeight();
30528 this.resizeTo(this.el.getWidth(), this.header.getHeight());
30533 * Expands a collapsed dialog back to its normal state. Equivalent to the user
30534 * clicking the expand dialog button.
30536 expand : function(){
30537 if(this.collapsed){
30538 this.collapsed = false;
30539 this.el.removeClass("x-dlg-collapsed");
30540 this.resizeTo(this.el.getWidth(), this.restoreHeight);
30545 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
30546 * @return {Roo.TabPanel} The tabs component
30548 initTabs : function(){
30549 var tabs = this.getTabs();
30550 while(tabs.getTab(0)){
30553 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
30555 tabs.addTab(Roo.id(dom), dom.title);
30563 beforeResize : function(){
30564 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
30568 onResize : function(){
30569 this.refreshSize();
30570 this.syncBodyHeight();
30571 this.adjustAssets();
30573 this.fireEvent("resize", this, this.size.width, this.size.height);
30577 onKeyDown : function(e){
30578 if(this.isVisible()){
30579 this.fireEvent("keydown", this, e);
30584 * Resizes the dialog.
30585 * @param {Number} width
30586 * @param {Number} height
30587 * @return {Roo.BasicDialog} this
30589 resizeTo : function(width, height){
30590 this.el.setSize(width, height);
30591 this.size = {width: width, height: height};
30592 this.syncBodyHeight();
30593 if(this.fixedcenter){
30596 if(this.isVisible()){
30597 this.constrainXY();
30598 this.adjustAssets();
30600 this.fireEvent("resize", this, width, height);
30606 * Resizes the dialog to fit the specified content size.
30607 * @param {Number} width
30608 * @param {Number} height
30609 * @return {Roo.BasicDialog} this
30611 setContentSize : function(w, h){
30612 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
30613 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
30614 //if(!this.el.isBorderBox()){
30615 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
30616 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
30619 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
30620 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
30622 this.resizeTo(w, h);
30627 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
30628 * executed in response to a particular key being pressed while the dialog is active.
30629 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
30630 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
30631 * @param {Function} fn The function to call
30632 * @param {Object} scope (optional) The scope of the function
30633 * @return {Roo.BasicDialog} this
30635 addKeyListener : function(key, fn, scope){
30636 var keyCode, shift, ctrl, alt;
30637 if(typeof key == "object" && !(key instanceof Array)){
30638 keyCode = key["key"];
30639 shift = key["shift"];
30640 ctrl = key["ctrl"];
30645 var handler = function(dlg, e){
30646 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
30647 var k = e.getKey();
30648 if(keyCode instanceof Array){
30649 for(var i = 0, len = keyCode.length; i < len; i++){
30650 if(keyCode[i] == k){
30651 fn.call(scope || window, dlg, k, e);
30657 fn.call(scope || window, dlg, k, e);
30662 this.on("keydown", handler);
30667 * Returns the TabPanel component (creates it if it doesn't exist).
30668 * Note: If you wish to simply check for the existence of tabs without creating them,
30669 * check for a null 'tabs' property.
30670 * @return {Roo.TabPanel} The tabs component
30672 getTabs : function(){
30674 this.el.addClass("x-dlg-auto-tabs");
30675 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
30676 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
30682 * Adds a button to the footer section of the dialog.
30683 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
30684 * object or a valid Roo.DomHelper element config
30685 * @param {Function} handler The function called when the button is clicked
30686 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
30687 * @return {Roo.Button} The new button
30689 addButton : function(config, handler, scope){
30690 var dh = Roo.DomHelper;
30692 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
30694 if(!this.btnContainer){
30695 var tb = this.footer.createChild({
30697 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
30698 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
30700 this.btnContainer = tb.firstChild.firstChild.firstChild;
30705 minWidth: this.minButtonWidth,
30708 if(typeof config == "string"){
30709 bconfig.text = config;
30712 bconfig.dhconfig = config;
30714 Roo.apply(bconfig, config);
30718 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
30719 bconfig.position = Math.max(0, bconfig.position);
30720 fc = this.btnContainer.childNodes[bconfig.position];
30723 var btn = new Roo.Button(
30725 this.btnContainer.insertBefore(document.createElement("td"),fc)
30726 : this.btnContainer.appendChild(document.createElement("td")),
30727 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
30730 this.syncBodyHeight();
30733 * Array of all the buttons that have been added to this dialog via addButton
30738 this.buttons.push(btn);
30743 * Sets the default button to be focused when the dialog is displayed.
30744 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
30745 * @return {Roo.BasicDialog} this
30747 setDefaultButton : function(btn){
30748 this.defaultButton = btn;
30753 getHeaderFooterHeight : function(safe){
30756 height += this.header.getHeight();
30759 var fm = this.footer.getMargins();
30760 height += (this.footer.getHeight()+fm.top+fm.bottom);
30762 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
30763 height += this.centerBg.getPadding("tb");
30768 syncBodyHeight : function()
30770 var bd = this.body, // the text
30771 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
30773 var height = this.size.height - this.getHeaderFooterHeight(false);
30774 bd.setHeight(height-bd.getMargins("tb"));
30775 var hh = this.header.getHeight();
30776 var h = this.size.height-hh;
30779 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
30780 bw.setHeight(h-cb.getPadding("tb"));
30782 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
30783 bd.setWidth(bw.getWidth(true));
30785 this.tabs.syncHeight();
30787 this.tabs.el.repaint();
30793 * Restores the previous state of the dialog if Roo.state is configured.
30794 * @return {Roo.BasicDialog} this
30796 restoreState : function(){
30797 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
30798 if(box && box.width){
30799 this.xy = [box.x, box.y];
30800 this.resizeTo(box.width, box.height);
30806 beforeShow : function(){
30808 if(this.fixedcenter){
30809 this.xy = this.el.getCenterXY(true);
30812 Roo.get(document.body).addClass("x-body-masked");
30813 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
30816 this.constrainXY();
30820 animShow : function(){
30821 var b = Roo.get(this.animateTarget).getBox();
30822 this.proxy.setSize(b.width, b.height);
30823 this.proxy.setLocation(b.x, b.y);
30825 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
30826 true, .35, this.showEl.createDelegate(this));
30830 * Shows the dialog.
30831 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
30832 * @return {Roo.BasicDialog} this
30834 show : function(animateTarget){
30835 if (this.fireEvent("beforeshow", this) === false){
30838 if(this.syncHeightBeforeShow){
30839 this.syncBodyHeight();
30840 }else if(this.firstShow){
30841 this.firstShow = false;
30842 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
30844 this.animateTarget = animateTarget || this.animateTarget;
30845 if(!this.el.isVisible()){
30847 if(this.animateTarget && Roo.get(this.animateTarget)){
30857 showEl : function(){
30859 this.el.setXY(this.xy);
30861 this.adjustAssets(true);
30864 // IE peekaboo bug - fix found by Dave Fenwick
30868 this.fireEvent("show", this);
30872 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
30873 * dialog itself will receive focus.
30875 focus : function(){
30876 if(this.defaultButton){
30877 this.defaultButton.focus();
30879 this.focusEl.focus();
30884 constrainXY : function(){
30885 if(this.constraintoviewport !== false){
30886 if(!this.viewSize){
30887 if(this.container){
30888 var s = this.container.getSize();
30889 this.viewSize = [s.width, s.height];
30891 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
30894 var s = Roo.get(this.container||document).getScroll();
30896 var x = this.xy[0], y = this.xy[1];
30897 var w = this.size.width, h = this.size.height;
30898 var vw = this.viewSize[0], vh = this.viewSize[1];
30899 // only move it if it needs it
30901 // first validate right/bottom
30902 if(x + w > vw+s.left){
30906 if(y + h > vh+s.top){
30910 // then make sure top/left isn't negative
30922 if(this.isVisible()){
30923 this.el.setLocation(x, y);
30924 this.adjustAssets();
30931 onDrag : function(){
30932 if(!this.proxyDrag){
30933 this.xy = this.el.getXY();
30934 this.adjustAssets();
30939 adjustAssets : function(doShow){
30940 var x = this.xy[0], y = this.xy[1];
30941 var w = this.size.width, h = this.size.height;
30942 if(doShow === true){
30944 this.shadow.show(this.el);
30950 if(this.shadow && this.shadow.isVisible()){
30951 this.shadow.show(this.el);
30953 if(this.shim && this.shim.isVisible()){
30954 this.shim.setBounds(x, y, w, h);
30959 adjustViewport : function(w, h){
30961 w = Roo.lib.Dom.getViewWidth();
30962 h = Roo.lib.Dom.getViewHeight();
30965 this.viewSize = [w, h];
30966 if(this.modal && this.mask.isVisible()){
30967 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
30968 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
30970 if(this.isVisible()){
30971 this.constrainXY();
30976 * Destroys this dialog and all its supporting elements (including any tabs, shim,
30977 * shadow, proxy, mask, etc.) Also removes all event listeners.
30978 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
30980 destroy : function(removeEl){
30981 if(this.isVisible()){
30982 this.animateTarget = null;
30985 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
30987 this.tabs.destroy(removeEl);
31000 for(var i = 0, len = this.buttons.length; i < len; i++){
31001 this.buttons[i].destroy();
31004 this.el.removeAllListeners();
31005 if(removeEl === true){
31006 this.el.update("");
31009 Roo.DialogManager.unregister(this);
31013 startMove : function(){
31014 if(this.proxyDrag){
31017 if(this.constraintoviewport !== false){
31018 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
31023 endMove : function(){
31024 if(!this.proxyDrag){
31025 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
31027 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
31030 this.refreshSize();
31031 this.adjustAssets();
31033 this.fireEvent("move", this, this.xy[0], this.xy[1]);
31037 * Brings this dialog to the front of any other visible dialogs
31038 * @return {Roo.BasicDialog} this
31040 toFront : function(){
31041 Roo.DialogManager.bringToFront(this);
31046 * Sends this dialog to the back (under) of any other visible dialogs
31047 * @return {Roo.BasicDialog} this
31049 toBack : function(){
31050 Roo.DialogManager.sendToBack(this);
31055 * Centers this dialog in the viewport
31056 * @return {Roo.BasicDialog} this
31058 center : function(){
31059 var xy = this.el.getCenterXY(true);
31060 this.moveTo(xy[0], xy[1]);
31065 * Moves the dialog's top-left corner to the specified point
31066 * @param {Number} x
31067 * @param {Number} y
31068 * @return {Roo.BasicDialog} this
31070 moveTo : function(x, y){
31072 if(this.isVisible()){
31073 this.el.setXY(this.xy);
31074 this.adjustAssets();
31080 * Aligns the dialog to the specified element
31081 * @param {String/HTMLElement/Roo.Element} element The element to align to.
31082 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
31083 * @param {Array} offsets (optional) Offset the positioning by [x, y]
31084 * @return {Roo.BasicDialog} this
31086 alignTo : function(element, position, offsets){
31087 this.xy = this.el.getAlignToXY(element, position, offsets);
31088 if(this.isVisible()){
31089 this.el.setXY(this.xy);
31090 this.adjustAssets();
31096 * Anchors an element to another element and realigns it when the window is resized.
31097 * @param {String/HTMLElement/Roo.Element} element The element to align to.
31098 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
31099 * @param {Array} offsets (optional) Offset the positioning by [x, y]
31100 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
31101 * is a number, it is used as the buffer delay (defaults to 50ms).
31102 * @return {Roo.BasicDialog} this
31104 anchorTo : function(el, alignment, offsets, monitorScroll){
31105 var action = function(){
31106 this.alignTo(el, alignment, offsets);
31108 Roo.EventManager.onWindowResize(action, this);
31109 var tm = typeof monitorScroll;
31110 if(tm != 'undefined'){
31111 Roo.EventManager.on(window, 'scroll', action, this,
31112 {buffer: tm == 'number' ? monitorScroll : 50});
31119 * Returns true if the dialog is visible
31120 * @return {Boolean}
31122 isVisible : function(){
31123 return this.el.isVisible();
31127 animHide : function(callback){
31128 var b = Roo.get(this.animateTarget).getBox();
31130 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
31132 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
31133 this.hideEl.createDelegate(this, [callback]));
31137 * Hides the dialog.
31138 * @param {Function} callback (optional) Function to call when the dialog is hidden
31139 * @return {Roo.BasicDialog} this
31141 hide : function(callback){
31142 if (this.fireEvent("beforehide", this) === false){
31146 this.shadow.hide();
31151 // sometimes animateTarget seems to get set.. causing problems...
31152 // this just double checks..
31153 if(this.animateTarget && Roo.get(this.animateTarget)) {
31154 this.animHide(callback);
31157 this.hideEl(callback);
31163 hideEl : function(callback){
31167 Roo.get(document.body).removeClass("x-body-masked");
31169 this.fireEvent("hide", this);
31170 if(typeof callback == "function"){
31176 hideAction : function(){
31177 this.setLeft("-10000px");
31178 this.setTop("-10000px");
31179 this.setStyle("visibility", "hidden");
31183 refreshSize : function(){
31184 this.size = this.el.getSize();
31185 this.xy = this.el.getXY();
31186 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
31190 // z-index is managed by the DialogManager and may be overwritten at any time
31191 setZIndex : function(index){
31193 this.mask.setStyle("z-index", index);
31196 this.shim.setStyle("z-index", ++index);
31199 this.shadow.setZIndex(++index);
31201 this.el.setStyle("z-index", ++index);
31203 this.proxy.setStyle("z-index", ++index);
31206 this.resizer.proxy.setStyle("z-index", ++index);
31209 this.lastZIndex = index;
31213 * Returns the element for this dialog
31214 * @return {Roo.Element} The underlying dialog Element
31216 getEl : function(){
31222 * @class Roo.DialogManager
31223 * Provides global access to BasicDialogs that have been created and
31224 * support for z-indexing (layering) multiple open dialogs.
31226 Roo.DialogManager = function(){
31228 var accessList = [];
31232 var sortDialogs = function(d1, d2){
31233 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
31237 var orderDialogs = function(){
31238 accessList.sort(sortDialogs);
31239 var seed = Roo.DialogManager.zseed;
31240 for(var i = 0, len = accessList.length; i < len; i++){
31241 var dlg = accessList[i];
31243 dlg.setZIndex(seed + (i*10));
31250 * The starting z-index for BasicDialogs (defaults to 9000)
31251 * @type Number The z-index value
31256 register : function(dlg){
31257 list[dlg.id] = dlg;
31258 accessList.push(dlg);
31262 unregister : function(dlg){
31263 delete list[dlg.id];
31266 if(!accessList.indexOf){
31267 for( i = 0, len = accessList.length; i < len; i++){
31268 if(accessList[i] == dlg){
31269 accessList.splice(i, 1);
31274 i = accessList.indexOf(dlg);
31276 accessList.splice(i, 1);
31282 * Gets a registered dialog by id
31283 * @param {String/Object} id The id of the dialog or a dialog
31284 * @return {Roo.BasicDialog} this
31286 get : function(id){
31287 return typeof id == "object" ? id : list[id];
31291 * Brings the specified dialog to the front
31292 * @param {String/Object} dlg The id of the dialog or a dialog
31293 * @return {Roo.BasicDialog} this
31295 bringToFront : function(dlg){
31296 dlg = this.get(dlg);
31299 dlg._lastAccess = new Date().getTime();
31306 * Sends the specified dialog to the back
31307 * @param {String/Object} dlg The id of the dialog or a dialog
31308 * @return {Roo.BasicDialog} this
31310 sendToBack : function(dlg){
31311 dlg = this.get(dlg);
31312 dlg._lastAccess = -(new Date().getTime());
31318 * Hides all dialogs
31320 hideAll : function(){
31321 for(var id in list){
31322 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
31331 * @class Roo.LayoutDialog
31332 * @extends Roo.BasicDialog
31333 * Dialog which provides adjustments for working with a layout in a Dialog.
31334 * Add your necessary layout config options to the dialog's config.<br>
31335 * Example usage (including a nested layout):
31338 dialog = new Roo.LayoutDialog("download-dlg", {
31347 // layout config merges with the dialog config
31349 tabPosition: "top",
31350 alwaysShowTabs: true
31353 dialog.addKeyListener(27, dialog.hide, dialog);
31354 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
31355 dialog.addButton("Build It!", this.getDownload, this);
31357 // we can even add nested layouts
31358 var innerLayout = new Roo.BorderLayout("dl-inner", {
31368 innerLayout.beginUpdate();
31369 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
31370 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
31371 innerLayout.endUpdate(true);
31373 var layout = dialog.getLayout();
31374 layout.beginUpdate();
31375 layout.add("center", new Roo.ContentPanel("standard-panel",
31376 {title: "Download the Source", fitToFrame:true}));
31377 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
31378 {title: "Build your own roo.js"}));
31379 layout.getRegion("center").showPanel(sp);
31380 layout.endUpdate();
31384 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
31385 * @param {Object} config configuration options
31387 Roo.LayoutDialog = function(el, cfg){
31390 if (typeof(cfg) == 'undefined') {
31391 config = Roo.apply({}, el);
31392 // not sure why we use documentElement here.. - it should always be body.
31393 // IE7 borks horribly if we use documentElement.
31394 // webkit also does not like documentElement - it creates a body element...
31395 el = Roo.get( document.body || document.documentElement ).createChild();
31396 //config.autoCreate = true;
31400 config.autoTabs = false;
31401 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
31402 this.body.setStyle({overflow:"hidden", position:"relative"});
31403 this.layout = new Roo.BorderLayout(this.body.dom, config);
31404 this.layout.monitorWindowResize = false;
31405 this.el.addClass("x-dlg-auto-layout");
31406 // fix case when center region overwrites center function
31407 this.center = Roo.BasicDialog.prototype.center;
31408 this.on("show", this.layout.layout, this.layout, true);
31409 if (config.items) {
31410 var xitems = config.items;
31411 delete config.items;
31412 Roo.each(xitems, this.addxtype, this);
31417 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
31419 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
31422 endUpdate : function(){
31423 this.layout.endUpdate();
31427 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
31430 beginUpdate : function(){
31431 this.layout.beginUpdate();
31435 * Get the BorderLayout for this dialog
31436 * @return {Roo.BorderLayout}
31438 getLayout : function(){
31439 return this.layout;
31442 showEl : function(){
31443 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
31445 this.layout.layout();
31450 // Use the syncHeightBeforeShow config option to control this automatically
31451 syncBodyHeight : function(){
31452 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
31453 if(this.layout){this.layout.layout();}
31457 * Add an xtype element (actually adds to the layout.)
31458 * @return {Object} xdata xtype object data.
31461 addxtype : function(c) {
31462 return this.layout.addxtype(c);
31466 * Ext JS Library 1.1.1
31467 * Copyright(c) 2006-2007, Ext JS, LLC.
31469 * Originally Released Under LGPL - original licence link has changed is not relivant.
31472 * <script type="text/javascript">
31476 * @class Roo.MessageBox
31477 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
31481 Roo.Msg.alert('Status', 'Changes saved successfully.');
31483 // Prompt for user data:
31484 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
31486 // process text value...
31490 // Show a dialog using config options:
31492 title:'Save Changes?',
31493 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
31494 buttons: Roo.Msg.YESNOCANCEL,
31501 Roo.MessageBox = function(){
31502 var dlg, opt, mask, waitTimer;
31503 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
31504 var buttons, activeTextEl, bwidth;
31507 var handleButton = function(button){
31509 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
31513 var handleHide = function(){
31514 if(opt && opt.cls){
31515 dlg.el.removeClass(opt.cls);
31518 Roo.TaskMgr.stop(waitTimer);
31524 var updateButtons = function(b){
31527 buttons["ok"].hide();
31528 buttons["cancel"].hide();
31529 buttons["yes"].hide();
31530 buttons["no"].hide();
31531 dlg.footer.dom.style.display = 'none';
31534 dlg.footer.dom.style.display = '';
31535 for(var k in buttons){
31536 if(typeof buttons[k] != "function"){
31539 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
31540 width += buttons[k].el.getWidth()+15;
31550 var handleEsc = function(d, k, e){
31551 if(opt && opt.closable !== false){
31561 * Returns a reference to the underlying {@link Roo.BasicDialog} element
31562 * @return {Roo.BasicDialog} The BasicDialog element
31564 getDialog : function(){
31566 dlg = new Roo.BasicDialog("x-msg-box", {
31571 constraintoviewport:false,
31573 collapsible : false,
31576 width:400, height:100,
31577 buttonAlign:"center",
31578 closeClick : function(){
31579 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
31580 handleButton("no");
31582 handleButton("cancel");
31586 dlg.on("hide", handleHide);
31588 dlg.addKeyListener(27, handleEsc);
31590 var bt = this.buttonText;
31591 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
31592 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
31593 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
31594 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
31595 bodyEl = dlg.body.createChild({
31597 html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" /><textarea class="roo-mb-textarea"></textarea><div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar"> </div></div></div>'
31599 msgEl = bodyEl.dom.firstChild;
31600 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
31601 textboxEl.enableDisplayMode();
31602 textboxEl.addKeyListener([10,13], function(){
31603 if(dlg.isVisible() && opt && opt.buttons){
31604 if(opt.buttons.ok){
31605 handleButton("ok");
31606 }else if(opt.buttons.yes){
31607 handleButton("yes");
31611 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
31612 textareaEl.enableDisplayMode();
31613 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
31614 progressEl.enableDisplayMode();
31615 var pf = progressEl.dom.firstChild;
31617 pp = Roo.get(pf.firstChild);
31618 pp.setHeight(pf.offsetHeight);
31626 * Updates the message box body text
31627 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
31628 * the XHTML-compliant non-breaking space character '&#160;')
31629 * @return {Roo.MessageBox} This message box
31631 updateText : function(text){
31632 if(!dlg.isVisible() && !opt.width){
31633 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
31635 msgEl.innerHTML = text || ' ';
31637 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
31638 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
31640 Math.min(opt.width || cw , this.maxWidth),
31641 Math.max(opt.minWidth || this.minWidth, bwidth)
31644 activeTextEl.setWidth(w);
31646 if(dlg.isVisible()){
31647 dlg.fixedcenter = false;
31649 // to big, make it scroll. = But as usual stupid IE does not support
31652 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
31653 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
31654 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
31656 bodyEl.dom.style.height = '';
31657 bodyEl.dom.style.overflowY = '';
31660 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
31662 bodyEl.dom.style.overflowX = '';
31665 dlg.setContentSize(w, bodyEl.getHeight());
31666 if(dlg.isVisible()){
31667 dlg.fixedcenter = true;
31673 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
31674 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
31675 * @param {Number} value Any number between 0 and 1 (e.g., .5)
31676 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
31677 * @return {Roo.MessageBox} This message box
31679 updateProgress : function(value, text){
31681 this.updateText(text);
31683 if (pp) { // weird bug on my firefox - for some reason this is not defined
31684 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
31690 * Returns true if the message box is currently displayed
31691 * @return {Boolean} True if the message box is visible, else false
31693 isVisible : function(){
31694 return dlg && dlg.isVisible();
31698 * Hides the message box if it is displayed
31701 if(this.isVisible()){
31707 * Displays a new message box, or reinitializes an existing message box, based on the config options
31708 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
31709 * The following config object properties are supported:
31711 Property Type Description
31712 ---------- --------------- ------------------------------------------------------------------------------------
31713 animEl String/Element An id or Element from which the message box should animate as it opens and
31714 closes (defaults to undefined)
31715 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
31716 cancel:'Bar'}), or false to not show any buttons (defaults to false)
31717 closable Boolean False to hide the top-right close button (defaults to true). Note that
31718 progress and wait dialogs will ignore this property and always hide the
31719 close button as they can only be closed programmatically.
31720 cls String A custom CSS class to apply to the message box element
31721 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
31722 displayed (defaults to 75)
31723 fn Function A callback function to execute after closing the dialog. The arguments to the
31724 function will be btn (the name of the button that was clicked, if applicable,
31725 e.g. "ok"), and text (the value of the active text field, if applicable).
31726 Progress and wait dialogs will ignore this option since they do not respond to
31727 user actions and can only be closed programmatically, so any required function
31728 should be called by the same code after it closes the dialog.
31729 icon String A CSS class that provides a background image to be used as an icon for
31730 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
31731 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
31732 minWidth Number The minimum width in pixels of the message box (defaults to 100)
31733 modal Boolean False to allow user interaction with the page while the message box is
31734 displayed (defaults to true)
31735 msg String A string that will replace the existing message box body text (defaults
31736 to the XHTML-compliant non-breaking space character ' ')
31737 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
31738 progress Boolean True to display a progress bar (defaults to false)
31739 progressText String The text to display inside the progress bar if progress = true (defaults to '')
31740 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
31741 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
31742 title String The title text
31743 value String The string value to set into the active textbox element if displayed
31744 wait Boolean True to display a progress bar (defaults to false)
31745 width Number The width of the dialog in pixels
31752 msg: 'Please enter your address:',
31754 buttons: Roo.MessageBox.OKCANCEL,
31757 animEl: 'addAddressBtn'
31760 * @param {Object} config Configuration options
31761 * @return {Roo.MessageBox} This message box
31763 show : function(options)
31766 // this causes nightmares if you show one dialog after another
31767 // especially on callbacks..
31769 if(this.isVisible()){
31772 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
31773 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
31774 Roo.log("New Dialog Message:" + options.msg )
31775 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
31776 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
31779 var d = this.getDialog();
31781 d.setTitle(opt.title || " ");
31782 d.close.setDisplayed(opt.closable !== false);
31783 activeTextEl = textboxEl;
31784 opt.prompt = opt.prompt || (opt.multiline ? true : false);
31789 textareaEl.setHeight(typeof opt.multiline == "number" ?
31790 opt.multiline : this.defaultTextHeight);
31791 activeTextEl = textareaEl;
31800 progressEl.setDisplayed(opt.progress === true);
31801 this.updateProgress(0);
31802 activeTextEl.dom.value = opt.value || "";
31804 dlg.setDefaultButton(activeTextEl);
31806 var bs = opt.buttons;
31809 db = buttons["ok"];
31810 }else if(bs && bs.yes){
31811 db = buttons["yes"];
31813 dlg.setDefaultButton(db);
31815 bwidth = updateButtons(opt.buttons);
31816 this.updateText(opt.msg);
31818 d.el.addClass(opt.cls);
31820 d.proxyDrag = opt.proxyDrag === true;
31821 d.modal = opt.modal !== false;
31822 d.mask = opt.modal !== false ? mask : false;
31823 if(!d.isVisible()){
31824 // force it to the end of the z-index stack so it gets a cursor in FF
31825 document.body.appendChild(dlg.el.dom);
31826 d.animateTarget = null;
31827 d.show(options.animEl);
31833 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
31834 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
31835 * and closing the message box when the process is complete.
31836 * @param {String} title The title bar text
31837 * @param {String} msg The message box body text
31838 * @return {Roo.MessageBox} This message box
31840 progress : function(title, msg){
31847 minWidth: this.minProgressWidth,
31854 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
31855 * If a callback function is passed it will be called after the user clicks the button, and the
31856 * id of the button that was clicked will be passed as the only parameter to the callback
31857 * (could also be the top-right close button).
31858 * @param {String} title The title bar text
31859 * @param {String} msg The message box body text
31860 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31861 * @param {Object} scope (optional) The scope of the callback function
31862 * @return {Roo.MessageBox} This message box
31864 alert : function(title, msg, fn, scope){
31877 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
31878 * interaction while waiting for a long-running process to complete that does not have defined intervals.
31879 * You are responsible for closing the message box when the process is complete.
31880 * @param {String} msg The message box body text
31881 * @param {String} title (optional) The title bar text
31882 * @return {Roo.MessageBox} This message box
31884 wait : function(msg, title){
31895 waitTimer = Roo.TaskMgr.start({
31897 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
31905 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
31906 * If a callback function is passed it will be called after the user clicks either button, and the id of the
31907 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
31908 * @param {String} title The title bar text
31909 * @param {String} msg The message box body text
31910 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31911 * @param {Object} scope (optional) The scope of the callback function
31912 * @return {Roo.MessageBox} This message box
31914 confirm : function(title, msg, fn, scope){
31918 buttons: this.YESNO,
31927 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
31928 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
31929 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
31930 * (could also be the top-right close button) and the text that was entered will be passed as the two
31931 * parameters to the callback.
31932 * @param {String} title The title bar text
31933 * @param {String} msg The message box body text
31934 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31935 * @param {Object} scope (optional) The scope of the callback function
31936 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
31937 * property, or the height in pixels to create the textbox (defaults to false / single-line)
31938 * @return {Roo.MessageBox} This message box
31940 prompt : function(title, msg, fn, scope, multiline){
31944 buttons: this.OKCANCEL,
31949 multiline: multiline,
31956 * Button config that displays a single OK button
31961 * Button config that displays Yes and No buttons
31964 YESNO : {yes:true, no:true},
31966 * Button config that displays OK and Cancel buttons
31969 OKCANCEL : {ok:true, cancel:true},
31971 * Button config that displays Yes, No and Cancel buttons
31974 YESNOCANCEL : {yes:true, no:true, cancel:true},
31977 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
31980 defaultTextHeight : 75,
31982 * The maximum width in pixels of the message box (defaults to 600)
31987 * The minimum width in pixels of the message box (defaults to 100)
31992 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
31993 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
31996 minProgressWidth : 250,
31998 * An object containing the default button text strings that can be overriden for localized language support.
31999 * Supported properties are: ok, cancel, yes and no.
32000 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
32013 * Shorthand for {@link Roo.MessageBox}
32015 Roo.Msg = Roo.MessageBox;/*
32017 * Ext JS Library 1.1.1
32018 * Copyright(c) 2006-2007, Ext JS, LLC.
32020 * Originally Released Under LGPL - original licence link has changed is not relivant.
32023 * <script type="text/javascript">
32026 * @class Roo.QuickTips
32027 * Provides attractive and customizable tooltips for any element.
32030 Roo.QuickTips = function(){
32031 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
32032 var ce, bd, xy, dd;
32033 var visible = false, disabled = true, inited = false;
32034 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
32036 var onOver = function(e){
32040 var t = e.getTarget();
32041 if(!t || t.nodeType !== 1 || t == document || t == document.body){
32044 if(ce && t == ce.el){
32045 clearTimeout(hideProc);
32048 if(t && tagEls[t.id]){
32049 tagEls[t.id].el = t;
32050 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
32053 var ttp, et = Roo.fly(t);
32054 var ns = cfg.namespace;
32055 if(tm.interceptTitles && t.title){
32058 t.removeAttribute("title");
32059 e.preventDefault();
32061 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
32064 showProc = show.defer(tm.showDelay, tm, [{
32067 width: et.getAttributeNS(ns, cfg.width),
32068 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
32069 title: et.getAttributeNS(ns, cfg.title),
32070 cls: et.getAttributeNS(ns, cfg.cls)
32075 var onOut = function(e){
32076 clearTimeout(showProc);
32077 var t = e.getTarget();
32078 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
32079 hideProc = setTimeout(hide, tm.hideDelay);
32083 var onMove = function(e){
32089 if(tm.trackMouse && ce){
32094 var onDown = function(e){
32095 clearTimeout(showProc);
32096 clearTimeout(hideProc);
32098 if(tm.hideOnClick){
32101 tm.enable.defer(100, tm);
32106 var getPad = function(){
32107 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
32110 var show = function(o){
32114 clearTimeout(dismissProc);
32116 if(removeCls){ // in case manually hidden
32117 el.removeClass(removeCls);
32121 el.addClass(ce.cls);
32122 removeCls = ce.cls;
32125 tipTitle.update(ce.title);
32128 tipTitle.update('');
32131 el.dom.style.width = tm.maxWidth+'px';
32132 //tipBody.dom.style.width = '';
32133 tipBodyText.update(o.text);
32134 var p = getPad(), w = ce.width;
32136 var td = tipBodyText.dom;
32137 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
32138 if(aw > tm.maxWidth){
32140 }else if(aw < tm.minWidth){
32146 //tipBody.setWidth(w);
32147 el.setWidth(parseInt(w, 10) + p);
32148 if(ce.autoHide === false){
32149 close.setDisplayed(true);
32154 close.setDisplayed(false);
32160 el.avoidY = xy[1]-18;
32165 el.setStyle("visibility", "visible");
32166 el.fadeIn({callback: afterShow});
32172 var afterShow = function(){
32176 if(tm.autoDismiss && ce.autoHide !== false){
32177 dismissProc = setTimeout(hide, tm.autoDismissDelay);
32182 var hide = function(noanim){
32183 clearTimeout(dismissProc);
32184 clearTimeout(hideProc);
32186 if(el.isVisible()){
32188 if(noanim !== true && tm.animate){
32189 el.fadeOut({callback: afterHide});
32196 var afterHide = function(){
32199 el.removeClass(removeCls);
32206 * @cfg {Number} minWidth
32207 * The minimum width of the quick tip (defaults to 40)
32211 * @cfg {Number} maxWidth
32212 * The maximum width of the quick tip (defaults to 300)
32216 * @cfg {Boolean} interceptTitles
32217 * True to automatically use the element's DOM title value if available (defaults to false)
32219 interceptTitles : false,
32221 * @cfg {Boolean} trackMouse
32222 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
32224 trackMouse : false,
32226 * @cfg {Boolean} hideOnClick
32227 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
32229 hideOnClick : true,
32231 * @cfg {Number} showDelay
32232 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
32236 * @cfg {Number} hideDelay
32237 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
32241 * @cfg {Boolean} autoHide
32242 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
32243 * Used in conjunction with hideDelay.
32248 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
32249 * (defaults to true). Used in conjunction with autoDismissDelay.
32251 autoDismiss : true,
32254 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
32256 autoDismissDelay : 5000,
32258 * @cfg {Boolean} animate
32259 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
32264 * @cfg {String} title
32265 * Title text to display (defaults to ''). This can be any valid HTML markup.
32269 * @cfg {String} text
32270 * Body text to display (defaults to ''). This can be any valid HTML markup.
32274 * @cfg {String} cls
32275 * A CSS class to apply to the base quick tip element (defaults to '').
32279 * @cfg {Number} width
32280 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
32281 * minWidth or maxWidth.
32286 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
32287 * or display QuickTips in a page.
32290 tm = Roo.QuickTips;
32291 cfg = tm.tagConfig;
32293 if(!Roo.isReady){ // allow calling of init() before onReady
32294 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
32297 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
32298 el.fxDefaults = {stopFx: true};
32299 // maximum custom styling
32300 //el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>');
32301 el.update('<div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div>');
32302 tipTitle = el.child('h3');
32303 tipTitle.enableDisplayMode("block");
32304 tipBody = el.child('div.x-tip-bd');
32305 tipBodyText = el.child('div.x-tip-bd-inner');
32306 //bdLeft = el.child('div.x-tip-bd-left');
32307 //bdRight = el.child('div.x-tip-bd-right');
32308 close = el.child('div.x-tip-close');
32309 close.enableDisplayMode("block");
32310 close.on("click", hide);
32311 var d = Roo.get(document);
32312 d.on("mousedown", onDown);
32313 d.on("mouseover", onOver);
32314 d.on("mouseout", onOut);
32315 d.on("mousemove", onMove);
32316 esc = d.addKeyListener(27, hide);
32319 dd = el.initDD("default", null, {
32320 onDrag : function(){
32324 dd.setHandleElId(tipTitle.id);
32333 * Configures a new quick tip instance and assigns it to a target element. The following config options
32336 Property Type Description
32337 ---------- --------------------- ------------------------------------------------------------------------
32338 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
32340 * @param {Object} config The config object
32342 register : function(config){
32343 var cs = config instanceof Array ? config : arguments;
32344 for(var i = 0, len = cs.length; i < len; i++) {
32346 var target = c.target;
32348 if(target instanceof Array){
32349 for(var j = 0, jlen = target.length; j < jlen; j++){
32350 tagEls[target[j]] = c;
32353 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
32360 * Removes this quick tip from its element and destroys it.
32361 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
32363 unregister : function(el){
32364 delete tagEls[Roo.id(el)];
32368 * Enable this quick tip.
32370 enable : function(){
32371 if(inited && disabled){
32373 if(locks.length < 1){
32380 * Disable this quick tip.
32382 disable : function(){
32384 clearTimeout(showProc);
32385 clearTimeout(hideProc);
32386 clearTimeout(dismissProc);
32394 * Returns true if the quick tip is enabled, else false.
32396 isEnabled : function(){
32403 attribute : "qtip",
32413 // backwards compat
32414 Roo.QuickTips.tips = Roo.QuickTips.register;/*
32416 * Ext JS Library 1.1.1
32417 * Copyright(c) 2006-2007, Ext JS, LLC.
32419 * Originally Released Under LGPL - original licence link has changed is not relivant.
32422 * <script type="text/javascript">
32427 * @class Roo.tree.TreePanel
32428 * @extends Roo.data.Tree
32430 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
32431 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
32432 * @cfg {Boolean} enableDD true to enable drag and drop
32433 * @cfg {Boolean} enableDrag true to enable just drag
32434 * @cfg {Boolean} enableDrop true to enable just drop
32435 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
32436 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
32437 * @cfg {String} ddGroup The DD group this TreePanel belongs to
32438 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
32439 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
32440 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
32441 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
32442 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
32443 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
32444 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
32445 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
32446 * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
32447 * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
32448 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
32449 * @cfg {Function} renderer DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes. to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
32450 * @cfg {Function} rendererTip DEPRECATED - use TreeLoader:create event / Sets the rendering (formatting) function for the nodes hovertip to return HTML markup for the tree view. The render function is called with the following parameters:<ul><li>The {Object} The data for the node.</li></ul>
32453 * @param {String/HTMLElement/Element} el The container element
32454 * @param {Object} config
32456 Roo.tree.TreePanel = function(el, config){
32458 var loader = false;
32460 root = config.root;
32461 delete config.root;
32463 if (config.loader) {
32464 loader = config.loader;
32465 delete config.loader;
32468 Roo.apply(this, config);
32469 Roo.tree.TreePanel.superclass.constructor.call(this);
32470 this.el = Roo.get(el);
32471 this.el.addClass('x-tree');
32472 //console.log(root);
32474 this.setRootNode( Roo.factory(root, Roo.tree));
32477 this.loader = Roo.factory(loader, Roo.tree);
32480 * Read-only. The id of the container element becomes this TreePanel's id.
32482 this.id = this.el.id;
32485 * @event beforeload
32486 * Fires before a node is loaded, return false to cancel
32487 * @param {Node} node The node being loaded
32489 "beforeload" : true,
32492 * Fires when a node is loaded
32493 * @param {Node} node The node that was loaded
32497 * @event textchange
32498 * Fires when the text for a node is changed
32499 * @param {Node} node The node
32500 * @param {String} text The new text
32501 * @param {String} oldText The old text
32503 "textchange" : true,
32505 * @event beforeexpand
32506 * Fires before a node is expanded, return false to cancel.
32507 * @param {Node} node The node
32508 * @param {Boolean} deep
32509 * @param {Boolean} anim
32511 "beforeexpand" : true,
32513 * @event beforecollapse
32514 * Fires before a node is collapsed, return false to cancel.
32515 * @param {Node} node The node
32516 * @param {Boolean} deep
32517 * @param {Boolean} anim
32519 "beforecollapse" : true,
32522 * Fires when a node is expanded
32523 * @param {Node} node The node
32527 * @event disabledchange
32528 * Fires when the disabled status of a node changes
32529 * @param {Node} node The node
32530 * @param {Boolean} disabled
32532 "disabledchange" : true,
32535 * Fires when a node is collapsed
32536 * @param {Node} node The node
32540 * @event beforeclick
32541 * Fires before click processing on a node. Return false to cancel the default action.
32542 * @param {Node} node The node
32543 * @param {Roo.EventObject} e The event object
32545 "beforeclick":true,
32547 * @event checkchange
32548 * Fires when a node with a checkbox's checked property changes
32549 * @param {Node} this This node
32550 * @param {Boolean} checked
32552 "checkchange":true,
32555 * Fires when a node is clicked
32556 * @param {Node} node The node
32557 * @param {Roo.EventObject} e The event object
32562 * Fires when a node is double clicked
32563 * @param {Node} node The node
32564 * @param {Roo.EventObject} e The event object
32568 * @event contextmenu
32569 * Fires when a node is right clicked
32570 * @param {Node} node The node
32571 * @param {Roo.EventObject} e The event object
32573 "contextmenu":true,
32575 * @event beforechildrenrendered
32576 * Fires right before the child nodes for a node are rendered
32577 * @param {Node} node The node
32579 "beforechildrenrendered":true,
32582 * Fires when a node starts being dragged
32583 * @param {Roo.tree.TreePanel} this
32584 * @param {Roo.tree.TreeNode} node
32585 * @param {event} e The raw browser event
32587 "startdrag" : true,
32590 * Fires when a drag operation is complete
32591 * @param {Roo.tree.TreePanel} this
32592 * @param {Roo.tree.TreeNode} node
32593 * @param {event} e The raw browser event
32598 * Fires when a dragged node is dropped on a valid DD target
32599 * @param {Roo.tree.TreePanel} this
32600 * @param {Roo.tree.TreeNode} node
32601 * @param {DD} dd The dd it was dropped on
32602 * @param {event} e The raw browser event
32606 * @event beforenodedrop
32607 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
32608 * passed to handlers has the following properties:<br />
32609 * <ul style="padding:5px;padding-left:16px;">
32610 * <li>tree - The TreePanel</li>
32611 * <li>target - The node being targeted for the drop</li>
32612 * <li>data - The drag data from the drag source</li>
32613 * <li>point - The point of the drop - append, above or below</li>
32614 * <li>source - The drag source</li>
32615 * <li>rawEvent - Raw mouse event</li>
32616 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
32617 * to be inserted by setting them on this object.</li>
32618 * <li>cancel - Set this to true to cancel the drop.</li>
32620 * @param {Object} dropEvent
32622 "beforenodedrop" : true,
32625 * Fires after a DD object is dropped on a node in this tree. The dropEvent
32626 * passed to handlers has the following properties:<br />
32627 * <ul style="padding:5px;padding-left:16px;">
32628 * <li>tree - The TreePanel</li>
32629 * <li>target - The node being targeted for the drop</li>
32630 * <li>data - The drag data from the drag source</li>
32631 * <li>point - The point of the drop - append, above or below</li>
32632 * <li>source - The drag source</li>
32633 * <li>rawEvent - Raw mouse event</li>
32634 * <li>dropNode - Dropped node(s).</li>
32636 * @param {Object} dropEvent
32640 * @event nodedragover
32641 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
32642 * passed to handlers has the following properties:<br />
32643 * <ul style="padding:5px;padding-left:16px;">
32644 * <li>tree - The TreePanel</li>
32645 * <li>target - The node being targeted for the drop</li>
32646 * <li>data - The drag data from the drag source</li>
32647 * <li>point - The point of the drop - append, above or below</li>
32648 * <li>source - The drag source</li>
32649 * <li>rawEvent - Raw mouse event</li>
32650 * <li>dropNode - Drop node(s) provided by the source.</li>
32651 * <li>cancel - Set this to true to signal drop not allowed.</li>
32653 * @param {Object} dragOverEvent
32655 "nodedragover" : true
32658 if(this.singleExpand){
32659 this.on("beforeexpand", this.restrictExpand, this);
32662 this.editor.tree = this;
32663 this.editor = Roo.factory(this.editor, Roo.tree);
32666 if (this.selModel) {
32667 this.selModel = Roo.factory(this.selModel, Roo.tree);
32671 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
32672 rootVisible : true,
32673 animate: Roo.enableFx,
32676 hlDrop : Roo.enableFx,
32680 rendererTip: false,
32682 restrictExpand : function(node){
32683 var p = node.parentNode;
32685 if(p.expandedChild && p.expandedChild.parentNode == p){
32686 p.expandedChild.collapse();
32688 p.expandedChild = node;
32692 // private override
32693 setRootNode : function(node){
32694 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
32695 if(!this.rootVisible){
32696 node.ui = new Roo.tree.RootTreeNodeUI(node);
32702 * Returns the container element for this TreePanel
32704 getEl : function(){
32709 * Returns the default TreeLoader for this TreePanel
32711 getLoader : function(){
32712 return this.loader;
32718 expandAll : function(){
32719 this.root.expand(true);
32723 * Collapse all nodes
32725 collapseAll : function(){
32726 this.root.collapse(true);
32730 * Returns the selection model used by this TreePanel
32732 getSelectionModel : function(){
32733 if(!this.selModel){
32734 this.selModel = new Roo.tree.DefaultSelectionModel();
32736 return this.selModel;
32740 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
32741 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
32742 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
32745 getChecked : function(a, startNode){
32746 startNode = startNode || this.root;
32748 var f = function(){
32749 if(this.attributes.checked){
32750 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
32753 startNode.cascade(f);
32758 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
32759 * @param {String} path
32760 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
32761 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
32762 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
32764 expandPath : function(path, attr, callback){
32765 attr = attr || "id";
32766 var keys = path.split(this.pathSeparator);
32767 var curNode = this.root;
32768 if(curNode.attributes[attr] != keys[1]){ // invalid root
32770 callback(false, null);
32775 var f = function(){
32776 if(++index == keys.length){
32778 callback(true, curNode);
32782 var c = curNode.findChild(attr, keys[index]);
32785 callback(false, curNode);
32790 c.expand(false, false, f);
32792 curNode.expand(false, false, f);
32796 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
32797 * @param {String} path
32798 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
32799 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
32800 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
32802 selectPath : function(path, attr, callback){
32803 attr = attr || "id";
32804 var keys = path.split(this.pathSeparator);
32805 var v = keys.pop();
32806 if(keys.length > 0){
32807 var f = function(success, node){
32808 if(success && node){
32809 var n = node.findChild(attr, v);
32815 }else if(callback){
32816 callback(false, n);
32820 callback(false, n);
32824 this.expandPath(keys.join(this.pathSeparator), attr, f);
32826 this.root.select();
32828 callback(true, this.root);
32833 getTreeEl : function(){
32838 * Trigger rendering of this TreePanel
32840 render : function(){
32841 if (this.innerCt) {
32842 return this; // stop it rendering more than once!!
32845 this.innerCt = this.el.createChild({tag:"ul",
32846 cls:"x-tree-root-ct " +
32847 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
32849 if(this.containerScroll){
32850 Roo.dd.ScrollManager.register(this.el);
32852 if((this.enableDD || this.enableDrop) && !this.dropZone){
32854 * The dropZone used by this tree if drop is enabled
32855 * @type Roo.tree.TreeDropZone
32857 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
32858 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
32861 if((this.enableDD || this.enableDrag) && !this.dragZone){
32863 * The dragZone used by this tree if drag is enabled
32864 * @type Roo.tree.TreeDragZone
32866 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
32867 ddGroup: this.ddGroup || "TreeDD",
32868 scroll: this.ddScroll
32871 this.getSelectionModel().init(this);
32873 Roo.log("ROOT not set in tree");
32876 this.root.render();
32877 if(!this.rootVisible){
32878 this.root.renderChildren();
32884 * Ext JS Library 1.1.1
32885 * Copyright(c) 2006-2007, Ext JS, LLC.
32887 * Originally Released Under LGPL - original licence link has changed is not relivant.
32890 * <script type="text/javascript">
32895 * @class Roo.tree.DefaultSelectionModel
32896 * @extends Roo.util.Observable
32897 * The default single selection for a TreePanel.
32898 * @param {Object} cfg Configuration
32900 Roo.tree.DefaultSelectionModel = function(cfg){
32901 this.selNode = null;
32907 * @event selectionchange
32908 * Fires when the selected node changes
32909 * @param {DefaultSelectionModel} this
32910 * @param {TreeNode} node the new selection
32912 "selectionchange" : true,
32915 * @event beforeselect
32916 * Fires before the selected node changes, return false to cancel the change
32917 * @param {DefaultSelectionModel} this
32918 * @param {TreeNode} node the new selection
32919 * @param {TreeNode} node the old selection
32921 "beforeselect" : true
32924 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
32927 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
32928 init : function(tree){
32930 tree.getTreeEl().on("keydown", this.onKeyDown, this);
32931 tree.on("click", this.onNodeClick, this);
32934 onNodeClick : function(node, e){
32935 if (e.ctrlKey && this.selNode == node) {
32936 this.unselect(node);
32944 * @param {TreeNode} node The node to select
32945 * @return {TreeNode} The selected node
32947 select : function(node){
32948 var last = this.selNode;
32949 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
32951 last.ui.onSelectedChange(false);
32953 this.selNode = node;
32954 node.ui.onSelectedChange(true);
32955 this.fireEvent("selectionchange", this, node, last);
32962 * @param {TreeNode} node The node to unselect
32964 unselect : function(node){
32965 if(this.selNode == node){
32966 this.clearSelections();
32971 * Clear all selections
32973 clearSelections : function(){
32974 var n = this.selNode;
32976 n.ui.onSelectedChange(false);
32977 this.selNode = null;
32978 this.fireEvent("selectionchange", this, null);
32984 * Get the selected node
32985 * @return {TreeNode} The selected node
32987 getSelectedNode : function(){
32988 return this.selNode;
32992 * Returns true if the node is selected
32993 * @param {TreeNode} node The node to check
32994 * @return {Boolean}
32996 isSelected : function(node){
32997 return this.selNode == node;
33001 * Selects the node above the selected node in the tree, intelligently walking the nodes
33002 * @return TreeNode The new selection
33004 selectPrevious : function(){
33005 var s = this.selNode || this.lastSelNode;
33009 var ps = s.previousSibling;
33011 if(!ps.isExpanded() || ps.childNodes.length < 1){
33012 return this.select(ps);
33014 var lc = ps.lastChild;
33015 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
33018 return this.select(lc);
33020 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
33021 return this.select(s.parentNode);
33027 * Selects the node above the selected node in the tree, intelligently walking the nodes
33028 * @return TreeNode The new selection
33030 selectNext : function(){
33031 var s = this.selNode || this.lastSelNode;
33035 if(s.firstChild && s.isExpanded()){
33036 return this.select(s.firstChild);
33037 }else if(s.nextSibling){
33038 return this.select(s.nextSibling);
33039 }else if(s.parentNode){
33041 s.parentNode.bubble(function(){
33042 if(this.nextSibling){
33043 newS = this.getOwnerTree().selModel.select(this.nextSibling);
33052 onKeyDown : function(e){
33053 var s = this.selNode || this.lastSelNode;
33054 // undesirable, but required
33059 var k = e.getKey();
33067 this.selectPrevious();
33070 e.preventDefault();
33071 if(s.hasChildNodes()){
33072 if(!s.isExpanded()){
33074 }else if(s.firstChild){
33075 this.select(s.firstChild, e);
33080 e.preventDefault();
33081 if(s.hasChildNodes() && s.isExpanded()){
33083 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
33084 this.select(s.parentNode, e);
33092 * @class Roo.tree.MultiSelectionModel
33093 * @extends Roo.util.Observable
33094 * Multi selection for a TreePanel.
33095 * @param {Object} cfg Configuration
33097 Roo.tree.MultiSelectionModel = function(){
33098 this.selNodes = [];
33102 * @event selectionchange
33103 * Fires when the selected nodes change
33104 * @param {MultiSelectionModel} this
33105 * @param {Array} nodes Array of the selected nodes
33107 "selectionchange" : true
33109 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
33113 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
33114 init : function(tree){
33116 tree.getTreeEl().on("keydown", this.onKeyDown, this);
33117 tree.on("click", this.onNodeClick, this);
33120 onNodeClick : function(node, e){
33121 this.select(node, e, e.ctrlKey);
33126 * @param {TreeNode} node The node to select
33127 * @param {EventObject} e (optional) An event associated with the selection
33128 * @param {Boolean} keepExisting True to retain existing selections
33129 * @return {TreeNode} The selected node
33131 select : function(node, e, keepExisting){
33132 if(keepExisting !== true){
33133 this.clearSelections(true);
33135 if(this.isSelected(node)){
33136 this.lastSelNode = node;
33139 this.selNodes.push(node);
33140 this.selMap[node.id] = node;
33141 this.lastSelNode = node;
33142 node.ui.onSelectedChange(true);
33143 this.fireEvent("selectionchange", this, this.selNodes);
33149 * @param {TreeNode} node The node to unselect
33151 unselect : function(node){
33152 if(this.selMap[node.id]){
33153 node.ui.onSelectedChange(false);
33154 var sn = this.selNodes;
33157 index = sn.indexOf(node);
33159 for(var i = 0, len = sn.length; i < len; i++){
33167 this.selNodes.splice(index, 1);
33169 delete this.selMap[node.id];
33170 this.fireEvent("selectionchange", this, this.selNodes);
33175 * Clear all selections
33177 clearSelections : function(suppressEvent){
33178 var sn = this.selNodes;
33180 for(var i = 0, len = sn.length; i < len; i++){
33181 sn[i].ui.onSelectedChange(false);
33183 this.selNodes = [];
33185 if(suppressEvent !== true){
33186 this.fireEvent("selectionchange", this, this.selNodes);
33192 * Returns true if the node is selected
33193 * @param {TreeNode} node The node to check
33194 * @return {Boolean}
33196 isSelected : function(node){
33197 return this.selMap[node.id] ? true : false;
33201 * Returns an array of the selected nodes
33204 getSelectedNodes : function(){
33205 return this.selNodes;
33208 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
33210 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
33212 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
33215 * Ext JS Library 1.1.1
33216 * Copyright(c) 2006-2007, Ext JS, LLC.
33218 * Originally Released Under LGPL - original licence link has changed is not relivant.
33221 * <script type="text/javascript">
33225 * @class Roo.tree.TreeNode
33226 * @extends Roo.data.Node
33227 * @cfg {String} text The text for this node
33228 * @cfg {Boolean} expanded true to start the node expanded
33229 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
33230 * @cfg {Boolean} allowDrop false if this node cannot be drop on
33231 * @cfg {Boolean} disabled true to start the node disabled
33232 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
33233 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
33234 * @cfg {String} cls A css class to be added to the node
33235 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
33236 * @cfg {String} href URL of the link used for the node (defaults to #)
33237 * @cfg {String} hrefTarget target frame for the link
33238 * @cfg {String} qtip An Ext QuickTip for the node
33239 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
33240 * @cfg {Boolean} singleClickExpand True for single click expand on this node
33241 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
33242 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
33243 * (defaults to undefined with no checkbox rendered)
33245 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
33247 Roo.tree.TreeNode = function(attributes){
33248 attributes = attributes || {};
33249 if(typeof attributes == "string"){
33250 attributes = {text: attributes};
33252 this.childrenRendered = false;
33253 this.rendered = false;
33254 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
33255 this.expanded = attributes.expanded === true;
33256 this.isTarget = attributes.isTarget !== false;
33257 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
33258 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
33261 * Read-only. The text for this node. To change it use setText().
33264 this.text = attributes.text;
33266 * True if this node is disabled.
33269 this.disabled = attributes.disabled === true;
33273 * @event textchange
33274 * Fires when the text for this node is changed
33275 * @param {Node} this This node
33276 * @param {String} text The new text
33277 * @param {String} oldText The old text
33279 "textchange" : true,
33281 * @event beforeexpand
33282 * Fires before this node is expanded, return false to cancel.
33283 * @param {Node} this This node
33284 * @param {Boolean} deep
33285 * @param {Boolean} anim
33287 "beforeexpand" : true,
33289 * @event beforecollapse
33290 * Fires before this node is collapsed, return false to cancel.
33291 * @param {Node} this This node
33292 * @param {Boolean} deep
33293 * @param {Boolean} anim
33295 "beforecollapse" : true,
33298 * Fires when this node is expanded
33299 * @param {Node} this This node
33303 * @event disabledchange
33304 * Fires when the disabled status of this node changes
33305 * @param {Node} this This node
33306 * @param {Boolean} disabled
33308 "disabledchange" : true,
33311 * Fires when this node is collapsed
33312 * @param {Node} this This node
33316 * @event beforeclick
33317 * Fires before click processing. Return false to cancel the default action.
33318 * @param {Node} this This node
33319 * @param {Roo.EventObject} e The event object
33321 "beforeclick":true,
33323 * @event checkchange
33324 * Fires when a node with a checkbox's checked property changes
33325 * @param {Node} this This node
33326 * @param {Boolean} checked
33328 "checkchange":true,
33331 * Fires when this node is clicked
33332 * @param {Node} this This node
33333 * @param {Roo.EventObject} e The event object
33338 * Fires when this node is double clicked
33339 * @param {Node} this This node
33340 * @param {Roo.EventObject} e The event object
33344 * @event contextmenu
33345 * Fires when this node is right clicked
33346 * @param {Node} this This node
33347 * @param {Roo.EventObject} e The event object
33349 "contextmenu":true,
33351 * @event beforechildrenrendered
33352 * Fires right before the child nodes for this node are rendered
33353 * @param {Node} this This node
33355 "beforechildrenrendered":true
33358 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
33361 * Read-only. The UI for this node
33364 this.ui = new uiClass(this);
33366 // finally support items[]
33367 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
33372 Roo.each(this.attributes.items, function(c) {
33373 this.appendChild(Roo.factory(c,Roo.Tree));
33375 delete this.attributes.items;
33380 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
33381 preventHScroll: true,
33383 * Returns true if this node is expanded
33384 * @return {Boolean}
33386 isExpanded : function(){
33387 return this.expanded;
33391 * Returns the UI object for this node
33392 * @return {TreeNodeUI}
33394 getUI : function(){
33398 // private override
33399 setFirstChild : function(node){
33400 var of = this.firstChild;
33401 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
33402 if(this.childrenRendered && of && node != of){
33403 of.renderIndent(true, true);
33406 this.renderIndent(true, true);
33410 // private override
33411 setLastChild : function(node){
33412 var ol = this.lastChild;
33413 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
33414 if(this.childrenRendered && ol && node != ol){
33415 ol.renderIndent(true, true);
33418 this.renderIndent(true, true);
33422 // these methods are overridden to provide lazy rendering support
33423 // private override
33424 appendChild : function()
33426 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
33427 if(node && this.childrenRendered){
33430 this.ui.updateExpandIcon();
33434 // private override
33435 removeChild : function(node){
33436 this.ownerTree.getSelectionModel().unselect(node);
33437 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
33438 // if it's been rendered remove dom node
33439 if(this.childrenRendered){
33442 if(this.childNodes.length < 1){
33443 this.collapse(false, false);
33445 this.ui.updateExpandIcon();
33447 if(!this.firstChild) {
33448 this.childrenRendered = false;
33453 // private override
33454 insertBefore : function(node, refNode){
33455 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
33456 if(newNode && refNode && this.childrenRendered){
33459 this.ui.updateExpandIcon();
33464 * Sets the text for this node
33465 * @param {String} text
33467 setText : function(text){
33468 var oldText = this.text;
33470 this.attributes.text = text;
33471 if(this.rendered){ // event without subscribing
33472 this.ui.onTextChange(this, text, oldText);
33474 this.fireEvent("textchange", this, text, oldText);
33478 * Triggers selection of this node
33480 select : function(){
33481 this.getOwnerTree().getSelectionModel().select(this);
33485 * Triggers deselection of this node
33487 unselect : function(){
33488 this.getOwnerTree().getSelectionModel().unselect(this);
33492 * Returns true if this node is selected
33493 * @return {Boolean}
33495 isSelected : function(){
33496 return this.getOwnerTree().getSelectionModel().isSelected(this);
33500 * Expand this node.
33501 * @param {Boolean} deep (optional) True to expand all children as well
33502 * @param {Boolean} anim (optional) false to cancel the default animation
33503 * @param {Function} callback (optional) A callback to be called when
33504 * expanding this node completes (does not wait for deep expand to complete).
33505 * Called with 1 parameter, this node.
33507 expand : function(deep, anim, callback){
33508 if(!this.expanded){
33509 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
33512 if(!this.childrenRendered){
33513 this.renderChildren();
33515 this.expanded = true;
33516 if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
33517 this.ui.animExpand(function(){
33518 this.fireEvent("expand", this);
33519 if(typeof callback == "function"){
33523 this.expandChildNodes(true);
33525 }.createDelegate(this));
33529 this.fireEvent("expand", this);
33530 if(typeof callback == "function"){
33535 if(typeof callback == "function"){
33540 this.expandChildNodes(true);
33544 isHiddenRoot : function(){
33545 return this.isRoot && !this.getOwnerTree().rootVisible;
33549 * Collapse this node.
33550 * @param {Boolean} deep (optional) True to collapse all children as well
33551 * @param {Boolean} anim (optional) false to cancel the default animation
33553 collapse : function(deep, anim){
33554 if(this.expanded && !this.isHiddenRoot()){
33555 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
33558 this.expanded = false;
33559 if((this.getOwnerTree().animate && anim !== false) || anim){
33560 this.ui.animCollapse(function(){
33561 this.fireEvent("collapse", this);
33563 this.collapseChildNodes(true);
33565 }.createDelegate(this));
33568 this.ui.collapse();
33569 this.fireEvent("collapse", this);
33573 var cs = this.childNodes;
33574 for(var i = 0, len = cs.length; i < len; i++) {
33575 cs[i].collapse(true, false);
33581 delayedExpand : function(delay){
33582 if(!this.expandProcId){
33583 this.expandProcId = this.expand.defer(delay, this);
33588 cancelExpand : function(){
33589 if(this.expandProcId){
33590 clearTimeout(this.expandProcId);
33592 this.expandProcId = false;
33596 * Toggles expanded/collapsed state of the node
33598 toggle : function(){
33607 * Ensures all parent nodes are expanded
33609 ensureVisible : function(callback){
33610 var tree = this.getOwnerTree();
33611 tree.expandPath(this.parentNode.getPath(), false, function(){
33612 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
33613 Roo.callback(callback);
33614 }.createDelegate(this));
33618 * Expand all child nodes
33619 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
33621 expandChildNodes : function(deep){
33622 var cs = this.childNodes;
33623 for(var i = 0, len = cs.length; i < len; i++) {
33624 cs[i].expand(deep);
33629 * Collapse all child nodes
33630 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
33632 collapseChildNodes : function(deep){
33633 var cs = this.childNodes;
33634 for(var i = 0, len = cs.length; i < len; i++) {
33635 cs[i].collapse(deep);
33640 * Disables this node
33642 disable : function(){
33643 this.disabled = true;
33645 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
33646 this.ui.onDisableChange(this, true);
33648 this.fireEvent("disabledchange", this, true);
33652 * Enables this node
33654 enable : function(){
33655 this.disabled = false;
33656 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
33657 this.ui.onDisableChange(this, false);
33659 this.fireEvent("disabledchange", this, false);
33663 renderChildren : function(suppressEvent){
33664 if(suppressEvent !== false){
33665 this.fireEvent("beforechildrenrendered", this);
33667 var cs = this.childNodes;
33668 for(var i = 0, len = cs.length; i < len; i++){
33669 cs[i].render(true);
33671 this.childrenRendered = true;
33675 sort : function(fn, scope){
33676 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
33677 if(this.childrenRendered){
33678 var cs = this.childNodes;
33679 for(var i = 0, len = cs.length; i < len; i++){
33680 cs[i].render(true);
33686 render : function(bulkRender){
33687 this.ui.render(bulkRender);
33688 if(!this.rendered){
33689 this.rendered = true;
33691 this.expanded = false;
33692 this.expand(false, false);
33698 renderIndent : function(deep, refresh){
33700 this.ui.childIndent = null;
33702 this.ui.renderIndent();
33703 if(deep === true && this.childrenRendered){
33704 var cs = this.childNodes;
33705 for(var i = 0, len = cs.length; i < len; i++){
33706 cs[i].renderIndent(true, refresh);
33712 * Ext JS Library 1.1.1
33713 * Copyright(c) 2006-2007, Ext JS, LLC.
33715 * Originally Released Under LGPL - original licence link has changed is not relivant.
33718 * <script type="text/javascript">
33722 * @class Roo.tree.AsyncTreeNode
33723 * @extends Roo.tree.TreeNode
33724 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
33726 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
33728 Roo.tree.AsyncTreeNode = function(config){
33729 this.loaded = false;
33730 this.loading = false;
33731 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
33733 * @event beforeload
33734 * Fires before this node is loaded, return false to cancel
33735 * @param {Node} this This node
33737 this.addEvents({'beforeload':true, 'load': true});
33740 * Fires when this node is loaded
33741 * @param {Node} this This node
33744 * The loader used by this node (defaults to using the tree's defined loader)
33749 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
33750 expand : function(deep, anim, callback){
33751 if(this.loading){ // if an async load is already running, waiting til it's done
33753 var f = function(){
33754 if(!this.loading){ // done loading
33755 clearInterval(timer);
33756 this.expand(deep, anim, callback);
33758 }.createDelegate(this);
33759 timer = setInterval(f, 200);
33763 if(this.fireEvent("beforeload", this) === false){
33766 this.loading = true;
33767 this.ui.beforeLoad(this);
33768 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
33770 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
33774 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
33778 * Returns true if this node is currently loading
33779 * @return {Boolean}
33781 isLoading : function(){
33782 return this.loading;
33785 loadComplete : function(deep, anim, callback){
33786 this.loading = false;
33787 this.loaded = true;
33788 this.ui.afterLoad(this);
33789 this.fireEvent("load", this);
33790 this.expand(deep, anim, callback);
33794 * Returns true if this node has been loaded
33795 * @return {Boolean}
33797 isLoaded : function(){
33798 return this.loaded;
33801 hasChildNodes : function(){
33802 if(!this.isLeaf() && !this.loaded){
33805 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
33810 * Trigger a reload for this node
33811 * @param {Function} callback
33813 reload : function(callback){
33814 this.collapse(false, false);
33815 while(this.firstChild){
33816 this.removeChild(this.firstChild);
33818 this.childrenRendered = false;
33819 this.loaded = false;
33820 if(this.isHiddenRoot()){
33821 this.expanded = false;
33823 this.expand(false, false, callback);
33827 * Ext JS Library 1.1.1
33828 * Copyright(c) 2006-2007, Ext JS, LLC.
33830 * Originally Released Under LGPL - original licence link has changed is not relivant.
33833 * <script type="text/javascript">
33837 * @class Roo.tree.TreeNodeUI
33839 * @param {Object} node The node to render
33840 * The TreeNode UI implementation is separate from the
33841 * tree implementation. Unless you are customizing the tree UI,
33842 * you should never have to use this directly.
33844 Roo.tree.TreeNodeUI = function(node){
33846 this.rendered = false;
33847 this.animating = false;
33848 this.emptyIcon = Roo.BLANK_IMAGE_URL;
33851 Roo.tree.TreeNodeUI.prototype = {
33852 removeChild : function(node){
33854 this.ctNode.removeChild(node.ui.getEl());
33858 beforeLoad : function(){
33859 this.addClass("x-tree-node-loading");
33862 afterLoad : function(){
33863 this.removeClass("x-tree-node-loading");
33866 onTextChange : function(node, text, oldText){
33868 this.textNode.innerHTML = text;
33872 onDisableChange : function(node, state){
33873 this.disabled = state;
33875 this.addClass("x-tree-node-disabled");
33877 this.removeClass("x-tree-node-disabled");
33881 onSelectedChange : function(state){
33884 this.addClass("x-tree-selected");
33887 this.removeClass("x-tree-selected");
33891 onMove : function(tree, node, oldParent, newParent, index, refNode){
33892 this.childIndent = null;
33894 var targetNode = newParent.ui.getContainer();
33895 if(!targetNode){//target not rendered
33896 this.holder = document.createElement("div");
33897 this.holder.appendChild(this.wrap);
33900 var insertBefore = refNode ? refNode.ui.getEl() : null;
33902 targetNode.insertBefore(this.wrap, insertBefore);
33904 targetNode.appendChild(this.wrap);
33906 this.node.renderIndent(true);
33910 addClass : function(cls){
33912 Roo.fly(this.elNode).addClass(cls);
33916 removeClass : function(cls){
33918 Roo.fly(this.elNode).removeClass(cls);
33922 remove : function(){
33924 this.holder = document.createElement("div");
33925 this.holder.appendChild(this.wrap);
33929 fireEvent : function(){
33930 return this.node.fireEvent.apply(this.node, arguments);
33933 initEvents : function(){
33934 this.node.on("move", this.onMove, this);
33935 var E = Roo.EventManager;
33936 var a = this.anchor;
33938 var el = Roo.fly(a, '_treeui');
33940 if(Roo.isOpera){ // opera render bug ignores the CSS
33941 el.setStyle("text-decoration", "none");
33944 el.on("click", this.onClick, this);
33945 el.on("dblclick", this.onDblClick, this);
33948 Roo.EventManager.on(this.checkbox,
33949 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
33952 el.on("contextmenu", this.onContextMenu, this);
33954 var icon = Roo.fly(this.iconNode);
33955 icon.on("click", this.onClick, this);
33956 icon.on("dblclick", this.onDblClick, this);
33957 icon.on("contextmenu", this.onContextMenu, this);
33958 E.on(this.ecNode, "click", this.ecClick, this, true);
33960 if(this.node.disabled){
33961 this.addClass("x-tree-node-disabled");
33963 if(this.node.hidden){
33964 this.addClass("x-tree-node-disabled");
33966 var ot = this.node.getOwnerTree();
33967 var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
33968 if(dd && (!this.node.isRoot || ot.rootVisible)){
33969 Roo.dd.Registry.register(this.elNode, {
33971 handles: this.getDDHandles(),
33977 getDDHandles : function(){
33978 return [this.iconNode, this.textNode];
33983 this.wrap.style.display = "none";
33989 this.wrap.style.display = "";
33993 onContextMenu : function(e){
33994 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
33995 e.preventDefault();
33997 this.fireEvent("contextmenu", this.node, e);
34001 onClick : function(e){
34006 if(this.fireEvent("beforeclick", this.node, e) !== false){
34007 if(!this.disabled && this.node.attributes.href){
34008 this.fireEvent("click", this.node, e);
34011 e.preventDefault();
34016 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
34017 this.node.toggle();
34020 this.fireEvent("click", this.node, e);
34026 onDblClick : function(e){
34027 e.preventDefault();
34032 this.toggleCheck();
34034 if(!this.animating && this.node.hasChildNodes()){
34035 this.node.toggle();
34037 this.fireEvent("dblclick", this.node, e);
34040 onCheckChange : function(){
34041 var checked = this.checkbox.checked;
34042 this.node.attributes.checked = checked;
34043 this.fireEvent('checkchange', this.node, checked);
34046 ecClick : function(e){
34047 if(!this.animating && this.node.hasChildNodes()){
34048 this.node.toggle();
34052 startDrop : function(){
34053 this.dropping = true;
34056 // delayed drop so the click event doesn't get fired on a drop
34057 endDrop : function(){
34058 setTimeout(function(){
34059 this.dropping = false;
34060 }.createDelegate(this), 50);
34063 expand : function(){
34064 this.updateExpandIcon();
34065 this.ctNode.style.display = "";
34068 focus : function(){
34069 if(!this.node.preventHScroll){
34070 try{this.anchor.focus();
34072 }else if(!Roo.isIE){
34074 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
34075 var l = noscroll.scrollLeft;
34076 this.anchor.focus();
34077 noscroll.scrollLeft = l;
34082 toggleCheck : function(value){
34083 var cb = this.checkbox;
34085 cb.checked = (value === undefined ? !cb.checked : value);
34091 this.anchor.blur();
34095 animExpand : function(callback){
34096 var ct = Roo.get(this.ctNode);
34098 if(!this.node.hasChildNodes()){
34099 this.updateExpandIcon();
34100 this.ctNode.style.display = "";
34101 Roo.callback(callback);
34104 this.animating = true;
34105 this.updateExpandIcon();
34108 callback : function(){
34109 this.animating = false;
34110 Roo.callback(callback);
34113 duration: this.node.ownerTree.duration || .25
34117 highlight : function(){
34118 var tree = this.node.getOwnerTree();
34119 Roo.fly(this.wrap).highlight(
34120 tree.hlColor || "C3DAF9",
34121 {endColor: tree.hlBaseColor}
34125 collapse : function(){
34126 this.updateExpandIcon();
34127 this.ctNode.style.display = "none";
34130 animCollapse : function(callback){
34131 var ct = Roo.get(this.ctNode);
34132 ct.enableDisplayMode('block');
34135 this.animating = true;
34136 this.updateExpandIcon();
34139 callback : function(){
34140 this.animating = false;
34141 Roo.callback(callback);
34144 duration: this.node.ownerTree.duration || .25
34148 getContainer : function(){
34149 return this.ctNode;
34152 getEl : function(){
34156 appendDDGhost : function(ghostNode){
34157 ghostNode.appendChild(this.elNode.cloneNode(true));
34160 getDDRepairXY : function(){
34161 return Roo.lib.Dom.getXY(this.iconNode);
34164 onRender : function(){
34168 render : function(bulkRender){
34169 var n = this.node, a = n.attributes;
34170 var targetNode = n.parentNode ?
34171 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
34173 if(!this.rendered){
34174 this.rendered = true;
34176 this.renderElements(n, a, targetNode, bulkRender);
34179 if(this.textNode.setAttributeNS){
34180 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
34182 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
34185 this.textNode.setAttribute("ext:qtip", a.qtip);
34187 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
34190 }else if(a.qtipCfg){
34191 a.qtipCfg.target = Roo.id(this.textNode);
34192 Roo.QuickTips.register(a.qtipCfg);
34195 if(!this.node.expanded){
34196 this.updateExpandIcon();
34199 if(bulkRender === true) {
34200 targetNode.appendChild(this.wrap);
34205 renderElements : function(n, a, targetNode, bulkRender)
34207 // add some indent caching, this helps performance when rendering a large tree
34208 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
34209 var t = n.getOwnerTree();
34210 var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
34211 if (typeof(n.attributes.html) != 'undefined') {
34212 txt = n.attributes.html;
34214 var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
34215 var cb = typeof a.checked == 'boolean';
34216 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
34217 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
34218 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
34219 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
34220 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
34221 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
34222 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
34223 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
34224 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
34225 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
34228 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
34229 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
34230 n.nextSibling.ui.getEl(), buf.join(""));
34232 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
34235 this.elNode = this.wrap.childNodes[0];
34236 this.ctNode = this.wrap.childNodes[1];
34237 var cs = this.elNode.childNodes;
34238 this.indentNode = cs[0];
34239 this.ecNode = cs[1];
34240 this.iconNode = cs[2];
34243 this.checkbox = cs[3];
34246 this.anchor = cs[index];
34247 this.textNode = cs[index].firstChild;
34250 getAnchor : function(){
34251 return this.anchor;
34254 getTextEl : function(){
34255 return this.textNode;
34258 getIconEl : function(){
34259 return this.iconNode;
34262 isChecked : function(){
34263 return this.checkbox ? this.checkbox.checked : false;
34266 updateExpandIcon : function(){
34268 var n = this.node, c1, c2;
34269 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
34270 var hasChild = n.hasChildNodes();
34274 c1 = "x-tree-node-collapsed";
34275 c2 = "x-tree-node-expanded";
34278 c1 = "x-tree-node-expanded";
34279 c2 = "x-tree-node-collapsed";
34282 this.removeClass("x-tree-node-leaf");
34283 this.wasLeaf = false;
34285 if(this.c1 != c1 || this.c2 != c2){
34286 Roo.fly(this.elNode).replaceClass(c1, c2);
34287 this.c1 = c1; this.c2 = c2;
34290 // this changes non-leafs into leafs if they have no children.
34291 // it's not very rational behaviour..
34293 if(!this.wasLeaf && this.node.leaf){
34294 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
34297 this.wasLeaf = true;
34300 var ecc = "x-tree-ec-icon "+cls;
34301 if(this.ecc != ecc){
34302 this.ecNode.className = ecc;
34308 getChildIndent : function(){
34309 if(!this.childIndent){
34313 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
34315 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
34317 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
34322 this.childIndent = buf.join("");
34324 return this.childIndent;
34327 renderIndent : function(){
34330 var p = this.node.parentNode;
34332 indent = p.ui.getChildIndent();
34334 if(this.indentMarkup != indent){ // don't rerender if not required
34335 this.indentNode.innerHTML = indent;
34336 this.indentMarkup = indent;
34338 this.updateExpandIcon();
34343 Roo.tree.RootTreeNodeUI = function(){
34344 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
34346 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
34347 render : function(){
34348 if(!this.rendered){
34349 var targetNode = this.node.ownerTree.innerCt.dom;
34350 this.node.expanded = true;
34351 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
34352 this.wrap = this.ctNode = targetNode.firstChild;
34355 collapse : function(){
34357 expand : function(){
34361 * Ext JS Library 1.1.1
34362 * Copyright(c) 2006-2007, Ext JS, LLC.
34364 * Originally Released Under LGPL - original licence link has changed is not relivant.
34367 * <script type="text/javascript">
34370 * @class Roo.tree.TreeLoader
34371 * @extends Roo.util.Observable
34372 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
34373 * nodes from a specified URL. The response must be a javascript Array definition
34374 * who's elements are node definition objects. eg:
34379 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
34380 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
34387 * The old style respose with just an array is still supported, but not recommended.
34390 * A server request is sent, and child nodes are loaded only when a node is expanded.
34391 * The loading node's id is passed to the server under the parameter name "node" to
34392 * enable the server to produce the correct child nodes.
34394 * To pass extra parameters, an event handler may be attached to the "beforeload"
34395 * event, and the parameters specified in the TreeLoader's baseParams property:
34397 myTreeLoader.on("beforeload", function(treeLoader, node) {
34398 this.baseParams.category = node.attributes.category;
34401 * This would pass an HTTP parameter called "category" to the server containing
34402 * the value of the Node's "category" attribute.
34404 * Creates a new Treeloader.
34405 * @param {Object} config A config object containing config properties.
34407 Roo.tree.TreeLoader = function(config){
34408 this.baseParams = {};
34409 this.requestMethod = "POST";
34410 Roo.apply(this, config);
34415 * @event beforeload
34416 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
34417 * @param {Object} This TreeLoader object.
34418 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34419 * @param {Object} callback The callback function specified in the {@link #load} call.
34424 * Fires when the node has been successfuly loaded.
34425 * @param {Object} This TreeLoader object.
34426 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34427 * @param {Object} response The response object containing the data from the server.
34431 * @event loadexception
34432 * Fires if the network request failed.
34433 * @param {Object} This TreeLoader object.
34434 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34435 * @param {Object} response The response object containing the data from the server.
34437 loadexception : true,
34440 * Fires before a node is created, enabling you to return custom Node types
34441 * @param {Object} This TreeLoader object.
34442 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
34447 Roo.tree.TreeLoader.superclass.constructor.call(this);
34450 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
34452 * @cfg {String} dataUrl The URL from which to request a Json string which
34453 * specifies an array of node definition object representing the child nodes
34457 * @cfg {String} requestMethod either GET or POST
34458 * defaults to POST (due to BC)
34462 * @cfg {Object} baseParams (optional) An object containing properties which
34463 * specify HTTP parameters to be passed to each request for child nodes.
34466 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
34467 * created by this loader. If the attributes sent by the server have an attribute in this object,
34468 * they take priority.
34471 * @cfg {Object} uiProviders (optional) An object containing properties which
34473 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
34474 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
34475 * <i>uiProvider</i> attribute of a returned child node is a string rather
34476 * than a reference to a TreeNodeUI implementation, this that string value
34477 * is used as a property name in the uiProviders object. You can define the provider named
34478 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
34483 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
34484 * child nodes before loading.
34486 clearOnLoad : true,
34489 * @cfg {String} root (optional) Default to false. Use this to read data from an object
34490 * property on loading, rather than expecting an array. (eg. more compatible to a standard
34491 * Grid query { data : [ .....] }
34496 * @cfg {String} queryParam (optional)
34497 * Name of the query as it will be passed on the querystring (defaults to 'node')
34498 * eg. the request will be ?node=[id]
34505 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
34506 * This is called automatically when a node is expanded, but may be used to reload
34507 * a node (or append new children if the {@link #clearOnLoad} option is false.)
34508 * @param {Roo.tree.TreeNode} node
34509 * @param {Function} callback
34511 load : function(node, callback){
34512 if(this.clearOnLoad){
34513 while(node.firstChild){
34514 node.removeChild(node.firstChild);
34517 if(node.attributes.children){ // preloaded json children
34518 var cs = node.attributes.children;
34519 for(var i = 0, len = cs.length; i < len; i++){
34520 node.appendChild(this.createNode(cs[i]));
34522 if(typeof callback == "function"){
34525 }else if(this.dataUrl){
34526 this.requestData(node, callback);
34530 getParams: function(node){
34531 var buf = [], bp = this.baseParams;
34532 for(var key in bp){
34533 if(typeof bp[key] != "function"){
34534 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
34537 var n = this.queryParam === false ? 'node' : this.queryParam;
34538 buf.push(n + "=", encodeURIComponent(node.id));
34539 return buf.join("");
34542 requestData : function(node, callback){
34543 if(this.fireEvent("beforeload", this, node, callback) !== false){
34544 this.transId = Roo.Ajax.request({
34545 method:this.requestMethod,
34546 url: this.dataUrl||this.url,
34547 success: this.handleResponse,
34548 failure: this.handleFailure,
34550 argument: {callback: callback, node: node},
34551 params: this.getParams(node)
34554 // if the load is cancelled, make sure we notify
34555 // the node that we are done
34556 if(typeof callback == "function"){
34562 isLoading : function(){
34563 return this.transId ? true : false;
34566 abort : function(){
34567 if(this.isLoading()){
34568 Roo.Ajax.abort(this.transId);
34573 createNode : function(attr)
34575 // apply baseAttrs, nice idea Corey!
34576 if(this.baseAttrs){
34577 Roo.applyIf(attr, this.baseAttrs);
34579 if(this.applyLoader !== false){
34580 attr.loader = this;
34582 // uiProvider = depreciated..
34584 if(typeof(attr.uiProvider) == 'string'){
34585 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
34586 /** eval:var:attr */ eval(attr.uiProvider);
34588 if(typeof(this.uiProviders['default']) != 'undefined') {
34589 attr.uiProvider = this.uiProviders['default'];
34592 this.fireEvent('create', this, attr);
34594 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
34596 new Roo.tree.TreeNode(attr) :
34597 new Roo.tree.AsyncTreeNode(attr));
34600 processResponse : function(response, node, callback)
34602 var json = response.responseText;
34605 var o = Roo.decode(json);
34607 if (this.root === false && typeof(o.success) != undefined) {
34608 this.root = 'data'; // the default behaviour for list like data..
34611 if (this.root !== false && !o.success) {
34612 // it's a failure condition.
34613 var a = response.argument;
34614 this.fireEvent("loadexception", this, a.node, response);
34615 Roo.log("Load failed - should have a handler really");
34621 if (this.root !== false) {
34625 for(var i = 0, len = o.length; i < len; i++){
34626 var n = this.createNode(o[i]);
34628 node.appendChild(n);
34631 if(typeof callback == "function"){
34632 callback(this, node);
34635 this.handleFailure(response);
34639 handleResponse : function(response){
34640 this.transId = false;
34641 var a = response.argument;
34642 this.processResponse(response, a.node, a.callback);
34643 this.fireEvent("load", this, a.node, response);
34646 handleFailure : function(response)
34648 // should handle failure better..
34649 this.transId = false;
34650 var a = response.argument;
34651 this.fireEvent("loadexception", this, a.node, response);
34652 if(typeof a.callback == "function"){
34653 a.callback(this, a.node);
34658 * Ext JS Library 1.1.1
34659 * Copyright(c) 2006-2007, Ext JS, LLC.
34661 * Originally Released Under LGPL - original licence link has changed is not relivant.
34664 * <script type="text/javascript">
34668 * @class Roo.tree.TreeFilter
34669 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
34670 * @param {TreePanel} tree
34671 * @param {Object} config (optional)
34673 Roo.tree.TreeFilter = function(tree, config){
34675 this.filtered = {};
34676 Roo.apply(this, config);
34679 Roo.tree.TreeFilter.prototype = {
34686 * Filter the data by a specific attribute.
34687 * @param {String/RegExp} value Either string that the attribute value
34688 * should start with or a RegExp to test against the attribute
34689 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
34690 * @param {TreeNode} startNode (optional) The node to start the filter at.
34692 filter : function(value, attr, startNode){
34693 attr = attr || "text";
34695 if(typeof value == "string"){
34696 var vlen = value.length;
34697 // auto clear empty filter
34698 if(vlen == 0 && this.clearBlank){
34702 value = value.toLowerCase();
34704 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
34706 }else if(value.exec){ // regex?
34708 return value.test(n.attributes[attr]);
34711 throw 'Illegal filter type, must be string or regex';
34713 this.filterBy(f, null, startNode);
34717 * Filter by a function. The passed function will be called with each
34718 * node in the tree (or from the startNode). If the function returns true, the node is kept
34719 * otherwise it is filtered. If a node is filtered, its children are also filtered.
34720 * @param {Function} fn The filter function
34721 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
34723 filterBy : function(fn, scope, startNode){
34724 startNode = startNode || this.tree.root;
34725 if(this.autoClear){
34728 var af = this.filtered, rv = this.reverse;
34729 var f = function(n){
34730 if(n == startNode){
34736 var m = fn.call(scope || n, n);
34744 startNode.cascade(f);
34747 if(typeof id != "function"){
34749 if(n && n.parentNode){
34750 n.parentNode.removeChild(n);
34758 * Clears the current filter. Note: with the "remove" option
34759 * set a filter cannot be cleared.
34761 clear : function(){
34763 var af = this.filtered;
34765 if(typeof id != "function"){
34772 this.filtered = {};
34777 * Ext JS Library 1.1.1
34778 * Copyright(c) 2006-2007, Ext JS, LLC.
34780 * Originally Released Under LGPL - original licence link has changed is not relivant.
34783 * <script type="text/javascript">
34788 * @class Roo.tree.TreeSorter
34789 * Provides sorting of nodes in a TreePanel
34791 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
34792 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
34793 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
34794 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
34795 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
34796 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
34798 * @param {TreePanel} tree
34799 * @param {Object} config
34801 Roo.tree.TreeSorter = function(tree, config){
34802 Roo.apply(this, config);
34803 tree.on("beforechildrenrendered", this.doSort, this);
34804 tree.on("append", this.updateSort, this);
34805 tree.on("insert", this.updateSort, this);
34807 var dsc = this.dir && this.dir.toLowerCase() == "desc";
34808 var p = this.property || "text";
34809 var sortType = this.sortType;
34810 var fs = this.folderSort;
34811 var cs = this.caseSensitive === true;
34812 var leafAttr = this.leafAttr || 'leaf';
34814 this.sortFn = function(n1, n2){
34816 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
34819 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
34823 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
34824 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
34826 return dsc ? +1 : -1;
34828 return dsc ? -1 : +1;
34835 Roo.tree.TreeSorter.prototype = {
34836 doSort : function(node){
34837 node.sort(this.sortFn);
34840 compareNodes : function(n1, n2){
34841 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
34844 updateSort : function(tree, node){
34845 if(node.childrenRendered){
34846 this.doSort.defer(1, this, [node]);
34851 * Ext JS Library 1.1.1
34852 * Copyright(c) 2006-2007, Ext JS, LLC.
34854 * Originally Released Under LGPL - original licence link has changed is not relivant.
34857 * <script type="text/javascript">
34860 if(Roo.dd.DropZone){
34862 Roo.tree.TreeDropZone = function(tree, config){
34863 this.allowParentInsert = false;
34864 this.allowContainerDrop = false;
34865 this.appendOnly = false;
34866 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
34868 this.lastInsertClass = "x-tree-no-status";
34869 this.dragOverData = {};
34872 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
34873 ddGroup : "TreeDD",
34876 expandDelay : 1000,
34878 expandNode : function(node){
34879 if(node.hasChildNodes() && !node.isExpanded()){
34880 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
34884 queueExpand : function(node){
34885 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
34888 cancelExpand : function(){
34889 if(this.expandProcId){
34890 clearTimeout(this.expandProcId);
34891 this.expandProcId = false;
34895 isValidDropPoint : function(n, pt, dd, e, data){
34896 if(!n || !data){ return false; }
34897 var targetNode = n.node;
34898 var dropNode = data.node;
34899 // default drop rules
34900 if(!(targetNode && targetNode.isTarget && pt)){
34903 if(pt == "append" && targetNode.allowChildren === false){
34906 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
34909 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
34912 // reuse the object
34913 var overEvent = this.dragOverData;
34914 overEvent.tree = this.tree;
34915 overEvent.target = targetNode;
34916 overEvent.data = data;
34917 overEvent.point = pt;
34918 overEvent.source = dd;
34919 overEvent.rawEvent = e;
34920 overEvent.dropNode = dropNode;
34921 overEvent.cancel = false;
34922 var result = this.tree.fireEvent("nodedragover", overEvent);
34923 return overEvent.cancel === false && result !== false;
34926 getDropPoint : function(e, n, dd)
34930 return tn.allowChildren !== false ? "append" : false; // always append for root
34932 var dragEl = n.ddel;
34933 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
34934 var y = Roo.lib.Event.getPageY(e);
34935 //var noAppend = tn.allowChildren === false || tn.isLeaf();
34937 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
34938 var noAppend = tn.allowChildren === false;
34939 if(this.appendOnly || tn.parentNode.allowChildren === false){
34940 return noAppend ? false : "append";
34942 var noBelow = false;
34943 if(!this.allowParentInsert){
34944 noBelow = tn.hasChildNodes() && tn.isExpanded();
34946 var q = (b - t) / (noAppend ? 2 : 3);
34947 if(y >= t && y < (t + q)){
34949 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
34956 onNodeEnter : function(n, dd, e, data)
34958 this.cancelExpand();
34961 onNodeOver : function(n, dd, e, data)
34964 var pt = this.getDropPoint(e, n, dd);
34967 // auto node expand check
34968 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
34969 this.queueExpand(node);
34970 }else if(pt != "append"){
34971 this.cancelExpand();
34974 // set the insert point style on the target node
34975 var returnCls = this.dropNotAllowed;
34976 if(this.isValidDropPoint(n, pt, dd, e, data)){
34981 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
34982 cls = "x-tree-drag-insert-above";
34983 }else if(pt == "below"){
34984 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
34985 cls = "x-tree-drag-insert-below";
34987 returnCls = "x-tree-drop-ok-append";
34988 cls = "x-tree-drag-append";
34990 if(this.lastInsertClass != cls){
34991 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
34992 this.lastInsertClass = cls;
34999 onNodeOut : function(n, dd, e, data){
35001 this.cancelExpand();
35002 this.removeDropIndicators(n);
35005 onNodeDrop : function(n, dd, e, data){
35006 var point = this.getDropPoint(e, n, dd);
35007 var targetNode = n.node;
35008 targetNode.ui.startDrop();
35009 if(!this.isValidDropPoint(n, point, dd, e, data)){
35010 targetNode.ui.endDrop();
35013 // first try to find the drop node
35014 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
35017 target: targetNode,
35022 dropNode: dropNode,
35025 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
35026 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
35027 targetNode.ui.endDrop();
35030 // allow target changing
35031 targetNode = dropEvent.target;
35032 if(point == "append" && !targetNode.isExpanded()){
35033 targetNode.expand(false, null, function(){
35034 this.completeDrop(dropEvent);
35035 }.createDelegate(this));
35037 this.completeDrop(dropEvent);
35042 completeDrop : function(de){
35043 var ns = de.dropNode, p = de.point, t = de.target;
35044 if(!(ns instanceof Array)){
35048 for(var i = 0, len = ns.length; i < len; i++){
35051 t.parentNode.insertBefore(n, t);
35052 }else if(p == "below"){
35053 t.parentNode.insertBefore(n, t.nextSibling);
35059 if(this.tree.hlDrop){
35063 this.tree.fireEvent("nodedrop", de);
35066 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
35067 if(this.tree.hlDrop){
35068 dropNode.ui.focus();
35069 dropNode.ui.highlight();
35071 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
35074 getTree : function(){
35078 removeDropIndicators : function(n){
35081 Roo.fly(el).removeClass([
35082 "x-tree-drag-insert-above",
35083 "x-tree-drag-insert-below",
35084 "x-tree-drag-append"]);
35085 this.lastInsertClass = "_noclass";
35089 beforeDragDrop : function(target, e, id){
35090 this.cancelExpand();
35094 afterRepair : function(data){
35095 if(data && Roo.enableFx){
35096 data.node.ui.highlight();
35106 * Ext JS Library 1.1.1
35107 * Copyright(c) 2006-2007, Ext JS, LLC.
35109 * Originally Released Under LGPL - original licence link has changed is not relivant.
35112 * <script type="text/javascript">
35116 if(Roo.dd.DragZone){
35117 Roo.tree.TreeDragZone = function(tree, config){
35118 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
35122 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
35123 ddGroup : "TreeDD",
35125 onBeforeDrag : function(data, e){
35127 return n && n.draggable && !n.disabled;
35131 onInitDrag : function(e){
35132 var data = this.dragData;
35133 this.tree.getSelectionModel().select(data.node);
35134 this.proxy.update("");
35135 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
35136 this.tree.fireEvent("startdrag", this.tree, data.node, e);
35139 getRepairXY : function(e, data){
35140 return data.node.ui.getDDRepairXY();
35143 onEndDrag : function(data, e){
35144 this.tree.fireEvent("enddrag", this.tree, data.node, e);
35149 onValidDrop : function(dd, e, id){
35150 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
35154 beforeInvalidDrop : function(e, id){
35155 // this scrolls the original position back into view
35156 var sm = this.tree.getSelectionModel();
35157 sm.clearSelections();
35158 sm.select(this.dragData.node);
35163 * Ext JS Library 1.1.1
35164 * Copyright(c) 2006-2007, Ext JS, LLC.
35166 * Originally Released Under LGPL - original licence link has changed is not relivant.
35169 * <script type="text/javascript">
35172 * @class Roo.tree.TreeEditor
35173 * @extends Roo.Editor
35174 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
35175 * as the editor field.
35177 * @param {Object} config (used to be the tree panel.)
35178 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
35180 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
35181 * @cfg {Roo.form.TextField|Object} field The field configuration
35185 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
35188 if (oldconfig) { // old style..
35189 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
35192 tree = config.tree;
35193 config.field = config.field || {};
35194 config.field.xtype = 'TextField';
35195 field = Roo.factory(config.field, Roo.form);
35197 config = config || {};
35202 * @event beforenodeedit
35203 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
35204 * false from the handler of this event.
35205 * @param {Editor} this
35206 * @param {Roo.tree.Node} node
35208 "beforenodeedit" : true
35212 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
35216 tree.on('beforeclick', this.beforeNodeClick, this);
35217 tree.getTreeEl().on('mousedown', this.hide, this);
35218 this.on('complete', this.updateNode, this);
35219 this.on('beforestartedit', this.fitToTree, this);
35220 this.on('startedit', this.bindScroll, this, {delay:10});
35221 this.on('specialkey', this.onSpecialKey, this);
35224 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
35226 * @cfg {String} alignment
35227 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
35233 * @cfg {Boolean} hideEl
35234 * True to hide the bound element while the editor is displayed (defaults to false)
35238 * @cfg {String} cls
35239 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
35241 cls: "x-small-editor x-tree-editor",
35243 * @cfg {Boolean} shim
35244 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
35250 * @cfg {Number} maxWidth
35251 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
35252 * the containing tree element's size, it will be automatically limited for you to the container width, taking
35253 * scroll and client offsets into account prior to each edit.
35260 fitToTree : function(ed, el){
35261 var td = this.tree.getTreeEl().dom, nd = el.dom;
35262 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
35263 td.scrollLeft = nd.offsetLeft;
35267 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
35268 this.setSize(w, '');
35270 return this.fireEvent('beforenodeedit', this, this.editNode);
35275 triggerEdit : function(node){
35276 this.completeEdit();
35277 this.editNode = node;
35278 this.startEdit(node.ui.textNode, node.text);
35282 bindScroll : function(){
35283 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
35287 beforeNodeClick : function(node, e){
35288 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
35289 this.lastClick = new Date();
35290 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
35292 this.triggerEdit(node);
35299 updateNode : function(ed, value){
35300 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
35301 this.editNode.setText(value);
35305 onHide : function(){
35306 Roo.tree.TreeEditor.superclass.onHide.call(this);
35308 this.editNode.ui.focus();
35313 onSpecialKey : function(field, e){
35314 var k = e.getKey();
35318 }else if(k == e.ENTER && !e.hasModifier()){
35320 this.completeEdit();
35323 });//<Script type="text/javascript">
35326 * Ext JS Library 1.1.1
35327 * Copyright(c) 2006-2007, Ext JS, LLC.
35329 * Originally Released Under LGPL - original licence link has changed is not relivant.
35332 * <script type="text/javascript">
35336 * Not documented??? - probably should be...
35339 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
35340 //focus: Roo.emptyFn, // prevent odd scrolling behavior
35342 renderElements : function(n, a, targetNode, bulkRender){
35343 //consel.log("renderElements?");
35344 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
35346 var t = n.getOwnerTree();
35347 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
35349 var cols = t.columns;
35350 var bw = t.borderWidth;
35352 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
35353 var cb = typeof a.checked == "boolean";
35354 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
35355 var colcls = 'x-t-' + tid + '-c0';
35357 '<li class="x-tree-node">',
35360 '<div class="x-tree-node-el ', a.cls,'">',
35362 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
35365 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
35366 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
35367 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
35368 (a.icon ? ' x-tree-node-inline-icon' : ''),
35369 (a.iconCls ? ' '+a.iconCls : ''),
35370 '" unselectable="on" />',
35371 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
35372 (a.checked ? 'checked="checked" />' : ' />')) : ''),
35374 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
35375 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
35376 '<span unselectable="on" qtip="' + tx + '">',
35380 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
35381 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
35383 for(var i = 1, len = cols.length; i < len; i++){
35385 colcls = 'x-t-' + tid + '-c' +i;
35386 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
35387 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
35388 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
35394 '<div class="x-clear"></div></div>',
35395 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
35398 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
35399 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
35400 n.nextSibling.ui.getEl(), buf.join(""));
35402 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
35404 var el = this.wrap.firstChild;
35406 this.elNode = el.firstChild;
35407 this.ranchor = el.childNodes[1];
35408 this.ctNode = this.wrap.childNodes[1];
35409 var cs = el.firstChild.childNodes;
35410 this.indentNode = cs[0];
35411 this.ecNode = cs[1];
35412 this.iconNode = cs[2];
35415 this.checkbox = cs[3];
35418 this.anchor = cs[index];
35420 this.textNode = cs[index].firstChild;
35422 //el.on("click", this.onClick, this);
35423 //el.on("dblclick", this.onDblClick, this);
35426 // console.log(this);
35428 initEvents : function(){
35429 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
35432 var a = this.ranchor;
35434 var el = Roo.get(a);
35436 if(Roo.isOpera){ // opera render bug ignores the CSS
35437 el.setStyle("text-decoration", "none");
35440 el.on("click", this.onClick, this);
35441 el.on("dblclick", this.onDblClick, this);
35442 el.on("contextmenu", this.onContextMenu, this);
35446 /*onSelectedChange : function(state){
35449 this.addClass("x-tree-selected");
35452 this.removeClass("x-tree-selected");
35455 addClass : function(cls){
35457 Roo.fly(this.elRow).addClass(cls);
35463 removeClass : function(cls){
35465 Roo.fly(this.elRow).removeClass(cls);
35471 });//<Script type="text/javascript">
35475 * Ext JS Library 1.1.1
35476 * Copyright(c) 2006-2007, Ext JS, LLC.
35478 * Originally Released Under LGPL - original licence link has changed is not relivant.
35481 * <script type="text/javascript">
35486 * @class Roo.tree.ColumnTree
35487 * @extends Roo.data.TreePanel
35488 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
35489 * @cfg {int} borderWidth compined right/left border allowance
35491 * @param {String/HTMLElement/Element} el The container element
35492 * @param {Object} config
35494 Roo.tree.ColumnTree = function(el, config)
35496 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
35500 * Fire this event on a container when it resizes
35501 * @param {int} w Width
35502 * @param {int} h Height
35506 this.on('resize', this.onResize, this);
35509 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
35513 borderWidth: Roo.isBorderBox ? 0 : 2,
35516 render : function(){
35517 // add the header.....
35519 Roo.tree.ColumnTree.superclass.render.apply(this);
35521 this.el.addClass('x-column-tree');
35523 this.headers = this.el.createChild(
35524 {cls:'x-tree-headers'},this.innerCt.dom);
35526 var cols = this.columns, c;
35527 var totalWidth = 0;
35529 var len = cols.length;
35530 for(var i = 0; i < len; i++){
35532 totalWidth += c.width;
35533 this.headEls.push(this.headers.createChild({
35534 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
35536 cls:'x-tree-hd-text',
35539 style:'width:'+(c.width-this.borderWidth)+'px;'
35542 this.headers.createChild({cls:'x-clear'});
35543 // prevent floats from wrapping when clipped
35544 this.headers.setWidth(totalWidth);
35545 //this.innerCt.setWidth(totalWidth);
35546 this.innerCt.setStyle({ overflow: 'auto' });
35547 this.onResize(this.width, this.height);
35551 onResize : function(w,h)
35556 this.innerCt.setWidth(this.width);
35557 this.innerCt.setHeight(this.height-20);
35560 var cols = this.columns, c;
35561 var totalWidth = 0;
35563 var len = cols.length;
35564 for(var i = 0; i < len; i++){
35566 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
35567 // it's the expander..
35568 expEl = this.headEls[i];
35571 totalWidth += c.width;
35575 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
35577 this.headers.setWidth(w-20);
35586 * Ext JS Library 1.1.1
35587 * Copyright(c) 2006-2007, Ext JS, LLC.
35589 * Originally Released Under LGPL - original licence link has changed is not relivant.
35592 * <script type="text/javascript">
35596 * @class Roo.menu.Menu
35597 * @extends Roo.util.Observable
35598 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
35599 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
35601 * Creates a new Menu
35602 * @param {Object} config Configuration options
35604 Roo.menu.Menu = function(config){
35605 Roo.apply(this, config);
35606 this.id = this.id || Roo.id();
35609 * @event beforeshow
35610 * Fires before this menu is displayed
35611 * @param {Roo.menu.Menu} this
35615 * @event beforehide
35616 * Fires before this menu is hidden
35617 * @param {Roo.menu.Menu} this
35622 * Fires after this menu is displayed
35623 * @param {Roo.menu.Menu} this
35628 * Fires after this menu is hidden
35629 * @param {Roo.menu.Menu} this
35634 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
35635 * @param {Roo.menu.Menu} this
35636 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35637 * @param {Roo.EventObject} e
35642 * Fires when the mouse is hovering over this menu
35643 * @param {Roo.menu.Menu} this
35644 * @param {Roo.EventObject} e
35645 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35650 * Fires when the mouse exits this menu
35651 * @param {Roo.menu.Menu} this
35652 * @param {Roo.EventObject} e
35653 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35658 * Fires when a menu item contained in this menu is clicked
35659 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
35660 * @param {Roo.EventObject} e
35664 if (this.registerMenu) {
35665 Roo.menu.MenuMgr.register(this);
35668 var mis = this.items;
35669 this.items = new Roo.util.MixedCollection();
35671 this.add.apply(this, mis);
35675 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
35677 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
35681 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
35682 * for bottom-right shadow (defaults to "sides")
35686 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
35687 * this menu (defaults to "tl-tr?")
35689 subMenuAlign : "tl-tr?",
35691 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
35692 * relative to its element of origin (defaults to "tl-bl?")
35694 defaultAlign : "tl-bl?",
35696 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
35698 allowOtherMenus : false,
35700 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
35702 registerMenu : true,
35707 render : function(){
35711 var el = this.el = new Roo.Layer({
35713 shadow:this.shadow,
35715 parentEl: this.parentEl || document.body,
35719 this.keyNav = new Roo.menu.MenuNav(this);
35722 el.addClass("x-menu-plain");
35725 el.addClass(this.cls);
35727 // generic focus element
35728 this.focusEl = el.createChild({
35729 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
35731 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
35732 ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
35734 ul.on("mouseover", this.onMouseOver, this);
35735 ul.on("mouseout", this.onMouseOut, this);
35736 this.items.each(function(item){
35741 var li = document.createElement("li");
35742 li.className = "x-menu-list-item";
35743 ul.dom.appendChild(li);
35744 item.render(li, this);
35751 autoWidth : function(){
35752 var el = this.el, ul = this.ul;
35756 var w = this.width;
35759 }else if(Roo.isIE){
35760 el.setWidth(this.minWidth);
35761 var t = el.dom.offsetWidth; // force recalc
35762 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
35767 delayAutoWidth : function(){
35770 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
35772 this.awTask.delay(20);
35777 findTargetItem : function(e){
35778 var t = e.getTarget(".x-menu-list-item", this.ul, true);
35779 if(t && t.menuItemId){
35780 return this.items.get(t.menuItemId);
35785 onClick : function(e){
35786 Roo.log("menu.onClick");
35787 var t = this.findTargetItem(e);
35792 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
35793 if(t == this.activeItem && t.shouldDeactivate(e)){
35794 this.activeItem.deactivate();
35795 delete this.activeItem;
35799 this.setActiveItem(t, true);
35807 this.fireEvent("click", this, t, e);
35811 setActiveItem : function(item, autoExpand){
35812 if(item != this.activeItem){
35813 if(this.activeItem){
35814 this.activeItem.deactivate();
35816 this.activeItem = item;
35817 item.activate(autoExpand);
35818 }else if(autoExpand){
35824 tryActivate : function(start, step){
35825 var items = this.items;
35826 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
35827 var item = items.get(i);
35828 if(!item.disabled && item.canActivate){
35829 this.setActiveItem(item, false);
35837 onMouseOver : function(e){
35839 if(t = this.findTargetItem(e)){
35840 if(t.canActivate && !t.disabled){
35841 this.setActiveItem(t, true);
35844 this.fireEvent("mouseover", this, e, t);
35848 onMouseOut : function(e){
35850 if(t = this.findTargetItem(e)){
35851 if(t == this.activeItem && t.shouldDeactivate(e)){
35852 this.activeItem.deactivate();
35853 delete this.activeItem;
35856 this.fireEvent("mouseout", this, e, t);
35860 * Read-only. Returns true if the menu is currently displayed, else false.
35863 isVisible : function(){
35864 return this.el && !this.hidden;
35868 * Displays this menu relative to another element
35869 * @param {String/HTMLElement/Roo.Element} element The element to align to
35870 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
35871 * the element (defaults to this.defaultAlign)
35872 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
35874 show : function(el, pos, parentMenu){
35875 this.parentMenu = parentMenu;
35879 this.fireEvent("beforeshow", this);
35880 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
35884 * Displays this menu at a specific xy position
35885 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
35886 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
35888 showAt : function(xy, parentMenu, /* private: */_e){
35889 this.parentMenu = parentMenu;
35894 this.fireEvent("beforeshow", this);
35895 xy = this.el.adjustForConstraints(xy);
35899 this.hidden = false;
35901 this.fireEvent("show", this);
35904 focus : function(){
35906 this.doFocus.defer(50, this);
35910 doFocus : function(){
35912 this.focusEl.focus();
35917 * Hides this menu and optionally all parent menus
35918 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
35920 hide : function(deep){
35921 if(this.el && this.isVisible()){
35922 this.fireEvent("beforehide", this);
35923 if(this.activeItem){
35924 this.activeItem.deactivate();
35925 this.activeItem = null;
35928 this.hidden = true;
35929 this.fireEvent("hide", this);
35931 if(deep === true && this.parentMenu){
35932 this.parentMenu.hide(true);
35937 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
35938 * Any of the following are valid:
35940 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
35941 * <li>An HTMLElement object which will be converted to a menu item</li>
35942 * <li>A menu item config object that will be created as a new menu item</li>
35943 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
35944 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
35949 var menu = new Roo.menu.Menu();
35951 // Create a menu item to add by reference
35952 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
35954 // Add a bunch of items at once using different methods.
35955 // Only the last item added will be returned.
35956 var item = menu.add(
35957 menuItem, // add existing item by ref
35958 'Dynamic Item', // new TextItem
35959 '-', // new separator
35960 { text: 'Config Item' } // new item by config
35963 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
35964 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
35967 var a = arguments, l = a.length, item;
35968 for(var i = 0; i < l; i++){
35970 if ((typeof(el) == "object") && el.xtype && el.xns) {
35971 el = Roo.factory(el, Roo.menu);
35974 if(el.render){ // some kind of Item
35975 item = this.addItem(el);
35976 }else if(typeof el == "string"){ // string
35977 if(el == "separator" || el == "-"){
35978 item = this.addSeparator();
35980 item = this.addText(el);
35982 }else if(el.tagName || el.el){ // element
35983 item = this.addElement(el);
35984 }else if(typeof el == "object"){ // must be menu item config?
35985 item = this.addMenuItem(el);
35992 * Returns this menu's underlying {@link Roo.Element} object
35993 * @return {Roo.Element} The element
35995 getEl : function(){
36003 * Adds a separator bar to the menu
36004 * @return {Roo.menu.Item} The menu item that was added
36006 addSeparator : function(){
36007 return this.addItem(new Roo.menu.Separator());
36011 * Adds an {@link Roo.Element} object to the menu
36012 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
36013 * @return {Roo.menu.Item} The menu item that was added
36015 addElement : function(el){
36016 return this.addItem(new Roo.menu.BaseItem(el));
36020 * Adds an existing object based on {@link Roo.menu.Item} to the menu
36021 * @param {Roo.menu.Item} item The menu item to add
36022 * @return {Roo.menu.Item} The menu item that was added
36024 addItem : function(item){
36025 this.items.add(item);
36027 var li = document.createElement("li");
36028 li.className = "x-menu-list-item";
36029 this.ul.dom.appendChild(li);
36030 item.render(li, this);
36031 this.delayAutoWidth();
36037 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
36038 * @param {Object} config A MenuItem config object
36039 * @return {Roo.menu.Item} The menu item that was added
36041 addMenuItem : function(config){
36042 if(!(config instanceof Roo.menu.Item)){
36043 if(typeof config.checked == "boolean"){ // must be check menu item config?
36044 config = new Roo.menu.CheckItem(config);
36046 config = new Roo.menu.Item(config);
36049 return this.addItem(config);
36053 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
36054 * @param {String} text The text to display in the menu item
36055 * @return {Roo.menu.Item} The menu item that was added
36057 addText : function(text){
36058 return this.addItem(new Roo.menu.TextItem({ text : text }));
36062 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
36063 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
36064 * @param {Roo.menu.Item} item The menu item to add
36065 * @return {Roo.menu.Item} The menu item that was added
36067 insert : function(index, item){
36068 this.items.insert(index, item);
36070 var li = document.createElement("li");
36071 li.className = "x-menu-list-item";
36072 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
36073 item.render(li, this);
36074 this.delayAutoWidth();
36080 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
36081 * @param {Roo.menu.Item} item The menu item to remove
36083 remove : function(item){
36084 this.items.removeKey(item.id);
36089 * Removes and destroys all items in the menu
36091 removeAll : function(){
36093 while(f = this.items.first()){
36099 // MenuNav is a private utility class used internally by the Menu
36100 Roo.menu.MenuNav = function(menu){
36101 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
36102 this.scope = this.menu = menu;
36105 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
36106 doRelay : function(e, h){
36107 var k = e.getKey();
36108 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
36109 this.menu.tryActivate(0, 1);
36112 return h.call(this.scope || this, e, this.menu);
36115 up : function(e, m){
36116 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
36117 m.tryActivate(m.items.length-1, -1);
36121 down : function(e, m){
36122 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
36123 m.tryActivate(0, 1);
36127 right : function(e, m){
36129 m.activeItem.expandMenu(true);
36133 left : function(e, m){
36135 if(m.parentMenu && m.parentMenu.activeItem){
36136 m.parentMenu.activeItem.activate();
36140 enter : function(e, m){
36142 e.stopPropagation();
36143 m.activeItem.onClick(e);
36144 m.fireEvent("click", this, m.activeItem);
36150 * Ext JS Library 1.1.1
36151 * Copyright(c) 2006-2007, Ext JS, LLC.
36153 * Originally Released Under LGPL - original licence link has changed is not relivant.
36156 * <script type="text/javascript">
36160 * @class Roo.menu.MenuMgr
36161 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
36164 Roo.menu.MenuMgr = function(){
36165 var menus, active, groups = {}, attached = false, lastShow = new Date();
36167 // private - called when first menu is created
36170 active = new Roo.util.MixedCollection();
36171 Roo.get(document).addKeyListener(27, function(){
36172 if(active.length > 0){
36179 function hideAll(){
36180 if(active && active.length > 0){
36181 var c = active.clone();
36182 c.each(function(m){
36189 function onHide(m){
36191 if(active.length < 1){
36192 Roo.get(document).un("mousedown", onMouseDown);
36198 function onShow(m){
36199 var last = active.last();
36200 lastShow = new Date();
36203 Roo.get(document).on("mousedown", onMouseDown);
36207 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
36208 m.parentMenu.activeChild = m;
36209 }else if(last && last.isVisible()){
36210 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
36215 function onBeforeHide(m){
36217 m.activeChild.hide();
36219 if(m.autoHideTimer){
36220 clearTimeout(m.autoHideTimer);
36221 delete m.autoHideTimer;
36226 function onBeforeShow(m){
36227 var pm = m.parentMenu;
36228 if(!pm && !m.allowOtherMenus){
36230 }else if(pm && pm.activeChild && active != m){
36231 pm.activeChild.hide();
36236 function onMouseDown(e){
36237 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
36243 function onBeforeCheck(mi, state){
36245 var g = groups[mi.group];
36246 for(var i = 0, l = g.length; i < l; i++){
36248 g[i].setChecked(false);
36257 * Hides all menus that are currently visible
36259 hideAll : function(){
36264 register : function(menu){
36268 menus[menu.id] = menu;
36269 menu.on("beforehide", onBeforeHide);
36270 menu.on("hide", onHide);
36271 menu.on("beforeshow", onBeforeShow);
36272 menu.on("show", onShow);
36273 var g = menu.group;
36274 if(g && menu.events["checkchange"]){
36278 groups[g].push(menu);
36279 menu.on("checkchange", onCheck);
36284 * Returns a {@link Roo.menu.Menu} object
36285 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
36286 * be used to generate and return a new Menu instance.
36288 get : function(menu){
36289 if(typeof menu == "string"){ // menu id
36290 return menus[menu];
36291 }else if(menu.events){ // menu instance
36293 }else if(typeof menu.length == 'number'){ // array of menu items?
36294 return new Roo.menu.Menu({items:menu});
36295 }else{ // otherwise, must be a config
36296 return new Roo.menu.Menu(menu);
36301 unregister : function(menu){
36302 delete menus[menu.id];
36303 menu.un("beforehide", onBeforeHide);
36304 menu.un("hide", onHide);
36305 menu.un("beforeshow", onBeforeShow);
36306 menu.un("show", onShow);
36307 var g = menu.group;
36308 if(g && menu.events["checkchange"]){
36309 groups[g].remove(menu);
36310 menu.un("checkchange", onCheck);
36315 registerCheckable : function(menuItem){
36316 var g = menuItem.group;
36321 groups[g].push(menuItem);
36322 menuItem.on("beforecheckchange", onBeforeCheck);
36327 unregisterCheckable : function(menuItem){
36328 var g = menuItem.group;
36330 groups[g].remove(menuItem);
36331 menuItem.un("beforecheckchange", onBeforeCheck);
36337 * Ext JS Library 1.1.1
36338 * Copyright(c) 2006-2007, Ext JS, LLC.
36340 * Originally Released Under LGPL - original licence link has changed is not relivant.
36343 * <script type="text/javascript">
36348 * @class Roo.menu.BaseItem
36349 * @extends Roo.Component
36350 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
36351 * management and base configuration options shared by all menu components.
36353 * Creates a new BaseItem
36354 * @param {Object} config Configuration options
36356 Roo.menu.BaseItem = function(config){
36357 Roo.menu.BaseItem.superclass.constructor.call(this, config);
36362 * Fires when this item is clicked
36363 * @param {Roo.menu.BaseItem} this
36364 * @param {Roo.EventObject} e
36369 * Fires when this item is activated
36370 * @param {Roo.menu.BaseItem} this
36374 * @event deactivate
36375 * Fires when this item is deactivated
36376 * @param {Roo.menu.BaseItem} this
36382 this.on("click", this.handler, this.scope, true);
36386 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
36388 * @cfg {Function} handler
36389 * A function that will handle the click event of this menu item (defaults to undefined)
36392 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
36394 canActivate : false,
36397 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
36402 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
36404 activeClass : "x-menu-item-active",
36406 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
36408 hideOnClick : true,
36410 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
36415 ctype: "Roo.menu.BaseItem",
36418 actionMode : "container",
36421 render : function(container, parentMenu){
36422 this.parentMenu = parentMenu;
36423 Roo.menu.BaseItem.superclass.render.call(this, container);
36424 this.container.menuItemId = this.id;
36428 onRender : function(container, position){
36429 this.el = Roo.get(this.el);
36430 container.dom.appendChild(this.el.dom);
36434 onClick : function(e){
36435 if(!this.disabled && this.fireEvent("click", this, e) !== false
36436 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
36437 this.handleClick(e);
36444 activate : function(){
36448 var li = this.container;
36449 li.addClass(this.activeClass);
36450 this.region = li.getRegion().adjust(2, 2, -2, -2);
36451 this.fireEvent("activate", this);
36456 deactivate : function(){
36457 this.container.removeClass(this.activeClass);
36458 this.fireEvent("deactivate", this);
36462 shouldDeactivate : function(e){
36463 return !this.region || !this.region.contains(e.getPoint());
36467 handleClick : function(e){
36468 if(this.hideOnClick){
36469 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
36474 expandMenu : function(autoActivate){
36479 hideMenu : function(){
36484 * Ext JS Library 1.1.1
36485 * Copyright(c) 2006-2007, Ext JS, LLC.
36487 * Originally Released Under LGPL - original licence link has changed is not relivant.
36490 * <script type="text/javascript">
36494 * @class Roo.menu.Adapter
36495 * @extends Roo.menu.BaseItem
36496 * A base utility class that adapts a non-menu component so that it can be wrapped by a menu item and added to a menu.
36497 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
36499 * Creates a new Adapter
36500 * @param {Object} config Configuration options
36502 Roo.menu.Adapter = function(component, config){
36503 Roo.menu.Adapter.superclass.constructor.call(this, config);
36504 this.component = component;
36506 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
36508 canActivate : true,
36511 onRender : function(container, position){
36512 this.component.render(container);
36513 this.el = this.component.getEl();
36517 activate : function(){
36521 this.component.focus();
36522 this.fireEvent("activate", this);
36527 deactivate : function(){
36528 this.fireEvent("deactivate", this);
36532 disable : function(){
36533 this.component.disable();
36534 Roo.menu.Adapter.superclass.disable.call(this);
36538 enable : function(){
36539 this.component.enable();
36540 Roo.menu.Adapter.superclass.enable.call(this);
36544 * Ext JS Library 1.1.1
36545 * Copyright(c) 2006-2007, Ext JS, LLC.
36547 * Originally Released Under LGPL - original licence link has changed is not relivant.
36550 * <script type="text/javascript">
36554 * @class Roo.menu.TextItem
36555 * @extends Roo.menu.BaseItem
36556 * Adds a static text string to a menu, usually used as either a heading or group separator.
36557 * Note: old style constructor with text is still supported.
36560 * Creates a new TextItem
36561 * @param {Object} cfg Configuration
36563 Roo.menu.TextItem = function(cfg){
36564 if (typeof(cfg) == 'string') {
36567 Roo.apply(this,cfg);
36570 Roo.menu.TextItem.superclass.constructor.call(this);
36573 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
36575 * @cfg {Boolean} text Text to show on item.
36580 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
36582 hideOnClick : false,
36584 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
36586 itemCls : "x-menu-text",
36589 onRender : function(){
36590 var s = document.createElement("span");
36591 s.className = this.itemCls;
36592 s.innerHTML = this.text;
36594 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
36598 * Ext JS Library 1.1.1
36599 * Copyright(c) 2006-2007, Ext JS, LLC.
36601 * Originally Released Under LGPL - original licence link has changed is not relivant.
36604 * <script type="text/javascript">
36608 * @class Roo.menu.Separator
36609 * @extends Roo.menu.BaseItem
36610 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
36611 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
36613 * @param {Object} config Configuration options
36615 Roo.menu.Separator = function(config){
36616 Roo.menu.Separator.superclass.constructor.call(this, config);
36619 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
36621 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
36623 itemCls : "x-menu-sep",
36625 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
36627 hideOnClick : false,
36630 onRender : function(li){
36631 var s = document.createElement("span");
36632 s.className = this.itemCls;
36633 s.innerHTML = " ";
36635 li.addClass("x-menu-sep-li");
36636 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
36640 * Ext JS Library 1.1.1
36641 * Copyright(c) 2006-2007, Ext JS, LLC.
36643 * Originally Released Under LGPL - original licence link has changed is not relivant.
36646 * <script type="text/javascript">
36649 * @class Roo.menu.Item
36650 * @extends Roo.menu.BaseItem
36651 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
36652 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
36653 * activation and click handling.
36655 * Creates a new Item
36656 * @param {Object} config Configuration options
36658 Roo.menu.Item = function(config){
36659 Roo.menu.Item.superclass.constructor.call(this, config);
36661 this.menu = Roo.menu.MenuMgr.get(this.menu);
36664 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
36667 * @cfg {String} text
36668 * The text to show on the menu item.
36672 * @cfg {String} HTML to render in menu
36673 * The text to show on the menu item (HTML version).
36677 * @cfg {String} icon
36678 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
36682 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
36684 itemCls : "x-menu-item",
36686 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
36688 canActivate : true,
36690 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
36693 // doc'd in BaseItem
36697 ctype: "Roo.menu.Item",
36700 onRender : function(container, position){
36701 var el = document.createElement("a");
36702 el.hideFocus = true;
36703 el.unselectable = "on";
36704 el.href = this.href || "#";
36705 if(this.hrefTarget){
36706 el.target = this.hrefTarget;
36708 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
36710 var html = this.html.length ? this.html : String.format('{0}',this.text);
36712 el.innerHTML = String.format(
36713 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
36714 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
36716 Roo.menu.Item.superclass.onRender.call(this, container, position);
36720 * Sets the text to display in this menu item
36721 * @param {String} text The text to display
36722 * @param {Boolean} isHTML true to indicate text is pure html.
36724 setText : function(text, isHTML){
36732 var html = this.html.length ? this.html : String.format('{0}',this.text);
36734 this.el.update(String.format(
36735 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
36736 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
36737 this.parentMenu.autoWidth();
36742 handleClick : function(e){
36743 if(!this.href){ // if no link defined, stop the event automatically
36746 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
36750 activate : function(autoExpand){
36751 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
36761 shouldDeactivate : function(e){
36762 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
36763 if(this.menu && this.menu.isVisible()){
36764 return !this.menu.getEl().getRegion().contains(e.getPoint());
36772 deactivate : function(){
36773 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
36778 expandMenu : function(autoActivate){
36779 if(!this.disabled && this.menu){
36780 clearTimeout(this.hideTimer);
36781 delete this.hideTimer;
36782 if(!this.menu.isVisible() && !this.showTimer){
36783 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
36784 }else if (this.menu.isVisible() && autoActivate){
36785 this.menu.tryActivate(0, 1);
36791 deferExpand : function(autoActivate){
36792 delete this.showTimer;
36793 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
36795 this.menu.tryActivate(0, 1);
36800 hideMenu : function(){
36801 clearTimeout(this.showTimer);
36802 delete this.showTimer;
36803 if(!this.hideTimer && this.menu && this.menu.isVisible()){
36804 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
36809 deferHide : function(){
36810 delete this.hideTimer;
36815 * Ext JS Library 1.1.1
36816 * Copyright(c) 2006-2007, Ext JS, LLC.
36818 * Originally Released Under LGPL - original licence link has changed is not relivant.
36821 * <script type="text/javascript">
36825 * @class Roo.menu.CheckItem
36826 * @extends Roo.menu.Item
36827 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
36829 * Creates a new CheckItem
36830 * @param {Object} config Configuration options
36832 Roo.menu.CheckItem = function(config){
36833 Roo.menu.CheckItem.superclass.constructor.call(this, config);
36836 * @event beforecheckchange
36837 * Fires before the checked value is set, providing an opportunity to cancel if needed
36838 * @param {Roo.menu.CheckItem} this
36839 * @param {Boolean} checked The new checked value that will be set
36841 "beforecheckchange" : true,
36843 * @event checkchange
36844 * Fires after the checked value has been set
36845 * @param {Roo.menu.CheckItem} this
36846 * @param {Boolean} checked The checked value that was set
36848 "checkchange" : true
36850 if(this.checkHandler){
36851 this.on('checkchange', this.checkHandler, this.scope);
36854 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
36856 * @cfg {String} group
36857 * All check items with the same group name will automatically be grouped into a single-select
36858 * radio button group (defaults to '')
36861 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
36863 itemCls : "x-menu-item x-menu-check-item",
36865 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
36867 groupClass : "x-menu-group-item",
36870 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
36871 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
36872 * initialized with checked = true will be rendered as checked.
36877 ctype: "Roo.menu.CheckItem",
36880 onRender : function(c){
36881 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
36883 this.el.addClass(this.groupClass);
36885 Roo.menu.MenuMgr.registerCheckable(this);
36887 this.checked = false;
36888 this.setChecked(true, true);
36893 destroy : function(){
36895 Roo.menu.MenuMgr.unregisterCheckable(this);
36897 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
36901 * Set the checked state of this item
36902 * @param {Boolean} checked The new checked value
36903 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
36905 setChecked : function(state, suppressEvent){
36906 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
36907 if(this.container){
36908 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
36910 this.checked = state;
36911 if(suppressEvent !== true){
36912 this.fireEvent("checkchange", this, state);
36918 handleClick : function(e){
36919 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
36920 this.setChecked(!this.checked);
36922 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
36926 * Ext JS Library 1.1.1
36927 * Copyright(c) 2006-2007, Ext JS, LLC.
36929 * Originally Released Under LGPL - original licence link has changed is not relivant.
36932 * <script type="text/javascript">
36936 * @class Roo.menu.DateItem
36937 * @extends Roo.menu.Adapter
36938 * A menu item that wraps the {@link Roo.DatPicker} component.
36940 * Creates a new DateItem
36941 * @param {Object} config Configuration options
36943 Roo.menu.DateItem = function(config){
36944 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
36945 /** The Roo.DatePicker object @type Roo.DatePicker */
36946 this.picker = this.component;
36947 this.addEvents({select: true});
36949 this.picker.on("render", function(picker){
36950 picker.getEl().swallowEvent("click");
36951 picker.container.addClass("x-menu-date-item");
36954 this.picker.on("select", this.onSelect, this);
36957 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
36959 onSelect : function(picker, date){
36960 this.fireEvent("select", this, date, picker);
36961 Roo.menu.DateItem.superclass.handleClick.call(this);
36965 * Ext JS Library 1.1.1
36966 * Copyright(c) 2006-2007, Ext JS, LLC.
36968 * Originally Released Under LGPL - original licence link has changed is not relivant.
36971 * <script type="text/javascript">
36975 * @class Roo.menu.ColorItem
36976 * @extends Roo.menu.Adapter
36977 * A menu item that wraps the {@link Roo.ColorPalette} component.
36979 * Creates a new ColorItem
36980 * @param {Object} config Configuration options
36982 Roo.menu.ColorItem = function(config){
36983 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
36984 /** The Roo.ColorPalette object @type Roo.ColorPalette */
36985 this.palette = this.component;
36986 this.relayEvents(this.palette, ["select"]);
36987 if(this.selectHandler){
36988 this.on('select', this.selectHandler, this.scope);
36991 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
36993 * Ext JS Library 1.1.1
36994 * Copyright(c) 2006-2007, Ext JS, LLC.
36996 * Originally Released Under LGPL - original licence link has changed is not relivant.
36999 * <script type="text/javascript">
37004 * @class Roo.menu.DateMenu
37005 * @extends Roo.menu.Menu
37006 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
37008 * Creates a new DateMenu
37009 * @param {Object} config Configuration options
37011 Roo.menu.DateMenu = function(config){
37012 Roo.menu.DateMenu.superclass.constructor.call(this, config);
37014 var di = new Roo.menu.DateItem(config);
37017 * The {@link Roo.DatePicker} instance for this DateMenu
37020 this.picker = di.picker;
37023 * @param {DatePicker} picker
37024 * @param {Date} date
37026 this.relayEvents(di, ["select"]);
37027 this.on('beforeshow', function(){
37029 this.picker.hideMonthPicker(false);
37033 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
37037 * Ext JS Library 1.1.1
37038 * Copyright(c) 2006-2007, Ext JS, LLC.
37040 * Originally Released Under LGPL - original licence link has changed is not relivant.
37043 * <script type="text/javascript">
37048 * @class Roo.menu.ColorMenu
37049 * @extends Roo.menu.Menu
37050 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
37052 * Creates a new ColorMenu
37053 * @param {Object} config Configuration options
37055 Roo.menu.ColorMenu = function(config){
37056 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
37058 var ci = new Roo.menu.ColorItem(config);
37061 * The {@link Roo.ColorPalette} instance for this ColorMenu
37062 * @type ColorPalette
37064 this.palette = ci.palette;
37067 * @param {ColorPalette} palette
37068 * @param {String} color
37070 this.relayEvents(ci, ["select"]);
37072 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
37074 * Ext JS Library 1.1.1
37075 * Copyright(c) 2006-2007, Ext JS, LLC.
37077 * Originally Released Under LGPL - original licence link has changed is not relivant.
37080 * <script type="text/javascript">
37084 * @class Roo.form.Field
37085 * @extends Roo.BoxComponent
37086 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
37088 * Creates a new Field
37089 * @param {Object} config Configuration options
37091 Roo.form.Field = function(config){
37092 Roo.form.Field.superclass.constructor.call(this, config);
37095 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
37097 * @cfg {String} fieldLabel Label to use when rendering a form.
37100 * @cfg {String} qtip Mouse over tip
37104 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
37106 invalidClass : "x-form-invalid",
37108 * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
37110 invalidText : "The value in this field is invalid",
37112 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
37114 focusClass : "x-form-focus",
37116 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
37117 automatic validation (defaults to "keyup").
37119 validationEvent : "keyup",
37121 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
37123 validateOnBlur : true,
37125 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
37127 validationDelay : 250,
37129 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
37130 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
37132 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
37134 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
37136 fieldClass : "x-form-field",
37138 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
37141 ----------- ----------------------------------------------------------------------
37142 qtip Display a quick tip when the user hovers over the field
37143 title Display a default browser title attribute popup
37144 under Add a block div beneath the field containing the error text
37145 side Add an error icon to the right of the field with a popup on hover
37146 [element id] Add the error text directly to the innerHTML of the specified element
37149 msgTarget : 'qtip',
37151 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
37156 * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute.
37161 * @cfg {Boolean} disabled True to disable the field (defaults to false).
37166 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
37168 inputType : undefined,
37171 * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
37173 tabIndex : undefined,
37176 isFormField : true,
37181 * @property {Roo.Element} fieldEl
37182 * Element Containing the rendered Field (with label etc.)
37185 * @cfg {Mixed} value A value to initialize this field with.
37190 * @cfg {String} name The field's HTML name attribute.
37193 * @cfg {String} cls A CSS class to apply to the field's underlying element.
37197 initComponent : function(){
37198 Roo.form.Field.superclass.initComponent.call(this);
37202 * Fires when this field receives input focus.
37203 * @param {Roo.form.Field} this
37208 * Fires when this field loses input focus.
37209 * @param {Roo.form.Field} this
37213 * @event specialkey
37214 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
37215 * {@link Roo.EventObject#getKey} to determine which key was pressed.
37216 * @param {Roo.form.Field} this
37217 * @param {Roo.EventObject} e The event object
37222 * Fires just before the field blurs if the field value has changed.
37223 * @param {Roo.form.Field} this
37224 * @param {Mixed} newValue The new value
37225 * @param {Mixed} oldValue The original value
37230 * Fires after the field has been marked as invalid.
37231 * @param {Roo.form.Field} this
37232 * @param {String} msg The validation message
37237 * Fires after the field has been validated with no errors.
37238 * @param {Roo.form.Field} this
37243 * Fires after the key up
37244 * @param {Roo.form.Field} this
37245 * @param {Roo.EventObject} e The event Object
37252 * Returns the name attribute of the field if available
37253 * @return {String} name The field name
37255 getName: function(){
37256 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
37260 onRender : function(ct, position){
37261 Roo.form.Field.superclass.onRender.call(this, ct, position);
37263 var cfg = this.getAutoCreate();
37265 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
37267 if (!cfg.name.length) {
37270 if(this.inputType){
37271 cfg.type = this.inputType;
37273 this.el = ct.createChild(cfg, position);
37275 var type = this.el.dom.type;
37277 if(type == 'password'){
37280 this.el.addClass('x-form-'+type);
37283 this.el.dom.readOnly = true;
37285 if(this.tabIndex !== undefined){
37286 this.el.dom.setAttribute('tabIndex', this.tabIndex);
37289 this.el.addClass([this.fieldClass, this.cls]);
37294 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
37295 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
37296 * @return {Roo.form.Field} this
37298 applyTo : function(target){
37299 this.allowDomMove = false;
37300 this.el = Roo.get(target);
37301 this.render(this.el.dom.parentNode);
37306 initValue : function(){
37307 if(this.value !== undefined){
37308 this.setValue(this.value);
37309 }else if(this.el.dom.value.length > 0){
37310 this.setValue(this.el.dom.value);
37315 * Returns true if this field has been changed since it was originally loaded and is not disabled.
37317 isDirty : function() {
37318 if(this.disabled) {
37321 return String(this.getValue()) !== String(this.originalValue);
37325 afterRender : function(){
37326 Roo.form.Field.superclass.afterRender.call(this);
37331 fireKey : function(e){
37332 //Roo.log('field ' + e.getKey());
37333 if(e.isNavKeyPress()){
37334 this.fireEvent("specialkey", this, e);
37339 * Resets the current field value to the originally loaded value and clears any validation messages
37341 reset : function(){
37342 this.setValue(this.resetValue);
37343 this.clearInvalid();
37347 initEvents : function(){
37348 // safari killled keypress - so keydown is now used..
37349 this.el.on("keydown" , this.fireKey, this);
37350 this.el.on("focus", this.onFocus, this);
37351 this.el.on("blur", this.onBlur, this);
37352 this.el.relayEvent('keyup', this);
37354 // reference to original value for reset
37355 this.originalValue = this.getValue();
37356 this.resetValue = this.getValue();
37360 onFocus : function(){
37361 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
37362 this.el.addClass(this.focusClass);
37364 if(!this.hasFocus){
37365 this.hasFocus = true;
37366 this.startValue = this.getValue();
37367 this.fireEvent("focus", this);
37371 beforeBlur : Roo.emptyFn,
37374 onBlur : function(){
37376 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
37377 this.el.removeClass(this.focusClass);
37379 this.hasFocus = false;
37380 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
37383 var v = this.getValue();
37384 if(String(v) !== String(this.startValue)){
37385 this.fireEvent('change', this, v, this.startValue);
37387 this.fireEvent("blur", this);
37391 * Returns whether or not the field value is currently valid
37392 * @param {Boolean} preventMark True to disable marking the field invalid
37393 * @return {Boolean} True if the value is valid, else false
37395 isValid : function(preventMark){
37399 var restore = this.preventMark;
37400 this.preventMark = preventMark === true;
37401 var v = this.validateValue(this.processValue(this.getRawValue()));
37402 this.preventMark = restore;
37407 * Validates the field value
37408 * @return {Boolean} True if the value is valid, else false
37410 validate : function(){
37411 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
37412 this.clearInvalid();
37418 processValue : function(value){
37423 // Subclasses should provide the validation implementation by overriding this
37424 validateValue : function(value){
37429 * Mark this field as invalid
37430 * @param {String} msg The validation message
37432 markInvalid : function(msg){
37433 if(!this.rendered || this.preventMark){ // not rendered
37437 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
37439 obj.el.addClass(this.invalidClass);
37440 msg = msg || this.invalidText;
37441 switch(this.msgTarget){
37443 obj.el.dom.qtip = msg;
37444 obj.el.dom.qclass = 'x-form-invalid-tip';
37445 if(Roo.QuickTips){ // fix for floating editors interacting with DND
37446 Roo.QuickTips.enable();
37450 this.el.dom.title = msg;
37454 var elp = this.el.findParent('.x-form-element', 5, true);
37455 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
37456 this.errorEl.setWidth(elp.getWidth(true)-20);
37458 this.errorEl.update(msg);
37459 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
37462 if(!this.errorIcon){
37463 var elp = this.el.findParent('.x-form-element', 5, true);
37464 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
37466 this.alignErrorIcon();
37467 this.errorIcon.dom.qtip = msg;
37468 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
37469 this.errorIcon.show();
37470 this.on('resize', this.alignErrorIcon, this);
37473 var t = Roo.getDom(this.msgTarget);
37475 t.style.display = this.msgDisplay;
37478 this.fireEvent('invalid', this, msg);
37482 alignErrorIcon : function(){
37483 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
37487 * Clear any invalid styles/messages for this field
37489 clearInvalid : function(){
37490 if(!this.rendered || this.preventMark){ // not rendered
37493 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
37495 obj.el.removeClass(this.invalidClass);
37496 switch(this.msgTarget){
37498 obj.el.dom.qtip = '';
37501 this.el.dom.title = '';
37505 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
37509 if(this.errorIcon){
37510 this.errorIcon.dom.qtip = '';
37511 this.errorIcon.hide();
37512 this.un('resize', this.alignErrorIcon, this);
37516 var t = Roo.getDom(this.msgTarget);
37518 t.style.display = 'none';
37521 this.fireEvent('valid', this);
37525 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
37526 * @return {Mixed} value The field value
37528 getRawValue : function(){
37529 var v = this.el.getValue();
37535 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
37536 * @return {Mixed} value The field value
37538 getValue : function(){
37539 var v = this.el.getValue();
37545 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
37546 * @param {Mixed} value The value to set
37548 setRawValue : function(v){
37549 return this.el.dom.value = (v === null || v === undefined ? '' : v);
37553 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
37554 * @param {Mixed} value The value to set
37556 setValue : function(v){
37559 this.el.dom.value = (v === null || v === undefined ? '' : v);
37564 adjustSize : function(w, h){
37565 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
37566 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
37570 adjustWidth : function(tag, w){
37571 tag = tag.toLowerCase();
37572 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
37573 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
37574 if(tag == 'input'){
37577 if(tag == 'textarea'){
37580 }else if(Roo.isOpera){
37581 if(tag == 'input'){
37584 if(tag == 'textarea'){
37594 // anything other than normal should be considered experimental
37595 Roo.form.Field.msgFx = {
37597 show: function(msgEl, f){
37598 msgEl.setDisplayed('block');
37601 hide : function(msgEl, f){
37602 msgEl.setDisplayed(false).update('');
37607 show: function(msgEl, f){
37608 msgEl.slideIn('t', {stopFx:true});
37611 hide : function(msgEl, f){
37612 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
37617 show: function(msgEl, f){
37618 msgEl.fixDisplay();
37619 msgEl.alignTo(f.el, 'tl-tr');
37620 msgEl.slideIn('l', {stopFx:true});
37623 hide : function(msgEl, f){
37624 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
37629 * Ext JS Library 1.1.1
37630 * Copyright(c) 2006-2007, Ext JS, LLC.
37632 * Originally Released Under LGPL - original licence link has changed is not relivant.
37635 * <script type="text/javascript">
37640 * @class Roo.form.TextField
37641 * @extends Roo.form.Field
37642 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
37643 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
37645 * Creates a new TextField
37646 * @param {Object} config Configuration options
37648 Roo.form.TextField = function(config){
37649 Roo.form.TextField.superclass.constructor.call(this, config);
37653 * Fires when the autosize function is triggered. The field may or may not have actually changed size
37654 * according to the default logic, but this event provides a hook for the developer to apply additional
37655 * logic at runtime to resize the field if needed.
37656 * @param {Roo.form.Field} this This text field
37657 * @param {Number} width The new field width
37663 Roo.extend(Roo.form.TextField, Roo.form.Field, {
37665 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
37669 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
37673 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
37677 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
37681 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
37685 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
37687 disableKeyFilter : false,
37689 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
37693 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
37697 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
37699 maxLength : Number.MAX_VALUE,
37701 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
37703 minLengthText : "The minimum length for this field is {0}",
37705 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
37707 maxLengthText : "The maximum length for this field is {0}",
37709 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
37711 selectOnFocus : false,
37713 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
37715 blankText : "This field is required",
37717 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
37718 * If available, this function will be called only after the basic validators all return true, and will be passed the
37719 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
37723 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
37724 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
37725 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
37729 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
37733 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
37739 initEvents : function()
37741 if (this.emptyText) {
37742 this.el.attr('placeholder', this.emptyText);
37745 Roo.form.TextField.superclass.initEvents.call(this);
37746 if(this.validationEvent == 'keyup'){
37747 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
37748 this.el.on('keyup', this.filterValidation, this);
37750 else if(this.validationEvent !== false){
37751 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
37754 if(this.selectOnFocus){
37755 this.on("focus", this.preFocus, this);
37758 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
37759 this.el.on("keypress", this.filterKeys, this);
37762 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
37763 this.el.on("click", this.autoSize, this);
37765 if(this.el.is('input[type=password]') && Roo.isSafari){
37766 this.el.on('keydown', this.SafariOnKeyDown, this);
37770 processValue : function(value){
37771 if(this.stripCharsRe){
37772 var newValue = value.replace(this.stripCharsRe, '');
37773 if(newValue !== value){
37774 this.setRawValue(newValue);
37781 filterValidation : function(e){
37782 if(!e.isNavKeyPress()){
37783 this.validationTask.delay(this.validationDelay);
37788 onKeyUp : function(e){
37789 if(!e.isNavKeyPress()){
37795 * Resets the current field value to the originally-loaded value and clears any validation messages.
37798 reset : function(){
37799 Roo.form.TextField.superclass.reset.call(this);
37805 preFocus : function(){
37807 if(this.selectOnFocus){
37808 this.el.dom.select();
37814 filterKeys : function(e){
37815 var k = e.getKey();
37816 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
37819 var c = e.getCharCode(), cc = String.fromCharCode(c);
37820 if(Roo.isIE && (e.isSpecialKey() || !cc)){
37823 if(!this.maskRe.test(cc)){
37828 setValue : function(v){
37830 Roo.form.TextField.superclass.setValue.apply(this, arguments);
37836 * Validates a value according to the field's validation rules and marks the field as invalid
37837 * if the validation fails
37838 * @param {Mixed} value The value to validate
37839 * @return {Boolean} True if the value is valid, else false
37841 validateValue : function(value){
37842 if(value.length < 1) { // if it's blank
37843 if(this.allowBlank){
37844 this.clearInvalid();
37847 this.markInvalid(this.blankText);
37851 if(value.length < this.minLength){
37852 this.markInvalid(String.format(this.minLengthText, this.minLength));
37855 if(value.length > this.maxLength){
37856 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
37860 var vt = Roo.form.VTypes;
37861 if(!vt[this.vtype](value, this)){
37862 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
37866 if(typeof this.validator == "function"){
37867 var msg = this.validator(value);
37869 this.markInvalid(msg);
37873 if(this.regex && !this.regex.test(value)){
37874 this.markInvalid(this.regexText);
37881 * Selects text in this field
37882 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
37883 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
37885 selectText : function(start, end){
37886 var v = this.getRawValue();
37888 start = start === undefined ? 0 : start;
37889 end = end === undefined ? v.length : end;
37890 var d = this.el.dom;
37891 if(d.setSelectionRange){
37892 d.setSelectionRange(start, end);
37893 }else if(d.createTextRange){
37894 var range = d.createTextRange();
37895 range.moveStart("character", start);
37896 range.moveEnd("character", v.length-end);
37903 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
37904 * This only takes effect if grow = true, and fires the autosize event.
37906 autoSize : function(){
37907 if(!this.grow || !this.rendered){
37911 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
37914 var v = el.dom.value;
37915 var d = document.createElement('div');
37916 d.appendChild(document.createTextNode(v));
37920 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
37921 this.el.setWidth(w);
37922 this.fireEvent("autosize", this, w);
37926 SafariOnKeyDown : function(event)
37928 // this is a workaround for a password hang bug on chrome/ webkit.
37930 var isSelectAll = false;
37932 if(this.el.dom.selectionEnd > 0){
37933 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
37935 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
37936 event.preventDefault();
37941 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
37943 event.preventDefault();
37944 // this is very hacky as keydown always get's upper case.
37946 var cc = String.fromCharCode(event.getCharCode());
37949 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
37957 * Ext JS Library 1.1.1
37958 * Copyright(c) 2006-2007, Ext JS, LLC.
37960 * Originally Released Under LGPL - original licence link has changed is not relivant.
37963 * <script type="text/javascript">
37967 * @class Roo.form.Hidden
37968 * @extends Roo.form.TextField
37969 * Simple Hidden element used on forms
37971 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
37974 * Creates a new Hidden form element.
37975 * @param {Object} config Configuration options
37980 // easy hidden field...
37981 Roo.form.Hidden = function(config){
37982 Roo.form.Hidden.superclass.constructor.call(this, config);
37985 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
37987 inputType: 'hidden',
37990 labelSeparator: '',
37992 itemCls : 'x-form-item-display-none'
38000 * Ext JS Library 1.1.1
38001 * Copyright(c) 2006-2007, Ext JS, LLC.
38003 * Originally Released Under LGPL - original licence link has changed is not relivant.
38006 * <script type="text/javascript">
38010 * @class Roo.form.TriggerField
38011 * @extends Roo.form.TextField
38012 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
38013 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
38014 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
38015 * for which you can provide a custom implementation. For example:
38017 var trigger = new Roo.form.TriggerField();
38018 trigger.onTriggerClick = myTriggerFn;
38019 trigger.applyTo('my-field');
38022 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
38023 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
38024 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
38025 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
38027 * Create a new TriggerField.
38028 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
38029 * to the base TextField)
38031 Roo.form.TriggerField = function(config){
38032 this.mimicing = false;
38033 Roo.form.TriggerField.superclass.constructor.call(this, config);
38036 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
38038 * @cfg {String} triggerClass A CSS class to apply to the trigger
38041 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
38042 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
38044 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
38046 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
38050 /** @cfg {Boolean} grow @hide */
38051 /** @cfg {Number} growMin @hide */
38052 /** @cfg {Number} growMax @hide */
38058 autoSize: Roo.emptyFn,
38062 deferHeight : true,
38065 actionMode : 'wrap',
38067 onResize : function(w, h){
38068 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
38069 if(typeof w == 'number'){
38070 var x = w - this.trigger.getWidth();
38071 this.el.setWidth(this.adjustWidth('input', x));
38072 this.trigger.setStyle('left', x+'px');
38077 adjustSize : Roo.BoxComponent.prototype.adjustSize,
38080 getResizeEl : function(){
38085 getPositionEl : function(){
38090 alignErrorIcon : function(){
38091 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
38095 onRender : function(ct, position){
38096 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
38097 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
38098 this.trigger = this.wrap.createChild(this.triggerConfig ||
38099 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
38100 if(this.hideTrigger){
38101 this.trigger.setDisplayed(false);
38103 this.initTrigger();
38105 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
38110 initTrigger : function(){
38111 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
38112 this.trigger.addClassOnOver('x-form-trigger-over');
38113 this.trigger.addClassOnClick('x-form-trigger-click');
38117 onDestroy : function(){
38119 this.trigger.removeAllListeners();
38120 this.trigger.remove();
38123 this.wrap.remove();
38125 Roo.form.TriggerField.superclass.onDestroy.call(this);
38129 onFocus : function(){
38130 Roo.form.TriggerField.superclass.onFocus.call(this);
38131 if(!this.mimicing){
38132 this.wrap.addClass('x-trigger-wrap-focus');
38133 this.mimicing = true;
38134 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
38135 if(this.monitorTab){
38136 this.el.on("keydown", this.checkTab, this);
38142 checkTab : function(e){
38143 if(e.getKey() == e.TAB){
38144 this.triggerBlur();
38149 onBlur : function(){
38154 mimicBlur : function(e, t){
38155 if(!this.wrap.contains(t) && this.validateBlur()){
38156 this.triggerBlur();
38161 triggerBlur : function(){
38162 this.mimicing = false;
38163 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
38164 if(this.monitorTab){
38165 this.el.un("keydown", this.checkTab, this);
38167 this.wrap.removeClass('x-trigger-wrap-focus');
38168 Roo.form.TriggerField.superclass.onBlur.call(this);
38172 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
38173 validateBlur : function(e, t){
38178 onDisable : function(){
38179 Roo.form.TriggerField.superclass.onDisable.call(this);
38181 this.wrap.addClass('x-item-disabled');
38186 onEnable : function(){
38187 Roo.form.TriggerField.superclass.onEnable.call(this);
38189 this.wrap.removeClass('x-item-disabled');
38194 onShow : function(){
38195 var ae = this.getActionEl();
38198 ae.dom.style.display = '';
38199 ae.dom.style.visibility = 'visible';
38205 onHide : function(){
38206 var ae = this.getActionEl();
38207 ae.dom.style.display = 'none';
38211 * The function that should handle the trigger's click event. This method does nothing by default until overridden
38212 * by an implementing function.
38214 * @param {EventObject} e
38216 onTriggerClick : Roo.emptyFn
38219 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
38220 // to be extended by an implementing class. For an example of implementing this class, see the custom
38221 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
38222 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
38223 initComponent : function(){
38224 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
38226 this.triggerConfig = {
38227 tag:'span', cls:'x-form-twin-triggers', cn:[
38228 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
38229 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
38233 getTrigger : function(index){
38234 return this.triggers[index];
38237 initTrigger : function(){
38238 var ts = this.trigger.select('.x-form-trigger', true);
38239 this.wrap.setStyle('overflow', 'hidden');
38240 var triggerField = this;
38241 ts.each(function(t, all, index){
38242 t.hide = function(){
38243 var w = triggerField.wrap.getWidth();
38244 this.dom.style.display = 'none';
38245 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
38247 t.show = function(){
38248 var w = triggerField.wrap.getWidth();
38249 this.dom.style.display = '';
38250 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
38252 var triggerIndex = 'Trigger'+(index+1);
38254 if(this['hide'+triggerIndex]){
38255 t.dom.style.display = 'none';
38257 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
38258 t.addClassOnOver('x-form-trigger-over');
38259 t.addClassOnClick('x-form-trigger-click');
38261 this.triggers = ts.elements;
38264 onTrigger1Click : Roo.emptyFn,
38265 onTrigger2Click : Roo.emptyFn
38268 * Ext JS Library 1.1.1
38269 * Copyright(c) 2006-2007, Ext JS, LLC.
38271 * Originally Released Under LGPL - original licence link has changed is not relivant.
38274 * <script type="text/javascript">
38278 * @class Roo.form.TextArea
38279 * @extends Roo.form.TextField
38280 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
38281 * support for auto-sizing.
38283 * Creates a new TextArea
38284 * @param {Object} config Configuration options
38286 Roo.form.TextArea = function(config){
38287 Roo.form.TextArea.superclass.constructor.call(this, config);
38288 // these are provided exchanges for backwards compat
38289 // minHeight/maxHeight were replaced by growMin/growMax to be
38290 // compatible with TextField growing config values
38291 if(this.minHeight !== undefined){
38292 this.growMin = this.minHeight;
38294 if(this.maxHeight !== undefined){
38295 this.growMax = this.maxHeight;
38299 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
38301 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
38305 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
38309 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
38310 * in the field (equivalent to setting overflow: hidden, defaults to false)
38312 preventScrollbars: false,
38314 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
38315 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
38319 onRender : function(ct, position){
38321 this.defaultAutoCreate = {
38323 style:"width:300px;height:60px;",
38324 autocomplete: "new-password"
38327 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
38329 this.textSizeEl = Roo.DomHelper.append(document.body, {
38330 tag: "pre", cls: "x-form-grow-sizer"
38332 if(this.preventScrollbars){
38333 this.el.setStyle("overflow", "hidden");
38335 this.el.setHeight(this.growMin);
38339 onDestroy : function(){
38340 if(this.textSizeEl){
38341 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
38343 Roo.form.TextArea.superclass.onDestroy.call(this);
38347 onKeyUp : function(e){
38348 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
38354 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
38355 * This only takes effect if grow = true, and fires the autosize event if the height changes.
38357 autoSize : function(){
38358 if(!this.grow || !this.textSizeEl){
38362 var v = el.dom.value;
38363 var ts = this.textSizeEl;
38366 ts.appendChild(document.createTextNode(v));
38369 Roo.fly(ts).setWidth(this.el.getWidth());
38371 v = "  ";
38374 v = v.replace(/\n/g, '<p> </p>');
38376 v += " \n ";
38379 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
38380 if(h != this.lastHeight){
38381 this.lastHeight = h;
38382 this.el.setHeight(h);
38383 this.fireEvent("autosize", this, h);
38388 * Ext JS Library 1.1.1
38389 * Copyright(c) 2006-2007, Ext JS, LLC.
38391 * Originally Released Under LGPL - original licence link has changed is not relivant.
38394 * <script type="text/javascript">
38399 * @class Roo.form.NumberField
38400 * @extends Roo.form.TextField
38401 * Numeric text field that provides automatic keystroke filtering and numeric validation.
38403 * Creates a new NumberField
38404 * @param {Object} config Configuration options
38406 Roo.form.NumberField = function(config){
38407 Roo.form.NumberField.superclass.constructor.call(this, config);
38410 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
38412 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
38414 fieldClass: "x-form-field x-form-num-field",
38416 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
38418 allowDecimals : true,
38420 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
38422 decimalSeparator : ".",
38424 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
38426 decimalPrecision : 2,
38428 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
38430 allowNegative : true,
38432 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
38434 minValue : Number.NEGATIVE_INFINITY,
38436 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
38438 maxValue : Number.MAX_VALUE,
38440 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
38442 minText : "The minimum value for this field is {0}",
38444 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
38446 maxText : "The maximum value for this field is {0}",
38448 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
38449 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
38451 nanText : "{0} is not a valid number",
38454 initEvents : function(){
38455 Roo.form.NumberField.superclass.initEvents.call(this);
38456 var allowed = "0123456789";
38457 if(this.allowDecimals){
38458 allowed += this.decimalSeparator;
38460 if(this.allowNegative){
38463 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
38464 var keyPress = function(e){
38465 var k = e.getKey();
38466 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
38469 var c = e.getCharCode();
38470 if(allowed.indexOf(String.fromCharCode(c)) === -1){
38474 this.el.on("keypress", keyPress, this);
38478 validateValue : function(value){
38479 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
38482 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
38485 var num = this.parseValue(value);
38487 this.markInvalid(String.format(this.nanText, value));
38490 if(num < this.minValue){
38491 this.markInvalid(String.format(this.minText, this.minValue));
38494 if(num > this.maxValue){
38495 this.markInvalid(String.format(this.maxText, this.maxValue));
38501 getValue : function(){
38502 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
38506 parseValue : function(value){
38507 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
38508 return isNaN(value) ? '' : value;
38512 fixPrecision : function(value){
38513 var nan = isNaN(value);
38514 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
38515 return nan ? '' : value;
38517 return parseFloat(value).toFixed(this.decimalPrecision);
38520 setValue : function(v){
38521 v = this.fixPrecision(v);
38522 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
38526 decimalPrecisionFcn : function(v){
38527 return Math.floor(v);
38530 beforeBlur : function(){
38531 var v = this.parseValue(this.getRawValue());
38538 * Ext JS Library 1.1.1
38539 * Copyright(c) 2006-2007, Ext JS, LLC.
38541 * Originally Released Under LGPL - original licence link has changed is not relivant.
38544 * <script type="text/javascript">
38548 * @class Roo.form.DateField
38549 * @extends Roo.form.TriggerField
38550 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
38552 * Create a new DateField
38553 * @param {Object} config
38555 Roo.form.DateField = function(config){
38556 Roo.form.DateField.superclass.constructor.call(this, config);
38562 * Fires when a date is selected
38563 * @param {Roo.form.DateField} combo This combo box
38564 * @param {Date} date The date selected
38571 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
38572 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
38573 this.ddMatch = null;
38574 if(this.disabledDates){
38575 var dd = this.disabledDates;
38577 for(var i = 0; i < dd.length; i++){
38579 if(i != dd.length-1) re += "|";
38581 this.ddMatch = new RegExp(re + ")");
38585 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
38587 * @cfg {String} format
38588 * The default date format string which can be overriden for localization support. The format must be
38589 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
38593 * @cfg {String} altFormats
38594 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
38595 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
38597 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
38599 * @cfg {Array} disabledDays
38600 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
38602 disabledDays : null,
38604 * @cfg {String} disabledDaysText
38605 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
38607 disabledDaysText : "Disabled",
38609 * @cfg {Array} disabledDates
38610 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
38611 * expression so they are very powerful. Some examples:
38613 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
38614 * <li>["03/08", "09/16"] would disable those days for every year</li>
38615 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
38616 * <li>["03/../2006"] would disable every day in March 2006</li>
38617 * <li>["^03"] would disable every day in every March</li>
38619 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
38620 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
38622 disabledDates : null,
38624 * @cfg {String} disabledDatesText
38625 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
38627 disabledDatesText : "Disabled",
38629 * @cfg {Date/String} minValue
38630 * The minimum allowed date. Can be either a Javascript date object or a string date in a
38631 * valid format (defaults to null).
38635 * @cfg {Date/String} maxValue
38636 * The maximum allowed date. Can be either a Javascript date object or a string date in a
38637 * valid format (defaults to null).
38641 * @cfg {String} minText
38642 * The error text to display when the date in the cell is before minValue (defaults to
38643 * 'The date in this field must be after {minValue}').
38645 minText : "The date in this field must be equal to or after {0}",
38647 * @cfg {String} maxText
38648 * The error text to display when the date in the cell is after maxValue (defaults to
38649 * 'The date in this field must be before {maxValue}').
38651 maxText : "The date in this field must be equal to or before {0}",
38653 * @cfg {String} invalidText
38654 * The error text to display when the date in the field is invalid (defaults to
38655 * '{value} is not a valid date - it must be in the format {format}').
38657 invalidText : "{0} is not a valid date - it must be in the format {1}",
38659 * @cfg {String} triggerClass
38660 * An additional CSS class used to style the trigger button. The trigger will always get the
38661 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
38662 * which displays a calendar icon).
38664 triggerClass : 'x-form-date-trigger',
38668 * @cfg {Boolean} useIso
38669 * if enabled, then the date field will use a hidden field to store the
38670 * real value as iso formated date. default (false)
38674 * @cfg {String/Object} autoCreate
38675 * A DomHelper element spec, or true for a default element spec (defaults to
38676 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
38679 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
38682 hiddenField: false,
38684 onRender : function(ct, position)
38686 Roo.form.DateField.superclass.onRender.call(this, ct, position);
38688 //this.el.dom.removeAttribute('name');
38689 Roo.log("Changing name?");
38690 this.el.dom.setAttribute('name', this.name + '____hidden___' );
38691 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
38693 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
38694 // prevent input submission
38695 this.hiddenName = this.name;
38702 validateValue : function(value)
38704 value = this.formatDate(value);
38705 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
38706 Roo.log('super failed');
38709 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
38712 var svalue = value;
38713 value = this.parseDate(value);
38715 Roo.log('parse date failed' + svalue);
38716 this.markInvalid(String.format(this.invalidText, svalue, this.format));
38719 var time = value.getTime();
38720 if(this.minValue && time < this.minValue.getTime()){
38721 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
38724 if(this.maxValue && time > this.maxValue.getTime()){
38725 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
38728 if(this.disabledDays){
38729 var day = value.getDay();
38730 for(var i = 0; i < this.disabledDays.length; i++) {
38731 if(day === this.disabledDays[i]){
38732 this.markInvalid(this.disabledDaysText);
38737 var fvalue = this.formatDate(value);
38738 if(this.ddMatch && this.ddMatch.test(fvalue)){
38739 this.markInvalid(String.format(this.disabledDatesText, fvalue));
38746 // Provides logic to override the default TriggerField.validateBlur which just returns true
38747 validateBlur : function(){
38748 return !this.menu || !this.menu.isVisible();
38751 getName: function()
38753 // returns hidden if it's set..
38754 if (!this.rendered) {return ''};
38755 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
38760 * Returns the current date value of the date field.
38761 * @return {Date} The date value
38763 getValue : function(){
38765 return this.hiddenField ?
38766 this.hiddenField.value :
38767 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
38771 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
38772 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
38773 * (the default format used is "m/d/y").
38776 //All of these calls set the same date value (May 4, 2006)
38778 //Pass a date object:
38779 var dt = new Date('5/4/06');
38780 dateField.setValue(dt);
38782 //Pass a date string (default format):
38783 dateField.setValue('5/4/06');
38785 //Pass a date string (custom format):
38786 dateField.format = 'Y-m-d';
38787 dateField.setValue('2006-5-4');
38789 * @param {String/Date} date The date or valid date string
38791 setValue : function(date){
38792 if (this.hiddenField) {
38793 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
38795 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
38796 // make sure the value field is always stored as a date..
38797 this.value = this.parseDate(date);
38803 parseDate : function(value){
38804 if(!value || value instanceof Date){
38807 var v = Date.parseDate(value, this.format);
38808 if (!v && this.useIso) {
38809 v = Date.parseDate(value, 'Y-m-d');
38811 if(!v && this.altFormats){
38812 if(!this.altFormatsArray){
38813 this.altFormatsArray = this.altFormats.split("|");
38815 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
38816 v = Date.parseDate(value, this.altFormatsArray[i]);
38823 formatDate : function(date, fmt){
38824 return (!date || !(date instanceof Date)) ?
38825 date : date.dateFormat(fmt || this.format);
38830 select: function(m, d){
38833 this.fireEvent('select', this, d);
38835 show : function(){ // retain focus styling
38839 this.focus.defer(10, this);
38840 var ml = this.menuListeners;
38841 this.menu.un("select", ml.select, this);
38842 this.menu.un("show", ml.show, this);
38843 this.menu.un("hide", ml.hide, this);
38848 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
38849 onTriggerClick : function(){
38853 if(this.menu == null){
38854 this.menu = new Roo.menu.DateMenu();
38856 Roo.apply(this.menu.picker, {
38857 showClear: this.allowBlank,
38858 minDate : this.minValue,
38859 maxDate : this.maxValue,
38860 disabledDatesRE : this.ddMatch,
38861 disabledDatesText : this.disabledDatesText,
38862 disabledDays : this.disabledDays,
38863 disabledDaysText : this.disabledDaysText,
38864 format : this.useIso ? 'Y-m-d' : this.format,
38865 minText : String.format(this.minText, this.formatDate(this.minValue)),
38866 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
38868 this.menu.on(Roo.apply({}, this.menuListeners, {
38871 this.menu.picker.setValue(this.getValue() || new Date());
38872 this.menu.show(this.el, "tl-bl?");
38875 beforeBlur : function(){
38876 var v = this.parseDate(this.getRawValue());
38886 isDirty : function() {
38887 if(this.disabled) {
38891 if(typeof(this.startValue) === 'undefined'){
38895 return String(this.getValue()) !== String(this.startValue);
38900 * Ext JS Library 1.1.1
38901 * Copyright(c) 2006-2007, Ext JS, LLC.
38903 * Originally Released Under LGPL - original licence link has changed is not relivant.
38906 * <script type="text/javascript">
38910 * @class Roo.form.MonthField
38911 * @extends Roo.form.TriggerField
38912 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
38914 * Create a new MonthField
38915 * @param {Object} config
38917 Roo.form.MonthField = function(config){
38919 Roo.form.MonthField.superclass.constructor.call(this, config);
38925 * Fires when a date is selected
38926 * @param {Roo.form.MonthFieeld} combo This combo box
38927 * @param {Date} date The date selected
38934 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
38935 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
38936 this.ddMatch = null;
38937 if(this.disabledDates){
38938 var dd = this.disabledDates;
38940 for(var i = 0; i < dd.length; i++){
38942 if(i != dd.length-1) re += "|";
38944 this.ddMatch = new RegExp(re + ")");
38948 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
38950 * @cfg {String} format
38951 * The default date format string which can be overriden for localization support. The format must be
38952 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
38956 * @cfg {String} altFormats
38957 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
38958 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
38960 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
38962 * @cfg {Array} disabledDays
38963 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
38965 disabledDays : [0,1,2,3,4,5,6],
38967 * @cfg {String} disabledDaysText
38968 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
38970 disabledDaysText : "Disabled",
38972 * @cfg {Array} disabledDates
38973 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
38974 * expression so they are very powerful. Some examples:
38976 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
38977 * <li>["03/08", "09/16"] would disable those days for every year</li>
38978 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
38979 * <li>["03/../2006"] would disable every day in March 2006</li>
38980 * <li>["^03"] would disable every day in every March</li>
38982 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
38983 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
38985 disabledDates : null,
38987 * @cfg {String} disabledDatesText
38988 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
38990 disabledDatesText : "Disabled",
38992 * @cfg {Date/String} minValue
38993 * The minimum allowed date. Can be either a Javascript date object or a string date in a
38994 * valid format (defaults to null).
38998 * @cfg {Date/String} maxValue
38999 * The maximum allowed date. Can be either a Javascript date object or a string date in a
39000 * valid format (defaults to null).
39004 * @cfg {String} minText
39005 * The error text to display when the date in the cell is before minValue (defaults to
39006 * 'The date in this field must be after {minValue}').
39008 minText : "The date in this field must be equal to or after {0}",
39010 * @cfg {String} maxTextf
39011 * The error text to display when the date in the cell is after maxValue (defaults to
39012 * 'The date in this field must be before {maxValue}').
39014 maxText : "The date in this field must be equal to or before {0}",
39016 * @cfg {String} invalidText
39017 * The error text to display when the date in the field is invalid (defaults to
39018 * '{value} is not a valid date - it must be in the format {format}').
39020 invalidText : "{0} is not a valid date - it must be in the format {1}",
39022 * @cfg {String} triggerClass
39023 * An additional CSS class used to style the trigger button. The trigger will always get the
39024 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
39025 * which displays a calendar icon).
39027 triggerClass : 'x-form-date-trigger',
39031 * @cfg {Boolean} useIso
39032 * if enabled, then the date field will use a hidden field to store the
39033 * real value as iso formated date. default (true)
39037 * @cfg {String/Object} autoCreate
39038 * A DomHelper element spec, or true for a default element spec (defaults to
39039 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
39042 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
39045 hiddenField: false,
39047 hideMonthPicker : false,
39049 onRender : function(ct, position)
39051 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
39053 this.el.dom.removeAttribute('name');
39054 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
39056 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
39057 // prevent input submission
39058 this.hiddenName = this.name;
39065 validateValue : function(value)
39067 value = this.formatDate(value);
39068 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
39071 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
39074 var svalue = value;
39075 value = this.parseDate(value);
39077 this.markInvalid(String.format(this.invalidText, svalue, this.format));
39080 var time = value.getTime();
39081 if(this.minValue && time < this.minValue.getTime()){
39082 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
39085 if(this.maxValue && time > this.maxValue.getTime()){
39086 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
39089 /*if(this.disabledDays){
39090 var day = value.getDay();
39091 for(var i = 0; i < this.disabledDays.length; i++) {
39092 if(day === this.disabledDays[i]){
39093 this.markInvalid(this.disabledDaysText);
39099 var fvalue = this.formatDate(value);
39100 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
39101 this.markInvalid(String.format(this.disabledDatesText, fvalue));
39109 // Provides logic to override the default TriggerField.validateBlur which just returns true
39110 validateBlur : function(){
39111 return !this.menu || !this.menu.isVisible();
39115 * Returns the current date value of the date field.
39116 * @return {Date} The date value
39118 getValue : function(){
39122 return this.hiddenField ?
39123 this.hiddenField.value :
39124 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
39128 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
39129 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
39130 * (the default format used is "m/d/y").
39133 //All of these calls set the same date value (May 4, 2006)
39135 //Pass a date object:
39136 var dt = new Date('5/4/06');
39137 monthField.setValue(dt);
39139 //Pass a date string (default format):
39140 monthField.setValue('5/4/06');
39142 //Pass a date string (custom format):
39143 monthField.format = 'Y-m-d';
39144 monthField.setValue('2006-5-4');
39146 * @param {String/Date} date The date or valid date string
39148 setValue : function(date){
39149 Roo.log('month setValue' + date);
39150 // can only be first of month..
39152 var val = this.parseDate(date);
39154 if (this.hiddenField) {
39155 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
39157 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
39158 this.value = this.parseDate(date);
39162 parseDate : function(value){
39163 if(!value || value instanceof Date){
39164 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
39167 var v = Date.parseDate(value, this.format);
39168 if (!v && this.useIso) {
39169 v = Date.parseDate(value, 'Y-m-d');
39173 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
39177 if(!v && this.altFormats){
39178 if(!this.altFormatsArray){
39179 this.altFormatsArray = this.altFormats.split("|");
39181 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
39182 v = Date.parseDate(value, this.altFormatsArray[i]);
39189 formatDate : function(date, fmt){
39190 return (!date || !(date instanceof Date)) ?
39191 date : date.dateFormat(fmt || this.format);
39196 select: function(m, d){
39198 this.fireEvent('select', this, d);
39200 show : function(){ // retain focus styling
39204 this.focus.defer(10, this);
39205 var ml = this.menuListeners;
39206 this.menu.un("select", ml.select, this);
39207 this.menu.un("show", ml.show, this);
39208 this.menu.un("hide", ml.hide, this);
39212 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
39213 onTriggerClick : function(){
39217 if(this.menu == null){
39218 this.menu = new Roo.menu.DateMenu();
39222 Roo.apply(this.menu.picker, {
39224 showClear: this.allowBlank,
39225 minDate : this.minValue,
39226 maxDate : this.maxValue,
39227 disabledDatesRE : this.ddMatch,
39228 disabledDatesText : this.disabledDatesText,
39230 format : this.useIso ? 'Y-m-d' : this.format,
39231 minText : String.format(this.minText, this.formatDate(this.minValue)),
39232 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
39235 this.menu.on(Roo.apply({}, this.menuListeners, {
39243 // hide month picker get's called when we called by 'before hide';
39245 var ignorehide = true;
39246 p.hideMonthPicker = function(disableAnim){
39250 if(this.monthPicker){
39251 Roo.log("hideMonthPicker called");
39252 if(disableAnim === true){
39253 this.monthPicker.hide();
39255 this.monthPicker.slideOut('t', {duration:.2});
39256 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
39257 p.fireEvent("select", this, this.value);
39263 Roo.log('picker set value');
39264 Roo.log(this.getValue());
39265 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
39266 m.show(this.el, 'tl-bl?');
39267 ignorehide = false;
39268 // this will trigger hideMonthPicker..
39271 // hidden the day picker
39272 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
39278 p.showMonthPicker.defer(100, p);
39284 beforeBlur : function(){
39285 var v = this.parseDate(this.getRawValue());
39291 /** @cfg {Boolean} grow @hide */
39292 /** @cfg {Number} growMin @hide */
39293 /** @cfg {Number} growMax @hide */
39300 * Ext JS Library 1.1.1
39301 * Copyright(c) 2006-2007, Ext JS, LLC.
39303 * Originally Released Under LGPL - original licence link has changed is not relivant.
39306 * <script type="text/javascript">
39311 * @class Roo.form.ComboBox
39312 * @extends Roo.form.TriggerField
39313 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
39315 * Create a new ComboBox.
39316 * @param {Object} config Configuration options
39318 Roo.form.ComboBox = function(config){
39319 Roo.form.ComboBox.superclass.constructor.call(this, config);
39323 * Fires when the dropdown list is expanded
39324 * @param {Roo.form.ComboBox} combo This combo box
39329 * Fires when the dropdown list is collapsed
39330 * @param {Roo.form.ComboBox} combo This combo box
39334 * @event beforeselect
39335 * Fires before a list item is selected. Return false to cancel the selection.
39336 * @param {Roo.form.ComboBox} combo This combo box
39337 * @param {Roo.data.Record} record The data record returned from the underlying store
39338 * @param {Number} index The index of the selected item in the dropdown list
39340 'beforeselect' : true,
39343 * Fires when a list item is selected
39344 * @param {Roo.form.ComboBox} combo This combo box
39345 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
39346 * @param {Number} index The index of the selected item in the dropdown list
39350 * @event beforequery
39351 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
39352 * The event object passed has these properties:
39353 * @param {Roo.form.ComboBox} combo This combo box
39354 * @param {String} query The query
39355 * @param {Boolean} forceAll true to force "all" query
39356 * @param {Boolean} cancel true to cancel the query
39357 * @param {Object} e The query event object
39359 'beforequery': true,
39362 * Fires when the 'add' icon is pressed (add a listener to enable add button)
39363 * @param {Roo.form.ComboBox} combo This combo box
39368 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
39369 * @param {Roo.form.ComboBox} combo This combo box
39370 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
39376 if(this.transform){
39377 this.allowDomMove = false;
39378 var s = Roo.getDom(this.transform);
39379 if(!this.hiddenName){
39380 this.hiddenName = s.name;
39383 this.mode = 'local';
39384 var d = [], opts = s.options;
39385 for(var i = 0, len = opts.length;i < len; i++){
39387 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
39389 this.value = value;
39391 d.push([value, o.text]);
39393 this.store = new Roo.data.SimpleStore({
39395 fields: ['value', 'text'],
39398 this.valueField = 'value';
39399 this.displayField = 'text';
39401 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
39402 if(!this.lazyRender){
39403 this.target = true;
39404 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
39405 s.parentNode.removeChild(s); // remove it
39406 this.render(this.el.parentNode);
39408 s.parentNode.removeChild(s); // remove it
39413 this.store = Roo.factory(this.store, Roo.data);
39416 this.selectedIndex = -1;
39417 if(this.mode == 'local'){
39418 if(config.queryDelay === undefined){
39419 this.queryDelay = 10;
39421 if(config.minChars === undefined){
39427 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
39429 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
39432 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
39433 * rendering into an Roo.Editor, defaults to false)
39436 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
39437 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
39440 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
39443 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
39444 * the dropdown list (defaults to undefined, with no header element)
39448 * @cfg {String/Roo.Template} tpl The template to use to render the output
39452 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
39454 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
39456 listWidth: undefined,
39458 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
39459 * mode = 'remote' or 'text' if mode = 'local')
39461 displayField: undefined,
39463 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
39464 * mode = 'remote' or 'value' if mode = 'local').
39465 * Note: use of a valueField requires the user make a selection
39466 * in order for a value to be mapped.
39468 valueField: undefined,
39472 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
39473 * field's data value (defaults to the underlying DOM element's name)
39475 hiddenName: undefined,
39477 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
39481 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
39483 selectedClass: 'x-combo-selected',
39485 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
39486 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
39487 * which displays a downward arrow icon).
39489 triggerClass : 'x-form-arrow-trigger',
39491 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
39495 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
39496 * anchor positions (defaults to 'tl-bl')
39498 listAlign: 'tl-bl?',
39500 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
39504 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
39505 * query specified by the allQuery config option (defaults to 'query')
39507 triggerAction: 'query',
39509 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
39510 * (defaults to 4, does not apply if editable = false)
39514 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
39515 * delay (typeAheadDelay) if it matches a known value (defaults to false)
39519 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
39520 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
39524 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
39525 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
39529 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
39530 * when editable = true (defaults to false)
39532 selectOnFocus:false,
39534 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
39536 queryParam: 'query',
39538 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
39539 * when mode = 'remote' (defaults to 'Loading...')
39541 loadingText: 'Loading...',
39543 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
39547 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
39551 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
39552 * traditional select (defaults to true)
39556 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
39560 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
39564 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
39565 * listWidth has a higher value)
39569 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
39570 * allow the user to set arbitrary text into the field (defaults to false)
39572 forceSelection:false,
39574 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
39575 * if typeAhead = true (defaults to 250)
39577 typeAheadDelay : 250,
39579 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
39580 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
39582 valueNotFoundText : undefined,
39584 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
39586 blockFocus : false,
39589 * @cfg {Boolean} disableClear Disable showing of clear button.
39591 disableClear : false,
39593 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
39595 alwaysQuery : false,
39601 // element that contains real text value.. (when hidden is used..)
39604 onRender : function(ct, position){
39605 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
39606 if(this.hiddenName){
39607 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
39609 this.hiddenField.value =
39610 this.hiddenValue !== undefined ? this.hiddenValue :
39611 this.value !== undefined ? this.value : '';
39613 // prevent input submission
39614 this.el.dom.removeAttribute('name');
39619 this.el.dom.setAttribute('autocomplete', 'off');
39622 var cls = 'x-combo-list';
39624 this.list = new Roo.Layer({
39625 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
39628 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
39629 this.list.setWidth(lw);
39630 this.list.swallowEvent('mousewheel');
39631 this.assetHeight = 0;
39634 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
39635 this.assetHeight += this.header.getHeight();
39638 this.innerList = this.list.createChild({cls:cls+'-inner'});
39639 this.innerList.on('mouseover', this.onViewOver, this);
39640 this.innerList.on('mousemove', this.onViewMove, this);
39641 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
39643 if(this.allowBlank && !this.pageSize && !this.disableClear){
39644 this.footer = this.list.createChild({cls:cls+'-ft'});
39645 this.pageTb = new Roo.Toolbar(this.footer);
39649 this.footer = this.list.createChild({cls:cls+'-ft'});
39650 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
39651 {pageSize: this.pageSize});
39655 if (this.pageTb && this.allowBlank && !this.disableClear) {
39657 this.pageTb.add(new Roo.Toolbar.Fill(), {
39658 cls: 'x-btn-icon x-btn-clear',
39660 handler: function()
39663 _this.clearValue();
39664 _this.onSelect(false, -1);
39669 this.assetHeight += this.footer.getHeight();
39674 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
39677 this.view = new Roo.View(this.innerList, this.tpl, {
39678 singleSelect:true, store: this.store, selectedClass: this.selectedClass
39681 this.view.on('click', this.onViewClick, this);
39683 this.store.on('beforeload', this.onBeforeLoad, this);
39684 this.store.on('load', this.onLoad, this);
39685 this.store.on('loadexception', this.onLoadException, this);
39687 if(this.resizable){
39688 this.resizer = new Roo.Resizable(this.list, {
39689 pinned:true, handles:'se'
39691 this.resizer.on('resize', function(r, w, h){
39692 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
39693 this.listWidth = w;
39694 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
39695 this.restrictHeight();
39697 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
39699 if(!this.editable){
39700 this.editable = true;
39701 this.setEditable(false);
39705 if (typeof(this.events.add.listeners) != 'undefined') {
39707 this.addicon = this.wrap.createChild(
39708 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
39710 this.addicon.on('click', function(e) {
39711 this.fireEvent('add', this);
39714 if (typeof(this.events.edit.listeners) != 'undefined') {
39716 this.editicon = this.wrap.createChild(
39717 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
39718 if (this.addicon) {
39719 this.editicon.setStyle('margin-left', '40px');
39721 this.editicon.on('click', function(e) {
39723 // we fire even if inothing is selected..
39724 this.fireEvent('edit', this, this.lastData );
39734 initEvents : function(){
39735 Roo.form.ComboBox.superclass.initEvents.call(this);
39737 this.keyNav = new Roo.KeyNav(this.el, {
39738 "up" : function(e){
39739 this.inKeyMode = true;
39743 "down" : function(e){
39744 if(!this.isExpanded()){
39745 this.onTriggerClick();
39747 this.inKeyMode = true;
39752 "enter" : function(e){
39753 this.onViewClick();
39757 "esc" : function(e){
39761 "tab" : function(e){
39762 this.onViewClick(false);
39763 this.fireEvent("specialkey", this, e);
39769 doRelay : function(foo, bar, hname){
39770 if(hname == 'down' || this.scope.isExpanded()){
39771 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
39778 this.queryDelay = Math.max(this.queryDelay || 10,
39779 this.mode == 'local' ? 10 : 250);
39780 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
39781 if(this.typeAhead){
39782 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
39784 if(this.editable !== false){
39785 this.el.on("keyup", this.onKeyUp, this);
39787 if(this.forceSelection){
39788 this.on('blur', this.doForce, this);
39792 onDestroy : function(){
39794 this.view.setStore(null);
39795 this.view.el.removeAllListeners();
39796 this.view.el.remove();
39797 this.view.purgeListeners();
39800 this.list.destroy();
39803 this.store.un('beforeload', this.onBeforeLoad, this);
39804 this.store.un('load', this.onLoad, this);
39805 this.store.un('loadexception', this.onLoadException, this);
39807 Roo.form.ComboBox.superclass.onDestroy.call(this);
39811 fireKey : function(e){
39812 if(e.isNavKeyPress() && !this.list.isVisible()){
39813 this.fireEvent("specialkey", this, e);
39818 onResize: function(w, h){
39819 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
39821 if(typeof w != 'number'){
39822 // we do not handle it!?!?
39825 var tw = this.trigger.getWidth();
39826 tw += this.addicon ? this.addicon.getWidth() : 0;
39827 tw += this.editicon ? this.editicon.getWidth() : 0;
39829 this.el.setWidth( this.adjustWidth('input', x));
39831 this.trigger.setStyle('left', x+'px');
39833 if(this.list && this.listWidth === undefined){
39834 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
39835 this.list.setWidth(lw);
39836 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
39844 * Allow or prevent the user from directly editing the field text. If false is passed,
39845 * the user will only be able to select from the items defined in the dropdown list. This method
39846 * is the runtime equivalent of setting the 'editable' config option at config time.
39847 * @param {Boolean} value True to allow the user to directly edit the field text
39849 setEditable : function(value){
39850 if(value == this.editable){
39853 this.editable = value;
39855 this.el.dom.setAttribute('readOnly', true);
39856 this.el.on('mousedown', this.onTriggerClick, this);
39857 this.el.addClass('x-combo-noedit');
39859 this.el.dom.setAttribute('readOnly', false);
39860 this.el.un('mousedown', this.onTriggerClick, this);
39861 this.el.removeClass('x-combo-noedit');
39866 onBeforeLoad : function(){
39867 if(!this.hasFocus){
39870 this.innerList.update(this.loadingText ?
39871 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
39872 this.restrictHeight();
39873 this.selectedIndex = -1;
39877 onLoad : function(){
39878 if(!this.hasFocus){
39881 if(this.store.getCount() > 0){
39883 this.restrictHeight();
39884 if(this.lastQuery == this.allQuery){
39886 this.el.dom.select();
39888 if(!this.selectByValue(this.value, true)){
39889 this.select(0, true);
39893 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
39894 this.taTask.delay(this.typeAheadDelay);
39898 this.onEmptyResults();
39903 onLoadException : function()
39906 Roo.log(this.store.reader.jsonData);
39907 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
39908 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
39914 onTypeAhead : function(){
39915 if(this.store.getCount() > 0){
39916 var r = this.store.getAt(0);
39917 var newValue = r.data[this.displayField];
39918 var len = newValue.length;
39919 var selStart = this.getRawValue().length;
39920 if(selStart != len){
39921 this.setRawValue(newValue);
39922 this.selectText(selStart, newValue.length);
39928 onSelect : function(record, index){
39929 if(this.fireEvent('beforeselect', this, record, index) !== false){
39930 this.setFromData(index > -1 ? record.data : false);
39932 this.fireEvent('select', this, record, index);
39937 * Returns the currently selected field value or empty string if no value is set.
39938 * @return {String} value The selected value
39940 getValue : function(){
39941 if(this.valueField){
39942 return typeof this.value != 'undefined' ? this.value : '';
39944 return Roo.form.ComboBox.superclass.getValue.call(this);
39948 * Clears any text/value currently set in the field
39950 clearValue : function(){
39951 if(this.hiddenField){
39952 this.hiddenField.value = '';
39955 this.setRawValue('');
39956 this.lastSelectionText = '';
39961 * Sets the specified value into the field. If the value finds a match, the corresponding record text
39962 * will be displayed in the field. If the value does not match the data value of an existing item,
39963 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
39964 * Otherwise the field will be blank (although the value will still be set).
39965 * @param {String} value The value to match
39967 setValue : function(v){
39969 if(this.valueField){
39970 var r = this.findRecord(this.valueField, v);
39972 text = r.data[this.displayField];
39973 }else if(this.valueNotFoundText !== undefined){
39974 text = this.valueNotFoundText;
39977 this.lastSelectionText = text;
39978 if(this.hiddenField){
39979 this.hiddenField.value = v;
39981 Roo.form.ComboBox.superclass.setValue.call(this, text);
39985 * @property {Object} the last set data for the element
39990 * Sets the value of the field based on a object which is related to the record format for the store.
39991 * @param {Object} value the value to set as. or false on reset?
39993 setFromData : function(o){
39994 var dv = ''; // display value
39995 var vv = ''; // value value..
39997 if (this.displayField) {
39998 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
40000 // this is an error condition!!!
40001 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
40004 if(this.valueField){
40005 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
40007 if(this.hiddenField){
40008 this.hiddenField.value = vv;
40010 this.lastSelectionText = dv;
40011 Roo.form.ComboBox.superclass.setValue.call(this, dv);
40015 // no hidden field.. - we store the value in 'value', but still display
40016 // display field!!!!
40017 this.lastSelectionText = dv;
40018 Roo.form.ComboBox.superclass.setValue.call(this, dv);
40024 reset : function(){
40025 // overridden so that last data is reset..
40026 this.setValue(this.resetValue);
40027 this.clearInvalid();
40028 this.lastData = false;
40030 this.view.clearSelections();
40034 findRecord : function(prop, value){
40036 if(this.store.getCount() > 0){
40037 this.store.each(function(r){
40038 if(r.data[prop] == value){
40048 getName: function()
40050 // returns hidden if it's set..
40051 if (!this.rendered) {return ''};
40052 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40056 onViewMove : function(e, t){
40057 this.inKeyMode = false;
40061 onViewOver : function(e, t){
40062 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
40065 var item = this.view.findItemFromChild(t);
40067 var index = this.view.indexOf(item);
40068 this.select(index, false);
40073 onViewClick : function(doFocus)
40075 var index = this.view.getSelectedIndexes()[0];
40076 var r = this.store.getAt(index);
40078 this.onSelect(r, index);
40080 if(doFocus !== false && !this.blockFocus){
40086 restrictHeight : function(){
40087 this.innerList.dom.style.height = '';
40088 var inner = this.innerList.dom;
40089 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
40090 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
40091 this.list.beginUpdate();
40092 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
40093 this.list.alignTo(this.el, this.listAlign);
40094 this.list.endUpdate();
40098 onEmptyResults : function(){
40103 * Returns true if the dropdown list is expanded, else false.
40105 isExpanded : function(){
40106 return this.list.isVisible();
40110 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
40111 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
40112 * @param {String} value The data value of the item to select
40113 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
40114 * selected item if it is not currently in view (defaults to true)
40115 * @return {Boolean} True if the value matched an item in the list, else false
40117 selectByValue : function(v, scrollIntoView){
40118 if(v !== undefined && v !== null){
40119 var r = this.findRecord(this.valueField || this.displayField, v);
40121 this.select(this.store.indexOf(r), scrollIntoView);
40129 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
40130 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
40131 * @param {Number} index The zero-based index of the list item to select
40132 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
40133 * selected item if it is not currently in view (defaults to true)
40135 select : function(index, scrollIntoView){
40136 this.selectedIndex = index;
40137 this.view.select(index);
40138 if(scrollIntoView !== false){
40139 var el = this.view.getNode(index);
40141 this.innerList.scrollChildIntoView(el, false);
40147 selectNext : function(){
40148 var ct = this.store.getCount();
40150 if(this.selectedIndex == -1){
40152 }else if(this.selectedIndex < ct-1){
40153 this.select(this.selectedIndex+1);
40159 selectPrev : function(){
40160 var ct = this.store.getCount();
40162 if(this.selectedIndex == -1){
40164 }else if(this.selectedIndex != 0){
40165 this.select(this.selectedIndex-1);
40171 onKeyUp : function(e){
40172 if(this.editable !== false && !e.isSpecialKey()){
40173 this.lastKey = e.getKey();
40174 this.dqTask.delay(this.queryDelay);
40179 validateBlur : function(){
40180 return !this.list || !this.list.isVisible();
40184 initQuery : function(){
40185 this.doQuery(this.getRawValue());
40189 doForce : function(){
40190 if(this.el.dom.value.length > 0){
40191 this.el.dom.value =
40192 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
40198 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
40199 * query allowing the query action to be canceled if needed.
40200 * @param {String} query The SQL query to execute
40201 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
40202 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
40203 * saved in the current store (defaults to false)
40205 doQuery : function(q, forceAll){
40206 if(q === undefined || q === null){
40211 forceAll: forceAll,
40215 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
40219 forceAll = qe.forceAll;
40220 if(forceAll === true || (q.length >= this.minChars)){
40221 if(this.lastQuery != q || this.alwaysQuery){
40222 this.lastQuery = q;
40223 if(this.mode == 'local'){
40224 this.selectedIndex = -1;
40226 this.store.clearFilter();
40228 this.store.filter(this.displayField, q);
40232 this.store.baseParams[this.queryParam] = q;
40234 params: this.getParams(q)
40239 this.selectedIndex = -1;
40246 getParams : function(q){
40248 //p[this.queryParam] = q;
40251 p.limit = this.pageSize;
40257 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
40259 collapse : function(){
40260 if(!this.isExpanded()){
40264 Roo.get(document).un('mousedown', this.collapseIf, this);
40265 Roo.get(document).un('mousewheel', this.collapseIf, this);
40266 if (!this.editable) {
40267 Roo.get(document).un('keydown', this.listKeyPress, this);
40269 this.fireEvent('collapse', this);
40273 collapseIf : function(e){
40274 if(!e.within(this.wrap) && !e.within(this.list)){
40280 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
40282 expand : function(){
40283 if(this.isExpanded() || !this.hasFocus){
40286 this.list.alignTo(this.el, this.listAlign);
40288 Roo.get(document).on('mousedown', this.collapseIf, this);
40289 Roo.get(document).on('mousewheel', this.collapseIf, this);
40290 if (!this.editable) {
40291 Roo.get(document).on('keydown', this.listKeyPress, this);
40294 this.fireEvent('expand', this);
40298 // Implements the default empty TriggerField.onTriggerClick function
40299 onTriggerClick : function(){
40303 if(this.isExpanded()){
40305 if (!this.blockFocus) {
40310 this.hasFocus = true;
40311 if(this.triggerAction == 'all') {
40312 this.doQuery(this.allQuery, true);
40314 this.doQuery(this.getRawValue());
40316 if (!this.blockFocus) {
40321 listKeyPress : function(e)
40323 //Roo.log('listkeypress');
40324 // scroll to first matching element based on key pres..
40325 if (e.isSpecialKey()) {
40328 var k = String.fromCharCode(e.getKey()).toUpperCase();
40331 var csel = this.view.getSelectedNodes();
40332 var cselitem = false;
40334 var ix = this.view.indexOf(csel[0]);
40335 cselitem = this.store.getAt(ix);
40336 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
40342 this.store.each(function(v) {
40344 // start at existing selection.
40345 if (cselitem.id == v.id) {
40351 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
40352 match = this.store.indexOf(v);
40357 if (match === false) {
40358 return true; // no more action?
40361 this.view.select(match);
40362 var sn = Roo.get(this.view.getSelectedNodes()[0])
40363 sn.scrollIntoView(sn.dom.parentNode, false);
40367 * @cfg {Boolean} grow
40371 * @cfg {Number} growMin
40375 * @cfg {Number} growMax
40383 * Copyright(c) 2010-2012, Roo J Solutions Limited
40390 * @class Roo.form.ComboBoxArray
40391 * @extends Roo.form.TextField
40392 * A facebook style adder... for lists of email / people / countries etc...
40393 * pick multiple items from a combo box, and shows each one.
40395 * Fred [x] Brian [x] [Pick another |v]
40398 * For this to work: it needs various extra information
40399 * - normal combo problay has
40401 * + displayField, valueField
40403 * For our purpose...
40406 * If we change from 'extends' to wrapping...
40413 * Create a new ComboBoxArray.
40414 * @param {Object} config Configuration options
40418 Roo.form.ComboBoxArray = function(config)
40422 * @event beforeremove
40423 * Fires before remove the value from the list
40424 * @param {Roo.form.ComboBoxArray} _self This combo box array
40425 * @param {Roo.form.ComboBoxArray.Item} item removed item
40427 'beforeremove' : true,
40430 * Fires when remove the value from the list
40431 * @param {Roo.form.ComboBoxArray} _self This combo box array
40432 * @param {Roo.form.ComboBoxArray.Item} item removed item
40439 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
40441 this.items = new Roo.util.MixedCollection(false);
40443 // construct the child combo...
40453 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
40456 * @cfg {Roo.form.Combo} combo The combo box that is wrapped
40461 // behavies liek a hiddne field
40462 inputType: 'hidden',
40464 * @cfg {Number} width The width of the box that displays the selected element
40471 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
40475 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
40477 hiddenName : false,
40480 // private the array of items that are displayed..
40482 // private - the hidden field el.
40484 // private - the filed el..
40487 //validateValue : function() { return true; }, // all values are ok!
40488 //onAddClick: function() { },
40490 onRender : function(ct, position)
40493 // create the standard hidden element
40494 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
40497 // give fake names to child combo;
40498 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
40499 this.combo.name = this.name? (this.name+'-subcombo') : this.name;
40501 this.combo = Roo.factory(this.combo, Roo.form);
40502 this.combo.onRender(ct, position);
40503 if (typeof(this.combo.width) != 'undefined') {
40504 this.combo.onResize(this.combo.width,0);
40507 this.combo.initEvents();
40509 // assigned so form know we need to do this..
40510 this.store = this.combo.store;
40511 this.valueField = this.combo.valueField;
40512 this.displayField = this.combo.displayField ;
40515 this.combo.wrap.addClass('x-cbarray-grp');
40517 var cbwrap = this.combo.wrap.createChild(
40518 {tag: 'div', cls: 'x-cbarray-cb'},
40523 this.hiddenEl = this.combo.wrap.createChild({
40524 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
40526 this.el = this.combo.wrap.createChild({
40527 tag: 'input', type:'hidden' , name: this.name, value : ''
40529 // this.el.dom.removeAttribute("name");
40532 this.outerWrap = this.combo.wrap;
40533 this.wrap = cbwrap;
40535 this.outerWrap.setWidth(this.width);
40536 this.outerWrap.dom.removeChild(this.el.dom);
40538 this.wrap.dom.appendChild(this.el.dom);
40539 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
40540 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
40542 this.combo.trigger.setStyle('position','relative');
40543 this.combo.trigger.setStyle('left', '0px');
40544 this.combo.trigger.setStyle('top', '2px');
40546 this.combo.el.setStyle('vertical-align', 'text-bottom');
40548 //this.trigger.setStyle('vertical-align', 'top');
40550 // this should use the code from combo really... on('add' ....)
40554 this.adder = this.outerWrap.createChild(
40555 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
40557 this.adder.on('click', function(e) {
40558 _t.fireEvent('adderclick', this, e);
40562 //this.adder.on('click', this.onAddClick, _t);
40565 this.combo.on('select', function(cb, rec, ix) {
40566 this.addItem(rec.data);
40569 cb.el.dom.value = '';
40570 //cb.lastData = rec.data;
40579 getName: function()
40581 // returns hidden if it's set..
40582 if (!this.rendered) {return ''};
40583 return this.hiddenName ? this.hiddenName : this.name;
40588 onResize: function(w, h){
40591 // not sure if this is needed..
40592 //this.combo.onResize(w,h);
40594 if(typeof w != 'number'){
40595 // we do not handle it!?!?
40598 var tw = this.combo.trigger.getWidth();
40599 tw += this.addicon ? this.addicon.getWidth() : 0;
40600 tw += this.editicon ? this.editicon.getWidth() : 0;
40602 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
40604 this.combo.trigger.setStyle('left', '0px');
40606 if(this.list && this.listWidth === undefined){
40607 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
40608 this.list.setWidth(lw);
40609 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
40616 addItem: function(rec)
40618 var valueField = this.combo.valueField;
40619 var displayField = this.combo.displayField;
40620 if (this.items.indexOfKey(rec[valueField]) > -1) {
40621 //console.log("GOT " + rec.data.id);
40625 var x = new Roo.form.ComboBoxArray.Item({
40626 //id : rec[this.idField],
40628 displayField : displayField ,
40629 tipField : displayField ,
40633 this.items.add(rec[valueField],x);
40634 // add it before the element..
40635 this.updateHiddenEl();
40636 x.render(this.outerWrap, this.wrap.dom);
40637 // add the image handler..
40640 updateHiddenEl : function()
40643 if (!this.hiddenEl) {
40647 var idField = this.combo.valueField;
40649 this.items.each(function(f) {
40650 ar.push(f.data[idField]);
40653 this.hiddenEl.dom.value = ar.join(',');
40659 //Roo.form.ComboBoxArray.superclass.reset.call(this);
40660 this.items.each(function(f) {
40663 this.el.dom.value = '';
40664 if (this.hiddenEl) {
40665 this.hiddenEl.dom.value = '';
40669 getValue: function()
40671 return this.hiddenEl ? this.hiddenEl.dom.value : '';
40673 setValue: function(v) // not a valid action - must use addItems..
40680 if (this.store.isLocal && (typeof(v) == 'string')) {
40681 // then we can use the store to find the values..
40682 // comma seperated at present.. this needs to allow JSON based encoding..
40683 this.hiddenEl.value = v;
40685 Roo.each(v.split(','), function(k) {
40686 Roo.log("CHECK " + this.valueField + ',' + k);
40687 var li = this.store.query(this.valueField, k);
40692 add[this.valueField] = k;
40693 add[this.displayField] = li.item(0).data[this.displayField];
40699 if (typeof(v) == 'object' ) {
40700 // then let's assume it's an array of objects..
40701 Roo.each(v, function(l) {
40709 setFromData: function(v)
40711 // this recieves an object, if setValues is called.
40713 this.el.dom.value = v[this.displayField];
40714 this.hiddenEl.dom.value = v[this.valueField];
40715 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
40718 var kv = v[this.valueField];
40719 var dv = v[this.displayField];
40720 kv = typeof(kv) != 'string' ? '' : kv;
40721 dv = typeof(dv) != 'string' ? '' : dv;
40724 var keys = kv.split(',');
40725 var display = dv.split(',');
40726 for (var i = 0 ; i < keys.length; i++) {
40729 add[this.valueField] = keys[i];
40730 add[this.displayField] = display[i];
40738 * Validates the combox array value
40739 * @return {Boolean} True if the value is valid, else false
40741 validate : function(){
40742 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
40743 this.clearInvalid();
40749 validateValue : function(value){
40750 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
40758 isDirty : function() {
40759 if(this.disabled) {
40764 var d = Roo.decode(String(this.originalValue));
40766 return String(this.getValue()) !== String(this.originalValue);
40769 var originalValue = [];
40771 for (var i = 0; i < d.length; i++){
40772 originalValue.push(d[i][this.valueField]);
40775 return String(this.getValue()) !== String(originalValue.join(','));
40784 * @class Roo.form.ComboBoxArray.Item
40785 * @extends Roo.BoxComponent
40786 * A selected item in the list
40787 * Fred [x] Brian [x] [Pick another |v]
40790 * Create a new item.
40791 * @param {Object} config Configuration options
40794 Roo.form.ComboBoxArray.Item = function(config) {
40795 config.id = Roo.id();
40796 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
40799 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
40802 displayField : false,
40806 defaultAutoCreate : {
40808 cls: 'x-cbarray-item',
40815 src : Roo.BLANK_IMAGE_URL ,
40823 onRender : function(ct, position)
40825 Roo.form.Field.superclass.onRender.call(this, ct, position);
40828 var cfg = this.getAutoCreate();
40829 this.el = ct.createChild(cfg, position);
40832 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
40834 this.el.child('div').dom.innerHTML = this.cb.renderer ?
40835 this.cb.renderer(this.data) :
40836 String.format('{0}',this.data[this.displayField]);
40839 this.el.child('div').dom.setAttribute('qtip',
40840 String.format('{0}',this.data[this.tipField])
40843 this.el.child('img').on('click', this.remove, this);
40847 remove : function()
40849 if(this.cb.disabled){
40853 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
40854 this.cb.items.remove(this);
40855 this.el.child('img').un('click', this.remove, this);
40857 this.cb.updateHiddenEl();
40859 this.cb.fireEvent('remove', this.cb, this);
40865 * Ext JS Library 1.1.1
40866 * Copyright(c) 2006-2007, Ext JS, LLC.
40868 * Originally Released Under LGPL - original licence link has changed is not relivant.
40871 * <script type="text/javascript">
40874 * @class Roo.form.Checkbox
40875 * @extends Roo.form.Field
40876 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
40878 * Creates a new Checkbox
40879 * @param {Object} config Configuration options
40881 Roo.form.Checkbox = function(config){
40882 Roo.form.Checkbox.superclass.constructor.call(this, config);
40886 * Fires when the checkbox is checked or unchecked.
40887 * @param {Roo.form.Checkbox} this This checkbox
40888 * @param {Boolean} checked The new checked value
40894 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
40896 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
40898 focusClass : undefined,
40900 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
40902 fieldClass: "x-form-field",
40904 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
40908 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40909 * {tag: "input", type: "checkbox", autocomplete: "off"})
40911 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
40913 * @cfg {String} boxLabel The text that appears beside the checkbox
40917 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
40921 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
40923 valueOff: '0', // value when not checked..
40925 actionMode : 'viewEl',
40928 itemCls : 'x-menu-check-item x-form-item',
40929 groupClass : 'x-menu-group-item',
40930 inputType : 'hidden',
40933 inSetChecked: false, // check that we are not calling self...
40935 inputElement: false, // real input element?
40936 basedOn: false, // ????
40938 isFormField: true, // not sure where this is needed!!!!
40940 onResize : function(){
40941 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
40942 if(!this.boxLabel){
40943 this.el.alignTo(this.wrap, 'c-c');
40947 initEvents : function(){
40948 Roo.form.Checkbox.superclass.initEvents.call(this);
40949 this.el.on("click", this.onClick, this);
40950 this.el.on("change", this.onClick, this);
40954 getResizeEl : function(){
40958 getPositionEl : function(){
40963 onRender : function(ct, position){
40964 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
40966 if(this.inputValue !== undefined){
40967 this.el.dom.value = this.inputValue;
40970 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
40971 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
40972 var viewEl = this.wrap.createChild({
40973 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
40974 this.viewEl = viewEl;
40975 this.wrap.on('click', this.onClick, this);
40977 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
40978 this.el.on('propertychange', this.setFromHidden, this); //ie
40983 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
40984 // viewEl.on('click', this.onClick, this);
40986 //if(this.checked){
40987 this.setChecked(this.checked);
40989 //this.checked = this.el.dom;
40995 initValue : Roo.emptyFn,
40998 * Returns the checked state of the checkbox.
40999 * @return {Boolean} True if checked, else false
41001 getValue : function(){
41003 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
41005 return this.valueOff;
41010 onClick : function(){
41011 if (this.disabled) {
41014 this.setChecked(!this.checked);
41016 //if(this.el.dom.checked != this.checked){
41017 // this.setValue(this.el.dom.checked);
41022 * Sets the checked state of the checkbox.
41023 * On is always based on a string comparison between inputValue and the param.
41024 * @param {Boolean/String} value - the value to set
41025 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
41027 setValue : function(v,suppressEvent){
41030 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
41031 //if(this.el && this.el.dom){
41032 // this.el.dom.checked = this.checked;
41033 // this.el.dom.defaultChecked = this.checked;
41035 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
41036 //this.fireEvent("check", this, this.checked);
41039 setChecked : function(state,suppressEvent)
41041 if (this.inSetChecked) {
41042 this.checked = state;
41048 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
41050 this.checked = state;
41051 if(suppressEvent !== true){
41052 this.fireEvent('check', this, state);
41054 this.inSetChecked = true;
41055 this.el.dom.value = state ? this.inputValue : this.valueOff;
41056 this.inSetChecked = false;
41059 // handle setting of hidden value by some other method!!?!?
41060 setFromHidden: function()
41065 //console.log("SET FROM HIDDEN");
41066 //alert('setFrom hidden');
41067 this.setValue(this.el.dom.value);
41070 onDestroy : function()
41073 Roo.get(this.viewEl).remove();
41076 Roo.form.Checkbox.superclass.onDestroy.call(this);
41081 * Ext JS Library 1.1.1
41082 * Copyright(c) 2006-2007, Ext JS, LLC.
41084 * Originally Released Under LGPL - original licence link has changed is not relivant.
41087 * <script type="text/javascript">
41091 * @class Roo.form.Radio
41092 * @extends Roo.form.Checkbox
41093 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
41094 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
41096 * Creates a new Radio
41097 * @param {Object} config Configuration options
41099 Roo.form.Radio = function(){
41100 Roo.form.Radio.superclass.constructor.apply(this, arguments);
41102 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
41103 inputType: 'radio',
41106 * If this radio is part of a group, it will return the selected value
41109 getGroupValue : function(){
41110 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
41114 onRender : function(ct, position){
41115 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
41117 if(this.inputValue !== undefined){
41118 this.el.dom.value = this.inputValue;
41121 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
41122 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
41123 //var viewEl = this.wrap.createChild({
41124 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
41125 //this.viewEl = viewEl;
41126 //this.wrap.on('click', this.onClick, this);
41128 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
41129 //this.el.on('propertychange', this.setFromHidden, this); //ie
41134 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
41135 // viewEl.on('click', this.onClick, this);
41138 this.el.dom.checked = 'checked' ;
41144 });//<script type="text/javascript">
41147 * Based Ext JS Library 1.1.1
41148 * Copyright(c) 2006-2007, Ext JS, LLC.
41154 * @class Roo.HtmlEditorCore
41155 * @extends Roo.Component
41156 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
41158 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
41161 Roo.HtmlEditorCore = function(config){
41164 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
41169 * @event initialize
41170 * Fires when the editor is fully initialized (including the iframe)
41171 * @param {Roo.HtmlEditorCore} this
41176 * Fires when the editor is first receives the focus. Any insertion must wait
41177 * until after this event.
41178 * @param {Roo.HtmlEditorCore} this
41182 * @event beforesync
41183 * Fires before the textarea is updated with content from the editor iframe. Return false
41184 * to cancel the sync.
41185 * @param {Roo.HtmlEditorCore} this
41186 * @param {String} html
41190 * @event beforepush
41191 * Fires before the iframe editor is updated with content from the textarea. Return false
41192 * to cancel the push.
41193 * @param {Roo.HtmlEditorCore} this
41194 * @param {String} html
41199 * Fires when the textarea is updated with content from the editor iframe.
41200 * @param {Roo.HtmlEditorCore} this
41201 * @param {String} html
41206 * Fires when the iframe editor is updated with content from the textarea.
41207 * @param {Roo.HtmlEditorCore} this
41208 * @param {String} html
41213 * @event editorevent
41214 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
41215 * @param {Roo.HtmlEditorCore} this
41221 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
41223 // defaults : white / black...
41224 this.applyBlacklists();
41231 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
41235 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
41241 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
41246 * @cfg {Number} height (in pixels)
41250 * @cfg {Number} width (in pixels)
41255 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
41258 stylesheets: false,
41263 // private properties
41264 validationEvent : false,
41266 initialized : false,
41268 sourceEditMode : false,
41269 onFocus : Roo.emptyFn,
41271 hideMode:'offsets',
41275 // blacklist + whitelisted elements..
41282 * Protected method that will not generally be called directly. It
41283 * is called when the editor initializes the iframe with HTML contents. Override this method if you
41284 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
41286 getDocMarkup : function(){
41290 // inherit styels from page...??
41291 if (this.stylesheets === false) {
41293 Roo.get(document.head).select('style').each(function(node) {
41294 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
41297 Roo.get(document.head).select('link').each(function(node) {
41298 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
41301 } else if (!this.stylesheets.length) {
41303 st = '<style type="text/css">' +
41304 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
41310 st += '<style type="text/css">' +
41311 'IMG { cursor: pointer } ' +
41315 return '<html><head>' + st +
41316 //<style type="text/css">' +
41317 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
41319 ' </head><body class="roo-htmleditor-body"></body></html>';
41323 onRender : function(ct, position)
41326 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
41327 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
41330 this.el.dom.style.border = '0 none';
41331 this.el.dom.setAttribute('tabIndex', -1);
41332 this.el.addClass('x-hidden hide');
41336 if(Roo.isIE){ // fix IE 1px bogus margin
41337 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
41341 this.frameId = Roo.id();
41345 var iframe = this.owner.wrap.createChild({
41347 cls: 'form-control', // bootstrap..
41349 name: this.frameId,
41350 frameBorder : 'no',
41351 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
41356 this.iframe = iframe.dom;
41358 this.assignDocWin();
41360 this.doc.designMode = 'on';
41363 this.doc.write(this.getDocMarkup());
41367 var task = { // must defer to wait for browser to be ready
41369 //console.log("run task?" + this.doc.readyState);
41370 this.assignDocWin();
41371 if(this.doc.body || this.doc.readyState == 'complete'){
41373 this.doc.designMode="on";
41377 Roo.TaskMgr.stop(task);
41378 this.initEditor.defer(10, this);
41385 Roo.TaskMgr.start(task);
41390 onResize : function(w, h)
41392 Roo.log('resize: ' +w + ',' + h );
41393 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
41397 if(typeof w == 'number'){
41399 this.iframe.style.width = w + 'px';
41401 if(typeof h == 'number'){
41403 this.iframe.style.height = h + 'px';
41405 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
41412 * Toggles the editor between standard and source edit mode.
41413 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
41415 toggleSourceEdit : function(sourceEditMode){
41417 this.sourceEditMode = sourceEditMode === true;
41419 if(this.sourceEditMode){
41421 Roo.get(this.iframe).addClass(['x-hidden','hide']); //FIXME - what's the BS styles for these
41424 Roo.get(this.iframe).removeClass(['x-hidden','hide']);
41425 //this.iframe.className = '';
41428 //this.setSize(this.owner.wrap.getSize());
41429 //this.fireEvent('editmodechange', this, this.sourceEditMode);
41436 * Protected method that will not generally be called directly. If you need/want
41437 * custom HTML cleanup, this is the method you should override.
41438 * @param {String} html The HTML to be cleaned
41439 * return {String} The cleaned HTML
41441 cleanHtml : function(html){
41442 html = String(html);
41443 if(html.length > 5){
41444 if(Roo.isSafari){ // strip safari nonsense
41445 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
41448 if(html == ' '){
41455 * HTML Editor -> Textarea
41456 * Protected method that will not generally be called directly. Syncs the contents
41457 * of the editor iframe with the textarea.
41459 syncValue : function(){
41460 if(this.initialized){
41461 var bd = (this.doc.body || this.doc.documentElement);
41462 //this.cleanUpPaste(); -- this is done else where and causes havoc..
41463 var html = bd.innerHTML;
41465 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
41466 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
41468 html = '<div style="'+m[0]+'">' + html + '</div>';
41471 html = this.cleanHtml(html);
41472 // fix up the special chars.. normaly like back quotes in word...
41473 // however we do not want to do this with chinese..
41474 html = html.replace(/([\x80-\uffff])/g, function (a, b) {
41475 var cc = b.charCodeAt();
41477 (cc >= 0x4E00 && cc < 0xA000 ) ||
41478 (cc >= 0x3400 && cc < 0x4E00 ) ||
41479 (cc >= 0xf900 && cc < 0xfb00 )
41485 if(this.owner.fireEvent('beforesync', this, html) !== false){
41486 this.el.dom.value = html;
41487 this.owner.fireEvent('sync', this, html);
41493 * Protected method that will not generally be called directly. Pushes the value of the textarea
41494 * into the iframe editor.
41496 pushValue : function(){
41497 if(this.initialized){
41498 var v = this.el.dom.value.trim();
41500 // if(v.length < 1){
41504 if(this.owner.fireEvent('beforepush', this, v) !== false){
41505 var d = (this.doc.body || this.doc.documentElement);
41507 this.cleanUpPaste();
41508 this.el.dom.value = d.innerHTML;
41509 this.owner.fireEvent('push', this, v);
41515 deferFocus : function(){
41516 this.focus.defer(10, this);
41520 focus : function(){
41521 if(this.win && !this.sourceEditMode){
41528 assignDocWin: function()
41530 var iframe = this.iframe;
41533 this.doc = iframe.contentWindow.document;
41534 this.win = iframe.contentWindow;
41536 // if (!Roo.get(this.frameId)) {
41539 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
41540 // this.win = Roo.get(this.frameId).dom.contentWindow;
41542 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
41546 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
41547 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
41552 initEditor : function(){
41553 //console.log("INIT EDITOR");
41554 this.assignDocWin();
41558 this.doc.designMode="on";
41560 this.doc.write(this.getDocMarkup());
41563 var dbody = (this.doc.body || this.doc.documentElement);
41564 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
41565 // this copies styles from the containing element into thsi one..
41566 // not sure why we need all of this..
41567 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
41569 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
41570 //ss['background-attachment'] = 'fixed'; // w3c
41571 dbody.bgProperties = 'fixed'; // ie
41572 //Roo.DomHelper.applyStyles(dbody, ss);
41573 Roo.EventManager.on(this.doc, {
41574 //'mousedown': this.onEditorEvent,
41575 'mouseup': this.onEditorEvent,
41576 'dblclick': this.onEditorEvent,
41577 'click': this.onEditorEvent,
41578 'keyup': this.onEditorEvent,
41583 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
41585 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
41586 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
41588 this.initialized = true;
41590 this.owner.fireEvent('initialize', this);
41595 onDestroy : function(){
41601 //for (var i =0; i < this.toolbars.length;i++) {
41602 // // fixme - ask toolbars for heights?
41603 // this.toolbars[i].onDestroy();
41606 //this.wrap.dom.innerHTML = '';
41607 //this.wrap.remove();
41612 onFirstFocus : function(){
41614 this.assignDocWin();
41617 this.activated = true;
41620 if(Roo.isGecko){ // prevent silly gecko errors
41622 var s = this.win.getSelection();
41623 if(!s.focusNode || s.focusNode.nodeType != 3){
41624 var r = s.getRangeAt(0);
41625 r.selectNodeContents((this.doc.body || this.doc.documentElement));
41630 this.execCmd('useCSS', true);
41631 this.execCmd('styleWithCSS', false);
41634 this.owner.fireEvent('activate', this);
41638 adjustFont: function(btn){
41639 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
41640 //if(Roo.isSafari){ // safari
41643 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
41644 if(Roo.isSafari){ // safari
41645 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
41646 v = (v < 10) ? 10 : v;
41647 v = (v > 48) ? 48 : v;
41648 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
41653 v = Math.max(1, v+adjust);
41655 this.execCmd('FontSize', v );
41658 onEditorEvent : function(e){
41659 this.owner.fireEvent('editorevent', this, e);
41660 // this.updateToolbar();
41661 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
41664 insertTag : function(tg)
41666 // could be a bit smarter... -> wrap the current selected tRoo..
41667 if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
41669 range = this.createRange(this.getSelection());
41670 var wrappingNode = this.doc.createElement(tg.toLowerCase());
41671 wrappingNode.appendChild(range.extractContents());
41672 range.insertNode(wrappingNode);
41679 this.execCmd("formatblock", tg);
41683 insertText : function(txt)
41687 var range = this.createRange();
41688 range.deleteContents();
41689 //alert(Sender.getAttribute('label'));
41691 range.insertNode(this.doc.createTextNode(txt));
41697 * Executes a Midas editor command on the editor document and performs necessary focus and
41698 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
41699 * @param {String} cmd The Midas command
41700 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
41702 relayCmd : function(cmd, value){
41704 this.execCmd(cmd, value);
41705 this.owner.fireEvent('editorevent', this);
41706 //this.updateToolbar();
41707 this.owner.deferFocus();
41711 * Executes a Midas editor command directly on the editor document.
41712 * For visual commands, you should use {@link #relayCmd} instead.
41713 * <b>This should only be called after the editor is initialized.</b>
41714 * @param {String} cmd The Midas command
41715 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
41717 execCmd : function(cmd, value){
41718 this.doc.execCommand(cmd, false, value === undefined ? null : value);
41725 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
41727 * @param {String} text | dom node..
41729 insertAtCursor : function(text)
41734 if(!this.activated){
41740 var r = this.doc.selection.createRange();
41751 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
41755 // from jquery ui (MIT licenced)
41757 var win = this.win;
41759 if (win.getSelection && win.getSelection().getRangeAt) {
41760 range = win.getSelection().getRangeAt(0);
41761 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
41762 range.insertNode(node);
41763 } else if (win.document.selection && win.document.selection.createRange) {
41764 // no firefox support
41765 var txt = typeof(text) == 'string' ? text : text.outerHTML;
41766 win.document.selection.createRange().pasteHTML(txt);
41768 // no firefox support
41769 var txt = typeof(text) == 'string' ? text : text.outerHTML;
41770 this.execCmd('InsertHTML', txt);
41779 mozKeyPress : function(e){
41781 var c = e.getCharCode(), cmd;
41784 c = String.fromCharCode(c).toLowerCase();
41798 this.cleanUpPaste.defer(100, this);
41806 e.preventDefault();
41814 fixKeys : function(){ // load time branching for fastest keydown performance
41816 return function(e){
41817 var k = e.getKey(), r;
41820 r = this.doc.selection.createRange();
41823 r.pasteHTML('    ');
41830 r = this.doc.selection.createRange();
41832 var target = r.parentElement();
41833 if(!target || target.tagName.toLowerCase() != 'li'){
41835 r.pasteHTML('<br />');
41841 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41842 this.cleanUpPaste.defer(100, this);
41848 }else if(Roo.isOpera){
41849 return function(e){
41850 var k = e.getKey();
41854 this.execCmd('InsertHTML','    ');
41857 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41858 this.cleanUpPaste.defer(100, this);
41863 }else if(Roo.isSafari){
41864 return function(e){
41865 var k = e.getKey();
41869 this.execCmd('InsertText','\t');
41873 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41874 this.cleanUpPaste.defer(100, this);
41882 getAllAncestors: function()
41884 var p = this.getSelectedNode();
41887 a.push(p); // push blank onto stack..
41888 p = this.getParentElement();
41892 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
41896 a.push(this.doc.body);
41900 lastSelNode : false,
41903 getSelection : function()
41905 this.assignDocWin();
41906 return Roo.isIE ? this.doc.selection : this.win.getSelection();
41909 getSelectedNode: function()
41911 // this may only work on Gecko!!!
41913 // should we cache this!!!!
41918 var range = this.createRange(this.getSelection()).cloneRange();
41921 var parent = range.parentElement();
41923 var testRange = range.duplicate();
41924 testRange.moveToElementText(parent);
41925 if (testRange.inRange(range)) {
41928 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
41931 parent = parent.parentElement;
41936 // is ancestor a text element.
41937 var ac = range.commonAncestorContainer;
41938 if (ac.nodeType == 3) {
41939 ac = ac.parentNode;
41942 var ar = ac.childNodes;
41945 var other_nodes = [];
41946 var has_other_nodes = false;
41947 for (var i=0;i<ar.length;i++) {
41948 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
41951 // fullly contained node.
41953 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
41958 // probably selected..
41959 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
41960 other_nodes.push(ar[i]);
41964 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
41969 has_other_nodes = true;
41971 if (!nodes.length && other_nodes.length) {
41972 nodes= other_nodes;
41974 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
41980 createRange: function(sel)
41982 // this has strange effects when using with
41983 // top toolbar - not sure if it's a great idea.
41984 //this.editor.contentWindow.focus();
41985 if (typeof sel != "undefined") {
41987 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
41989 return this.doc.createRange();
41992 return this.doc.createRange();
41995 getParentElement: function()
41998 this.assignDocWin();
41999 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
42001 var range = this.createRange(sel);
42004 var p = range.commonAncestorContainer;
42005 while (p.nodeType == 3) { // text node
42016 * Range intersection.. the hard stuff...
42020 * [ -- selected range --- ]
42024 * if end is before start or hits it. fail.
42025 * if start is after end or hits it fail.
42027 * if either hits (but other is outside. - then it's not
42033 // @see http://www.thismuchiknow.co.uk/?p=64.
42034 rangeIntersectsNode : function(range, node)
42036 var nodeRange = node.ownerDocument.createRange();
42038 nodeRange.selectNode(node);
42040 nodeRange.selectNodeContents(node);
42043 var rangeStartRange = range.cloneRange();
42044 rangeStartRange.collapse(true);
42046 var rangeEndRange = range.cloneRange();
42047 rangeEndRange.collapse(false);
42049 var nodeStartRange = nodeRange.cloneRange();
42050 nodeStartRange.collapse(true);
42052 var nodeEndRange = nodeRange.cloneRange();
42053 nodeEndRange.collapse(false);
42055 return rangeStartRange.compareBoundaryPoints(
42056 Range.START_TO_START, nodeEndRange) == -1 &&
42057 rangeEndRange.compareBoundaryPoints(
42058 Range.START_TO_START, nodeStartRange) == 1;
42062 rangeCompareNode : function(range, node)
42064 var nodeRange = node.ownerDocument.createRange();
42066 nodeRange.selectNode(node);
42068 nodeRange.selectNodeContents(node);
42072 range.collapse(true);
42074 nodeRange.collapse(true);
42076 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
42077 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
42079 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
42081 var nodeIsBefore = ss == 1;
42082 var nodeIsAfter = ee == -1;
42084 if (nodeIsBefore && nodeIsAfter)
42086 if (!nodeIsBefore && nodeIsAfter)
42087 return 1; //right trailed.
42089 if (nodeIsBefore && !nodeIsAfter)
42090 return 2; // left trailed.
42095 // private? - in a new class?
42096 cleanUpPaste : function()
42098 // cleans up the whole document..
42099 Roo.log('cleanuppaste');
42101 this.cleanUpChildren(this.doc.body);
42102 var clean = this.cleanWordChars(this.doc.body.innerHTML);
42103 if (clean != this.doc.body.innerHTML) {
42104 this.doc.body.innerHTML = clean;
42109 cleanWordChars : function(input) {// change the chars to hex code
42110 var he = Roo.HtmlEditorCore;
42112 var output = input;
42113 Roo.each(he.swapCodes, function(sw) {
42114 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
42116 output = output.replace(swapper, sw[1]);
42123 cleanUpChildren : function (n)
42125 if (!n.childNodes.length) {
42128 for (var i = n.childNodes.length-1; i > -1 ; i--) {
42129 this.cleanUpChild(n.childNodes[i]);
42136 cleanUpChild : function (node)
42139 //console.log(node);
42140 if (node.nodeName == "#text") {
42141 // clean up silly Windows -- stuff?
42144 if (node.nodeName == "#comment") {
42145 node.parentNode.removeChild(node);
42146 // clean up silly Windows -- stuff?
42149 var lcname = node.tagName.toLowerCase();
42150 // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
42151 // whitelist of tags..
42153 if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
42155 node.parentNode.removeChild(node);
42160 var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
42162 // remove <a name=....> as rendering on yahoo mailer is borked with this.
42163 // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
42165 //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
42166 // remove_keep_children = true;
42169 if (remove_keep_children) {
42170 this.cleanUpChildren(node);
42171 // inserts everything just before this node...
42172 while (node.childNodes.length) {
42173 var cn = node.childNodes[0];
42174 node.removeChild(cn);
42175 node.parentNode.insertBefore(cn, node);
42177 node.parentNode.removeChild(node);
42181 if (!node.attributes || !node.attributes.length) {
42182 this.cleanUpChildren(node);
42186 function cleanAttr(n,v)
42189 if (v.match(/^\./) || v.match(/^\//)) {
42192 if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
42195 if (v.match(/^#/)) {
42198 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
42199 node.removeAttribute(n);
42203 var cwhite = this.cwhite;
42204 var cblack = this.cblack;
42206 function cleanStyle(n,v)
42208 if (v.match(/expression/)) { //XSS?? should we even bother..
42209 node.removeAttribute(n);
42213 var parts = v.split(/;/);
42216 Roo.each(parts, function(p) {
42217 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
42221 var l = p.split(':').shift().replace(/\s+/g,'');
42222 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
42224 if ( cwhite.length && cblack.indexOf(l) > -1) {
42225 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
42226 //node.removeAttribute(n);
42230 // only allow 'c whitelisted system attributes'
42231 if ( cwhite.length && cwhite.indexOf(l) < 0) {
42232 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
42233 //node.removeAttribute(n);
42243 if (clean.length) {
42244 node.setAttribute(n, clean.join(';'));
42246 node.removeAttribute(n);
42252 for (var i = node.attributes.length-1; i > -1 ; i--) {
42253 var a = node.attributes[i];
42256 if (a.name.toLowerCase().substr(0,2)=='on') {
42257 node.removeAttribute(a.name);
42260 if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
42261 node.removeAttribute(a.name);
42264 if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
42265 cleanAttr(a.name,a.value); // fixme..
42268 if (a.name == 'style') {
42269 cleanStyle(a.name,a.value);
42272 /// clean up MS crap..
42273 // tecnically this should be a list of valid class'es..
42276 if (a.name == 'class') {
42277 if (a.value.match(/^Mso/)) {
42278 node.className = '';
42281 if (a.value.match(/body/)) {
42282 node.className = '';
42293 this.cleanUpChildren(node);
42298 * Clean up MS wordisms...
42300 cleanWord : function(node)
42303 var cleanWordChildren = function()
42305 if (!node.childNodes.length) {
42308 for (var i = node.childNodes.length-1; i > -1 ; i--) {
42309 _t.cleanWord(node.childNodes[i]);
42315 this.cleanWord(this.doc.body);
42318 if (node.nodeName == "#text") {
42319 // clean up silly Windows -- stuff?
42322 if (node.nodeName == "#comment") {
42323 node.parentNode.removeChild(node);
42324 // clean up silly Windows -- stuff?
42328 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
42329 node.parentNode.removeChild(node);
42333 // remove - but keep children..
42334 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|font)/)) {
42335 while (node.childNodes.length) {
42336 var cn = node.childNodes[0];
42337 node.removeChild(cn);
42338 node.parentNode.insertBefore(cn, node);
42340 node.parentNode.removeChild(node);
42341 cleanWordChildren();
42345 if (node.className.length) {
42347 var cn = node.className.split(/\W+/);
42349 Roo.each(cn, function(cls) {
42350 if (cls.match(/Mso[a-zA-Z]+/)) {
42355 node.className = cna.length ? cna.join(' ') : '';
42357 node.removeAttribute("class");
42361 if (node.hasAttribute("lang")) {
42362 node.removeAttribute("lang");
42365 if (node.hasAttribute("style")) {
42367 var styles = node.getAttribute("style").split(";");
42369 Roo.each(styles, function(s) {
42370 if (!s.match(/:/)) {
42373 var kv = s.split(":");
42374 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
42377 // what ever is left... we allow.
42380 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
42381 if (!nstyle.length) {
42382 node.removeAttribute('style');
42386 cleanWordChildren();
42390 domToHTML : function(currentElement, depth, nopadtext) {
42392 depth = depth || 0;
42393 nopadtext = nopadtext || false;
42395 if (!currentElement) {
42396 return this.domToHTML(this.doc.body);
42399 //Roo.log(currentElement);
42401 var allText = false;
42402 var nodeName = currentElement.nodeName;
42403 var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
42405 if (nodeName == '#text') {
42407 return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
42412 if (nodeName != 'BODY') {
42415 // Prints the node tagName, such as <A>, <IMG>, etc
42418 for(i = 0; i < currentElement.attributes.length;i++) {
42420 var aname = currentElement.attributes.item(i).name;
42421 if (!currentElement.attributes.item(i).value.length) {
42424 attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
42427 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
42436 if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
42439 if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
42444 // Traverse the tree
42446 var currentElementChild = currentElement.childNodes.item(i);
42447 var allText = true;
42448 var innerHTML = '';
42450 while (currentElementChild) {
42451 // Formatting code (indent the tree so it looks nice on the screen)
42452 var nopad = nopadtext;
42453 if (lastnode == 'SPAN') {
42457 if (currentElementChild.nodeName == '#text') {
42458 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
42459 toadd = nopadtext ? toadd : toadd.trim();
42460 if (!nopad && toadd.length > 80) {
42461 innerHTML += "\n" + (new Array( depth + 1 )).join( " " );
42463 innerHTML += toadd;
42466 currentElementChild = currentElement.childNodes.item(i);
42472 innerHTML += nopad ? '' : "\n" + (new Array( depth + 1 )).join( " " );
42474 // Recursively traverse the tree structure of the child node
42475 innerHTML += this.domToHTML(currentElementChild, depth+1, nopadtext);
42476 lastnode = currentElementChild.nodeName;
42478 currentElementChild=currentElement.childNodes.item(i);
42484 // The remaining code is mostly for formatting the tree
42485 ret+= nopadtext ? '' : "\n" + (new Array( depth )).join( " " );
42490 ret+= "</"+tagName+">";
42496 applyBlacklists : function()
42498 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
42499 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
42503 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
42504 if (b.indexOf(tag) > -1) {
42507 this.white.push(tag);
42511 Roo.each(w, function(tag) {
42512 if (b.indexOf(tag) > -1) {
42515 if (this.white.indexOf(tag) > -1) {
42518 this.white.push(tag);
42523 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
42524 if (w.indexOf(tag) > -1) {
42527 this.black.push(tag);
42531 Roo.each(b, function(tag) {
42532 if (w.indexOf(tag) > -1) {
42535 if (this.black.indexOf(tag) > -1) {
42538 this.black.push(tag);
42543 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
42544 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
42548 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
42549 if (b.indexOf(tag) > -1) {
42552 this.cwhite.push(tag);
42556 Roo.each(w, function(tag) {
42557 if (b.indexOf(tag) > -1) {
42560 if (this.cwhite.indexOf(tag) > -1) {
42563 this.cwhite.push(tag);
42568 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
42569 if (w.indexOf(tag) > -1) {
42572 this.cblack.push(tag);
42576 Roo.each(b, function(tag) {
42577 if (w.indexOf(tag) > -1) {
42580 if (this.cblack.indexOf(tag) > -1) {
42583 this.cblack.push(tag);
42588 setStylesheets : function(stylesheets)
42590 if(typeof(stylesheets) == 'string'){
42591 Roo.get(this.iframe.contentDocument.head).createChild({
42593 rel : 'stylesheet',
42602 Roo.each(stylesheets, function(s) {
42607 Roo.get(_this.iframe.contentDocument.head).createChild({
42609 rel : 'stylesheet',
42618 removeStylesheets : function()
42622 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
42627 // hide stuff that is not compatible
42641 * @event specialkey
42645 * @cfg {String} fieldClass @hide
42648 * @cfg {String} focusClass @hide
42651 * @cfg {String} autoCreate @hide
42654 * @cfg {String} inputType @hide
42657 * @cfg {String} invalidClass @hide
42660 * @cfg {String} invalidText @hide
42663 * @cfg {String} msgFx @hide
42666 * @cfg {String} validateOnBlur @hide
42670 Roo.HtmlEditorCore.white = [
42671 'area', 'br', 'img', 'input', 'hr', 'wbr',
42673 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
42674 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
42675 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
42676 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
42677 'table', 'ul', 'xmp',
42679 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
42682 'dir', 'menu', 'ol', 'ul', 'dl',
42688 Roo.HtmlEditorCore.black = [
42689 // 'embed', 'object', // enable - backend responsiblity to clean thiese
42691 'base', 'basefont', 'bgsound', 'blink', 'body',
42692 'frame', 'frameset', 'head', 'html', 'ilayer',
42693 'iframe', 'layer', 'link', 'meta', 'object',
42694 'script', 'style' ,'title', 'xml' // clean later..
42696 Roo.HtmlEditorCore.clean = [
42697 'script', 'style', 'title', 'xml'
42699 Roo.HtmlEditorCore.remove = [
42704 Roo.HtmlEditorCore.ablack = [
42708 Roo.HtmlEditorCore.aclean = [
42709 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
42713 Roo.HtmlEditorCore.pwhite= [
42714 'http', 'https', 'mailto'
42717 // white listed style attributes.
42718 Roo.HtmlEditorCore.cwhite= [
42719 // 'text-align', /// default is to allow most things..
42725 // black listed style attributes.
42726 Roo.HtmlEditorCore.cblack= [
42727 // 'font-size' -- this can be set by the project
42731 Roo.HtmlEditorCore.swapCodes =[
42742 //<script type="text/javascript">
42745 * Ext JS Library 1.1.1
42746 * Copyright(c) 2006-2007, Ext JS, LLC.
42752 Roo.form.HtmlEditor = function(config){
42756 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
42758 if (!this.toolbars) {
42759 this.toolbars = [];
42761 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
42767 * @class Roo.form.HtmlEditor
42768 * @extends Roo.form.Field
42769 * Provides a lightweight HTML Editor component.
42771 * This has been tested on Fireforx / Chrome.. IE may not be so great..
42773 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
42774 * supported by this editor.</b><br/><br/>
42775 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
42776 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
42778 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
42780 * @cfg {Boolean} clearUp
42784 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
42789 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
42794 * @cfg {Number} height (in pixels)
42798 * @cfg {Number} width (in pixels)
42803 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
42806 stylesheets: false,
42810 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
42815 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
42821 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
42826 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
42834 // private properties
42835 validationEvent : false,
42837 initialized : false,
42840 onFocus : Roo.emptyFn,
42842 hideMode:'offsets',
42844 actionMode : 'container', // defaults to hiding it...
42846 defaultAutoCreate : { // modified by initCompnoent..
42848 style:"width:500px;height:300px;",
42849 autocomplete: "new-password"
42853 initComponent : function(){
42856 * @event initialize
42857 * Fires when the editor is fully initialized (including the iframe)
42858 * @param {HtmlEditor} this
42863 * Fires when the editor is first receives the focus. Any insertion must wait
42864 * until after this event.
42865 * @param {HtmlEditor} this
42869 * @event beforesync
42870 * Fires before the textarea is updated with content from the editor iframe. Return false
42871 * to cancel the sync.
42872 * @param {HtmlEditor} this
42873 * @param {String} html
42877 * @event beforepush
42878 * Fires before the iframe editor is updated with content from the textarea. Return false
42879 * to cancel the push.
42880 * @param {HtmlEditor} this
42881 * @param {String} html
42886 * Fires when the textarea is updated with content from the editor iframe.
42887 * @param {HtmlEditor} this
42888 * @param {String} html
42893 * Fires when the iframe editor is updated with content from the textarea.
42894 * @param {HtmlEditor} this
42895 * @param {String} html
42899 * @event editmodechange
42900 * Fires when the editor switches edit modes
42901 * @param {HtmlEditor} this
42902 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
42904 editmodechange: true,
42906 * @event editorevent
42907 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
42908 * @param {HtmlEditor} this
42912 * @event firstfocus
42913 * Fires when on first focus - needed by toolbars..
42914 * @param {HtmlEditor} this
42919 * Auto save the htmlEditor value as a file into Events
42920 * @param {HtmlEditor} this
42924 * @event savedpreview
42925 * preview the saved version of htmlEditor
42926 * @param {HtmlEditor} this
42928 savedpreview: true,
42931 * @event stylesheetsclick
42932 * Fires when press the Sytlesheets button
42933 * @param {Roo.HtmlEditorCore} this
42935 stylesheetsclick: true
42937 this.defaultAutoCreate = {
42939 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
42940 autocomplete: "new-password"
42945 * Protected method that will not generally be called directly. It
42946 * is called when the editor creates its toolbar. Override this method if you need to
42947 * add custom toolbar buttons.
42948 * @param {HtmlEditor} editor
42950 createToolbar : function(editor){
42951 Roo.log("create toolbars");
42952 if (!editor.toolbars || !editor.toolbars.length) {
42953 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
42956 for (var i =0 ; i < editor.toolbars.length;i++) {
42957 editor.toolbars[i] = Roo.factory(
42958 typeof(editor.toolbars[i]) == 'string' ?
42959 { xtype: editor.toolbars[i]} : editor.toolbars[i],
42960 Roo.form.HtmlEditor);
42961 editor.toolbars[i].init(editor);
42969 onRender : function(ct, position)
42972 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
42974 this.wrap = this.el.wrap({
42975 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
42978 this.editorcore.onRender(ct, position);
42980 if (this.resizable) {
42981 this.resizeEl = new Roo.Resizable(this.wrap, {
42985 minHeight : this.height,
42986 height: this.height,
42987 handles : this.resizable,
42990 resize : function(r, w, h) {
42991 _t.onResize(w,h); // -something
42997 this.createToolbar(this);
43001 this.setSize(this.wrap.getSize());
43003 if (this.resizeEl) {
43004 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
43005 // should trigger onReize..
43008 this.keyNav = new Roo.KeyNav(this.el, {
43010 "tab" : function(e){
43011 e.preventDefault();
43013 var value = this.getValue();
43015 var start = this.el.dom.selectionStart;
43016 var end = this.el.dom.selectionEnd;
43020 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
43021 this.el.dom.setSelectionRange(end + 1, end + 1);
43025 var f = value.substring(0, start).split("\t");
43027 if(f.pop().length != 0){
43031 this.setValue(f.join("\t") + value.substring(end));
43032 this.el.dom.setSelectionRange(start - 1, start - 1);
43036 "home" : function(e){
43037 e.preventDefault();
43039 var curr = this.el.dom.selectionStart;
43040 var lines = this.getValue().split("\n");
43047 this.el.dom.setSelectionRange(0, 0);
43053 for (var i = 0; i < lines.length;i++) {
43054 pos += lines[i].length;
43064 pos -= lines[i].length;
43070 this.el.dom.setSelectionRange(pos, pos);
43074 this.el.dom.selectionStart = pos;
43075 this.el.dom.selectionEnd = curr;
43078 "end" : function(e){
43079 e.preventDefault();
43081 var curr = this.el.dom.selectionStart;
43082 var lines = this.getValue().split("\n");
43089 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
43095 for (var i = 0; i < lines.length;i++) {
43097 pos += lines[i].length;
43111 this.el.dom.setSelectionRange(pos, pos);
43115 this.el.dom.selectionStart = curr;
43116 this.el.dom.selectionEnd = pos;
43121 doRelay : function(foo, bar, hname){
43122 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
43128 // if(this.autosave && this.w){
43129 // this.autoSaveFn = setInterval(this.autosave, 1000);
43134 onResize : function(w, h)
43136 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
43141 if(typeof w == 'number'){
43142 var aw = w - this.wrap.getFrameWidth('lr');
43143 this.el.setWidth(this.adjustWidth('textarea', aw));
43146 if(typeof h == 'number'){
43148 for (var i =0; i < this.toolbars.length;i++) {
43149 // fixme - ask toolbars for heights?
43150 tbh += this.toolbars[i].tb.el.getHeight();
43151 if (this.toolbars[i].footer) {
43152 tbh += this.toolbars[i].footer.el.getHeight();
43159 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
43160 ah -= 5; // knock a few pixes off for look..
43162 this.el.setHeight(this.adjustWidth('textarea', ah));
43166 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
43167 this.editorcore.onResize(ew,eh);
43172 * Toggles the editor between standard and source edit mode.
43173 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
43175 toggleSourceEdit : function(sourceEditMode)
43177 this.editorcore.toggleSourceEdit(sourceEditMode);
43179 if(this.editorcore.sourceEditMode){
43180 Roo.log('editor - showing textarea');
43183 // Roo.log(this.syncValue());
43184 this.editorcore.syncValue();
43185 this.el.removeClass('x-hidden');
43186 this.el.dom.removeAttribute('tabIndex');
43189 for (var i = 0; i < this.toolbars.length; i++) {
43190 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
43191 this.toolbars[i].tb.hide();
43192 this.toolbars[i].footer.hide();
43197 Roo.log('editor - hiding textarea');
43199 // Roo.log(this.pushValue());
43200 this.editorcore.pushValue();
43202 this.el.addClass('x-hidden');
43203 this.el.dom.setAttribute('tabIndex', -1);
43205 for (var i = 0; i < this.toolbars.length; i++) {
43206 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
43207 this.toolbars[i].tb.show();
43208 this.toolbars[i].footer.show();
43212 //this.deferFocus();
43215 this.setSize(this.wrap.getSize());
43216 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
43218 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
43221 // private (for BoxComponent)
43222 adjustSize : Roo.BoxComponent.prototype.adjustSize,
43224 // private (for BoxComponent)
43225 getResizeEl : function(){
43229 // private (for BoxComponent)
43230 getPositionEl : function(){
43235 initEvents : function(){
43236 this.originalValue = this.getValue();
43240 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
43243 markInvalid : Roo.emptyFn,
43245 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
43248 clearInvalid : Roo.emptyFn,
43250 setValue : function(v){
43251 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
43252 this.editorcore.pushValue();
43257 deferFocus : function(){
43258 this.focus.defer(10, this);
43262 focus : function(){
43263 this.editorcore.focus();
43269 onDestroy : function(){
43275 for (var i =0; i < this.toolbars.length;i++) {
43276 // fixme - ask toolbars for heights?
43277 this.toolbars[i].onDestroy();
43280 this.wrap.dom.innerHTML = '';
43281 this.wrap.remove();
43286 onFirstFocus : function(){
43287 //Roo.log("onFirstFocus");
43288 this.editorcore.onFirstFocus();
43289 for (var i =0; i < this.toolbars.length;i++) {
43290 this.toolbars[i].onFirstFocus();
43296 syncValue : function()
43298 this.editorcore.syncValue();
43301 pushValue : function()
43303 this.editorcore.pushValue();
43306 setStylesheets : function(stylesheets)
43308 this.editorcore.setStylesheets(stylesheets);
43311 removeStylesheets : function()
43313 this.editorcore.removeStylesheets();
43317 // hide stuff that is not compatible
43331 * @event specialkey
43335 * @cfg {String} fieldClass @hide
43338 * @cfg {String} focusClass @hide
43341 * @cfg {String} autoCreate @hide
43344 * @cfg {String} inputType @hide
43347 * @cfg {String} invalidClass @hide
43350 * @cfg {String} invalidText @hide
43353 * @cfg {String} msgFx @hide
43356 * @cfg {String} validateOnBlur @hide
43360 // <script type="text/javascript">
43363 * Ext JS Library 1.1.1
43364 * Copyright(c) 2006-2007, Ext JS, LLC.
43370 * @class Roo.form.HtmlEditorToolbar1
43375 new Roo.form.HtmlEditor({
43378 new Roo.form.HtmlEditorToolbar1({
43379 disable : { fonts: 1 , format: 1, ..., ... , ...],
43385 * @cfg {Object} disable List of elements to disable..
43386 * @cfg {Array} btns List of additional buttons.
43390 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
43393 Roo.form.HtmlEditor.ToolbarStandard = function(config)
43396 Roo.apply(this, config);
43398 // default disabled, based on 'good practice'..
43399 this.disable = this.disable || {};
43400 Roo.applyIf(this.disable, {
43403 specialElements : true
43407 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
43408 // dont call parent... till later.
43411 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
43418 editorcore : false,
43420 * @cfg {Object} disable List of toolbar elements to disable
43427 * @cfg {String} createLinkText The default text for the create link prompt
43429 createLinkText : 'Please enter the URL for the link:',
43431 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
43433 defaultLinkValue : 'http:/'+'/',
43437 * @cfg {Array} fontFamilies An array of available font families
43455 // "á" , ?? a acute?
43460 "°" // , // degrees
43462 // "é" , // e ecute
43463 // "ú" , // u ecute?
43466 specialElements : [
43468 text: "Insert Table",
43471 ihtml : '<table><tr><td>Cell</td></tr></table>'
43475 text: "Insert Image",
43478 ihtml : '<img src="about:blank"/>'
43487 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
43488 "input:submit", "input:button", "select", "textarea", "label" ],
43491 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
43493 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
43501 * @cfg {String} defaultFont default font to use.
43503 defaultFont: 'tahoma',
43505 fontSelect : false,
43508 formatCombo : false,
43510 init : function(editor)
43512 this.editor = editor;
43513 this.editorcore = editor.editorcore ? editor.editorcore : editor;
43514 var editorcore = this.editorcore;
43518 var fid = editorcore.frameId;
43520 function btn(id, toggle, handler){
43521 var xid = fid + '-'+ id ;
43525 cls : 'x-btn-icon x-edit-'+id,
43526 enableToggle:toggle !== false,
43527 scope: _t, // was editor...
43528 handler:handler||_t.relayBtnCmd,
43529 clickEvent:'mousedown',
43530 tooltip: etb.buttonTips[id] || undefined, ///tips ???
43537 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
43539 // stop form submits
43540 tb.el.on('click', function(e){
43541 e.preventDefault(); // what does this do?
43544 if(!this.disable.font) { // && !Roo.isSafari){
43545 /* why no safari for fonts
43546 editor.fontSelect = tb.el.createChild({
43549 cls:'x-font-select',
43550 html: this.createFontOptions()
43553 editor.fontSelect.on('change', function(){
43554 var font = editor.fontSelect.dom.value;
43555 editor.relayCmd('fontname', font);
43556 editor.deferFocus();
43560 editor.fontSelect.dom,
43566 if(!this.disable.formats){
43567 this.formatCombo = new Roo.form.ComboBox({
43568 store: new Roo.data.SimpleStore({
43571 data : this.formats // from states.js
43575 //autoCreate : {tag: "div", size: "20"},
43576 displayField:'tag',
43580 triggerAction: 'all',
43581 emptyText:'Add tag',
43582 selectOnFocus:true,
43585 'select': function(c, r, i) {
43586 editorcore.insertTag(r.get('tag'));
43592 tb.addField(this.formatCombo);
43596 if(!this.disable.format){
43603 if(!this.disable.fontSize){
43608 btn('increasefontsize', false, editorcore.adjustFont),
43609 btn('decreasefontsize', false, editorcore.adjustFont)
43614 if(!this.disable.colors){
43617 id:editorcore.frameId +'-forecolor',
43618 cls:'x-btn-icon x-edit-forecolor',
43619 clickEvent:'mousedown',
43620 tooltip: this.buttonTips['forecolor'] || undefined,
43622 menu : new Roo.menu.ColorMenu({
43623 allowReselect: true,
43624 focus: Roo.emptyFn,
43627 selectHandler: function(cp, color){
43628 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
43629 editor.deferFocus();
43632 clickEvent:'mousedown'
43635 id:editorcore.frameId +'backcolor',
43636 cls:'x-btn-icon x-edit-backcolor',
43637 clickEvent:'mousedown',
43638 tooltip: this.buttonTips['backcolor'] || undefined,
43640 menu : new Roo.menu.ColorMenu({
43641 focus: Roo.emptyFn,
43644 allowReselect: true,
43645 selectHandler: function(cp, color){
43647 editorcore.execCmd('useCSS', false);
43648 editorcore.execCmd('hilitecolor', color);
43649 editorcore.execCmd('useCSS', true);
43650 editor.deferFocus();
43652 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
43653 Roo.isSafari || Roo.isIE ? '#'+color : color);
43654 editor.deferFocus();
43658 clickEvent:'mousedown'
43663 // now add all the items...
43666 if(!this.disable.alignments){
43669 btn('justifyleft'),
43670 btn('justifycenter'),
43671 btn('justifyright')
43675 //if(!Roo.isSafari){
43676 if(!this.disable.links){
43679 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
43683 if(!this.disable.lists){
43686 btn('insertorderedlist'),
43687 btn('insertunorderedlist')
43690 if(!this.disable.sourceEdit){
43693 btn('sourceedit', true, function(btn){
43694 this.toggleSourceEdit(btn.pressed);
43701 // special menu.. - needs to be tidied up..
43702 if (!this.disable.special) {
43705 cls: 'x-edit-none',
43711 for (var i =0; i < this.specialChars.length; i++) {
43712 smenu.menu.items.push({
43714 html: this.specialChars[i],
43715 handler: function(a,b) {
43716 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
43717 //editor.insertAtCursor(a.html);
43731 if (!this.disable.cleanStyles) {
43733 cls: 'x-btn-icon x-btn-clear',
43739 for (var i =0; i < this.cleanStyles.length; i++) {
43740 cmenu.menu.items.push({
43741 actiontype : this.cleanStyles[i],
43742 html: 'Remove ' + this.cleanStyles[i],
43743 handler: function(a,b) {
43746 var c = Roo.get(editorcore.doc.body);
43747 c.select('[style]').each(function(s) {
43748 s.dom.style.removeProperty(a.actiontype);
43750 editorcore.syncValue();
43755 cmenu.menu.items.push({
43756 actiontype : 'word',
43757 html: 'Remove MS Word Formating',
43758 handler: function(a,b) {
43759 editorcore.cleanWord();
43760 editorcore.syncValue();
43765 cmenu.menu.items.push({
43766 actiontype : 'all',
43767 html: 'Remove All Styles',
43768 handler: function(a,b) {
43770 var c = Roo.get(editorcore.doc.body);
43771 c.select('[style]').each(function(s) {
43772 s.dom.removeAttribute('style');
43774 editorcore.syncValue();
43778 cmenu.menu.items.push({
43779 actiontype : 'word',
43780 html: 'Tidy HTML Source',
43781 handler: function(a,b) {
43782 editorcore.doc.body.innerHTML = editorcore.domToHTML();
43783 editorcore.syncValue();
43792 if (!this.disable.specialElements) {
43795 cls: 'x-edit-none',
43800 for (var i =0; i < this.specialElements.length; i++) {
43801 semenu.menu.items.push(
43803 handler: function(a,b) {
43804 editor.insertAtCursor(this.ihtml);
43806 }, this.specialElements[i])
43818 for(var i =0; i< this.btns.length;i++) {
43819 var b = Roo.factory(this.btns[i],Roo.form);
43820 b.cls = 'x-edit-none';
43822 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
43823 b.cls += ' x-init-enable';
43826 b.scope = editorcore;
43834 // disable everything...
43836 this.tb.items.each(function(item){
43839 item.id != editorcore.frameId+ '-sourceedit' &&
43840 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
43846 this.rendered = true;
43848 // the all the btns;
43849 editor.on('editorevent', this.updateToolbar, this);
43850 // other toolbars need to implement this..
43851 //editor.on('editmodechange', this.updateToolbar, this);
43855 relayBtnCmd : function(btn) {
43856 this.editorcore.relayCmd(btn.cmd);
43858 // private used internally
43859 createLink : function(){
43860 Roo.log("create link?");
43861 var url = prompt(this.createLinkText, this.defaultLinkValue);
43862 if(url && url != 'http:/'+'/'){
43863 this.editorcore.relayCmd('createlink', url);
43869 * Protected method that will not generally be called directly. It triggers
43870 * a toolbar update by reading the markup state of the current selection in the editor.
43872 updateToolbar: function(){
43874 if(!this.editorcore.activated){
43875 this.editor.onFirstFocus();
43879 var btns = this.tb.items.map,
43880 doc = this.editorcore.doc,
43881 frameId = this.editorcore.frameId;
43883 if(!this.disable.font && !Roo.isSafari){
43885 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
43886 if(name != this.fontSelect.dom.value){
43887 this.fontSelect.dom.value = name;
43891 if(!this.disable.format){
43892 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
43893 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
43894 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
43896 if(!this.disable.alignments){
43897 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
43898 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
43899 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
43901 if(!Roo.isSafari && !this.disable.lists){
43902 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
43903 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
43906 var ans = this.editorcore.getAllAncestors();
43907 if (this.formatCombo) {
43910 var store = this.formatCombo.store;
43911 this.formatCombo.setValue("");
43912 for (var i =0; i < ans.length;i++) {
43913 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
43915 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
43923 // hides menus... - so this cant be on a menu...
43924 Roo.menu.MenuMgr.hideAll();
43926 //this.editorsyncValue();
43930 createFontOptions : function(){
43931 var buf = [], fs = this.fontFamilies, ff, lc;
43935 for(var i = 0, len = fs.length; i< len; i++){
43937 lc = ff.toLowerCase();
43939 '<option value="',lc,'" style="font-family:',ff,';"',
43940 (this.defaultFont == lc ? ' selected="true">' : '>'),
43945 return buf.join('');
43948 toggleSourceEdit : function(sourceEditMode){
43950 Roo.log("toolbar toogle");
43951 if(sourceEditMode === undefined){
43952 sourceEditMode = !this.sourceEditMode;
43954 this.sourceEditMode = sourceEditMode === true;
43955 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
43956 // just toggle the button?
43957 if(btn.pressed !== this.sourceEditMode){
43958 btn.toggle(this.sourceEditMode);
43962 if(sourceEditMode){
43963 Roo.log("disabling buttons");
43964 this.tb.items.each(function(item){
43965 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
43971 Roo.log("enabling buttons");
43972 if(this.editorcore.initialized){
43973 this.tb.items.each(function(item){
43979 Roo.log("calling toggole on editor");
43980 // tell the editor that it's been pressed..
43981 this.editor.toggleSourceEdit(sourceEditMode);
43985 * Object collection of toolbar tooltips for the buttons in the editor. The key
43986 * is the command id associated with that button and the value is a valid QuickTips object.
43991 title: 'Bold (Ctrl+B)',
43992 text: 'Make the selected text bold.',
43993 cls: 'x-html-editor-tip'
43996 title: 'Italic (Ctrl+I)',
43997 text: 'Make the selected text italic.',
43998 cls: 'x-html-editor-tip'
44006 title: 'Bold (Ctrl+B)',
44007 text: 'Make the selected text bold.',
44008 cls: 'x-html-editor-tip'
44011 title: 'Italic (Ctrl+I)',
44012 text: 'Make the selected text italic.',
44013 cls: 'x-html-editor-tip'
44016 title: 'Underline (Ctrl+U)',
44017 text: 'Underline the selected text.',
44018 cls: 'x-html-editor-tip'
44020 increasefontsize : {
44021 title: 'Grow Text',
44022 text: 'Increase the font size.',
44023 cls: 'x-html-editor-tip'
44025 decreasefontsize : {
44026 title: 'Shrink Text',
44027 text: 'Decrease the font size.',
44028 cls: 'x-html-editor-tip'
44031 title: 'Text Highlight Color',
44032 text: 'Change the background color of the selected text.',
44033 cls: 'x-html-editor-tip'
44036 title: 'Font Color',
44037 text: 'Change the color of the selected text.',
44038 cls: 'x-html-editor-tip'
44041 title: 'Align Text Left',
44042 text: 'Align text to the left.',
44043 cls: 'x-html-editor-tip'
44046 title: 'Center Text',
44047 text: 'Center text in the editor.',
44048 cls: 'x-html-editor-tip'
44051 title: 'Align Text Right',
44052 text: 'Align text to the right.',
44053 cls: 'x-html-editor-tip'
44055 insertunorderedlist : {
44056 title: 'Bullet List',
44057 text: 'Start a bulleted list.',
44058 cls: 'x-html-editor-tip'
44060 insertorderedlist : {
44061 title: 'Numbered List',
44062 text: 'Start a numbered list.',
44063 cls: 'x-html-editor-tip'
44066 title: 'Hyperlink',
44067 text: 'Make the selected text a hyperlink.',
44068 cls: 'x-html-editor-tip'
44071 title: 'Source Edit',
44072 text: 'Switch to source editing mode.',
44073 cls: 'x-html-editor-tip'
44077 onDestroy : function(){
44080 this.tb.items.each(function(item){
44082 item.menu.removeAll();
44084 item.menu.el.destroy();
44092 onFirstFocus: function() {
44093 this.tb.items.each(function(item){
44102 // <script type="text/javascript">
44105 * Ext JS Library 1.1.1
44106 * Copyright(c) 2006-2007, Ext JS, LLC.
44113 * @class Roo.form.HtmlEditor.ToolbarContext
44118 new Roo.form.HtmlEditor({
44121 { xtype: 'ToolbarStandard', styles : {} }
44122 { xtype: 'ToolbarContext', disable : {} }
44128 * @config : {Object} disable List of elements to disable.. (not done yet.)
44129 * @config : {Object} styles Map of styles available.
44133 Roo.form.HtmlEditor.ToolbarContext = function(config)
44136 Roo.apply(this, config);
44137 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
44138 // dont call parent... till later.
44139 this.styles = this.styles || {};
44144 Roo.form.HtmlEditor.ToolbarContext.types = {
44156 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
44222 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
44227 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
44237 style : 'fontFamily',
44238 displayField: 'display',
44239 optname : 'font-family',
44288 // should we really allow this??
44289 // should this just be
44300 style : 'fontFamily',
44301 displayField: 'display',
44302 optname : 'font-family',
44309 style : 'fontFamily',
44310 displayField: 'display',
44311 optname : 'font-family',
44318 style : 'fontFamily',
44319 displayField: 'display',
44320 optname : 'font-family',
44331 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
44332 Roo.form.HtmlEditor.ToolbarContext.stores = false;
44334 Roo.form.HtmlEditor.ToolbarContext.options = {
44336 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
44337 [ 'Courier New', 'Courier New'],
44338 [ 'Tahoma', 'Tahoma'],
44339 [ 'Times New Roman,serif', 'Times'],
44340 [ 'Verdana','Verdana' ]
44344 // fixme - these need to be configurable..
44347 Roo.form.HtmlEditor.ToolbarContext.types
44350 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
44357 editorcore : false,
44359 * @cfg {Object} disable List of toolbar elements to disable
44364 * @cfg {Object} styles List of styles
44365 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
44367 * These must be defined in the page, so they get rendered correctly..
44378 init : function(editor)
44380 this.editor = editor;
44381 this.editorcore = editor.editorcore ? editor.editorcore : editor;
44382 var editorcore = this.editorcore;
44384 var fid = editorcore.frameId;
44386 function btn(id, toggle, handler){
44387 var xid = fid + '-'+ id ;
44391 cls : 'x-btn-icon x-edit-'+id,
44392 enableToggle:toggle !== false,
44393 scope: editorcore, // was editor...
44394 handler:handler||editorcore.relayBtnCmd,
44395 clickEvent:'mousedown',
44396 tooltip: etb.buttonTips[id] || undefined, ///tips ???
44400 // create a new element.
44401 var wdiv = editor.wrap.createChild({
44403 }, editor.wrap.dom.firstChild.nextSibling, true);
44405 // can we do this more than once??
44407 // stop form submits
44410 // disable everything...
44411 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
44412 this.toolbars = {};
44414 for (var i in ty) {
44416 this.toolbars[i] = this.buildToolbar(ty[i],i);
44418 this.tb = this.toolbars.BODY;
44420 this.buildFooter();
44421 this.footer.show();
44422 editor.on('hide', function( ) { this.footer.hide() }, this);
44423 editor.on('show', function( ) { this.footer.show() }, this);
44426 this.rendered = true;
44428 // the all the btns;
44429 editor.on('editorevent', this.updateToolbar, this);
44430 // other toolbars need to implement this..
44431 //editor.on('editmodechange', this.updateToolbar, this);
44437 * Protected method that will not generally be called directly. It triggers
44438 * a toolbar update by reading the markup state of the current selection in the editor.
44440 updateToolbar: function(editor,ev,sel){
44443 // capture mouse up - this is handy for selecting images..
44444 // perhaps should go somewhere else...
44445 if(!this.editorcore.activated){
44446 this.editor.onFirstFocus();
44450 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
44451 // selectNode - might want to handle IE?
44453 (ev.type == 'mouseup' || ev.type == 'click' ) &&
44454 ev.target && ev.target.tagName == 'IMG') {
44455 // they have click on an image...
44456 // let's see if we can change the selection...
44459 var nodeRange = sel.ownerDocument.createRange();
44461 nodeRange.selectNode(sel);
44463 nodeRange.selectNodeContents(sel);
44465 //nodeRange.collapse(true);
44466 var s = this.editorcore.win.getSelection();
44467 s.removeAllRanges();
44468 s.addRange(nodeRange);
44472 var updateFooter = sel ? false : true;
44475 var ans = this.editorcore.getAllAncestors();
44478 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
44481 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
44482 sel = sel ? sel : this.editorcore.doc.body;
44483 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
44486 // pick a menu that exists..
44487 var tn = sel.tagName.toUpperCase();
44488 //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
44490 tn = sel.tagName.toUpperCase();
44492 var lastSel = this.tb.selectedNode
44494 this.tb.selectedNode = sel;
44496 // if current menu does not match..
44497 if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
44500 ///console.log("show: " + tn);
44501 this.tb = typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
44504 this.tb.items.first().el.innerHTML = tn + ': ';
44507 // update attributes
44508 if (this.tb.fields) {
44509 this.tb.fields.each(function(e) {
44511 e.setValue(sel.style[e.stylename]);
44514 e.setValue(sel.getAttribute(e.attrname));
44518 var hasStyles = false;
44519 for(var i in this.styles) {
44526 var st = this.tb.fields.item(0);
44528 st.store.removeAll();
44531 var cn = sel.className.split(/\s+/);
44534 if (this.styles['*']) {
44536 Roo.each(this.styles['*'], function(v) {
44537 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
44540 if (this.styles[tn]) {
44541 Roo.each(this.styles[tn], function(v) {
44542 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
44546 st.store.loadData(avs);
44550 // flag our selected Node.
44551 this.tb.selectedNode = sel;
44554 Roo.menu.MenuMgr.hideAll();
44558 if (!updateFooter) {
44559 //this.footDisp.dom.innerHTML = '';
44562 // update the footer
44566 this.footerEls = ans.reverse();
44567 Roo.each(this.footerEls, function(a,i) {
44568 if (!a) { return; }
44569 html += html.length ? ' > ' : '';
44571 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
44576 var sz = this.footDisp.up('td').getSize();
44577 this.footDisp.dom.style.width = (sz.width -10) + 'px';
44578 this.footDisp.dom.style.marginLeft = '5px';
44580 this.footDisp.dom.style.overflow = 'hidden';
44582 this.footDisp.dom.innerHTML = html;
44584 //this.editorsyncValue();
44591 onDestroy : function(){
44594 this.tb.items.each(function(item){
44596 item.menu.removeAll();
44598 item.menu.el.destroy();
44606 onFirstFocus: function() {
44607 // need to do this for all the toolbars..
44608 this.tb.items.each(function(item){
44612 buildToolbar: function(tlist, nm)
44614 var editor = this.editor;
44615 var editorcore = this.editorcore;
44616 // create a new element.
44617 var wdiv = editor.wrap.createChild({
44619 }, editor.wrap.dom.firstChild.nextSibling, true);
44622 var tb = new Roo.Toolbar(wdiv);
44625 tb.add(nm+ ": ");
44628 for(var i in this.styles) {
44633 if (styles && styles.length) {
44635 // this needs a multi-select checkbox...
44636 tb.addField( new Roo.form.ComboBox({
44637 store: new Roo.data.SimpleStore({
44639 fields: ['val', 'selected'],
44642 name : '-roo-edit-className',
44643 attrname : 'className',
44644 displayField: 'val',
44648 triggerAction: 'all',
44649 emptyText:'Select Style',
44650 selectOnFocus:true,
44653 'select': function(c, r, i) {
44654 // initial support only for on class per el..
44655 tb.selectedNode.className = r ? r.get('val') : '';
44656 editorcore.syncValue();
44663 var tbc = Roo.form.HtmlEditor.ToolbarContext;
44664 var tbops = tbc.options;
44666 for (var i in tlist) {
44668 var item = tlist[i];
44669 tb.add(item.title + ": ");
44672 //optname == used so you can configure the options available..
44673 var opts = item.opts ? item.opts : false;
44674 if (item.optname) {
44675 opts = tbops[item.optname];
44680 // opts == pulldown..
44681 tb.addField( new Roo.form.ComboBox({
44682 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
44684 fields: ['val', 'display'],
44687 name : '-roo-edit-' + i,
44689 stylename : item.style ? item.style : false,
44690 displayField: item.displayField ? item.displayField : 'val',
44691 valueField : 'val',
44693 mode: typeof(tbc.stores[i]) != 'undefined' ? 'remote' : 'local',
44695 triggerAction: 'all',
44696 emptyText:'Select',
44697 selectOnFocus:true,
44698 width: item.width ? item.width : 130,
44700 'select': function(c, r, i) {
44702 tb.selectedNode.style[c.stylename] = r.get('val');
44705 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
44714 tb.addField( new Roo.form.TextField({
44717 //allowBlank:false,
44722 tb.addField( new Roo.form.TextField({
44723 name: '-roo-edit-' + i,
44730 'change' : function(f, nv, ov) {
44731 tb.selectedNode.setAttribute(f.attrname, nv);
44744 text: 'Stylesheets',
44747 click : function ()
44749 _this.editor.fireEvent('stylesheetsclick', _this.editor);
44757 text: 'Remove Tag',
44760 click : function ()
44763 // undo does not work.
44765 var sn = tb.selectedNode;
44767 var pn = sn.parentNode;
44769 var stn = sn.childNodes[0];
44770 var en = sn.childNodes[sn.childNodes.length - 1 ];
44771 while (sn.childNodes.length) {
44772 var node = sn.childNodes[0];
44773 sn.removeChild(node);
44775 pn.insertBefore(node, sn);
44778 pn.removeChild(sn);
44779 var range = editorcore.createRange();
44781 range.setStart(stn,0);
44782 range.setEnd(en,0); //????
44783 //range.selectNode(sel);
44786 var selection = editorcore.getSelection();
44787 selection.removeAllRanges();
44788 selection.addRange(range);
44792 //_this.updateToolbar(null, null, pn);
44793 _this.updateToolbar(null, null, null);
44794 _this.footDisp.dom.innerHTML = '';
44804 tb.el.on('click', function(e){
44805 e.preventDefault(); // what does this do?
44807 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
44810 // dont need to disable them... as they will get hidden
44815 buildFooter : function()
44818 var fel = this.editor.wrap.createChild();
44819 this.footer = new Roo.Toolbar(fel);
44820 // toolbar has scrolly on left / right?
44821 var footDisp= new Roo.Toolbar.Fill();
44827 handler : function() {
44828 _t.footDisp.scrollTo('left',0,true)
44832 this.footer.add( footDisp );
44837 handler : function() {
44839 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
44843 var fel = Roo.get(footDisp.el);
44844 fel.addClass('x-editor-context');
44845 this.footDispWrap = fel;
44846 this.footDispWrap.overflow = 'hidden';
44848 this.footDisp = fel.createChild();
44849 this.footDispWrap.on('click', this.onContextClick, this)
44853 onContextClick : function (ev,dom)
44855 ev.preventDefault();
44856 var cn = dom.className;
44858 if (!cn.match(/x-ed-loc-/)) {
44861 var n = cn.split('-').pop();
44862 var ans = this.footerEls;
44866 var range = this.editorcore.createRange();
44868 range.selectNodeContents(sel);
44869 //range.selectNode(sel);
44872 var selection = this.editorcore.getSelection();
44873 selection.removeAllRanges();
44874 selection.addRange(range);
44878 this.updateToolbar(null, null, sel);
44895 * Ext JS Library 1.1.1
44896 * Copyright(c) 2006-2007, Ext JS, LLC.
44898 * Originally Released Under LGPL - original licence link has changed is not relivant.
44901 * <script type="text/javascript">
44905 * @class Roo.form.BasicForm
44906 * @extends Roo.util.Observable
44907 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
44909 * @param {String/HTMLElement/Roo.Element} el The form element or its id
44910 * @param {Object} config Configuration options
44912 Roo.form.BasicForm = function(el, config){
44913 this.allItems = [];
44914 this.childForms = [];
44915 Roo.apply(this, config);
44917 * The Roo.form.Field items in this form.
44918 * @type MixedCollection
44922 this.items = new Roo.util.MixedCollection(false, function(o){
44923 return o.id || (o.id = Roo.id());
44927 * @event beforeaction
44928 * Fires before any action is performed. Return false to cancel the action.
44929 * @param {Form} this
44930 * @param {Action} action The action to be performed
44932 beforeaction: true,
44934 * @event actionfailed
44935 * Fires when an action fails.
44936 * @param {Form} this
44937 * @param {Action} action The action that failed
44939 actionfailed : true,
44941 * @event actioncomplete
44942 * Fires when an action is completed.
44943 * @param {Form} this
44944 * @param {Action} action The action that completed
44946 actioncomplete : true
44951 Roo.form.BasicForm.superclass.constructor.call(this);
44954 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
44956 * @cfg {String} method
44957 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
44960 * @cfg {DataReader} reader
44961 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
44962 * This is optional as there is built-in support for processing JSON.
44965 * @cfg {DataReader} errorReader
44966 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
44967 * This is completely optional as there is built-in support for processing JSON.
44970 * @cfg {String} url
44971 * The URL to use for form actions if one isn't supplied in the action options.
44974 * @cfg {Boolean} fileUpload
44975 * Set to true if this form is a file upload.
44979 * @cfg {Object} baseParams
44980 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
44985 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
44990 activeAction : null,
44993 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
44994 * or setValues() data instead of when the form was first created.
44996 trackResetOnLoad : false,
45000 * childForms - used for multi-tab forms
45003 childForms : false,
45006 * allItems - full list of fields.
45012 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
45013 * element by passing it or its id or mask the form itself by passing in true.
45016 waitMsgTarget : false,
45019 initEl : function(el){
45020 this.el = Roo.get(el);
45021 this.id = this.el.id || Roo.id();
45022 this.el.on('submit', this.onSubmit, this);
45023 this.el.addClass('x-form');
45027 onSubmit : function(e){
45032 * Returns true if client-side validation on the form is successful.
45035 isValid : function(){
45037 this.items.each(function(f){
45046 * Returns true if any fields in this form have changed since their original load.
45049 isDirty : function(){
45051 this.items.each(function(f){
45061 * Performs a predefined action (submit or load) or custom actions you define on this form.
45062 * @param {String} actionName The name of the action type
45063 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
45064 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
45065 * accept other config options):
45067 Property Type Description
45068 ---------------- --------------- ----------------------------------------------------------------------------------
45069 url String The url for the action (defaults to the form's url)
45070 method String The form method to use (defaults to the form's method, or POST if not defined)
45071 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
45072 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
45073 validate the form on the client (defaults to false)
45075 * @return {BasicForm} this
45077 doAction : function(action, options){
45078 if(typeof action == 'string'){
45079 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
45081 if(this.fireEvent('beforeaction', this, action) !== false){
45082 this.beforeAction(action);
45083 action.run.defer(100, action);
45089 * Shortcut to do a submit action.
45090 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
45091 * @return {BasicForm} this
45093 submit : function(options){
45094 this.doAction('submit', options);
45099 * Shortcut to do a load action.
45100 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
45101 * @return {BasicForm} this
45103 load : function(options){
45104 this.doAction('load', options);
45109 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
45110 * @param {Record} record The record to edit
45111 * @return {BasicForm} this
45113 updateRecord : function(record){
45114 record.beginEdit();
45115 var fs = record.fields;
45116 fs.each(function(f){
45117 var field = this.findField(f.name);
45119 record.set(f.name, field.getValue());
45127 * Loads an Roo.data.Record into this form.
45128 * @param {Record} record The record to load
45129 * @return {BasicForm} this
45131 loadRecord : function(record){
45132 this.setValues(record.data);
45137 beforeAction : function(action){
45138 var o = action.options;
45141 if(this.waitMsgTarget === true){
45142 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
45143 }else if(this.waitMsgTarget){
45144 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
45145 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
45147 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
45153 afterAction : function(action, success){
45154 this.activeAction = null;
45155 var o = action.options;
45157 if(this.waitMsgTarget === true){
45159 }else if(this.waitMsgTarget){
45160 this.waitMsgTarget.unmask();
45162 Roo.MessageBox.updateProgress(1);
45163 Roo.MessageBox.hide();
45170 Roo.callback(o.success, o.scope, [this, action]);
45171 this.fireEvent('actioncomplete', this, action);
45175 // failure condition..
45176 // we have a scenario where updates need confirming.
45177 // eg. if a locking scenario exists..
45178 // we look for { errors : { needs_confirm : true }} in the response.
45180 (typeof(action.result) != 'undefined') &&
45181 (typeof(action.result.errors) != 'undefined') &&
45182 (typeof(action.result.errors.needs_confirm) != 'undefined')
45185 Roo.MessageBox.confirm(
45186 "Change requires confirmation",
45187 action.result.errorMsg,
45192 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
45202 Roo.callback(o.failure, o.scope, [this, action]);
45203 // show an error message if no failed handler is set..
45204 if (!this.hasListener('actionfailed')) {
45205 Roo.MessageBox.alert("Error",
45206 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
45207 action.result.errorMsg :
45208 "Saving Failed, please check your entries or try again"
45212 this.fireEvent('actionfailed', this, action);
45218 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
45219 * @param {String} id The value to search for
45222 findField : function(id){
45223 var field = this.items.get(id);
45225 this.items.each(function(f){
45226 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
45232 return field || null;
45236 * Add a secondary form to this one,
45237 * Used to provide tabbed forms. One form is primary, with hidden values
45238 * which mirror the elements from the other forms.
45240 * @param {Roo.form.Form} form to add.
45243 addForm : function(form)
45246 if (this.childForms.indexOf(form) > -1) {
45250 this.childForms.push(form);
45252 Roo.each(form.allItems, function (fe) {
45254 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
45255 if (this.findField(n)) { // already added..
45258 var add = new Roo.form.Hidden({
45261 add.render(this.el);
45268 * Mark fields in this form invalid in bulk.
45269 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
45270 * @return {BasicForm} this
45272 markInvalid : function(errors){
45273 if(errors instanceof Array){
45274 for(var i = 0, len = errors.length; i < len; i++){
45275 var fieldError = errors[i];
45276 var f = this.findField(fieldError.id);
45278 f.markInvalid(fieldError.msg);
45284 if(typeof errors[id] != 'function' && (field = this.findField(id))){
45285 field.markInvalid(errors[id]);
45289 Roo.each(this.childForms || [], function (f) {
45290 f.markInvalid(errors);
45297 * Set values for fields in this form in bulk.
45298 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
45299 * @return {BasicForm} this
45301 setValues : function(values){
45302 if(values instanceof Array){ // array of objects
45303 for(var i = 0, len = values.length; i < len; i++){
45305 var f = this.findField(v.id);
45307 f.setValue(v.value);
45308 if(this.trackResetOnLoad){
45309 f.originalValue = f.getValue();
45313 }else{ // object hash
45316 if(typeof values[id] != 'function' && (field = this.findField(id))){
45318 if (field.setFromData &&
45319 field.valueField &&
45320 field.displayField &&
45321 // combos' with local stores can
45322 // be queried via setValue()
45323 // to set their value..
45324 (field.store && !field.store.isLocal)
45328 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
45329 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
45330 field.setFromData(sd);
45333 field.setValue(values[id]);
45337 if(this.trackResetOnLoad){
45338 field.originalValue = field.getValue();
45344 Roo.each(this.childForms || [], function (f) {
45345 f.setValues(values);
45352 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
45353 * they are returned as an array.
45354 * @param {Boolean} asString
45357 getValues : function(asString){
45358 if (this.childForms) {
45359 // copy values from the child forms
45360 Roo.each(this.childForms, function (f) {
45361 this.setValues(f.getValues());
45367 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
45368 if(asString === true){
45371 return Roo.urlDecode(fs);
45375 * Returns the fields in this form as an object with key/value pairs.
45376 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
45379 getFieldValues : function(with_hidden)
45381 if (this.childForms) {
45382 // copy values from the child forms
45383 // should this call getFieldValues - probably not as we do not currently copy
45384 // hidden fields when we generate..
45385 Roo.each(this.childForms, function (f) {
45386 this.setValues(f.getValues());
45391 this.items.each(function(f){
45392 if (!f.getName()) {
45395 var v = f.getValue();
45396 if (f.inputType =='radio') {
45397 if (typeof(ret[f.getName()]) == 'undefined') {
45398 ret[f.getName()] = ''; // empty..
45401 if (!f.el.dom.checked) {
45405 v = f.el.dom.value;
45409 // not sure if this supported any more..
45410 if ((typeof(v) == 'object') && f.getRawValue) {
45411 v = f.getRawValue() ; // dates..
45413 // combo boxes where name != hiddenName...
45414 if (f.name != f.getName()) {
45415 ret[f.name] = f.getRawValue();
45417 ret[f.getName()] = v;
45424 * Clears all invalid messages in this form.
45425 * @return {BasicForm} this
45427 clearInvalid : function(){
45428 this.items.each(function(f){
45432 Roo.each(this.childForms || [], function (f) {
45441 * Resets this form.
45442 * @return {BasicForm} this
45444 reset : function(){
45445 this.items.each(function(f){
45449 Roo.each(this.childForms || [], function (f) {
45458 * Add Roo.form components to this form.
45459 * @param {Field} field1
45460 * @param {Field} field2 (optional)
45461 * @param {Field} etc (optional)
45462 * @return {BasicForm} this
45465 this.items.addAll(Array.prototype.slice.call(arguments, 0));
45471 * Removes a field from the items collection (does NOT remove its markup).
45472 * @param {Field} field
45473 * @return {BasicForm} this
45475 remove : function(field){
45476 this.items.remove(field);
45481 * Looks at the fields in this form, checks them for an id attribute,
45482 * and calls applyTo on the existing dom element with that id.
45483 * @return {BasicForm} this
45485 render : function(){
45486 this.items.each(function(f){
45487 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
45495 * Calls {@link Ext#apply} for all fields in this form with the passed object.
45496 * @param {Object} values
45497 * @return {BasicForm} this
45499 applyToFields : function(o){
45500 this.items.each(function(f){
45507 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
45508 * @param {Object} values
45509 * @return {BasicForm} this
45511 applyIfToFields : function(o){
45512 this.items.each(function(f){
45520 Roo.BasicForm = Roo.form.BasicForm;/*
45522 * Ext JS Library 1.1.1
45523 * Copyright(c) 2006-2007, Ext JS, LLC.
45525 * Originally Released Under LGPL - original licence link has changed is not relivant.
45528 * <script type="text/javascript">
45532 * @class Roo.form.Form
45533 * @extends Roo.form.BasicForm
45534 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
45536 * @param {Object} config Configuration options
45538 Roo.form.Form = function(config){
45540 if (config.items) {
45541 xitems = config.items;
45542 delete config.items;
45546 Roo.form.Form.superclass.constructor.call(this, null, config);
45547 this.url = this.url || this.action;
45549 this.root = new Roo.form.Layout(Roo.applyIf({
45553 this.active = this.root;
45555 * Array of all the buttons that have been added to this form via {@link addButton}
45559 this.allItems = [];
45562 * @event clientvalidation
45563 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
45564 * @param {Form} this
45565 * @param {Boolean} valid true if the form has passed client-side validation
45567 clientvalidation: true,
45570 * Fires when the form is rendered
45571 * @param {Roo.form.Form} form
45576 if (this.progressUrl) {
45577 // push a hidden field onto the list of fields..
45581 name : 'UPLOAD_IDENTIFIER'
45586 Roo.each(xitems, this.addxtype, this);
45592 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
45594 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
45597 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
45600 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
45602 buttonAlign:'center',
45605 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
45610 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
45611 * This property cascades to child containers if not set.
45616 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
45617 * fires a looping event with that state. This is required to bind buttons to the valid
45618 * state using the config value formBind:true on the button.
45620 monitorValid : false,
45623 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
45628 * @cfg {String} progressUrl - Url to return progress data
45631 progressUrl : false,
45634 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
45635 * fields are added and the column is closed. If no fields are passed the column remains open
45636 * until end() is called.
45637 * @param {Object} config The config to pass to the column
45638 * @param {Field} field1 (optional)
45639 * @param {Field} field2 (optional)
45640 * @param {Field} etc (optional)
45641 * @return Column The column container object
45643 column : function(c){
45644 var col = new Roo.form.Column(c);
45646 if(arguments.length > 1){ // duplicate code required because of Opera
45647 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45654 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
45655 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
45656 * until end() is called.
45657 * @param {Object} config The config to pass to the fieldset
45658 * @param {Field} field1 (optional)
45659 * @param {Field} field2 (optional)
45660 * @param {Field} etc (optional)
45661 * @return FieldSet The fieldset container object
45663 fieldset : function(c){
45664 var fs = new Roo.form.FieldSet(c);
45666 if(arguments.length > 1){ // duplicate code required because of Opera
45667 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45674 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
45675 * fields are added and the container is closed. If no fields are passed the container remains open
45676 * until end() is called.
45677 * @param {Object} config The config to pass to the Layout
45678 * @param {Field} field1 (optional)
45679 * @param {Field} field2 (optional)
45680 * @param {Field} etc (optional)
45681 * @return Layout The container object
45683 container : function(c){
45684 var l = new Roo.form.Layout(c);
45686 if(arguments.length > 1){ // duplicate code required because of Opera
45687 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45694 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
45695 * @param {Object} container A Roo.form.Layout or subclass of Layout
45696 * @return {Form} this
45698 start : function(c){
45699 // cascade label info
45700 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
45701 this.active.stack.push(c);
45702 c.ownerCt = this.active;
45708 * Closes the current open container
45709 * @return {Form} this
45712 if(this.active == this.root){
45715 this.active = this.active.ownerCt;
45720 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
45721 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
45722 * as the label of the field.
45723 * @param {Field} field1
45724 * @param {Field} field2 (optional)
45725 * @param {Field} etc. (optional)
45726 * @return {Form} this
45729 this.active.stack.push.apply(this.active.stack, arguments);
45730 this.allItems.push.apply(this.allItems,arguments);
45732 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
45733 if(a[i].isFormField){
45738 Roo.form.Form.superclass.add.apply(this, r);
45748 * Find any element that has been added to a form, using it's ID or name
45749 * This can include framesets, columns etc. along with regular fields..
45750 * @param {String} id - id or name to find.
45752 * @return {Element} e - or false if nothing found.
45754 findbyId : function(id)
45760 Roo.each(this.allItems, function(f){
45761 if (f.id == id || f.name == id ){
45772 * Render this form into the passed container. This should only be called once!
45773 * @param {String/HTMLElement/Element} container The element this component should be rendered into
45774 * @return {Form} this
45776 render : function(ct)
45782 var o = this.autoCreate || {
45784 method : this.method || 'POST',
45785 id : this.id || Roo.id()
45787 this.initEl(ct.createChild(o));
45789 this.root.render(this.el);
45793 this.items.each(function(f){
45794 f.render('x-form-el-'+f.id);
45797 if(this.buttons.length > 0){
45798 // tables are required to maintain order and for correct IE layout
45799 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
45800 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
45801 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
45803 var tr = tb.getElementsByTagName('tr')[0];
45804 for(var i = 0, len = this.buttons.length; i < len; i++) {
45805 var b = this.buttons[i];
45806 var td = document.createElement('td');
45807 td.className = 'x-form-btn-td';
45808 b.render(tr.appendChild(td));
45811 if(this.monitorValid){ // initialize after render
45812 this.startMonitoring();
45814 this.fireEvent('rendered', this);
45819 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
45820 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
45821 * object or a valid Roo.DomHelper element config
45822 * @param {Function} handler The function called when the button is clicked
45823 * @param {Object} scope (optional) The scope of the handler function
45824 * @return {Roo.Button}
45826 addButton : function(config, handler, scope){
45830 minWidth: this.minButtonWidth,
45833 if(typeof config == "string"){
45836 Roo.apply(bc, config);
45838 var btn = new Roo.Button(null, bc);
45839 this.buttons.push(btn);
45844 * Adds a series of form elements (using the xtype property as the factory method.
45845 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
45846 * @param {Object} config
45849 addxtype : function()
45851 var ar = Array.prototype.slice.call(arguments, 0);
45853 for(var i = 0; i < ar.length; i++) {
45855 continue; // skip -- if this happends something invalid got sent, we
45856 // should ignore it, as basically that interface element will not show up
45857 // and that should be pretty obvious!!
45860 if (Roo.form[ar[i].xtype]) {
45862 var fe = Roo.factory(ar[i], Roo.form);
45868 fe.store.form = this;
45873 this.allItems.push(fe);
45874 if (fe.items && fe.addxtype) {
45875 fe.addxtype.apply(fe, fe.items);
45885 // console.log('adding ' + ar[i].xtype);
45887 if (ar[i].xtype == 'Button') {
45888 //console.log('adding button');
45889 //console.log(ar[i]);
45890 this.addButton(ar[i]);
45891 this.allItems.push(fe);
45895 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
45896 alert('end is not supported on xtype any more, use items');
45898 // //console.log('adding end');
45906 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
45907 * option "monitorValid"
45909 startMonitoring : function(){
45912 Roo.TaskMgr.start({
45913 run : this.bindHandler,
45914 interval : this.monitorPoll || 200,
45921 * Stops monitoring of the valid state of this form
45923 stopMonitoring : function(){
45924 this.bound = false;
45928 bindHandler : function(){
45930 return false; // stops binding
45933 this.items.each(function(f){
45934 if(!f.isValid(true)){
45939 for(var i = 0, len = this.buttons.length; i < len; i++){
45940 var btn = this.buttons[i];
45941 if(btn.formBind === true && btn.disabled === valid){
45942 btn.setDisabled(!valid);
45945 this.fireEvent('clientvalidation', this, valid);
45959 Roo.Form = Roo.form.Form;
45962 * Ext JS Library 1.1.1
45963 * Copyright(c) 2006-2007, Ext JS, LLC.
45965 * Originally Released Under LGPL - original licence link has changed is not relivant.
45968 * <script type="text/javascript">
45971 // as we use this in bootstrap.
45972 Roo.namespace('Roo.form');
45974 * @class Roo.form.Action
45975 * Internal Class used to handle form actions
45977 * @param {Roo.form.BasicForm} el The form element or its id
45978 * @param {Object} config Configuration options
45983 // define the action interface
45984 Roo.form.Action = function(form, options){
45986 this.options = options || {};
45989 * Client Validation Failed
45992 Roo.form.Action.CLIENT_INVALID = 'client';
45994 * Server Validation Failed
45997 Roo.form.Action.SERVER_INVALID = 'server';
45999 * Connect to Server Failed
46002 Roo.form.Action.CONNECT_FAILURE = 'connect';
46004 * Reading Data from Server Failed
46007 Roo.form.Action.LOAD_FAILURE = 'load';
46009 Roo.form.Action.prototype = {
46011 failureType : undefined,
46012 response : undefined,
46013 result : undefined,
46015 // interface method
46016 run : function(options){
46020 // interface method
46021 success : function(response){
46025 // interface method
46026 handleResponse : function(response){
46030 // default connection failure
46031 failure : function(response){
46033 this.response = response;
46034 this.failureType = Roo.form.Action.CONNECT_FAILURE;
46035 this.form.afterAction(this, false);
46038 processResponse : function(response){
46039 this.response = response;
46040 if(!response.responseText){
46043 this.result = this.handleResponse(response);
46044 return this.result;
46047 // utility functions used internally
46048 getUrl : function(appendParams){
46049 var url = this.options.url || this.form.url || this.form.el.dom.action;
46051 var p = this.getParams();
46053 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
46059 getMethod : function(){
46060 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
46063 getParams : function(){
46064 var bp = this.form.baseParams;
46065 var p = this.options.params;
46067 if(typeof p == "object"){
46068 p = Roo.urlEncode(Roo.applyIf(p, bp));
46069 }else if(typeof p == 'string' && bp){
46070 p += '&' + Roo.urlEncode(bp);
46073 p = Roo.urlEncode(bp);
46078 createCallback : function(){
46080 success: this.success,
46081 failure: this.failure,
46083 timeout: (this.form.timeout*1000),
46084 upload: this.form.fileUpload ? this.success : undefined
46089 Roo.form.Action.Submit = function(form, options){
46090 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
46093 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
46096 haveProgress : false,
46097 uploadComplete : false,
46099 // uploadProgress indicator.
46100 uploadProgress : function()
46102 if (!this.form.progressUrl) {
46106 if (!this.haveProgress) {
46107 Roo.MessageBox.progress("Uploading", "Uploading");
46109 if (this.uploadComplete) {
46110 Roo.MessageBox.hide();
46114 this.haveProgress = true;
46116 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
46118 var c = new Roo.data.Connection();
46120 url : this.form.progressUrl,
46125 success : function(req){
46126 //console.log(data);
46130 rdata = Roo.decode(req.responseText)
46132 Roo.log("Invalid data from server..");
46136 if (!rdata || !rdata.success) {
46138 Roo.MessageBox.alert(Roo.encode(rdata));
46141 var data = rdata.data;
46143 if (this.uploadComplete) {
46144 Roo.MessageBox.hide();
46149 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
46150 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
46153 this.uploadProgress.defer(2000,this);
46156 failure: function(data) {
46157 Roo.log('progress url failed ');
46168 // run get Values on the form, so it syncs any secondary forms.
46169 this.form.getValues();
46171 var o = this.options;
46172 var method = this.getMethod();
46173 var isPost = method == 'POST';
46174 if(o.clientValidation === false || this.form.isValid()){
46176 if (this.form.progressUrl) {
46177 this.form.findField('UPLOAD_IDENTIFIER').setValue(
46178 (new Date() * 1) + '' + Math.random());
46183 Roo.Ajax.request(Roo.apply(this.createCallback(), {
46184 form:this.form.el.dom,
46185 url:this.getUrl(!isPost),
46187 params:isPost ? this.getParams() : null,
46188 isUpload: this.form.fileUpload
46191 this.uploadProgress();
46193 }else if (o.clientValidation !== false){ // client validation failed
46194 this.failureType = Roo.form.Action.CLIENT_INVALID;
46195 this.form.afterAction(this, false);
46199 success : function(response)
46201 this.uploadComplete= true;
46202 if (this.haveProgress) {
46203 Roo.MessageBox.hide();
46207 var result = this.processResponse(response);
46208 if(result === true || result.success){
46209 this.form.afterAction(this, true);
46213 this.form.markInvalid(result.errors);
46214 this.failureType = Roo.form.Action.SERVER_INVALID;
46216 this.form.afterAction(this, false);
46218 failure : function(response)
46220 this.uploadComplete= true;
46221 if (this.haveProgress) {
46222 Roo.MessageBox.hide();
46225 this.response = response;
46226 this.failureType = Roo.form.Action.CONNECT_FAILURE;
46227 this.form.afterAction(this, false);
46230 handleResponse : function(response){
46231 if(this.form.errorReader){
46232 var rs = this.form.errorReader.read(response);
46235 for(var i = 0, len = rs.records.length; i < len; i++) {
46236 var r = rs.records[i];
46237 errors[i] = r.data;
46240 if(errors.length < 1){
46244 success : rs.success,
46250 ret = Roo.decode(response.responseText);
46254 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
46264 Roo.form.Action.Load = function(form, options){
46265 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
46266 this.reader = this.form.reader;
46269 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
46274 Roo.Ajax.request(Roo.apply(
46275 this.createCallback(), {
46276 method:this.getMethod(),
46277 url:this.getUrl(false),
46278 params:this.getParams()
46282 success : function(response){
46284 var result = this.processResponse(response);
46285 if(result === true || !result.success || !result.data){
46286 this.failureType = Roo.form.Action.LOAD_FAILURE;
46287 this.form.afterAction(this, false);
46290 this.form.clearInvalid();
46291 this.form.setValues(result.data);
46292 this.form.afterAction(this, true);
46295 handleResponse : function(response){
46296 if(this.form.reader){
46297 var rs = this.form.reader.read(response);
46298 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
46300 success : rs.success,
46304 return Roo.decode(response.responseText);
46308 Roo.form.Action.ACTION_TYPES = {
46309 'load' : Roo.form.Action.Load,
46310 'submit' : Roo.form.Action.Submit
46313 * Ext JS Library 1.1.1
46314 * Copyright(c) 2006-2007, Ext JS, LLC.
46316 * Originally Released Under LGPL - original licence link has changed is not relivant.
46319 * <script type="text/javascript">
46323 * @class Roo.form.Layout
46324 * @extends Roo.Component
46325 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
46327 * @param {Object} config Configuration options
46329 Roo.form.Layout = function(config){
46331 if (config.items) {
46332 xitems = config.items;
46333 delete config.items;
46335 Roo.form.Layout.superclass.constructor.call(this, config);
46337 Roo.each(xitems, this.addxtype, this);
46341 Roo.extend(Roo.form.Layout, Roo.Component, {
46343 * @cfg {String/Object} autoCreate
46344 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
46347 * @cfg {String/Object/Function} style
46348 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
46349 * a function which returns such a specification.
46352 * @cfg {String} labelAlign
46353 * Valid values are "left," "top" and "right" (defaults to "left")
46356 * @cfg {Number} labelWidth
46357 * Fixed width in pixels of all field labels (defaults to undefined)
46360 * @cfg {Boolean} clear
46361 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
46365 * @cfg {String} labelSeparator
46366 * The separator to use after field labels (defaults to ':')
46368 labelSeparator : ':',
46370 * @cfg {Boolean} hideLabels
46371 * True to suppress the display of field labels in this layout (defaults to false)
46373 hideLabels : false,
46376 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
46381 onRender : function(ct, position){
46382 if(this.el){ // from markup
46383 this.el = Roo.get(this.el);
46384 }else { // generate
46385 var cfg = this.getAutoCreate();
46386 this.el = ct.createChild(cfg, position);
46389 this.el.applyStyles(this.style);
46391 if(this.labelAlign){
46392 this.el.addClass('x-form-label-'+this.labelAlign);
46394 if(this.hideLabels){
46395 this.labelStyle = "display:none";
46396 this.elementStyle = "padding-left:0;";
46398 if(typeof this.labelWidth == 'number'){
46399 this.labelStyle = "width:"+this.labelWidth+"px;";
46400 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
46402 if(this.labelAlign == 'top'){
46403 this.labelStyle = "width:auto;";
46404 this.elementStyle = "padding-left:0;";
46407 var stack = this.stack;
46408 var slen = stack.length;
46410 if(!this.fieldTpl){
46411 var t = new Roo.Template(
46412 '<div class="x-form-item {5}">',
46413 '<label for="{0}" style="{2}">{1}{4}</label>',
46414 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
46416 '</div><div class="x-form-clear-left"></div>'
46418 t.disableFormats = true;
46420 Roo.form.Layout.prototype.fieldTpl = t;
46422 for(var i = 0; i < slen; i++) {
46423 if(stack[i].isFormField){
46424 this.renderField(stack[i]);
46426 this.renderComponent(stack[i]);
46431 this.el.createChild({cls:'x-form-clear'});
46436 renderField : function(f){
46437 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
46440 f.labelStyle||this.labelStyle||'', //2
46441 this.elementStyle||'', //3
46442 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
46443 f.itemCls||this.itemCls||'' //5
46444 ], true).getPrevSibling());
46448 renderComponent : function(c){
46449 c.render(c.isLayout ? this.el : this.el.createChild());
46452 * Adds a object form elements (using the xtype property as the factory method.)
46453 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
46454 * @param {Object} config
46456 addxtype : function(o)
46458 // create the lement.
46459 o.form = this.form;
46460 var fe = Roo.factory(o, Roo.form);
46461 this.form.allItems.push(fe);
46462 this.stack.push(fe);
46464 if (fe.isFormField) {
46465 this.form.items.add(fe);
46473 * @class Roo.form.Column
46474 * @extends Roo.form.Layout
46475 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
46477 * @param {Object} config Configuration options
46479 Roo.form.Column = function(config){
46480 Roo.form.Column.superclass.constructor.call(this, config);
46483 Roo.extend(Roo.form.Column, Roo.form.Layout, {
46485 * @cfg {Number/String} width
46486 * The fixed width of the column in pixels or CSS value (defaults to "auto")
46489 * @cfg {String/Object} autoCreate
46490 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
46494 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
46497 onRender : function(ct, position){
46498 Roo.form.Column.superclass.onRender.call(this, ct, position);
46500 this.el.setWidth(this.width);
46507 * @class Roo.form.Row
46508 * @extends Roo.form.Layout
46509 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
46511 * @param {Object} config Configuration options
46515 Roo.form.Row = function(config){
46516 Roo.form.Row.superclass.constructor.call(this, config);
46519 Roo.extend(Roo.form.Row, Roo.form.Layout, {
46521 * @cfg {Number/String} width
46522 * The fixed width of the column in pixels or CSS value (defaults to "auto")
46525 * @cfg {Number/String} height
46526 * The fixed height of the column in pixels or CSS value (defaults to "auto")
46528 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
46532 onRender : function(ct, position){
46533 //console.log('row render');
46535 var t = new Roo.Template(
46536 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
46537 '<label for="{0}" style="{2}">{1}{4}</label>',
46538 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
46542 t.disableFormats = true;
46544 Roo.form.Layout.prototype.rowTpl = t;
46546 this.fieldTpl = this.rowTpl;
46548 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
46549 var labelWidth = 100;
46551 if ((this.labelAlign != 'top')) {
46552 if (typeof this.labelWidth == 'number') {
46553 labelWidth = this.labelWidth
46555 this.padWidth = 20 + labelWidth;
46559 Roo.form.Column.superclass.onRender.call(this, ct, position);
46561 this.el.setWidth(this.width);
46564 this.el.setHeight(this.height);
46569 renderField : function(f){
46570 f.fieldEl = this.fieldTpl.append(this.el, [
46571 f.id, f.fieldLabel,
46572 f.labelStyle||this.labelStyle||'',
46573 this.elementStyle||'',
46574 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
46575 f.itemCls||this.itemCls||'',
46576 f.width ? f.width + this.padWidth : 160 + this.padWidth
46583 * @class Roo.form.FieldSet
46584 * @extends Roo.form.Layout
46585 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
46587 * @param {Object} config Configuration options
46589 Roo.form.FieldSet = function(config){
46590 Roo.form.FieldSet.superclass.constructor.call(this, config);
46593 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
46595 * @cfg {String} legend
46596 * The text to display as the legend for the FieldSet (defaults to '')
46599 * @cfg {String/Object} autoCreate
46600 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
46604 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
46607 onRender : function(ct, position){
46608 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
46610 this.setLegend(this.legend);
46615 setLegend : function(text){
46617 this.el.child('legend').update(text);
46622 * Ext JS Library 1.1.1
46623 * Copyright(c) 2006-2007, Ext JS, LLC.
46625 * Originally Released Under LGPL - original licence link has changed is not relivant.
46628 * <script type="text/javascript">
46631 * @class Roo.form.VTypes
46632 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
46635 Roo.form.VTypes = function(){
46636 // closure these in so they are only created once.
46637 var alpha = /^[a-zA-Z_]+$/;
46638 var alphanum = /^[a-zA-Z0-9_]+$/;
46639 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
46640 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
46642 // All these messages and functions are configurable
46645 * The function used to validate email addresses
46646 * @param {String} value The email address
46648 'email' : function(v){
46649 return email.test(v);
46652 * The error text to display when the email validation function returns false
46655 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
46657 * The keystroke filter mask to be applied on email input
46660 'emailMask' : /[a-z0-9_\.\-@]/i,
46663 * The function used to validate URLs
46664 * @param {String} value The URL
46666 'url' : function(v){
46667 return url.test(v);
46670 * The error text to display when the url validation function returns false
46673 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
46676 * The function used to validate alpha values
46677 * @param {String} value The value
46679 'alpha' : function(v){
46680 return alpha.test(v);
46683 * The error text to display when the alpha validation function returns false
46686 'alphaText' : 'This field should only contain letters and _',
46688 * The keystroke filter mask to be applied on alpha input
46691 'alphaMask' : /[a-z_]/i,
46694 * The function used to validate alphanumeric values
46695 * @param {String} value The value
46697 'alphanum' : function(v){
46698 return alphanum.test(v);
46701 * The error text to display when the alphanumeric validation function returns false
46704 'alphanumText' : 'This field should only contain letters, numbers and _',
46706 * The keystroke filter mask to be applied on alphanumeric input
46709 'alphanumMask' : /[a-z0-9_]/i
46711 }();//<script type="text/javascript">
46714 * @class Roo.form.FCKeditor
46715 * @extends Roo.form.TextArea
46716 * Wrapper around the FCKEditor http://www.fckeditor.net
46718 * Creates a new FCKeditor
46719 * @param {Object} config Configuration options
46721 Roo.form.FCKeditor = function(config){
46722 Roo.form.FCKeditor.superclass.constructor.call(this, config);
46725 * @event editorinit
46726 * Fired when the editor is initialized - you can add extra handlers here..
46727 * @param {FCKeditor} this
46728 * @param {Object} the FCK object.
46735 Roo.form.FCKeditor.editors = { };
46736 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
46738 //defaultAutoCreate : {
46739 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
46743 * @cfg {Object} fck options - see fck manual for details.
46748 * @cfg {Object} fck toolbar set (Basic or Default)
46750 toolbarSet : 'Basic',
46752 * @cfg {Object} fck BasePath
46754 basePath : '/fckeditor/',
46762 onRender : function(ct, position)
46765 this.defaultAutoCreate = {
46767 style:"width:300px;height:60px;",
46768 autocomplete: "new-password"
46771 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
46774 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
46775 if(this.preventScrollbars){
46776 this.el.setStyle("overflow", "hidden");
46778 this.el.setHeight(this.growMin);
46781 //console.log('onrender' + this.getId() );
46782 Roo.form.FCKeditor.editors[this.getId()] = this;
46785 this.replaceTextarea() ;
46789 getEditor : function() {
46790 return this.fckEditor;
46793 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
46794 * @param {Mixed} value The value to set
46798 setValue : function(value)
46800 //console.log('setValue: ' + value);
46802 if(typeof(value) == 'undefined') { // not sure why this is happending...
46805 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
46807 //if(!this.el || !this.getEditor()) {
46808 // this.value = value;
46809 //this.setValue.defer(100,this,[value]);
46813 if(!this.getEditor()) {
46817 this.getEditor().SetData(value);
46824 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
46825 * @return {Mixed} value The field value
46827 getValue : function()
46830 if (this.frame && this.frame.dom.style.display == 'none') {
46831 return Roo.form.FCKeditor.superclass.getValue.call(this);
46834 if(!this.el || !this.getEditor()) {
46836 // this.getValue.defer(100,this);
46841 var value=this.getEditor().GetData();
46842 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
46843 return Roo.form.FCKeditor.superclass.getValue.call(this);
46849 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
46850 * @return {Mixed} value The field value
46852 getRawValue : function()
46854 if (this.frame && this.frame.dom.style.display == 'none') {
46855 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
46858 if(!this.el || !this.getEditor()) {
46859 //this.getRawValue.defer(100,this);
46866 var value=this.getEditor().GetData();
46867 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
46868 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
46872 setSize : function(w,h) {
46876 //if (this.frame && this.frame.dom.style.display == 'none') {
46877 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
46880 //if(!this.el || !this.getEditor()) {
46881 // this.setSize.defer(100,this, [w,h]);
46887 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
46889 this.frame.dom.setAttribute('width', w);
46890 this.frame.dom.setAttribute('height', h);
46891 this.frame.setSize(w,h);
46895 toggleSourceEdit : function(value) {
46899 this.el.dom.style.display = value ? '' : 'none';
46900 this.frame.dom.style.display = value ? 'none' : '';
46905 focus: function(tag)
46907 if (this.frame.dom.style.display == 'none') {
46908 return Roo.form.FCKeditor.superclass.focus.call(this);
46910 if(!this.el || !this.getEditor()) {
46911 this.focus.defer(100,this, [tag]);
46918 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
46919 this.getEditor().Focus();
46921 if (!this.getEditor().Selection.GetSelection()) {
46922 this.focus.defer(100,this, [tag]);
46927 var r = this.getEditor().EditorDocument.createRange();
46928 r.setStart(tgs[0],0);
46929 r.setEnd(tgs[0],0);
46930 this.getEditor().Selection.GetSelection().removeAllRanges();
46931 this.getEditor().Selection.GetSelection().addRange(r);
46932 this.getEditor().Focus();
46939 replaceTextarea : function()
46941 if ( document.getElementById( this.getId() + '___Frame' ) )
46943 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
46945 // We must check the elements firstly using the Id and then the name.
46946 var oTextarea = document.getElementById( this.getId() );
46948 var colElementsByName = document.getElementsByName( this.getId() ) ;
46950 oTextarea.style.display = 'none' ;
46952 if ( oTextarea.tabIndex ) {
46953 this.TabIndex = oTextarea.tabIndex ;
46956 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
46957 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
46958 this.frame = Roo.get(this.getId() + '___Frame')
46961 _getConfigHtml : function()
46965 for ( var o in this.fckconfig ) {
46966 sConfig += sConfig.length > 0 ? '&' : '';
46967 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
46970 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
46974 _getIFrameHtml : function()
46976 var sFile = 'fckeditor.html' ;
46977 /* no idea what this is about..
46980 if ( (/fcksource=true/i).test( window.top.location.search ) )
46981 sFile = 'fckeditor.original.html' ;
46986 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
46987 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
46990 var html = '<iframe id="' + this.getId() +
46991 '___Frame" src="' + sLink +
46992 '" width="' + this.width +
46993 '" height="' + this.height + '"' +
46994 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
46995 ' frameborder="0" scrolling="no"></iframe>' ;
47000 _insertHtmlBefore : function( html, element )
47002 if ( element.insertAdjacentHTML ) {
47004 element.insertAdjacentHTML( 'beforeBegin', html ) ;
47006 var oRange = document.createRange() ;
47007 oRange.setStartBefore( element ) ;
47008 var oFragment = oRange.createContextualFragment( html );
47009 element.parentNode.insertBefore( oFragment, element ) ;
47022 //Roo.reg('fckeditor', Roo.form.FCKeditor);
47024 function FCKeditor_OnComplete(editorInstance){
47025 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
47026 f.fckEditor = editorInstance;
47027 //console.log("loaded");
47028 f.fireEvent('editorinit', f, editorInstance);
47048 //<script type="text/javascript">
47050 * @class Roo.form.GridField
47051 * @extends Roo.form.Field
47052 * Embed a grid (or editable grid into a form)
47055 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
47057 * xgrid.store = Roo.data.Store
47058 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
47059 * xgrid.store.reader = Roo.data.JsonReader
47063 * Creates a new GridField
47064 * @param {Object} config Configuration options
47066 Roo.form.GridField = function(config){
47067 Roo.form.GridField.superclass.constructor.call(this, config);
47071 Roo.extend(Roo.form.GridField, Roo.form.Field, {
47073 * @cfg {Number} width - used to restrict width of grid..
47077 * @cfg {Number} height - used to restrict height of grid..
47081 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
47087 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47088 * {tag: "input", type: "checkbox", autocomplete: "off"})
47090 // defaultAutoCreate : { tag: 'div' },
47091 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
47093 * @cfg {String} addTitle Text to include for adding a title.
47097 onResize : function(){
47098 Roo.form.Field.superclass.onResize.apply(this, arguments);
47101 initEvents : function(){
47102 // Roo.form.Checkbox.superclass.initEvents.call(this);
47103 // has no events...
47108 getResizeEl : function(){
47112 getPositionEl : function(){
47117 onRender : function(ct, position){
47119 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
47120 var style = this.style;
47123 Roo.form.GridField.superclass.onRender.call(this, ct, position);
47124 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
47125 this.viewEl = this.wrap.createChild({ tag: 'div' });
47127 this.viewEl.applyStyles(style);
47130 this.viewEl.setWidth(this.width);
47133 this.viewEl.setHeight(this.height);
47135 //if(this.inputValue !== undefined){
47136 //this.setValue(this.value);
47139 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
47142 this.grid.render();
47143 this.grid.getDataSource().on('remove', this.refreshValue, this);
47144 this.grid.getDataSource().on('update', this.refreshValue, this);
47145 this.grid.on('afteredit', this.refreshValue, this);
47151 * Sets the value of the item.
47152 * @param {String} either an object or a string..
47154 setValue : function(v){
47156 v = v || []; // empty set..
47157 // this does not seem smart - it really only affects memoryproxy grids..
47158 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
47159 var ds = this.grid.getDataSource();
47160 // assumes a json reader..
47162 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
47163 ds.loadData( data);
47165 // clear selection so it does not get stale.
47166 if (this.grid.sm) {
47167 this.grid.sm.clearSelections();
47170 Roo.form.GridField.superclass.setValue.call(this, v);
47171 this.refreshValue();
47172 // should load data in the grid really....
47176 refreshValue: function() {
47178 this.grid.getDataSource().each(function(r) {
47181 this.el.dom.value = Roo.encode(val);
47189 * Ext JS Library 1.1.1
47190 * Copyright(c) 2006-2007, Ext JS, LLC.
47192 * Originally Released Under LGPL - original licence link has changed is not relivant.
47195 * <script type="text/javascript">
47198 * @class Roo.form.DisplayField
47199 * @extends Roo.form.Field
47200 * A generic Field to display non-editable data.
47202 * Creates a new Display Field item.
47203 * @param {Object} config Configuration options
47205 Roo.form.DisplayField = function(config){
47206 Roo.form.DisplayField.superclass.constructor.call(this, config);
47210 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
47211 inputType: 'hidden',
47217 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
47219 focusClass : undefined,
47221 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
47223 fieldClass: 'x-form-field',
47226 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
47228 valueRenderer: undefined,
47232 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47233 * {tag: "input", type: "checkbox", autocomplete: "off"})
47236 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
47238 onResize : function(){
47239 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
47243 initEvents : function(){
47244 // Roo.form.Checkbox.superclass.initEvents.call(this);
47245 // has no events...
47250 getResizeEl : function(){
47254 getPositionEl : function(){
47259 onRender : function(ct, position){
47261 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
47262 //if(this.inputValue !== undefined){
47263 this.wrap = this.el.wrap();
47265 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
47267 if (this.bodyStyle) {
47268 this.viewEl.applyStyles(this.bodyStyle);
47270 //this.viewEl.setStyle('padding', '2px');
47272 this.setValue(this.value);
47277 initValue : Roo.emptyFn,
47282 onClick : function(){
47287 * Sets the checked state of the checkbox.
47288 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
47290 setValue : function(v){
47292 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
47293 // this might be called before we have a dom element..
47294 if (!this.viewEl) {
47297 this.viewEl.dom.innerHTML = html;
47298 Roo.form.DisplayField.superclass.setValue.call(this, v);
47308 * @class Roo.form.DayPicker
47309 * @extends Roo.form.Field
47310 * A Day picker show [M] [T] [W] ....
47312 * Creates a new Day Picker
47313 * @param {Object} config Configuration options
47315 Roo.form.DayPicker= function(config){
47316 Roo.form.DayPicker.superclass.constructor.call(this, config);
47320 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
47322 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
47324 focusClass : undefined,
47326 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
47328 fieldClass: "x-form-field",
47331 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47332 * {tag: "input", type: "checkbox", autocomplete: "off"})
47334 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
47337 actionMode : 'viewEl',
47341 inputType : 'hidden',
47344 inputElement: false, // real input element?
47345 basedOn: false, // ????
47347 isFormField: true, // not sure where this is needed!!!!
47349 onResize : function(){
47350 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
47351 if(!this.boxLabel){
47352 this.el.alignTo(this.wrap, 'c-c');
47356 initEvents : function(){
47357 Roo.form.Checkbox.superclass.initEvents.call(this);
47358 this.el.on("click", this.onClick, this);
47359 this.el.on("change", this.onClick, this);
47363 getResizeEl : function(){
47367 getPositionEl : function(){
47373 onRender : function(ct, position){
47374 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
47376 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
47378 var r1 = '<table><tr>';
47379 var r2 = '<tr class="x-form-daypick-icons">';
47380 for (var i=0; i < 7; i++) {
47381 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
47382 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
47385 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
47386 viewEl.select('img').on('click', this.onClick, this);
47387 this.viewEl = viewEl;
47390 // this will not work on Chrome!!!
47391 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
47392 this.el.on('propertychange', this.setFromHidden, this); //ie
47400 initValue : Roo.emptyFn,
47403 * Returns the checked state of the checkbox.
47404 * @return {Boolean} True if checked, else false
47406 getValue : function(){
47407 return this.el.dom.value;
47412 onClick : function(e){
47413 //this.setChecked(!this.checked);
47414 Roo.get(e.target).toggleClass('x-menu-item-checked');
47415 this.refreshValue();
47416 //if(this.el.dom.checked != this.checked){
47417 // this.setValue(this.el.dom.checked);
47422 refreshValue : function()
47425 this.viewEl.select('img',true).each(function(e,i,n) {
47426 val += e.is(".x-menu-item-checked") ? String(n) : '';
47428 this.setValue(val, true);
47432 * Sets the checked state of the checkbox.
47433 * On is always based on a string comparison between inputValue and the param.
47434 * @param {Boolean/String} value - the value to set
47435 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
47437 setValue : function(v,suppressEvent){
47438 if (!this.el.dom) {
47441 var old = this.el.dom.value ;
47442 this.el.dom.value = v;
47443 if (suppressEvent) {
47447 // update display..
47448 this.viewEl.select('img',true).each(function(e,i,n) {
47450 var on = e.is(".x-menu-item-checked");
47451 var newv = v.indexOf(String(n)) > -1;
47453 e.toggleClass('x-menu-item-checked');
47459 this.fireEvent('change', this, v, old);
47464 // handle setting of hidden value by some other method!!?!?
47465 setFromHidden: function()
47470 //console.log("SET FROM HIDDEN");
47471 //alert('setFrom hidden');
47472 this.setValue(this.el.dom.value);
47475 onDestroy : function()
47478 Roo.get(this.viewEl).remove();
47481 Roo.form.DayPicker.superclass.onDestroy.call(this);
47485 * RooJS Library 1.1.1
47486 * Copyright(c) 2008-2011 Alan Knowles
47493 * @class Roo.form.ComboCheck
47494 * @extends Roo.form.ComboBox
47495 * A combobox for multiple select items.
47497 * FIXME - could do with a reset button..
47500 * Create a new ComboCheck
47501 * @param {Object} config Configuration options
47503 Roo.form.ComboCheck = function(config){
47504 Roo.form.ComboCheck.superclass.constructor.call(this, config);
47505 // should verify some data...
47507 // hiddenName = required..
47508 // displayField = required
47509 // valudField == required
47510 var req= [ 'hiddenName', 'displayField', 'valueField' ];
47512 Roo.each(req, function(e) {
47513 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
47514 throw "Roo.form.ComboCheck : missing value for: " + e;
47521 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
47526 selectedClass: 'x-menu-item-checked',
47529 onRender : function(ct, position){
47535 var cls = 'x-combo-list';
47538 this.tpl = new Roo.Template({
47539 html : '<div class="'+cls+'-item x-menu-check-item">' +
47540 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
47541 '<span>{' + this.displayField + '}</span>' +
47548 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
47549 this.view.singleSelect = false;
47550 this.view.multiSelect = true;
47551 this.view.toggleSelect = true;
47552 this.pageTb.add(new Roo.Toolbar.Fill(), {
47555 handler: function()
47562 onViewOver : function(e, t){
47568 onViewClick : function(doFocus,index){
47572 select: function () {
47573 //Roo.log("SELECT CALLED");
47576 selectByValue : function(xv, scrollIntoView){
47577 var ar = this.getValueArray();
47580 Roo.each(ar, function(v) {
47581 if(v === undefined || v === null){
47584 var r = this.findRecord(this.valueField, v);
47586 sels.push(this.store.indexOf(r))
47590 this.view.select(sels);
47596 onSelect : function(record, index){
47597 // Roo.log("onselect Called");
47598 // this is only called by the clear button now..
47599 this.view.clearSelections();
47600 this.setValue('[]');
47601 if (this.value != this.valueBefore) {
47602 this.fireEvent('change', this, this.value, this.valueBefore);
47603 this.valueBefore = this.value;
47606 getValueArray : function()
47611 //Roo.log(this.value);
47612 if (typeof(this.value) == 'undefined') {
47615 var ar = Roo.decode(this.value);
47616 return ar instanceof Array ? ar : []; //?? valid?
47619 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
47624 expand : function ()
47627 Roo.form.ComboCheck.superclass.expand.call(this);
47628 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
47629 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
47634 collapse : function(){
47635 Roo.form.ComboCheck.superclass.collapse.call(this);
47636 var sl = this.view.getSelectedIndexes();
47637 var st = this.store;
47641 Roo.each(sl, function(i) {
47643 nv.push(r.get(this.valueField));
47645 this.setValue(Roo.encode(nv));
47646 if (this.value != this.valueBefore) {
47648 this.fireEvent('change', this, this.value, this.valueBefore);
47649 this.valueBefore = this.value;
47654 setValue : function(v){
47658 var vals = this.getValueArray();
47660 Roo.each(vals, function(k) {
47661 var r = this.findRecord(this.valueField, k);
47663 tv.push(r.data[this.displayField]);
47664 }else if(this.valueNotFoundText !== undefined){
47665 tv.push( this.valueNotFoundText );
47670 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
47671 this.hiddenField.value = v;
47677 * Ext JS Library 1.1.1
47678 * Copyright(c) 2006-2007, Ext JS, LLC.
47680 * Originally Released Under LGPL - original licence link has changed is not relivant.
47683 * <script type="text/javascript">
47687 * @class Roo.form.Signature
47688 * @extends Roo.form.Field
47692 * @param {Object} config Configuration options
47695 Roo.form.Signature = function(config){
47696 Roo.form.Signature.superclass.constructor.call(this, config);
47698 this.addEvents({// not in used??
47701 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
47702 * @param {Roo.form.Signature} combo This combo box
47707 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
47708 * @param {Roo.form.ComboBox} combo This combo box
47709 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
47715 Roo.extend(Roo.form.Signature, Roo.form.Field, {
47717 * @cfg {Object} labels Label to use when rendering a form.
47721 * confirm : "Confirm"
47726 confirm : "Confirm"
47729 * @cfg {Number} width The signature panel width (defaults to 300)
47733 * @cfg {Number} height The signature panel height (defaults to 100)
47737 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
47739 allowBlank : false,
47742 // {Object} signPanel The signature SVG panel element (defaults to {})
47744 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
47745 isMouseDown : false,
47746 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
47747 isConfirmed : false,
47748 // {String} signatureTmp SVG mapping string (defaults to empty string)
47752 defaultAutoCreate : { // modified by initCompnoent..
47758 onRender : function(ct, position){
47760 Roo.form.Signature.superclass.onRender.call(this, ct, position);
47762 this.wrap = this.el.wrap({
47763 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
47766 this.createToolbar(this);
47767 this.signPanel = this.wrap.createChild({
47769 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
47773 this.svgID = Roo.id();
47774 this.svgEl = this.signPanel.createChild({
47775 xmlns : 'http://www.w3.org/2000/svg',
47777 id : this.svgID + "-svg",
47779 height: this.height,
47780 viewBox: '0 0 '+this.width+' '+this.height,
47784 id: this.svgID + "-svg-r",
47786 height: this.height,
47791 id: this.svgID + "-svg-l",
47793 y1: (this.height*0.8), // start set the line in 80% of height
47794 x2: this.width, // end
47795 y2: (this.height*0.8), // end set the line in 80% of height
47797 'stroke-width': "1",
47798 'stroke-dasharray': "3",
47799 'shape-rendering': "crispEdges",
47800 'pointer-events': "none"
47804 id: this.svgID + "-svg-p",
47806 'stroke-width': "3",
47808 'pointer-events': 'none'
47813 this.svgBox = this.svgEl.dom.getScreenCTM();
47815 createSVG : function(){
47816 var svg = this.signPanel;
47817 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
47820 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
47821 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
47822 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
47823 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
47824 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
47825 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
47826 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
47829 isTouchEvent : function(e){
47830 return e.type.match(/^touch/);
47832 getCoords : function (e) {
47833 var pt = this.svgEl.dom.createSVGPoint();
47836 if (this.isTouchEvent(e)) {
47837 pt.x = e.targetTouches[0].clientX
47838 pt.y = e.targetTouches[0].clientY;
47840 var a = this.svgEl.dom.getScreenCTM();
47841 var b = a.inverse();
47842 var mx = pt.matrixTransform(b);
47843 return mx.x + ',' + mx.y;
47845 //mouse event headler
47846 down : function (e) {
47847 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
47848 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
47850 this.isMouseDown = true;
47852 e.preventDefault();
47854 move : function (e) {
47855 if (this.isMouseDown) {
47856 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
47857 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
47860 e.preventDefault();
47862 up : function (e) {
47863 this.isMouseDown = false;
47864 var sp = this.signatureTmp.split(' ');
47867 if(!sp[sp.length-2].match(/^L/)){
47871 this.signatureTmp = sp.join(" ");
47874 if(this.getValue() != this.signatureTmp){
47875 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
47876 this.isConfirmed = false;
47878 e.preventDefault();
47882 * Protected method that will not generally be called directly. It
47883 * is called when the editor creates its toolbar. Override this method if you need to
47884 * add custom toolbar buttons.
47885 * @param {HtmlEditor} editor
47887 createToolbar : function(editor){
47888 function btn(id, toggle, handler){
47889 var xid = fid + '-'+ id ;
47893 cls : 'x-btn-icon x-edit-'+id,
47894 enableToggle:toggle !== false,
47895 scope: editor, // was editor...
47896 handler:handler||editor.relayBtnCmd,
47897 clickEvent:'mousedown',
47898 tooltip: etb.buttonTips[id] || undefined, ///tips ???
47904 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
47908 cls : ' x-signature-btn x-signature-'+id,
47909 scope: editor, // was editor...
47910 handler: this.reset,
47911 clickEvent:'mousedown',
47912 text: this.labels.clear
47919 cls : ' x-signature-btn x-signature-'+id,
47920 scope: editor, // was editor...
47921 handler: this.confirmHandler,
47922 clickEvent:'mousedown',
47923 text: this.labels.confirm
47930 * when user is clicked confirm then show this image.....
47932 * @return {String} Image Data URI
47934 getImageDataURI : function(){
47935 var svg = this.svgEl.dom.parentNode.innerHTML;
47936 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
47941 * @return {Boolean} this.isConfirmed
47943 getConfirmed : function(){
47944 return this.isConfirmed;
47948 * @return {Number} this.width
47950 getWidth : function(){
47955 * @return {Number} this.height
47957 getHeight : function(){
47958 return this.height;
47961 getSignature : function(){
47962 return this.signatureTmp;
47965 reset : function(){
47966 this.signatureTmp = '';
47967 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
47968 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
47969 this.isConfirmed = false;
47970 Roo.form.Signature.superclass.reset.call(this);
47972 setSignature : function(s){
47973 this.signatureTmp = s;
47974 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
47975 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
47977 this.isConfirmed = false;
47978 Roo.form.Signature.superclass.reset.call(this);
47981 // Roo.log(this.signPanel.dom.contentWindow.up())
47984 setConfirmed : function(){
47988 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
47991 confirmHandler : function(){
47992 if(!this.getSignature()){
47996 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
47997 this.setValue(this.getSignature());
47998 this.isConfirmed = true;
48000 this.fireEvent('confirm', this);
48003 // Subclasses should provide the validation implementation by overriding this
48004 validateValue : function(value){
48005 if(this.allowBlank){
48009 if(this.isConfirmed){
48016 * Ext JS Library 1.1.1
48017 * Copyright(c) 2006-2007, Ext JS, LLC.
48019 * Originally Released Under LGPL - original licence link has changed is not relivant.
48022 * <script type="text/javascript">
48027 * @class Roo.form.ComboBox
48028 * @extends Roo.form.TriggerField
48029 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
48031 * Create a new ComboBox.
48032 * @param {Object} config Configuration options
48034 Roo.form.Select = function(config){
48035 Roo.form.Select.superclass.constructor.call(this, config);
48039 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
48041 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
48044 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
48045 * rendering into an Roo.Editor, defaults to false)
48048 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
48049 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
48052 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
48055 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
48056 * the dropdown list (defaults to undefined, with no header element)
48060 * @cfg {String/Roo.Template} tpl The template to use to render the output
48064 defaultAutoCreate : {tag: "select" },
48066 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
48068 listWidth: undefined,
48070 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
48071 * mode = 'remote' or 'text' if mode = 'local')
48073 displayField: undefined,
48075 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
48076 * mode = 'remote' or 'value' if mode = 'local').
48077 * Note: use of a valueField requires the user make a selection
48078 * in order for a value to be mapped.
48080 valueField: undefined,
48084 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
48085 * field's data value (defaults to the underlying DOM element's name)
48087 hiddenName: undefined,
48089 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
48093 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
48095 selectedClass: 'x-combo-selected',
48097 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
48098 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
48099 * which displays a downward arrow icon).
48101 triggerClass : 'x-form-arrow-trigger',
48103 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
48107 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
48108 * anchor positions (defaults to 'tl-bl')
48110 listAlign: 'tl-bl?',
48112 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
48116 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
48117 * query specified by the allQuery config option (defaults to 'query')
48119 triggerAction: 'query',
48121 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
48122 * (defaults to 4, does not apply if editable = false)
48126 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
48127 * delay (typeAheadDelay) if it matches a known value (defaults to false)
48131 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
48132 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
48136 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
48137 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
48141 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
48142 * when editable = true (defaults to false)
48144 selectOnFocus:false,
48146 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
48148 queryParam: 'query',
48150 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
48151 * when mode = 'remote' (defaults to 'Loading...')
48153 loadingText: 'Loading...',
48155 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
48159 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
48163 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
48164 * traditional select (defaults to true)
48168 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
48172 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
48176 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
48177 * listWidth has a higher value)
48181 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
48182 * allow the user to set arbitrary text into the field (defaults to false)
48184 forceSelection:false,
48186 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
48187 * if typeAhead = true (defaults to 250)
48189 typeAheadDelay : 250,
48191 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
48192 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
48194 valueNotFoundText : undefined,
48197 * @cfg {String} defaultValue The value displayed after loading the store.
48202 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
48204 blockFocus : false,
48207 * @cfg {Boolean} disableClear Disable showing of clear button.
48209 disableClear : false,
48211 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
48213 alwaysQuery : false,
48219 // element that contains real text value.. (when hidden is used..)
48222 onRender : function(ct, position){
48223 Roo.form.Field.prototype.onRender.call(this, ct, position);
48226 this.store.on('beforeload', this.onBeforeLoad, this);
48227 this.store.on('load', this.onLoad, this);
48228 this.store.on('loadexception', this.onLoadException, this);
48229 this.store.load({});
48237 initEvents : function(){
48238 //Roo.form.ComboBox.superclass.initEvents.call(this);
48242 onDestroy : function(){
48245 this.store.un('beforeload', this.onBeforeLoad, this);
48246 this.store.un('load', this.onLoad, this);
48247 this.store.un('loadexception', this.onLoadException, this);
48249 //Roo.form.ComboBox.superclass.onDestroy.call(this);
48253 fireKey : function(e){
48254 if(e.isNavKeyPress() && !this.list.isVisible()){
48255 this.fireEvent("specialkey", this, e);
48260 onResize: function(w, h){
48268 * Allow or prevent the user from directly editing the field text. If false is passed,
48269 * the user will only be able to select from the items defined in the dropdown list. This method
48270 * is the runtime equivalent of setting the 'editable' config option at config time.
48271 * @param {Boolean} value True to allow the user to directly edit the field text
48273 setEditable : function(value){
48278 onBeforeLoad : function(){
48280 Roo.log("Select before load");
48283 this.innerList.update(this.loadingText ?
48284 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
48285 //this.restrictHeight();
48286 this.selectedIndex = -1;
48290 onLoad : function(){
48293 var dom = this.el.dom;
48294 dom.innerHTML = '';
48295 var od = dom.ownerDocument;
48297 if (this.emptyText) {
48298 var op = od.createElement('option');
48299 op.setAttribute('value', '');
48300 op.innerHTML = String.format('{0}', this.emptyText);
48301 dom.appendChild(op);
48303 if(this.store.getCount() > 0){
48305 var vf = this.valueField;
48306 var df = this.displayField;
48307 this.store.data.each(function(r) {
48308 // which colmsn to use... testing - cdoe / title..
48309 var op = od.createElement('option');
48310 op.setAttribute('value', r.data[vf]);
48311 op.innerHTML = String.format('{0}', r.data[df]);
48312 dom.appendChild(op);
48314 if (typeof(this.defaultValue != 'undefined')) {
48315 this.setValue(this.defaultValue);
48320 //this.onEmptyResults();
48325 onLoadException : function()
48327 dom.innerHTML = '';
48329 Roo.log("Select on load exception");
48333 Roo.log(this.store.reader.jsonData);
48334 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
48335 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
48341 onTypeAhead : function(){
48346 onSelect : function(record, index){
48347 Roo.log('on select?');
48349 if(this.fireEvent('beforeselect', this, record, index) !== false){
48350 this.setFromData(index > -1 ? record.data : false);
48352 this.fireEvent('select', this, record, index);
48357 * Returns the currently selected field value or empty string if no value is set.
48358 * @return {String} value The selected value
48360 getValue : function(){
48361 var dom = this.el.dom;
48362 this.value = dom.options[dom.selectedIndex].value;
48368 * Clears any text/value currently set in the field
48370 clearValue : function(){
48372 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
48377 * Sets the specified value into the field. If the value finds a match, the corresponding record text
48378 * will be displayed in the field. If the value does not match the data value of an existing item,
48379 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
48380 * Otherwise the field will be blank (although the value will still be set).
48381 * @param {String} value The value to match
48383 setValue : function(v){
48384 var d = this.el.dom;
48385 for (var i =0; i < d.options.length;i++) {
48386 if (v == d.options[i].value) {
48387 d.selectedIndex = i;
48395 * @property {Object} the last set data for the element
48400 * Sets the value of the field based on a object which is related to the record format for the store.
48401 * @param {Object} value the value to set as. or false on reset?
48403 setFromData : function(o){
48404 Roo.log('setfrom data?');
48410 reset : function(){
48414 findRecord : function(prop, value){
48419 if(this.store.getCount() > 0){
48420 this.store.each(function(r){
48421 if(r.data[prop] == value){
48431 getName: function()
48433 // returns hidden if it's set..
48434 if (!this.rendered) {return ''};
48435 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
48443 onEmptyResults : function(){
48444 Roo.log('empty results');
48449 * Returns true if the dropdown list is expanded, else false.
48451 isExpanded : function(){
48456 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
48457 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
48458 * @param {String} value The data value of the item to select
48459 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
48460 * selected item if it is not currently in view (defaults to true)
48461 * @return {Boolean} True if the value matched an item in the list, else false
48463 selectByValue : function(v, scrollIntoView){
48464 Roo.log('select By Value');
48467 if(v !== undefined && v !== null){
48468 var r = this.findRecord(this.valueField || this.displayField, v);
48470 this.select(this.store.indexOf(r), scrollIntoView);
48478 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
48479 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
48480 * @param {Number} index The zero-based index of the list item to select
48481 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
48482 * selected item if it is not currently in view (defaults to true)
48484 select : function(index, scrollIntoView){
48485 Roo.log('select ');
48488 this.selectedIndex = index;
48489 this.view.select(index);
48490 if(scrollIntoView !== false){
48491 var el = this.view.getNode(index);
48493 this.innerList.scrollChildIntoView(el, false);
48501 validateBlur : function(){
48508 initQuery : function(){
48509 this.doQuery(this.getRawValue());
48513 doForce : function(){
48514 if(this.el.dom.value.length > 0){
48515 this.el.dom.value =
48516 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
48522 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
48523 * query allowing the query action to be canceled if needed.
48524 * @param {String} query The SQL query to execute
48525 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
48526 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
48527 * saved in the current store (defaults to false)
48529 doQuery : function(q, forceAll){
48531 Roo.log('doQuery?');
48532 if(q === undefined || q === null){
48537 forceAll: forceAll,
48541 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
48545 forceAll = qe.forceAll;
48546 if(forceAll === true || (q.length >= this.minChars)){
48547 if(this.lastQuery != q || this.alwaysQuery){
48548 this.lastQuery = q;
48549 if(this.mode == 'local'){
48550 this.selectedIndex = -1;
48552 this.store.clearFilter();
48554 this.store.filter(this.displayField, q);
48558 this.store.baseParams[this.queryParam] = q;
48560 params: this.getParams(q)
48565 this.selectedIndex = -1;
48572 getParams : function(q){
48574 //p[this.queryParam] = q;
48577 p.limit = this.pageSize;
48583 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
48585 collapse : function(){
48590 collapseIf : function(e){
48595 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
48597 expand : function(){
48605 * @cfg {Boolean} grow
48609 * @cfg {Number} growMin
48613 * @cfg {Number} growMax
48621 setWidth : function()
48625 getResizeEl : function(){
48628 });//<script type="text/javasscript">
48632 * @class Roo.DDView
48633 * A DnD enabled version of Roo.View.
48634 * @param {Element/String} container The Element in which to create the View.
48635 * @param {String} tpl The template string used to create the markup for each element of the View
48636 * @param {Object} config The configuration properties. These include all the config options of
48637 * {@link Roo.View} plus some specific to this class.<br>
48639 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
48640 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
48642 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
48643 .x-view-drag-insert-above {
48644 border-top:1px dotted #3366cc;
48646 .x-view-drag-insert-below {
48647 border-bottom:1px dotted #3366cc;
48653 Roo.DDView = function(container, tpl, config) {
48654 Roo.DDView.superclass.constructor.apply(this, arguments);
48655 this.getEl().setStyle("outline", "0px none");
48656 this.getEl().unselectable();
48657 if (this.dragGroup) {
48658 this.setDraggable(this.dragGroup.split(","));
48660 if (this.dropGroup) {
48661 this.setDroppable(this.dropGroup.split(","));
48663 if (this.deletable) {
48664 this.setDeletable();
48666 this.isDirtyFlag = false;
48672 Roo.extend(Roo.DDView, Roo.View, {
48673 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
48674 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
48675 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
48676 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
48680 reset: Roo.emptyFn,
48682 clearInvalid: Roo.form.Field.prototype.clearInvalid,
48684 validate: function() {
48688 destroy: function() {
48689 this.purgeListeners();
48690 this.getEl.removeAllListeners();
48691 this.getEl().remove();
48692 if (this.dragZone) {
48693 if (this.dragZone.destroy) {
48694 this.dragZone.destroy();
48697 if (this.dropZone) {
48698 if (this.dropZone.destroy) {
48699 this.dropZone.destroy();
48704 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
48705 getName: function() {
48709 /** Loads the View from a JSON string representing the Records to put into the Store. */
48710 setValue: function(v) {
48712 throw "DDView.setValue(). DDView must be constructed with a valid Store";
48715 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
48716 this.store.proxy = new Roo.data.MemoryProxy(data);
48720 /** @return {String} a parenthesised list of the ids of the Records in the View. */
48721 getValue: function() {
48723 this.store.each(function(rec) {
48724 result += rec.id + ',';
48726 return result.substr(0, result.length - 1) + ')';
48729 getIds: function() {
48730 var i = 0, result = new Array(this.store.getCount());
48731 this.store.each(function(rec) {
48732 result[i++] = rec.id;
48737 isDirty: function() {
48738 return this.isDirtyFlag;
48742 * Part of the Roo.dd.DropZone interface. If no target node is found, the
48743 * whole Element becomes the target, and this causes the drop gesture to append.
48745 getTargetFromEvent : function(e) {
48746 var target = e.getTarget();
48747 while ((target !== null) && (target.parentNode != this.el.dom)) {
48748 target = target.parentNode;
48751 target = this.el.dom.lastChild || this.el.dom;
48757 * Create the drag data which consists of an object which has the property "ddel" as
48758 * the drag proxy element.
48760 getDragData : function(e) {
48761 var target = this.findItemFromChild(e.getTarget());
48763 this.handleSelection(e);
48764 var selNodes = this.getSelectedNodes();
48767 copy: this.copy || (this.allowCopy && e.ctrlKey),
48771 var selectedIndices = this.getSelectedIndexes();
48772 for (var i = 0; i < selectedIndices.length; i++) {
48773 dragData.records.push(this.store.getAt(selectedIndices[i]));
48775 if (selNodes.length == 1) {
48776 dragData.ddel = target.cloneNode(true); // the div element
48778 var div = document.createElement('div'); // create the multi element drag "ghost"
48779 div.className = 'multi-proxy';
48780 for (var i = 0, len = selNodes.length; i < len; i++) {
48781 div.appendChild(selNodes[i].cloneNode(true));
48783 dragData.ddel = div;
48785 //console.log(dragData)
48786 //console.log(dragData.ddel.innerHTML)
48789 //console.log('nodragData')
48793 /** Specify to which ddGroup items in this DDView may be dragged. */
48794 setDraggable: function(ddGroup) {
48795 if (ddGroup instanceof Array) {
48796 Roo.each(ddGroup, this.setDraggable, this);
48799 if (this.dragZone) {
48800 this.dragZone.addToGroup(ddGroup);
48802 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
48803 containerScroll: true,
48807 // Draggability implies selection. DragZone's mousedown selects the element.
48808 if (!this.multiSelect) { this.singleSelect = true; }
48810 // Wire the DragZone's handlers up to methods in *this*
48811 this.dragZone.getDragData = this.getDragData.createDelegate(this);
48815 /** Specify from which ddGroup this DDView accepts drops. */
48816 setDroppable: function(ddGroup) {
48817 if (ddGroup instanceof Array) {
48818 Roo.each(ddGroup, this.setDroppable, this);
48821 if (this.dropZone) {
48822 this.dropZone.addToGroup(ddGroup);
48824 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
48825 containerScroll: true,
48829 // Wire the DropZone's handlers up to methods in *this*
48830 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
48831 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
48832 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
48833 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
48834 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
48838 /** Decide whether to drop above or below a View node. */
48839 getDropPoint : function(e, n, dd){
48840 if (n == this.el.dom) { return "above"; }
48841 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
48842 var c = t + (b - t) / 2;
48843 var y = Roo.lib.Event.getPageY(e);
48851 onNodeEnter : function(n, dd, e, data){
48855 onNodeOver : function(n, dd, e, data){
48856 var pt = this.getDropPoint(e, n, dd);
48857 // set the insert point style on the target node
48858 var dragElClass = this.dropNotAllowed;
48861 if (pt == "above"){
48862 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
48863 targetElClass = "x-view-drag-insert-above";
48865 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
48866 targetElClass = "x-view-drag-insert-below";
48868 if (this.lastInsertClass != targetElClass){
48869 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
48870 this.lastInsertClass = targetElClass;
48873 return dragElClass;
48876 onNodeOut : function(n, dd, e, data){
48877 this.removeDropIndicators(n);
48880 onNodeDrop : function(n, dd, e, data){
48881 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
48884 var pt = this.getDropPoint(e, n, dd);
48885 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
48886 if (pt == "below") { insertAt++; }
48887 for (var i = 0; i < data.records.length; i++) {
48888 var r = data.records[i];
48889 var dup = this.store.getById(r.id);
48890 if (dup && (dd != this.dragZone)) {
48891 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
48894 this.store.insert(insertAt++, r.copy());
48896 data.source.isDirtyFlag = true;
48898 this.store.insert(insertAt++, r);
48900 this.isDirtyFlag = true;
48903 this.dragZone.cachedTarget = null;
48907 removeDropIndicators : function(n){
48909 Roo.fly(n).removeClass([
48910 "x-view-drag-insert-above",
48911 "x-view-drag-insert-below"]);
48912 this.lastInsertClass = "_noclass";
48917 * Utility method. Add a delete option to the DDView's context menu.
48918 * @param {String} imageUrl The URL of the "delete" icon image.
48920 setDeletable: function(imageUrl) {
48921 if (!this.singleSelect && !this.multiSelect) {
48922 this.singleSelect = true;
48924 var c = this.getContextMenu();
48925 this.contextMenu.on("itemclick", function(item) {
48928 this.remove(this.getSelectedIndexes());
48932 this.contextMenu.add({
48939 /** Return the context menu for this DDView. */
48940 getContextMenu: function() {
48941 if (!this.contextMenu) {
48942 // Create the View's context menu
48943 this.contextMenu = new Roo.menu.Menu({
48944 id: this.id + "-contextmenu"
48946 this.el.on("contextmenu", this.showContextMenu, this);
48948 return this.contextMenu;
48951 disableContextMenu: function() {
48952 if (this.contextMenu) {
48953 this.el.un("contextmenu", this.showContextMenu, this);
48957 showContextMenu: function(e, item) {
48958 item = this.findItemFromChild(e.getTarget());
48961 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
48962 this.contextMenu.showAt(e.getXY());
48967 * Remove {@link Roo.data.Record}s at the specified indices.
48968 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
48970 remove: function(selectedIndices) {
48971 selectedIndices = [].concat(selectedIndices);
48972 for (var i = 0; i < selectedIndices.length; i++) {
48973 var rec = this.store.getAt(selectedIndices[i]);
48974 this.store.remove(rec);
48979 * Double click fires the event, but also, if this is draggable, and there is only one other
48980 * related DropZone, it transfers the selected node.
48982 onDblClick : function(e){
48983 var item = this.findItemFromChild(e.getTarget());
48985 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
48988 if (this.dragGroup) {
48989 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
48990 while (targets.indexOf(this.dropZone) > -1) {
48991 targets.remove(this.dropZone);
48993 if (targets.length == 1) {
48994 this.dragZone.cachedTarget = null;
48995 var el = Roo.get(targets[0].getEl());
48996 var box = el.getBox(true);
48997 targets[0].onNodeDrop(el.dom, {
48999 xy: [box.x, box.y + box.height - 1]
49000 }, null, this.getDragData(e));
49006 handleSelection: function(e) {
49007 this.dragZone.cachedTarget = null;
49008 var item = this.findItemFromChild(e.getTarget());
49010 this.clearSelections(true);
49013 if (item && (this.multiSelect || this.singleSelect)){
49014 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
49015 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
49016 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
49017 this.unselect(item);
49019 this.select(item, this.multiSelect && e.ctrlKey);
49020 this.lastSelection = item;
49025 onItemClick : function(item, index, e){
49026 if(this.fireEvent("beforeclick", this, index, item, e) === false){
49032 unselect : function(nodeInfo, suppressEvent){
49033 var node = this.getNode(nodeInfo);
49034 if(node && this.isSelected(node)){
49035 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
49036 Roo.fly(node).removeClass(this.selectedClass);
49037 this.selections.remove(node);
49038 if(!suppressEvent){
49039 this.fireEvent("selectionchange", this, this.selections);
49047 * Ext JS Library 1.1.1
49048 * Copyright(c) 2006-2007, Ext JS, LLC.
49050 * Originally Released Under LGPL - original licence link has changed is not relivant.
49053 * <script type="text/javascript">
49057 * @class Roo.LayoutManager
49058 * @extends Roo.util.Observable
49059 * Base class for layout managers.
49061 Roo.LayoutManager = function(container, config){
49062 Roo.LayoutManager.superclass.constructor.call(this);
49063 this.el = Roo.get(container);
49064 // ie scrollbar fix
49065 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
49066 document.body.scroll = "no";
49067 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
49068 this.el.position('relative');
49070 this.id = this.el.id;
49071 this.el.addClass("x-layout-container");
49072 /** false to disable window resize monitoring @type Boolean */
49073 this.monitorWindowResize = true;
49078 * Fires when a layout is performed.
49079 * @param {Roo.LayoutManager} this
49083 * @event regionresized
49084 * Fires when the user resizes a region.
49085 * @param {Roo.LayoutRegion} region The resized region
49086 * @param {Number} newSize The new size (width for east/west, height for north/south)
49088 "regionresized" : true,
49090 * @event regioncollapsed
49091 * Fires when a region is collapsed.
49092 * @param {Roo.LayoutRegion} region The collapsed region
49094 "regioncollapsed" : true,
49096 * @event regionexpanded
49097 * Fires when a region is expanded.
49098 * @param {Roo.LayoutRegion} region The expanded region
49100 "regionexpanded" : true
49102 this.updating = false;
49103 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
49106 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
49108 * Returns true if this layout is currently being updated
49109 * @return {Boolean}
49111 isUpdating : function(){
49112 return this.updating;
49116 * Suspend the LayoutManager from doing auto-layouts while
49117 * making multiple add or remove calls
49119 beginUpdate : function(){
49120 this.updating = true;
49124 * Restore auto-layouts and optionally disable the manager from performing a layout
49125 * @param {Boolean} noLayout true to disable a layout update
49127 endUpdate : function(noLayout){
49128 this.updating = false;
49134 layout: function(){
49138 onRegionResized : function(region, newSize){
49139 this.fireEvent("regionresized", region, newSize);
49143 onRegionCollapsed : function(region){
49144 this.fireEvent("regioncollapsed", region);
49147 onRegionExpanded : function(region){
49148 this.fireEvent("regionexpanded", region);
49152 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
49153 * performs box-model adjustments.
49154 * @return {Object} The size as an object {width: (the width), height: (the height)}
49156 getViewSize : function(){
49158 if(this.el.dom != document.body){
49159 size = this.el.getSize();
49161 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
49163 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
49164 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
49169 * Returns the Element this layout is bound to.
49170 * @return {Roo.Element}
49172 getEl : function(){
49177 * Returns the specified region.
49178 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
49179 * @return {Roo.LayoutRegion}
49181 getRegion : function(target){
49182 return this.regions[target.toLowerCase()];
49185 onWindowResize : function(){
49186 if(this.monitorWindowResize){
49192 * Ext JS Library 1.1.1
49193 * Copyright(c) 2006-2007, Ext JS, LLC.
49195 * Originally Released Under LGPL - original licence link has changed is not relivant.
49198 * <script type="text/javascript">
49201 * @class Roo.BorderLayout
49202 * @extends Roo.LayoutManager
49203 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
49204 * please see: <br><br>
49205 * <a href="http://www.jackslocum.com/yui/2006/10/19/cross-browser-web-20-layouts-with-yahoo-ui/">Cross Browser Layouts - Part 1</a><br>
49206 * <a href="http://www.jackslocum.com/yui/2006/10/28/cross-browser-web-20-layouts-part-2-ajax-feed-viewer-20/">Cross Browser Layouts - Part 2</a><br><br>
49209 var layout = new Roo.BorderLayout(document.body, {
49243 preferredTabWidth: 150
49248 var CP = Roo.ContentPanel;
49250 layout.beginUpdate();
49251 layout.add("north", new CP("north", "North"));
49252 layout.add("south", new CP("south", {title: "South", closable: true}));
49253 layout.add("west", new CP("west", {title: "West"}));
49254 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
49255 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
49256 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
49257 layout.getRegion("center").showPanel("center1");
49258 layout.endUpdate();
49261 <b>The container the layout is rendered into can be either the body element or any other element.
49262 If it is not the body element, the container needs to either be an absolute positioned element,
49263 or you will need to add "position:relative" to the css of the container. You will also need to specify
49264 the container size if it is not the body element.</b>
49267 * Create a new BorderLayout
49268 * @param {String/HTMLElement/Element} container The container this layout is bound to
49269 * @param {Object} config Configuration options
49271 Roo.BorderLayout = function(container, config){
49272 config = config || {};
49273 Roo.BorderLayout.superclass.constructor.call(this, container, config);
49274 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
49275 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
49276 var target = this.factory.validRegions[i];
49277 if(config[target]){
49278 this.addRegion(target, config[target]);
49283 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
49285 * Creates and adds a new region if it doesn't already exist.
49286 * @param {String} target The target region key (north, south, east, west or center).
49287 * @param {Object} config The regions config object
49288 * @return {BorderLayoutRegion} The new region
49290 addRegion : function(target, config){
49291 if(!this.regions[target]){
49292 var r = this.factory.create(target, this, config);
49293 this.bindRegion(target, r);
49295 return this.regions[target];
49299 bindRegion : function(name, r){
49300 this.regions[name] = r;
49301 r.on("visibilitychange", this.layout, this);
49302 r.on("paneladded", this.layout, this);
49303 r.on("panelremoved", this.layout, this);
49304 r.on("invalidated", this.layout, this);
49305 r.on("resized", this.onRegionResized, this);
49306 r.on("collapsed", this.onRegionCollapsed, this);
49307 r.on("expanded", this.onRegionExpanded, this);
49311 * Performs a layout update.
49313 layout : function(){
49314 if(this.updating) return;
49315 var size = this.getViewSize();
49316 var w = size.width;
49317 var h = size.height;
49322 //var x = 0, y = 0;
49324 var rs = this.regions;
49325 var north = rs["north"];
49326 var south = rs["south"];
49327 var west = rs["west"];
49328 var east = rs["east"];
49329 var center = rs["center"];
49330 //if(this.hideOnLayout){ // not supported anymore
49331 //c.el.setStyle("display", "none");
49333 if(north && north.isVisible()){
49334 var b = north.getBox();
49335 var m = north.getMargins();
49336 b.width = w - (m.left+m.right);
49339 centerY = b.height + b.y + m.bottom;
49340 centerH -= centerY;
49341 north.updateBox(this.safeBox(b));
49343 if(south && south.isVisible()){
49344 var b = south.getBox();
49345 var m = south.getMargins();
49346 b.width = w - (m.left+m.right);
49348 var totalHeight = (b.height + m.top + m.bottom);
49349 b.y = h - totalHeight + m.top;
49350 centerH -= totalHeight;
49351 south.updateBox(this.safeBox(b));
49353 if(west && west.isVisible()){
49354 var b = west.getBox();
49355 var m = west.getMargins();
49356 b.height = centerH - (m.top+m.bottom);
49358 b.y = centerY + m.top;
49359 var totalWidth = (b.width + m.left + m.right);
49360 centerX += totalWidth;
49361 centerW -= totalWidth;
49362 west.updateBox(this.safeBox(b));
49364 if(east && east.isVisible()){
49365 var b = east.getBox();
49366 var m = east.getMargins();
49367 b.height = centerH - (m.top+m.bottom);
49368 var totalWidth = (b.width + m.left + m.right);
49369 b.x = w - totalWidth + m.left;
49370 b.y = centerY + m.top;
49371 centerW -= totalWidth;
49372 east.updateBox(this.safeBox(b));
49375 var m = center.getMargins();
49377 x: centerX + m.left,
49378 y: centerY + m.top,
49379 width: centerW - (m.left+m.right),
49380 height: centerH - (m.top+m.bottom)
49382 //if(this.hideOnLayout){
49383 //center.el.setStyle("display", "block");
49385 center.updateBox(this.safeBox(centerBox));
49388 this.fireEvent("layout", this);
49392 safeBox : function(box){
49393 box.width = Math.max(0, box.width);
49394 box.height = Math.max(0, box.height);
49399 * Adds a ContentPanel (or subclass) to this layout.
49400 * @param {String} target The target region key (north, south, east, west or center).
49401 * @param {Roo.ContentPanel} panel The panel to add
49402 * @return {Roo.ContentPanel} The added panel
49404 add : function(target, panel){
49406 target = target.toLowerCase();
49407 return this.regions[target].add(panel);
49411 * Remove a ContentPanel (or subclass) to this layout.
49412 * @param {String} target The target region key (north, south, east, west or center).
49413 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
49414 * @return {Roo.ContentPanel} The removed panel
49416 remove : function(target, panel){
49417 target = target.toLowerCase();
49418 return this.regions[target].remove(panel);
49422 * Searches all regions for a panel with the specified id
49423 * @param {String} panelId
49424 * @return {Roo.ContentPanel} The panel or null if it wasn't found
49426 findPanel : function(panelId){
49427 var rs = this.regions;
49428 for(var target in rs){
49429 if(typeof rs[target] != "function"){
49430 var p = rs[target].getPanel(panelId);
49440 * Searches all regions for a panel with the specified id and activates (shows) it.
49441 * @param {String/ContentPanel} panelId The panels id or the panel itself
49442 * @return {Roo.ContentPanel} The shown panel or null
49444 showPanel : function(panelId) {
49445 var rs = this.regions;
49446 for(var target in rs){
49447 var r = rs[target];
49448 if(typeof r != "function"){
49449 if(r.hasPanel(panelId)){
49450 return r.showPanel(panelId);
49458 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
49459 * @param {Roo.state.Provider} provider (optional) An alternate state provider
49461 restoreState : function(provider){
49463 provider = Roo.state.Manager;
49465 var sm = new Roo.LayoutStateManager();
49466 sm.init(this, provider);
49470 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
49471 * object should contain properties for each region to add ContentPanels to, and each property's value should be
49472 * a valid ContentPanel config object. Example:
49474 // Create the main layout
49475 var layout = new Roo.BorderLayout('main-ct', {
49486 // Create and add multiple ContentPanels at once via configs
49489 id: 'source-files',
49491 title:'Ext Source Files',
49504 * @param {Object} regions An object containing ContentPanel configs by region name
49506 batchAdd : function(regions){
49507 this.beginUpdate();
49508 for(var rname in regions){
49509 var lr = this.regions[rname];
49511 this.addTypedPanels(lr, regions[rname]);
49518 addTypedPanels : function(lr, ps){
49519 if(typeof ps == 'string'){
49520 lr.add(new Roo.ContentPanel(ps));
49522 else if(ps instanceof Array){
49523 for(var i =0, len = ps.length; i < len; i++){
49524 this.addTypedPanels(lr, ps[i]);
49527 else if(!ps.events){ // raw config?
49529 delete ps.el; // prevent conflict
49530 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
49532 else { // panel object assumed!
49537 * Adds a xtype elements to the layout.
49541 xtype : 'ContentPanel',
49548 xtype : 'NestedLayoutPanel',
49554 items : [ ... list of content panels or nested layout panels.. ]
49558 * @param {Object} cfg Xtype definition of item to add.
49560 addxtype : function(cfg)
49562 // basically accepts a pannel...
49563 // can accept a layout region..!?!?
49564 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
49566 if (!cfg.xtype.match(/Panel$/)) {
49571 if (typeof(cfg.region) == 'undefined') {
49572 Roo.log("Failed to add Panel, region was not set");
49576 var region = cfg.region;
49582 xitems = cfg.items;
49589 case 'ContentPanel': // ContentPanel (el, cfg)
49590 case 'ScrollPanel': // ContentPanel (el, cfg)
49592 if(cfg.autoCreate) {
49593 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49595 var el = this.el.createChild();
49596 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
49599 this.add(region, ret);
49603 case 'TreePanel': // our new panel!
49604 cfg.el = this.el.createChild();
49605 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49606 this.add(region, ret);
49609 case 'NestedLayoutPanel':
49610 // create a new Layout (which is a Border Layout...
49611 var el = this.el.createChild();
49612 var clayout = cfg.layout;
49614 clayout.items = clayout.items || [];
49615 // replace this exitems with the clayout ones..
49616 xitems = clayout.items;
49619 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
49620 cfg.background = false;
49622 var layout = new Roo.BorderLayout(el, clayout);
49624 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
49625 //console.log('adding nested layout panel ' + cfg.toSource());
49626 this.add(region, ret);
49627 nb = {}; /// find first...
49632 // needs grid and region
49634 //var el = this.getRegion(region).el.createChild();
49635 var el = this.el.createChild();
49636 // create the grid first...
49638 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
49640 if (region == 'center' && this.active ) {
49641 cfg.background = false;
49643 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
49645 this.add(region, ret);
49646 if (cfg.background) {
49647 ret.on('activate', function(gp) {
49648 if (!gp.grid.rendered) {
49663 if (typeof(Roo[cfg.xtype]) != 'undefined') {
49665 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49666 this.add(region, ret);
49669 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
49673 // GridPanel (grid, cfg)
49676 this.beginUpdate();
49680 Roo.each(xitems, function(i) {
49681 region = nb && i.region ? i.region : false;
49683 var add = ret.addxtype(i);
49686 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
49687 if (!i.background) {
49688 abn[region] = nb[region] ;
49695 // make the last non-background panel active..
49696 //if (nb) { Roo.log(abn); }
49699 for(var r in abn) {
49700 region = this.getRegion(r);
49702 // tried using nb[r], but it does not work..
49704 region.showPanel(abn[r]);
49715 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
49716 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
49717 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
49718 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
49721 var CP = Roo.ContentPanel;
49723 var layout = Roo.BorderLayout.create({
49727 panels: [new CP("north", "North")]
49736 panels: [new CP("west", {title: "West"})]
49745 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
49754 panels: [new CP("south", {title: "South", closable: true})]
49761 preferredTabWidth: 150,
49763 new CP("center1", {title: "Close Me", closable: true}),
49764 new CP("center2", {title: "Center Panel", closable: false})
49769 layout.getRegion("center").showPanel("center1");
49774 Roo.BorderLayout.create = function(config, targetEl){
49775 var layout = new Roo.BorderLayout(targetEl || document.body, config);
49776 layout.beginUpdate();
49777 var regions = Roo.BorderLayout.RegionFactory.validRegions;
49778 for(var j = 0, jlen = regions.length; j < jlen; j++){
49779 var lr = regions[j];
49780 if(layout.regions[lr] && config[lr].panels){
49781 var r = layout.regions[lr];
49782 var ps = config[lr].panels;
49783 layout.addTypedPanels(r, ps);
49786 layout.endUpdate();
49791 Roo.BorderLayout.RegionFactory = {
49793 validRegions : ["north","south","east","west","center"],
49796 create : function(target, mgr, config){
49797 target = target.toLowerCase();
49798 if(config.lightweight || config.basic){
49799 return new Roo.BasicLayoutRegion(mgr, config, target);
49803 return new Roo.NorthLayoutRegion(mgr, config);
49805 return new Roo.SouthLayoutRegion(mgr, config);
49807 return new Roo.EastLayoutRegion(mgr, config);
49809 return new Roo.WestLayoutRegion(mgr, config);
49811 return new Roo.CenterLayoutRegion(mgr, config);
49813 throw 'Layout region "'+target+'" not supported.';
49817 * Ext JS Library 1.1.1
49818 * Copyright(c) 2006-2007, Ext JS, LLC.
49820 * Originally Released Under LGPL - original licence link has changed is not relivant.
49823 * <script type="text/javascript">
49827 * @class Roo.BasicLayoutRegion
49828 * @extends Roo.util.Observable
49829 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
49830 * and does not have a titlebar, tabs or any other features. All it does is size and position
49831 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
49833 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
49835 this.position = pos;
49838 * @scope Roo.BasicLayoutRegion
49842 * @event beforeremove
49843 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
49844 * @param {Roo.LayoutRegion} this
49845 * @param {Roo.ContentPanel} panel The panel
49846 * @param {Object} e The cancel event object
49848 "beforeremove" : true,
49850 * @event invalidated
49851 * Fires when the layout for this region is changed.
49852 * @param {Roo.LayoutRegion} this
49854 "invalidated" : true,
49856 * @event visibilitychange
49857 * Fires when this region is shown or hidden
49858 * @param {Roo.LayoutRegion} this
49859 * @param {Boolean} visibility true or false
49861 "visibilitychange" : true,
49863 * @event paneladded
49864 * Fires when a panel is added.
49865 * @param {Roo.LayoutRegion} this
49866 * @param {Roo.ContentPanel} panel The panel
49868 "paneladded" : true,
49870 * @event panelremoved
49871 * Fires when a panel is removed.
49872 * @param {Roo.LayoutRegion} this
49873 * @param {Roo.ContentPanel} panel The panel
49875 "panelremoved" : true,
49878 * Fires when this region is collapsed.
49879 * @param {Roo.LayoutRegion} this
49881 "collapsed" : true,
49884 * Fires when this region is expanded.
49885 * @param {Roo.LayoutRegion} this
49890 * Fires when this region is slid into view.
49891 * @param {Roo.LayoutRegion} this
49893 "slideshow" : true,
49896 * Fires when this region slides out of view.
49897 * @param {Roo.LayoutRegion} this
49899 "slidehide" : true,
49901 * @event panelactivated
49902 * Fires when a panel is activated.
49903 * @param {Roo.LayoutRegion} this
49904 * @param {Roo.ContentPanel} panel The activated panel
49906 "panelactivated" : true,
49909 * Fires when the user resizes this region.
49910 * @param {Roo.LayoutRegion} this
49911 * @param {Number} newSize The new size (width for east/west, height for north/south)
49915 /** A collection of panels in this region. @type Roo.util.MixedCollection */
49916 this.panels = new Roo.util.MixedCollection();
49917 this.panels.getKey = this.getPanelId.createDelegate(this);
49919 this.activePanel = null;
49920 // ensure listeners are added...
49922 if (config.listeners || config.events) {
49923 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
49924 listeners : config.listeners || {},
49925 events : config.events || {}
49929 if(skipConfig !== true){
49930 this.applyConfig(config);
49934 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
49935 getPanelId : function(p){
49939 applyConfig : function(config){
49940 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
49941 this.config = config;
49946 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
49947 * the width, for horizontal (north, south) the height.
49948 * @param {Number} newSize The new width or height
49950 resizeTo : function(newSize){
49951 var el = this.el ? this.el :
49952 (this.activePanel ? this.activePanel.getEl() : null);
49954 switch(this.position){
49957 el.setWidth(newSize);
49958 this.fireEvent("resized", this, newSize);
49962 el.setHeight(newSize);
49963 this.fireEvent("resized", this, newSize);
49969 getBox : function(){
49970 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
49973 getMargins : function(){
49974 return this.margins;
49977 updateBox : function(box){
49979 var el = this.activePanel.getEl();
49980 el.dom.style.left = box.x + "px";
49981 el.dom.style.top = box.y + "px";
49982 this.activePanel.setSize(box.width, box.height);
49986 * Returns the container element for this region.
49987 * @return {Roo.Element}
49989 getEl : function(){
49990 return this.activePanel;
49994 * Returns true if this region is currently visible.
49995 * @return {Boolean}
49997 isVisible : function(){
49998 return this.activePanel ? true : false;
50001 setActivePanel : function(panel){
50002 panel = this.getPanel(panel);
50003 if(this.activePanel && this.activePanel != panel){
50004 this.activePanel.setActiveState(false);
50005 this.activePanel.getEl().setLeftTop(-10000,-10000);
50007 this.activePanel = panel;
50008 panel.setActiveState(true);
50010 panel.setSize(this.box.width, this.box.height);
50012 this.fireEvent("panelactivated", this, panel);
50013 this.fireEvent("invalidated");
50017 * Show the specified panel.
50018 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
50019 * @return {Roo.ContentPanel} The shown panel or null
50021 showPanel : function(panel){
50022 if(panel = this.getPanel(panel)){
50023 this.setActivePanel(panel);
50029 * Get the active panel for this region.
50030 * @return {Roo.ContentPanel} The active panel or null
50032 getActivePanel : function(){
50033 return this.activePanel;
50037 * Add the passed ContentPanel(s)
50038 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
50039 * @return {Roo.ContentPanel} The panel added (if only one was added)
50041 add : function(panel){
50042 if(arguments.length > 1){
50043 for(var i = 0, len = arguments.length; i < len; i++) {
50044 this.add(arguments[i]);
50048 if(this.hasPanel(panel)){
50049 this.showPanel(panel);
50052 var el = panel.getEl();
50053 if(el.dom.parentNode != this.mgr.el.dom){
50054 this.mgr.el.dom.appendChild(el.dom);
50056 if(panel.setRegion){
50057 panel.setRegion(this);
50059 this.panels.add(panel);
50060 el.setStyle("position", "absolute");
50061 if(!panel.background){
50062 this.setActivePanel(panel);
50063 if(this.config.initialSize && this.panels.getCount()==1){
50064 this.resizeTo(this.config.initialSize);
50067 this.fireEvent("paneladded", this, panel);
50072 * Returns true if the panel is in this region.
50073 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50074 * @return {Boolean}
50076 hasPanel : function(panel){
50077 if(typeof panel == "object"){ // must be panel obj
50078 panel = panel.getId();
50080 return this.getPanel(panel) ? true : false;
50084 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
50085 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50086 * @param {Boolean} preservePanel Overrides the config preservePanel option
50087 * @return {Roo.ContentPanel} The panel that was removed
50089 remove : function(panel, preservePanel){
50090 panel = this.getPanel(panel);
50095 this.fireEvent("beforeremove", this, panel, e);
50096 if(e.cancel === true){
50099 var panelId = panel.getId();
50100 this.panels.removeKey(panelId);
50105 * Returns the panel specified or null if it's not in this region.
50106 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50107 * @return {Roo.ContentPanel}
50109 getPanel : function(id){
50110 if(typeof id == "object"){ // must be panel obj
50113 return this.panels.get(id);
50117 * Returns this regions position (north/south/east/west/center).
50120 getPosition: function(){
50121 return this.position;
50125 * Ext JS Library 1.1.1
50126 * Copyright(c) 2006-2007, Ext JS, LLC.
50128 * Originally Released Under LGPL - original licence link has changed is not relivant.
50131 * <script type="text/javascript">
50135 * @class Roo.LayoutRegion
50136 * @extends Roo.BasicLayoutRegion
50137 * This class represents a region in a layout manager.
50138 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
50139 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
50140 * @cfg {Boolean} floatable False to disable floating (defaults to true)
50141 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
50142 * @cfg {Object} cmargins Margins for the element when collapsed (defaults to: north/south {top: 2, left: 0, right:0, bottom: 2} or east/west {top: 0, left: 2, right:2, bottom: 0})
50143 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
50144 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
50145 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
50146 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
50147 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
50148 * @cfg {String} title The title for the region (overrides panel titles)
50149 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
50150 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
50151 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
50152 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
50153 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
50154 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
50155 * the space available, similar to FireFox 1.5 tabs (defaults to false)
50156 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
50157 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
50158 * @cfg {Boolean} showPin True to show a pin button
50159 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
50160 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
50161 * @cfg {Boolean} disableTabTips True to disable tab tooltips
50162 * @cfg {Number} width For East/West panels
50163 * @cfg {Number} height For North/South panels
50164 * @cfg {Boolean} split To show the splitter
50165 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
50167 Roo.LayoutRegion = function(mgr, config, pos){
50168 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
50169 var dh = Roo.DomHelper;
50170 /** This region's container element
50171 * @type Roo.Element */
50172 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
50173 /** This region's title element
50174 * @type Roo.Element */
50176 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
50177 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
50178 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
50180 this.titleEl.enableDisplayMode();
50181 /** This region's title text element
50182 * @type HTMLElement */
50183 this.titleTextEl = this.titleEl.dom.firstChild;
50184 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
50185 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
50186 this.closeBtn.enableDisplayMode();
50187 this.closeBtn.on("click", this.closeClicked, this);
50188 this.closeBtn.hide();
50190 this.createBody(config);
50191 this.visible = true;
50192 this.collapsed = false;
50194 if(config.hideWhenEmpty){
50196 this.on("paneladded", this.validateVisibility, this);
50197 this.on("panelremoved", this.validateVisibility, this);
50199 this.applyConfig(config);
50202 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
50204 createBody : function(){
50205 /** This region's body element
50206 * @type Roo.Element */
50207 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
50210 applyConfig : function(c){
50211 if(c.collapsible && this.position != "center" && !this.collapsedEl){
50212 var dh = Roo.DomHelper;
50213 if(c.titlebar !== false){
50214 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
50215 this.collapseBtn.on("click", this.collapse, this);
50216 this.collapseBtn.enableDisplayMode();
50218 if(c.showPin === true || this.showPin){
50219 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
50220 this.stickBtn.enableDisplayMode();
50221 this.stickBtn.on("click", this.expand, this);
50222 this.stickBtn.hide();
50225 /** This region's collapsed element
50226 * @type Roo.Element */
50227 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
50228 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
50230 if(c.floatable !== false){
50231 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
50232 this.collapsedEl.on("click", this.collapseClick, this);
50235 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
50236 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
50237 id: "message", unselectable: "on", style:{"float":"left"}});
50238 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
50240 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
50241 this.expandBtn.on("click", this.expand, this);
50243 if(this.collapseBtn){
50244 this.collapseBtn.setVisible(c.collapsible == true);
50246 this.cmargins = c.cmargins || this.cmargins ||
50247 (this.position == "west" || this.position == "east" ?
50248 {top: 0, left: 2, right:2, bottom: 0} :
50249 {top: 2, left: 0, right:0, bottom: 2});
50250 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
50251 this.bottomTabs = c.tabPosition != "top";
50252 this.autoScroll = c.autoScroll || false;
50253 if(this.autoScroll){
50254 this.bodyEl.setStyle("overflow", "auto");
50256 this.bodyEl.setStyle("overflow", "hidden");
50258 //if(c.titlebar !== false){
50259 if((!c.titlebar && !c.title) || c.titlebar === false){
50260 this.titleEl.hide();
50262 this.titleEl.show();
50264 this.titleTextEl.innerHTML = c.title;
50268 this.duration = c.duration || .30;
50269 this.slideDuration = c.slideDuration || .45;
50272 this.collapse(true);
50279 * Returns true if this region is currently visible.
50280 * @return {Boolean}
50282 isVisible : function(){
50283 return this.visible;
50287 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
50288 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
50290 setCollapsedTitle : function(title){
50291 title = title || " ";
50292 if(this.collapsedTitleTextEl){
50293 this.collapsedTitleTextEl.innerHTML = title;
50297 getBox : function(){
50299 if(!this.collapsed){
50300 b = this.el.getBox(false, true);
50302 b = this.collapsedEl.getBox(false, true);
50307 getMargins : function(){
50308 return this.collapsed ? this.cmargins : this.margins;
50311 highlight : function(){
50312 this.el.addClass("x-layout-panel-dragover");
50315 unhighlight : function(){
50316 this.el.removeClass("x-layout-panel-dragover");
50319 updateBox : function(box){
50321 if(!this.collapsed){
50322 this.el.dom.style.left = box.x + "px";
50323 this.el.dom.style.top = box.y + "px";
50324 this.updateBody(box.width, box.height);
50326 this.collapsedEl.dom.style.left = box.x + "px";
50327 this.collapsedEl.dom.style.top = box.y + "px";
50328 this.collapsedEl.setSize(box.width, box.height);
50331 this.tabs.autoSizeTabs();
50335 updateBody : function(w, h){
50337 this.el.setWidth(w);
50338 w -= this.el.getBorderWidth("rl");
50339 if(this.config.adjustments){
50340 w += this.config.adjustments[0];
50344 this.el.setHeight(h);
50345 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
50346 h -= this.el.getBorderWidth("tb");
50347 if(this.config.adjustments){
50348 h += this.config.adjustments[1];
50350 this.bodyEl.setHeight(h);
50352 h = this.tabs.syncHeight(h);
50355 if(this.panelSize){
50356 w = w !== null ? w : this.panelSize.width;
50357 h = h !== null ? h : this.panelSize.height;
50359 if(this.activePanel){
50360 var el = this.activePanel.getEl();
50361 w = w !== null ? w : el.getWidth();
50362 h = h !== null ? h : el.getHeight();
50363 this.panelSize = {width: w, height: h};
50364 this.activePanel.setSize(w, h);
50366 if(Roo.isIE && this.tabs){
50367 this.tabs.el.repaint();
50372 * Returns the container element for this region.
50373 * @return {Roo.Element}
50375 getEl : function(){
50380 * Hides this region.
50383 if(!this.collapsed){
50384 this.el.dom.style.left = "-2000px";
50387 this.collapsedEl.dom.style.left = "-2000px";
50388 this.collapsedEl.hide();
50390 this.visible = false;
50391 this.fireEvent("visibilitychange", this, false);
50395 * Shows this region if it was previously hidden.
50398 if(!this.collapsed){
50401 this.collapsedEl.show();
50403 this.visible = true;
50404 this.fireEvent("visibilitychange", this, true);
50407 closeClicked : function(){
50408 if(this.activePanel){
50409 this.remove(this.activePanel);
50413 collapseClick : function(e){
50415 e.stopPropagation();
50418 e.stopPropagation();
50424 * Collapses this region.
50425 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
50427 collapse : function(skipAnim){
50428 if(this.collapsed) return;
50429 this.collapsed = true;
50431 this.split.el.hide();
50433 if(this.config.animate && skipAnim !== true){
50434 this.fireEvent("invalidated", this);
50435 this.animateCollapse();
50437 this.el.setLocation(-20000,-20000);
50439 this.collapsedEl.show();
50440 this.fireEvent("collapsed", this);
50441 this.fireEvent("invalidated", this);
50445 animateCollapse : function(){
50450 * Expands this region if it was previously collapsed.
50451 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
50452 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
50454 expand : function(e, skipAnim){
50455 if(e) e.stopPropagation();
50456 if(!this.collapsed || this.el.hasActiveFx()) return;
50458 this.afterSlideIn();
50461 this.collapsed = false;
50462 if(this.config.animate && skipAnim !== true){
50463 this.animateExpand();
50467 this.split.el.show();
50469 this.collapsedEl.setLocation(-2000,-2000);
50470 this.collapsedEl.hide();
50471 this.fireEvent("invalidated", this);
50472 this.fireEvent("expanded", this);
50476 animateExpand : function(){
50480 initTabs : function()
50482 this.bodyEl.setStyle("overflow", "hidden");
50483 var ts = new Roo.TabPanel(
50486 tabPosition: this.bottomTabs ? 'bottom' : 'top',
50487 disableTooltips: this.config.disableTabTips,
50488 toolbar : this.config.toolbar
50491 if(this.config.hideTabs){
50492 ts.stripWrap.setDisplayed(false);
50495 ts.resizeTabs = this.config.resizeTabs === true;
50496 ts.minTabWidth = this.config.minTabWidth || 40;
50497 ts.maxTabWidth = this.config.maxTabWidth || 250;
50498 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
50499 ts.monitorResize = false;
50500 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
50501 ts.bodyEl.addClass('x-layout-tabs-body');
50502 this.panels.each(this.initPanelAsTab, this);
50505 initPanelAsTab : function(panel){
50506 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
50507 this.config.closeOnTab && panel.isClosable());
50508 if(panel.tabTip !== undefined){
50509 ti.setTooltip(panel.tabTip);
50511 ti.on("activate", function(){
50512 this.setActivePanel(panel);
50514 if(this.config.closeOnTab){
50515 ti.on("beforeclose", function(t, e){
50517 this.remove(panel);
50523 updatePanelTitle : function(panel, title){
50524 if(this.activePanel == panel){
50525 this.updateTitle(title);
50528 var ti = this.tabs.getTab(panel.getEl().id);
50530 if(panel.tabTip !== undefined){
50531 ti.setTooltip(panel.tabTip);
50536 updateTitle : function(title){
50537 if(this.titleTextEl && !this.config.title){
50538 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
50542 setActivePanel : function(panel){
50543 panel = this.getPanel(panel);
50544 if(this.activePanel && this.activePanel != panel){
50545 this.activePanel.setActiveState(false);
50547 this.activePanel = panel;
50548 panel.setActiveState(true);
50549 if(this.panelSize){
50550 panel.setSize(this.panelSize.width, this.panelSize.height);
50553 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
50555 this.updateTitle(panel.getTitle());
50557 this.fireEvent("invalidated", this);
50559 this.fireEvent("panelactivated", this, panel);
50563 * Shows the specified panel.
50564 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
50565 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
50567 showPanel : function(panel)
50569 panel = this.getPanel(panel);
50572 var tab = this.tabs.getTab(panel.getEl().id);
50573 if(tab.isHidden()){
50574 this.tabs.unhideTab(tab.id);
50578 this.setActivePanel(panel);
50585 * Get the active panel for this region.
50586 * @return {Roo.ContentPanel} The active panel or null
50588 getActivePanel : function(){
50589 return this.activePanel;
50592 validateVisibility : function(){
50593 if(this.panels.getCount() < 1){
50594 this.updateTitle(" ");
50595 this.closeBtn.hide();
50598 if(!this.isVisible()){
50605 * Adds the passed ContentPanel(s) to this region.
50606 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
50607 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
50609 add : function(panel){
50610 if(arguments.length > 1){
50611 for(var i = 0, len = arguments.length; i < len; i++) {
50612 this.add(arguments[i]);
50616 if(this.hasPanel(panel)){
50617 this.showPanel(panel);
50620 panel.setRegion(this);
50621 this.panels.add(panel);
50622 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
50623 this.bodyEl.dom.appendChild(panel.getEl().dom);
50624 if(panel.background !== true){
50625 this.setActivePanel(panel);
50627 this.fireEvent("paneladded", this, panel);
50633 this.initPanelAsTab(panel);
50635 if(panel.background !== true){
50636 this.tabs.activate(panel.getEl().id);
50638 this.fireEvent("paneladded", this, panel);
50643 * Hides the tab for the specified panel.
50644 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50646 hidePanel : function(panel){
50647 if(this.tabs && (panel = this.getPanel(panel))){
50648 this.tabs.hideTab(panel.getEl().id);
50653 * Unhides the tab for a previously hidden panel.
50654 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50656 unhidePanel : function(panel){
50657 if(this.tabs && (panel = this.getPanel(panel))){
50658 this.tabs.unhideTab(panel.getEl().id);
50662 clearPanels : function(){
50663 while(this.panels.getCount() > 0){
50664 this.remove(this.panels.first());
50669 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
50670 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50671 * @param {Boolean} preservePanel Overrides the config preservePanel option
50672 * @return {Roo.ContentPanel} The panel that was removed
50674 remove : function(panel, preservePanel){
50675 panel = this.getPanel(panel);
50680 this.fireEvent("beforeremove", this, panel, e);
50681 if(e.cancel === true){
50684 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
50685 var panelId = panel.getId();
50686 this.panels.removeKey(panelId);
50688 document.body.appendChild(panel.getEl().dom);
50691 this.tabs.removeTab(panel.getEl().id);
50692 }else if (!preservePanel){
50693 this.bodyEl.dom.removeChild(panel.getEl().dom);
50695 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
50696 var p = this.panels.first();
50697 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
50698 tempEl.appendChild(p.getEl().dom);
50699 this.bodyEl.update("");
50700 this.bodyEl.dom.appendChild(p.getEl().dom);
50702 this.updateTitle(p.getTitle());
50704 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
50705 this.setActivePanel(p);
50707 panel.setRegion(null);
50708 if(this.activePanel == panel){
50709 this.activePanel = null;
50711 if(this.config.autoDestroy !== false && preservePanel !== true){
50712 try{panel.destroy();}catch(e){}
50714 this.fireEvent("panelremoved", this, panel);
50719 * Returns the TabPanel component used by this region
50720 * @return {Roo.TabPanel}
50722 getTabs : function(){
50726 createTool : function(parentEl, className){
50727 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
50728 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
50729 btn.addClassOnOver("x-layout-tools-button-over");
50734 * Ext JS Library 1.1.1
50735 * Copyright(c) 2006-2007, Ext JS, LLC.
50737 * Originally Released Under LGPL - original licence link has changed is not relivant.
50740 * <script type="text/javascript">
50746 * @class Roo.SplitLayoutRegion
50747 * @extends Roo.LayoutRegion
50748 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
50750 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
50751 this.cursor = cursor;
50752 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
50755 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
50756 splitTip : "Drag to resize.",
50757 collapsibleSplitTip : "Drag to resize. Double click to hide.",
50758 useSplitTips : false,
50760 applyConfig : function(config){
50761 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
50764 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
50765 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
50766 /** The SplitBar for this region
50767 * @type Roo.SplitBar */
50768 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
50769 this.split.on("moved", this.onSplitMove, this);
50770 this.split.useShim = config.useShim === true;
50771 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
50772 if(this.useSplitTips){
50773 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
50775 if(config.collapsible){
50776 this.split.el.on("dblclick", this.collapse, this);
50779 if(typeof config.minSize != "undefined"){
50780 this.split.minSize = config.minSize;
50782 if(typeof config.maxSize != "undefined"){
50783 this.split.maxSize = config.maxSize;
50785 if(config.hideWhenEmpty || config.hidden || config.collapsed){
50786 this.hideSplitter();
50791 getHMaxSize : function(){
50792 var cmax = this.config.maxSize || 10000;
50793 var center = this.mgr.getRegion("center");
50794 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
50797 getVMaxSize : function(){
50798 var cmax = this.config.maxSize || 10000;
50799 var center = this.mgr.getRegion("center");
50800 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
50803 onSplitMove : function(split, newSize){
50804 this.fireEvent("resized", this, newSize);
50808 * Returns the {@link Roo.SplitBar} for this region.
50809 * @return {Roo.SplitBar}
50811 getSplitBar : function(){
50816 this.hideSplitter();
50817 Roo.SplitLayoutRegion.superclass.hide.call(this);
50820 hideSplitter : function(){
50822 this.split.el.setLocation(-2000,-2000);
50823 this.split.el.hide();
50829 this.split.el.show();
50831 Roo.SplitLayoutRegion.superclass.show.call(this);
50834 beforeSlide: function(){
50835 if(Roo.isGecko){// firefox overflow auto bug workaround
50836 this.bodyEl.clip();
50837 if(this.tabs) this.tabs.bodyEl.clip();
50838 if(this.activePanel){
50839 this.activePanel.getEl().clip();
50841 if(this.activePanel.beforeSlide){
50842 this.activePanel.beforeSlide();
50848 afterSlide : function(){
50849 if(Roo.isGecko){// firefox overflow auto bug workaround
50850 this.bodyEl.unclip();
50851 if(this.tabs) this.tabs.bodyEl.unclip();
50852 if(this.activePanel){
50853 this.activePanel.getEl().unclip();
50854 if(this.activePanel.afterSlide){
50855 this.activePanel.afterSlide();
50861 initAutoHide : function(){
50862 if(this.autoHide !== false){
50863 if(!this.autoHideHd){
50864 var st = new Roo.util.DelayedTask(this.slideIn, this);
50865 this.autoHideHd = {
50866 "mouseout": function(e){
50867 if(!e.within(this.el, true)){
50871 "mouseover" : function(e){
50877 this.el.on(this.autoHideHd);
50881 clearAutoHide : function(){
50882 if(this.autoHide !== false){
50883 this.el.un("mouseout", this.autoHideHd.mouseout);
50884 this.el.un("mouseover", this.autoHideHd.mouseover);
50888 clearMonitor : function(){
50889 Roo.get(document).un("click", this.slideInIf, this);
50892 // these names are backwards but not changed for compat
50893 slideOut : function(){
50894 if(this.isSlid || this.el.hasActiveFx()){
50897 this.isSlid = true;
50898 if(this.collapseBtn){
50899 this.collapseBtn.hide();
50901 this.closeBtnState = this.closeBtn.getStyle('display');
50902 this.closeBtn.hide();
50904 this.stickBtn.show();
50907 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
50908 this.beforeSlide();
50909 this.el.setStyle("z-index", 10001);
50910 this.el.slideIn(this.getSlideAnchor(), {
50911 callback: function(){
50913 this.initAutoHide();
50914 Roo.get(document).on("click", this.slideInIf, this);
50915 this.fireEvent("slideshow", this);
50922 afterSlideIn : function(){
50923 this.clearAutoHide();
50924 this.isSlid = false;
50925 this.clearMonitor();
50926 this.el.setStyle("z-index", "");
50927 if(this.collapseBtn){
50928 this.collapseBtn.show();
50930 this.closeBtn.setStyle('display', this.closeBtnState);
50932 this.stickBtn.hide();
50934 this.fireEvent("slidehide", this);
50937 slideIn : function(cb){
50938 if(!this.isSlid || this.el.hasActiveFx()){
50942 this.isSlid = false;
50943 this.beforeSlide();
50944 this.el.slideOut(this.getSlideAnchor(), {
50945 callback: function(){
50946 this.el.setLeftTop(-10000, -10000);
50948 this.afterSlideIn();
50956 slideInIf : function(e){
50957 if(!e.within(this.el)){
50962 animateCollapse : function(){
50963 this.beforeSlide();
50964 this.el.setStyle("z-index", 20000);
50965 var anchor = this.getSlideAnchor();
50966 this.el.slideOut(anchor, {
50967 callback : function(){
50968 this.el.setStyle("z-index", "");
50969 this.collapsedEl.slideIn(anchor, {duration:.3});
50971 this.el.setLocation(-10000,-10000);
50973 this.fireEvent("collapsed", this);
50980 animateExpand : function(){
50981 this.beforeSlide();
50982 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
50983 this.el.setStyle("z-index", 20000);
50984 this.collapsedEl.hide({
50987 this.el.slideIn(this.getSlideAnchor(), {
50988 callback : function(){
50989 this.el.setStyle("z-index", "");
50992 this.split.el.show();
50994 this.fireEvent("invalidated", this);
50995 this.fireEvent("expanded", this);
51023 getAnchor : function(){
51024 return this.anchors[this.position];
51027 getCollapseAnchor : function(){
51028 return this.canchors[this.position];
51031 getSlideAnchor : function(){
51032 return this.sanchors[this.position];
51035 getAlignAdj : function(){
51036 var cm = this.cmargins;
51037 switch(this.position){
51053 getExpandAdj : function(){
51054 var c = this.collapsedEl, cm = this.cmargins;
51055 switch(this.position){
51057 return [-(cm.right+c.getWidth()+cm.left), 0];
51060 return [cm.right+c.getWidth()+cm.left, 0];
51063 return [0, -(cm.top+cm.bottom+c.getHeight())];
51066 return [0, cm.top+cm.bottom+c.getHeight()];
51072 * Ext JS Library 1.1.1
51073 * Copyright(c) 2006-2007, Ext JS, LLC.
51075 * Originally Released Under LGPL - original licence link has changed is not relivant.
51078 * <script type="text/javascript">
51081 * These classes are private internal classes
51083 Roo.CenterLayoutRegion = function(mgr, config){
51084 Roo.LayoutRegion.call(this, mgr, config, "center");
51085 this.visible = true;
51086 this.minWidth = config.minWidth || 20;
51087 this.minHeight = config.minHeight || 20;
51090 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
51092 // center panel can't be hidden
51096 // center panel can't be hidden
51099 getMinWidth: function(){
51100 return this.minWidth;
51103 getMinHeight: function(){
51104 return this.minHeight;
51109 Roo.NorthLayoutRegion = function(mgr, config){
51110 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
51112 this.split.placement = Roo.SplitBar.TOP;
51113 this.split.orientation = Roo.SplitBar.VERTICAL;
51114 this.split.el.addClass("x-layout-split-v");
51116 var size = config.initialSize || config.height;
51117 if(typeof size != "undefined"){
51118 this.el.setHeight(size);
51121 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
51122 orientation: Roo.SplitBar.VERTICAL,
51123 getBox : function(){
51124 if(this.collapsed){
51125 return this.collapsedEl.getBox();
51127 var box = this.el.getBox();
51129 box.height += this.split.el.getHeight();
51134 updateBox : function(box){
51135 if(this.split && !this.collapsed){
51136 box.height -= this.split.el.getHeight();
51137 this.split.el.setLeft(box.x);
51138 this.split.el.setTop(box.y+box.height);
51139 this.split.el.setWidth(box.width);
51141 if(this.collapsed){
51142 this.updateBody(box.width, null);
51144 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51148 Roo.SouthLayoutRegion = function(mgr, config){
51149 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
51151 this.split.placement = Roo.SplitBar.BOTTOM;
51152 this.split.orientation = Roo.SplitBar.VERTICAL;
51153 this.split.el.addClass("x-layout-split-v");
51155 var size = config.initialSize || config.height;
51156 if(typeof size != "undefined"){
51157 this.el.setHeight(size);
51160 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
51161 orientation: Roo.SplitBar.VERTICAL,
51162 getBox : function(){
51163 if(this.collapsed){
51164 return this.collapsedEl.getBox();
51166 var box = this.el.getBox();
51168 var sh = this.split.el.getHeight();
51175 updateBox : function(box){
51176 if(this.split && !this.collapsed){
51177 var sh = this.split.el.getHeight();
51180 this.split.el.setLeft(box.x);
51181 this.split.el.setTop(box.y-sh);
51182 this.split.el.setWidth(box.width);
51184 if(this.collapsed){
51185 this.updateBody(box.width, null);
51187 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51191 Roo.EastLayoutRegion = function(mgr, config){
51192 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
51194 this.split.placement = Roo.SplitBar.RIGHT;
51195 this.split.orientation = Roo.SplitBar.HORIZONTAL;
51196 this.split.el.addClass("x-layout-split-h");
51198 var size = config.initialSize || config.width;
51199 if(typeof size != "undefined"){
51200 this.el.setWidth(size);
51203 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
51204 orientation: Roo.SplitBar.HORIZONTAL,
51205 getBox : function(){
51206 if(this.collapsed){
51207 return this.collapsedEl.getBox();
51209 var box = this.el.getBox();
51211 var sw = this.split.el.getWidth();
51218 updateBox : function(box){
51219 if(this.split && !this.collapsed){
51220 var sw = this.split.el.getWidth();
51222 this.split.el.setLeft(box.x);
51223 this.split.el.setTop(box.y);
51224 this.split.el.setHeight(box.height);
51227 if(this.collapsed){
51228 this.updateBody(null, box.height);
51230 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51234 Roo.WestLayoutRegion = function(mgr, config){
51235 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
51237 this.split.placement = Roo.SplitBar.LEFT;
51238 this.split.orientation = Roo.SplitBar.HORIZONTAL;
51239 this.split.el.addClass("x-layout-split-h");
51241 var size = config.initialSize || config.width;
51242 if(typeof size != "undefined"){
51243 this.el.setWidth(size);
51246 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
51247 orientation: Roo.SplitBar.HORIZONTAL,
51248 getBox : function(){
51249 if(this.collapsed){
51250 return this.collapsedEl.getBox();
51252 var box = this.el.getBox();
51254 box.width += this.split.el.getWidth();
51259 updateBox : function(box){
51260 if(this.split && !this.collapsed){
51261 var sw = this.split.el.getWidth();
51263 this.split.el.setLeft(box.x+box.width);
51264 this.split.el.setTop(box.y);
51265 this.split.el.setHeight(box.height);
51267 if(this.collapsed){
51268 this.updateBody(null, box.height);
51270 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51275 * Ext JS Library 1.1.1
51276 * Copyright(c) 2006-2007, Ext JS, LLC.
51278 * Originally Released Under LGPL - original licence link has changed is not relivant.
51281 * <script type="text/javascript">
51286 * Private internal class for reading and applying state
51288 Roo.LayoutStateManager = function(layout){
51289 // default empty state
51298 Roo.LayoutStateManager.prototype = {
51299 init : function(layout, provider){
51300 this.provider = provider;
51301 var state = provider.get(layout.id+"-layout-state");
51303 var wasUpdating = layout.isUpdating();
51305 layout.beginUpdate();
51307 for(var key in state){
51308 if(typeof state[key] != "function"){
51309 var rstate = state[key];
51310 var r = layout.getRegion(key);
51313 r.resizeTo(rstate.size);
51315 if(rstate.collapsed == true){
51318 r.expand(null, true);
51324 layout.endUpdate();
51326 this.state = state;
51328 this.layout = layout;
51329 layout.on("regionresized", this.onRegionResized, this);
51330 layout.on("regioncollapsed", this.onRegionCollapsed, this);
51331 layout.on("regionexpanded", this.onRegionExpanded, this);
51334 storeState : function(){
51335 this.provider.set(this.layout.id+"-layout-state", this.state);
51338 onRegionResized : function(region, newSize){
51339 this.state[region.getPosition()].size = newSize;
51343 onRegionCollapsed : function(region){
51344 this.state[region.getPosition()].collapsed = true;
51348 onRegionExpanded : function(region){
51349 this.state[region.getPosition()].collapsed = false;
51354 * Ext JS Library 1.1.1
51355 * Copyright(c) 2006-2007, Ext JS, LLC.
51357 * Originally Released Under LGPL - original licence link has changed is not relivant.
51360 * <script type="text/javascript">
51363 * @class Roo.ContentPanel
51364 * @extends Roo.util.Observable
51365 * A basic ContentPanel element.
51366 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
51367 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
51368 * @cfg {Boolean/Object} autoCreate True to auto generate the DOM element for this panel, or a {@link Roo.DomHelper} config of the element to create
51369 * @cfg {Boolean} closable True if the panel can be closed/removed
51370 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
51371 * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
51372 * @cfg {Toolbar} toolbar A toolbar for this panel
51373 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
51374 * @cfg {String} title The title for this panel
51375 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
51376 * @cfg {String} url Calls {@link #setUrl} with this value
51377 * @cfg {String} region (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
51378 * @cfg {String/Object} params When used with {@link #url}, calls {@link #setUrl} with this value
51379 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
51380 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
51383 * Create a new ContentPanel.
51384 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
51385 * @param {String/Object} config A string to set only the title or a config object
51386 * @param {String} content (optional) Set the HTML content for this panel
51387 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
51389 Roo.ContentPanel = function(el, config, content){
51393 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
51397 if (config && config.parentLayout) {
51398 el = config.parentLayout.el.createChild();
51401 if(el.autoCreate){ // xtype is available if this is called from factory
51405 this.el = Roo.get(el);
51406 if(!this.el && config && config.autoCreate){
51407 if(typeof config.autoCreate == "object"){
51408 if(!config.autoCreate.id){
51409 config.autoCreate.id = config.id||el;
51411 this.el = Roo.DomHelper.append(document.body,
51412 config.autoCreate, true);
51414 this.el = Roo.DomHelper.append(document.body,
51415 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
51418 this.closable = false;
51419 this.loaded = false;
51420 this.active = false;
51421 if(typeof config == "string"){
51422 this.title = config;
51424 Roo.apply(this, config);
51427 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
51428 this.wrapEl = this.el.wrap();
51429 this.toolbar.container = this.el.insertSibling(false, 'before');
51430 this.toolbar = new Roo.Toolbar(this.toolbar);
51433 // xtype created footer. - not sure if will work as we normally have to render first..
51434 if (this.footer && !this.footer.el && this.footer.xtype) {
51435 if (!this.wrapEl) {
51436 this.wrapEl = this.el.wrap();
51439 this.footer.container = this.wrapEl.createChild();
51441 this.footer = Roo.factory(this.footer, Roo);
51446 this.resizeEl = Roo.get(this.resizeEl, true);
51448 this.resizeEl = this.el;
51450 // handle view.xtype
51458 * Fires when this panel is activated.
51459 * @param {Roo.ContentPanel} this
51463 * @event deactivate
51464 * Fires when this panel is activated.
51465 * @param {Roo.ContentPanel} this
51467 "deactivate" : true,
51471 * Fires when this panel is resized if fitToFrame is true.
51472 * @param {Roo.ContentPanel} this
51473 * @param {Number} width The width after any component adjustments
51474 * @param {Number} height The height after any component adjustments
51480 * Fires when this tab is created
51481 * @param {Roo.ContentPanel} this
51492 if(this.autoScroll){
51493 this.resizeEl.setStyle("overflow", "auto");
51495 // fix randome scrolling
51496 this.el.on('scroll', function() {
51497 Roo.log('fix random scolling');
51498 this.scrollTo('top',0);
51501 content = content || this.content;
51503 this.setContent(content);
51505 if(config && config.url){
51506 this.setUrl(this.url, this.params, this.loadOnce);
51511 Roo.ContentPanel.superclass.constructor.call(this);
51513 if (this.view && typeof(this.view.xtype) != 'undefined') {
51514 this.view.el = this.el.appendChild(document.createElement("div"));
51515 this.view = Roo.factory(this.view);
51516 this.view.render && this.view.render(false, '');
51520 this.fireEvent('render', this);
51523 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
51525 setRegion : function(region){
51526 this.region = region;
51528 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
51530 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
51535 * Returns the toolbar for this Panel if one was configured.
51536 * @return {Roo.Toolbar}
51538 getToolbar : function(){
51539 return this.toolbar;
51542 setActiveState : function(active){
51543 this.active = active;
51545 this.fireEvent("deactivate", this);
51547 this.fireEvent("activate", this);
51551 * Updates this panel's element
51552 * @param {String} content The new content
51553 * @param {Boolean} loadScripts (optional) true to look for and process scripts
51555 setContent : function(content, loadScripts){
51556 this.el.update(content, loadScripts);
51559 ignoreResize : function(w, h){
51560 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
51563 this.lastSize = {width: w, height: h};
51568 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
51569 * @return {Roo.UpdateManager} The UpdateManager
51571 getUpdateManager : function(){
51572 return this.el.getUpdateManager();
51575 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
51576 * @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:
51579 url: "your-url.php",
51580 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
51581 callback: yourFunction,
51582 scope: yourObject, //(optional scope)
51585 text: "Loading...",
51590 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
51591 * are shorthand for <i>disableCaching</i>, <i>indicatorText</i> and <i>loadScripts</i> and are used to set their associated property on this panel UpdateManager instance.
51592 * @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}
51593 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
51594 * @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.
51595 * @return {Roo.ContentPanel} this
51598 var um = this.el.getUpdateManager();
51599 um.update.apply(um, arguments);
51605 * Set a URL to be used to load the content for this panel. When this panel is activated, the content will be loaded from that URL.
51606 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
51607 * @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Roo.UpdateManager#update} for more details. (Defaults to null)
51608 * @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this panel is activated. (Defaults to false)
51609 * @return {Roo.UpdateManager} The UpdateManager
51611 setUrl : function(url, params, loadOnce){
51612 if(this.refreshDelegate){
51613 this.removeListener("activate", this.refreshDelegate);
51615 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
51616 this.on("activate", this.refreshDelegate);
51617 return this.el.getUpdateManager();
51620 _handleRefresh : function(url, params, loadOnce){
51621 if(!loadOnce || !this.loaded){
51622 var updater = this.el.getUpdateManager();
51623 updater.update(url, params, this._setLoaded.createDelegate(this));
51627 _setLoaded : function(){
51628 this.loaded = true;
51632 * Returns this panel's id
51635 getId : function(){
51640 * Returns this panel's element - used by regiosn to add.
51641 * @return {Roo.Element}
51643 getEl : function(){
51644 return this.wrapEl || this.el;
51647 adjustForComponents : function(width, height)
51649 //Roo.log('adjustForComponents ');
51650 if(this.resizeEl != this.el){
51651 width -= this.el.getFrameWidth('lr');
51652 height -= this.el.getFrameWidth('tb');
51655 var te = this.toolbar.getEl();
51656 height -= te.getHeight();
51657 te.setWidth(width);
51660 var te = this.footer.getEl();
51661 Roo.log("footer:" + te.getHeight());
51663 height -= te.getHeight();
51664 te.setWidth(width);
51668 if(this.adjustments){
51669 width += this.adjustments[0];
51670 height += this.adjustments[1];
51672 return {"width": width, "height": height};
51675 setSize : function(width, height){
51676 if(this.fitToFrame && !this.ignoreResize(width, height)){
51677 if(this.fitContainer && this.resizeEl != this.el){
51678 this.el.setSize(width, height);
51680 var size = this.adjustForComponents(width, height);
51681 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
51682 this.fireEvent('resize', this, size.width, size.height);
51687 * Returns this panel's title
51690 getTitle : function(){
51695 * Set this panel's title
51696 * @param {String} title
51698 setTitle : function(title){
51699 this.title = title;
51701 this.region.updatePanelTitle(this, title);
51706 * Returns true is this panel was configured to be closable
51707 * @return {Boolean}
51709 isClosable : function(){
51710 return this.closable;
51713 beforeSlide : function(){
51715 this.resizeEl.clip();
51718 afterSlide : function(){
51720 this.resizeEl.unclip();
51724 * Force a content refresh from the URL specified in the {@link #setUrl} method.
51725 * Will fail silently if the {@link #setUrl} method has not been called.
51726 * This does not activate the panel, just updates its content.
51728 refresh : function(){
51729 if(this.refreshDelegate){
51730 this.loaded = false;
51731 this.refreshDelegate();
51736 * Destroys this panel
51738 destroy : function(){
51739 this.el.removeAllListeners();
51740 var tempEl = document.createElement("span");
51741 tempEl.appendChild(this.el.dom);
51742 tempEl.innerHTML = "";
51748 * form - if the content panel contains a form - this is a reference to it.
51749 * @type {Roo.form.Form}
51753 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
51754 * This contains a reference to it.
51760 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
51770 * @param {Object} cfg Xtype definition of item to add.
51773 addxtype : function(cfg) {
51775 if (cfg.xtype.match(/^Form$/)) {
51778 //if (this.footer) {
51779 // el = this.footer.container.insertSibling(false, 'before');
51781 el = this.el.createChild();
51784 this.form = new Roo.form.Form(cfg);
51787 if ( this.form.allItems.length) this.form.render(el.dom);
51790 // should only have one of theses..
51791 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
51792 // views.. should not be just added - used named prop 'view''
51794 cfg.el = this.el.appendChild(document.createElement("div"));
51797 var ret = new Roo.factory(cfg);
51799 ret.render && ret.render(false, ''); // render blank..
51808 * @class Roo.GridPanel
51809 * @extends Roo.ContentPanel
51811 * Create a new GridPanel.
51812 * @param {Roo.grid.Grid} grid The grid for this panel
51813 * @param {String/Object} config A string to set only the panel's title, or a config object
51815 Roo.GridPanel = function(grid, config){
51818 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
51819 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
51821 this.wrapper.dom.appendChild(grid.getGridEl().dom);
51823 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
51826 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
51828 // xtype created footer. - not sure if will work as we normally have to render first..
51829 if (this.footer && !this.footer.el && this.footer.xtype) {
51831 this.footer.container = this.grid.getView().getFooterPanel(true);
51832 this.footer.dataSource = this.grid.dataSource;
51833 this.footer = Roo.factory(this.footer, Roo);
51837 grid.monitorWindowResize = false; // turn off autosizing
51838 grid.autoHeight = false;
51839 grid.autoWidth = false;
51841 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
51844 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
51845 getId : function(){
51846 return this.grid.id;
51850 * Returns the grid for this panel
51851 * @return {Roo.grid.Grid}
51853 getGrid : function(){
51857 setSize : function(width, height){
51858 if(!this.ignoreResize(width, height)){
51859 var grid = this.grid;
51860 var size = this.adjustForComponents(width, height);
51861 grid.getGridEl().setSize(size.width, size.height);
51866 beforeSlide : function(){
51867 this.grid.getView().scroller.clip();
51870 afterSlide : function(){
51871 this.grid.getView().scroller.unclip();
51874 destroy : function(){
51875 this.grid.destroy();
51877 Roo.GridPanel.superclass.destroy.call(this);
51883 * @class Roo.NestedLayoutPanel
51884 * @extends Roo.ContentPanel
51886 * Create a new NestedLayoutPanel.
51889 * @param {Roo.BorderLayout} layout The layout for this panel
51890 * @param {String/Object} config A string to set only the title or a config object
51892 Roo.NestedLayoutPanel = function(layout, config)
51894 // construct with only one argument..
51895 /* FIXME - implement nicer consturctors
51896 if (layout.layout) {
51898 layout = config.layout;
51899 delete config.layout;
51901 if (layout.xtype && !layout.getEl) {
51902 // then layout needs constructing..
51903 layout = Roo.factory(layout, Roo);
51908 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
51910 layout.monitorWindowResize = false; // turn off autosizing
51911 this.layout = layout;
51912 this.layout.getEl().addClass("x-layout-nested-layout");
51919 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
51921 setSize : function(width, height){
51922 if(!this.ignoreResize(width, height)){
51923 var size = this.adjustForComponents(width, height);
51924 var el = this.layout.getEl();
51925 el.setSize(size.width, size.height);
51926 var touch = el.dom.offsetWidth;
51927 this.layout.layout();
51928 // ie requires a double layout on the first pass
51929 if(Roo.isIE && !this.initialized){
51930 this.initialized = true;
51931 this.layout.layout();
51936 // activate all subpanels if not currently active..
51938 setActiveState : function(active){
51939 this.active = active;
51941 this.fireEvent("deactivate", this);
51945 this.fireEvent("activate", this);
51946 // not sure if this should happen before or after..
51947 if (!this.layout) {
51948 return; // should not happen..
51951 for (var r in this.layout.regions) {
51952 reg = this.layout.getRegion(r);
51953 if (reg.getActivePanel()) {
51954 //reg.showPanel(reg.getActivePanel()); // force it to activate..
51955 reg.setActivePanel(reg.getActivePanel());
51958 if (!reg.panels.length) {
51961 reg.showPanel(reg.getPanel(0));
51970 * Returns the nested BorderLayout for this panel
51971 * @return {Roo.BorderLayout}
51973 getLayout : function(){
51974 return this.layout;
51978 * Adds a xtype elements to the layout of the nested panel
51982 xtype : 'ContentPanel',
51989 xtype : 'NestedLayoutPanel',
51995 items : [ ... list of content panels or nested layout panels.. ]
51999 * @param {Object} cfg Xtype definition of item to add.
52001 addxtype : function(cfg) {
52002 return this.layout.addxtype(cfg);
52007 Roo.ScrollPanel = function(el, config, content){
52008 config = config || {};
52009 config.fitToFrame = true;
52010 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
52012 this.el.dom.style.overflow = "hidden";
52013 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
52014 this.el.removeClass("x-layout-inactive-content");
52015 this.el.on("mousewheel", this.onWheel, this);
52017 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
52018 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
52019 up.unselectable(); down.unselectable();
52020 up.on("click", this.scrollUp, this);
52021 down.on("click", this.scrollDown, this);
52022 up.addClassOnOver("x-scroller-btn-over");
52023 down.addClassOnOver("x-scroller-btn-over");
52024 up.addClassOnClick("x-scroller-btn-click");
52025 down.addClassOnClick("x-scroller-btn-click");
52026 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
52028 this.resizeEl = this.el;
52029 this.el = wrap; this.up = up; this.down = down;
52032 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
52034 wheelIncrement : 5,
52035 scrollUp : function(){
52036 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
52039 scrollDown : function(){
52040 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
52043 afterScroll : function(){
52044 var el = this.resizeEl;
52045 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
52046 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
52047 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
52050 setSize : function(){
52051 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
52052 this.afterScroll();
52055 onWheel : function(e){
52056 var d = e.getWheelDelta();
52057 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
52058 this.afterScroll();
52062 setContent : function(content, loadScripts){
52063 this.resizeEl.update(content, loadScripts);
52077 * @class Roo.TreePanel
52078 * @extends Roo.ContentPanel
52080 * Create a new TreePanel. - defaults to fit/scoll contents.
52081 * @param {String/Object} config A string to set only the panel's title, or a config object
52082 * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
52084 Roo.TreePanel = function(config){
52085 var el = config.el;
52086 var tree = config.tree;
52087 delete config.tree;
52088 delete config.el; // hopefull!
52090 // wrapper for IE7 strict & safari scroll issue
52092 var treeEl = el.createChild();
52093 config.resizeEl = treeEl;
52097 Roo.TreePanel.superclass.constructor.call(this, el, config);
52100 this.tree = new Roo.tree.TreePanel(treeEl , tree);
52101 //console.log(tree);
52102 this.on('activate', function()
52104 if (this.tree.rendered) {
52107 //console.log('render tree');
52108 this.tree.render();
52110 // this should not be needed.. - it's actually the 'el' that resizes?
52111 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
52113 //this.on('resize', function (cp, w, h) {
52114 // this.tree.innerCt.setWidth(w);
52115 // this.tree.innerCt.setHeight(h);
52116 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
52123 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
52140 * Ext JS Library 1.1.1
52141 * Copyright(c) 2006-2007, Ext JS, LLC.
52143 * Originally Released Under LGPL - original licence link has changed is not relivant.
52146 * <script type="text/javascript">
52151 * @class Roo.ReaderLayout
52152 * @extends Roo.BorderLayout
52153 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
52154 * center region containing two nested regions (a top one for a list view and one for item preview below),
52155 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
52156 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
52157 * expedites the setup of the overall layout and regions for this common application style.
52160 var reader = new Roo.ReaderLayout();
52161 var CP = Roo.ContentPanel; // shortcut for adding
52163 reader.beginUpdate();
52164 reader.add("north", new CP("north", "North"));
52165 reader.add("west", new CP("west", {title: "West"}));
52166 reader.add("east", new CP("east", {title: "East"}));
52168 reader.regions.listView.add(new CP("listView", "List"));
52169 reader.regions.preview.add(new CP("preview", "Preview"));
52170 reader.endUpdate();
52173 * Create a new ReaderLayout
52174 * @param {Object} config Configuration options
52175 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
52176 * document.body if omitted)
52178 Roo.ReaderLayout = function(config, renderTo){
52179 var c = config || {size:{}};
52180 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
52181 north: c.north !== false ? Roo.apply({
52185 }, c.north) : false,
52186 west: c.west !== false ? Roo.apply({
52194 margins:{left:5,right:0,bottom:5,top:5},
52195 cmargins:{left:5,right:5,bottom:5,top:5}
52196 }, c.west) : false,
52197 east: c.east !== false ? Roo.apply({
52205 margins:{left:0,right:5,bottom:5,top:5},
52206 cmargins:{left:5,right:5,bottom:5,top:5}
52207 }, c.east) : false,
52208 center: Roo.apply({
52209 tabPosition: 'top',
52213 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
52217 this.el.addClass('x-reader');
52219 this.beginUpdate();
52221 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
52222 south: c.preview !== false ? Roo.apply({
52229 cmargins:{top:5,left:0, right:0, bottom:0}
52230 }, c.preview) : false,
52231 center: Roo.apply({
52237 this.add('center', new Roo.NestedLayoutPanel(inner,
52238 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
52242 this.regions.preview = inner.getRegion('south');
52243 this.regions.listView = inner.getRegion('center');
52246 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
52248 * Ext JS Library 1.1.1
52249 * Copyright(c) 2006-2007, Ext JS, LLC.
52251 * Originally Released Under LGPL - original licence link has changed is not relivant.
52254 * <script type="text/javascript">
52258 * @class Roo.grid.Grid
52259 * @extends Roo.util.Observable
52260 * This class represents the primary interface of a component based grid control.
52261 * <br><br>Usage:<pre><code>
52262 var grid = new Roo.grid.Grid("my-container-id", {
52265 selModel: mySelectionModel,
52266 autoSizeColumns: true,
52267 monitorWindowResize: false,
52268 trackMouseOver: true
52273 * <b>Common Problems:</b><br/>
52274 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
52275 * element will correct this<br/>
52276 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
52277 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
52278 * are unpredictable.<br/>
52279 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
52280 * grid to calculate dimensions/offsets.<br/>
52282 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
52283 * The container MUST have some type of size defined for the grid to fill. The container will be
52284 * automatically set to position relative if it isn't already.
52285 * @param {Object} config A config object that sets properties on this grid.
52287 Roo.grid.Grid = function(container, config){
52288 // initialize the container
52289 this.container = Roo.get(container);
52290 this.container.update("");
52291 this.container.setStyle("overflow", "hidden");
52292 this.container.addClass('x-grid-container');
52294 this.id = this.container.id;
52296 Roo.apply(this, config);
52297 // check and correct shorthanded configs
52299 this.dataSource = this.ds;
52303 this.colModel = this.cm;
52307 this.selModel = this.sm;
52311 if (this.selModel) {
52312 this.selModel = Roo.factory(this.selModel, Roo.grid);
52313 this.sm = this.selModel;
52314 this.sm.xmodule = this.xmodule || false;
52316 if (typeof(this.colModel.config) == 'undefined') {
52317 this.colModel = new Roo.grid.ColumnModel(this.colModel);
52318 this.cm = this.colModel;
52319 this.cm.xmodule = this.xmodule || false;
52321 if (this.dataSource) {
52322 this.dataSource= Roo.factory(this.dataSource, Roo.data);
52323 this.ds = this.dataSource;
52324 this.ds.xmodule = this.xmodule || false;
52331 this.container.setWidth(this.width);
52335 this.container.setHeight(this.height);
52342 * The raw click event for the entire grid.
52343 * @param {Roo.EventObject} e
52348 * The raw dblclick event for the entire grid.
52349 * @param {Roo.EventObject} e
52353 * @event contextmenu
52354 * The raw contextmenu event for the entire grid.
52355 * @param {Roo.EventObject} e
52357 "contextmenu" : true,
52360 * The raw mousedown event for the entire grid.
52361 * @param {Roo.EventObject} e
52363 "mousedown" : true,
52366 * The raw mouseup event for the entire grid.
52367 * @param {Roo.EventObject} e
52372 * The raw mouseover event for the entire grid.
52373 * @param {Roo.EventObject} e
52375 "mouseover" : true,
52378 * The raw mouseout event for the entire grid.
52379 * @param {Roo.EventObject} e
52384 * The raw keypress event for the entire grid.
52385 * @param {Roo.EventObject} e
52390 * The raw keydown event for the entire grid.
52391 * @param {Roo.EventObject} e
52399 * Fires when a cell is clicked
52400 * @param {Grid} this
52401 * @param {Number} rowIndex
52402 * @param {Number} columnIndex
52403 * @param {Roo.EventObject} e
52405 "cellclick" : true,
52407 * @event celldblclick
52408 * Fires when a cell is double clicked
52409 * @param {Grid} this
52410 * @param {Number} rowIndex
52411 * @param {Number} columnIndex
52412 * @param {Roo.EventObject} e
52414 "celldblclick" : true,
52417 * Fires when a row is clicked
52418 * @param {Grid} this
52419 * @param {Number} rowIndex
52420 * @param {Roo.EventObject} e
52424 * @event rowdblclick
52425 * Fires when a row is double clicked
52426 * @param {Grid} this
52427 * @param {Number} rowIndex
52428 * @param {Roo.EventObject} e
52430 "rowdblclick" : true,
52432 * @event headerclick
52433 * Fires when a header is clicked
52434 * @param {Grid} this
52435 * @param {Number} columnIndex
52436 * @param {Roo.EventObject} e
52438 "headerclick" : true,
52440 * @event headerdblclick
52441 * Fires when a header cell is double clicked
52442 * @param {Grid} this
52443 * @param {Number} columnIndex
52444 * @param {Roo.EventObject} e
52446 "headerdblclick" : true,
52448 * @event rowcontextmenu
52449 * Fires when a row is right clicked
52450 * @param {Grid} this
52451 * @param {Number} rowIndex
52452 * @param {Roo.EventObject} e
52454 "rowcontextmenu" : true,
52456 * @event cellcontextmenu
52457 * Fires when a cell is right clicked
52458 * @param {Grid} this
52459 * @param {Number} rowIndex
52460 * @param {Number} cellIndex
52461 * @param {Roo.EventObject} e
52463 "cellcontextmenu" : true,
52465 * @event headercontextmenu
52466 * Fires when a header is right clicked
52467 * @param {Grid} this
52468 * @param {Number} columnIndex
52469 * @param {Roo.EventObject} e
52471 "headercontextmenu" : true,
52473 * @event bodyscroll
52474 * Fires when the body element is scrolled
52475 * @param {Number} scrollLeft
52476 * @param {Number} scrollTop
52478 "bodyscroll" : true,
52480 * @event columnresize
52481 * Fires when the user resizes a column
52482 * @param {Number} columnIndex
52483 * @param {Number} newSize
52485 "columnresize" : true,
52487 * @event columnmove
52488 * Fires when the user moves a column
52489 * @param {Number} oldIndex
52490 * @param {Number} newIndex
52492 "columnmove" : true,
52495 * Fires when row(s) start being dragged
52496 * @param {Grid} this
52497 * @param {Roo.GridDD} dd The drag drop object
52498 * @param {event} e The raw browser event
52500 "startdrag" : true,
52503 * Fires when a drag operation is complete
52504 * @param {Grid} this
52505 * @param {Roo.GridDD} dd The drag drop object
52506 * @param {event} e The raw browser event
52511 * Fires when dragged row(s) are dropped on a valid DD target
52512 * @param {Grid} this
52513 * @param {Roo.GridDD} dd The drag drop object
52514 * @param {String} targetId The target drag drop object
52515 * @param {event} e The raw browser event
52520 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
52521 * @param {Grid} this
52522 * @param {Roo.GridDD} dd The drag drop object
52523 * @param {String} targetId The target drag drop object
52524 * @param {event} e The raw browser event
52529 * Fires when the dragged row(s) first cross another DD target while being dragged
52530 * @param {Grid} this
52531 * @param {Roo.GridDD} dd The drag drop object
52532 * @param {String} targetId The target drag drop object
52533 * @param {event} e The raw browser event
52535 "dragenter" : true,
52538 * Fires when the dragged row(s) leave another DD target while being dragged
52539 * @param {Grid} this
52540 * @param {Roo.GridDD} dd The drag drop object
52541 * @param {String} targetId The target drag drop object
52542 * @param {event} e The raw browser event
52547 * Fires when a row is rendered, so you can change add a style to it.
52548 * @param {GridView} gridview The grid view
52549 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
52555 * Fires when the grid is rendered
52556 * @param {Grid} grid
52561 Roo.grid.Grid.superclass.constructor.call(this);
52563 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
52566 * @cfg {String} ddGroup - drag drop group.
52570 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
52572 minColumnWidth : 25,
52575 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
52576 * <b>on initial render.</b> It is more efficient to explicitly size the columns
52577 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
52579 autoSizeColumns : false,
52582 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
52584 autoSizeHeaders : true,
52587 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
52589 monitorWindowResize : true,
52592 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
52593 * rows measured to get a columns size. Default is 0 (all rows).
52595 maxRowsToMeasure : 0,
52598 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
52600 trackMouseOver : true,
52603 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
52607 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
52609 enableDragDrop : false,
52612 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
52614 enableColumnMove : true,
52617 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
52619 enableColumnHide : true,
52622 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
52624 enableRowHeightSync : false,
52627 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
52632 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
52634 autoHeight : false,
52637 * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
52639 autoExpandColumn : false,
52642 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
52645 autoExpandMin : 50,
52648 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
52650 autoExpandMax : 1000,
52653 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
52658 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
52662 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
52672 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
52673 * of a fixed width. Default is false.
52676 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
52679 * Called once after all setup has been completed and the grid is ready to be rendered.
52680 * @return {Roo.grid.Grid} this
52682 render : function()
52684 var c = this.container;
52685 // try to detect autoHeight/width mode
52686 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
52687 this.autoHeight = true;
52689 var view = this.getView();
52692 c.on("click", this.onClick, this);
52693 c.on("dblclick", this.onDblClick, this);
52694 c.on("contextmenu", this.onContextMenu, this);
52695 c.on("keydown", this.onKeyDown, this);
52697 c.on("touchstart", this.onTouchStart, this);
52700 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
52702 this.getSelectionModel().init(this);
52707 this.loadMask = new Roo.LoadMask(this.container,
52708 Roo.apply({store:this.dataSource}, this.loadMask));
52712 if (this.toolbar && this.toolbar.xtype) {
52713 this.toolbar.container = this.getView().getHeaderPanel(true);
52714 this.toolbar = new Roo.Toolbar(this.toolbar);
52716 if (this.footer && this.footer.xtype) {
52717 this.footer.dataSource = this.getDataSource();
52718 this.footer.container = this.getView().getFooterPanel(true);
52719 this.footer = Roo.factory(this.footer, Roo);
52721 if (this.dropTarget && this.dropTarget.xtype) {
52722 delete this.dropTarget.xtype;
52723 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
52727 this.rendered = true;
52728 this.fireEvent('render', this);
52733 * Reconfigures the grid to use a different Store and Column Model.
52734 * The View will be bound to the new objects and refreshed.
52735 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
52736 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
52738 reconfigure : function(dataSource, colModel){
52740 this.loadMask.destroy();
52741 this.loadMask = new Roo.LoadMask(this.container,
52742 Roo.apply({store:dataSource}, this.loadMask));
52744 this.view.bind(dataSource, colModel);
52745 this.dataSource = dataSource;
52746 this.colModel = colModel;
52747 this.view.refresh(true);
52751 onKeyDown : function(e){
52752 this.fireEvent("keydown", e);
52756 * Destroy this grid.
52757 * @param {Boolean} removeEl True to remove the element
52759 destroy : function(removeEl, keepListeners){
52761 this.loadMask.destroy();
52763 var c = this.container;
52764 c.removeAllListeners();
52765 this.view.destroy();
52766 this.colModel.purgeListeners();
52767 if(!keepListeners){
52768 this.purgeListeners();
52771 if(removeEl === true){
52777 processEvent : function(name, e){
52778 // does this fire select???
52779 //Roo.log('grid:processEvent ' + name);
52781 if (name != 'touchstart' ) {
52782 this.fireEvent(name, e);
52785 var t = e.getTarget();
52787 var header = v.findHeaderIndex(t);
52788 if(header !== false){
52789 var ename = name == 'touchstart' ? 'click' : name;
52791 this.fireEvent("header" + ename, this, header, e);
52793 var row = v.findRowIndex(t);
52794 var cell = v.findCellIndex(t);
52795 if (name == 'touchstart') {
52796 // first touch is always a click.
52797 // hopefull this happens after selection is updated.?
52800 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
52801 var cs = this.selModel.getSelectedCell();
52802 if (row == cs[0] && cell == cs[1]){
52806 if (typeof(this.selModel.getSelections) != 'undefined') {
52807 var cs = this.selModel.getSelections();
52808 var ds = this.dataSource;
52809 if (cs.length == 1 && ds.getAt(row) == cs[0]){
52820 this.fireEvent("row" + name, this, row, e);
52821 if(cell !== false){
52822 this.fireEvent("cell" + name, this, row, cell, e);
52829 onClick : function(e){
52830 this.processEvent("click", e);
52833 onTouchStart : function(e){
52834 this.processEvent("touchstart", e);
52838 onContextMenu : function(e, t){
52839 this.processEvent("contextmenu", e);
52843 onDblClick : function(e){
52844 this.processEvent("dblclick", e);
52848 walkCells : function(row, col, step, fn, scope){
52849 var cm = this.colModel, clen = cm.getColumnCount();
52850 var ds = this.dataSource, rlen = ds.getCount(), first = true;
52862 if(fn.call(scope || this, row, col, cm) === true){
52880 if(fn.call(scope || this, row, col, cm) === true){
52892 getSelections : function(){
52893 return this.selModel.getSelections();
52897 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
52898 * but if manual update is required this method will initiate it.
52900 autoSize : function(){
52902 this.view.layout();
52903 if(this.view.adjustForScroll){
52904 this.view.adjustForScroll();
52910 * Returns the grid's underlying element.
52911 * @return {Element} The element
52913 getGridEl : function(){
52914 return this.container;
52917 // private for compatibility, overridden by editor grid
52918 stopEditing : function(){},
52921 * Returns the grid's SelectionModel.
52922 * @return {SelectionModel}
52924 getSelectionModel : function(){
52925 if(!this.selModel){
52926 this.selModel = new Roo.grid.RowSelectionModel();
52928 return this.selModel;
52932 * Returns the grid's DataSource.
52933 * @return {DataSource}
52935 getDataSource : function(){
52936 return this.dataSource;
52940 * Returns the grid's ColumnModel.
52941 * @return {ColumnModel}
52943 getColumnModel : function(){
52944 return this.colModel;
52948 * Returns the grid's GridView object.
52949 * @return {GridView}
52951 getView : function(){
52953 this.view = new Roo.grid.GridView(this.viewConfig);
52958 * Called to get grid's drag proxy text, by default returns this.ddText.
52961 getDragDropText : function(){
52962 var count = this.selModel.getCount();
52963 return String.format(this.ddText, count, count == 1 ? '' : 's');
52967 * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
52968 * %0 is replaced with the number of selected rows.
52971 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
52973 * Ext JS Library 1.1.1
52974 * Copyright(c) 2006-2007, Ext JS, LLC.
52976 * Originally Released Under LGPL - original licence link has changed is not relivant.
52979 * <script type="text/javascript">
52982 Roo.grid.AbstractGridView = function(){
52986 "beforerowremoved" : true,
52987 "beforerowsinserted" : true,
52988 "beforerefresh" : true,
52989 "rowremoved" : true,
52990 "rowsinserted" : true,
52991 "rowupdated" : true,
52994 Roo.grid.AbstractGridView.superclass.constructor.call(this);
52997 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
52998 rowClass : "x-grid-row",
52999 cellClass : "x-grid-cell",
53000 tdClass : "x-grid-td",
53001 hdClass : "x-grid-hd",
53002 splitClass : "x-grid-hd-split",
53004 init: function(grid){
53006 var cid = this.grid.getGridEl().id;
53007 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
53008 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
53009 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
53010 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
53013 getColumnRenderers : function(){
53014 var renderers = [];
53015 var cm = this.grid.colModel;
53016 var colCount = cm.getColumnCount();
53017 for(var i = 0; i < colCount; i++){
53018 renderers[i] = cm.getRenderer(i);
53023 getColumnIds : function(){
53025 var cm = this.grid.colModel;
53026 var colCount = cm.getColumnCount();
53027 for(var i = 0; i < colCount; i++){
53028 ids[i] = cm.getColumnId(i);
53033 getDataIndexes : function(){
53034 if(!this.indexMap){
53035 this.indexMap = this.buildIndexMap();
53037 return this.indexMap.colToData;
53040 getColumnIndexByDataIndex : function(dataIndex){
53041 if(!this.indexMap){
53042 this.indexMap = this.buildIndexMap();
53044 return this.indexMap.dataToCol[dataIndex];
53048 * Set a css style for a column dynamically.
53049 * @param {Number} colIndex The index of the column
53050 * @param {String} name The css property name
53051 * @param {String} value The css value
53053 setCSSStyle : function(colIndex, name, value){
53054 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
53055 Roo.util.CSS.updateRule(selector, name, value);
53058 generateRules : function(cm){
53059 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
53060 Roo.util.CSS.removeStyleSheet(rulesId);
53061 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53062 var cid = cm.getColumnId(i);
53063 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
53064 this.tdSelector, cid, " {\n}\n",
53065 this.hdSelector, cid, " {\n}\n",
53066 this.splitSelector, cid, " {\n}\n");
53068 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
53072 * Ext JS Library 1.1.1
53073 * Copyright(c) 2006-2007, Ext JS, LLC.
53075 * Originally Released Under LGPL - original licence link has changed is not relivant.
53078 * <script type="text/javascript">
53082 // This is a support class used internally by the Grid components
53083 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
53085 this.view = grid.getView();
53086 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
53087 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
53089 this.setHandleElId(Roo.id(hd));
53090 this.setOuterHandleElId(Roo.id(hd2));
53092 this.scroll = false;
53094 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
53096 getDragData : function(e){
53097 var t = Roo.lib.Event.getTarget(e);
53098 var h = this.view.findHeaderCell(t);
53100 return {ddel: h.firstChild, header:h};
53105 onInitDrag : function(e){
53106 this.view.headersDisabled = true;
53107 var clone = this.dragData.ddel.cloneNode(true);
53108 clone.id = Roo.id();
53109 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
53110 this.proxy.update(clone);
53114 afterValidDrop : function(){
53116 setTimeout(function(){
53117 v.headersDisabled = false;
53121 afterInvalidDrop : function(){
53123 setTimeout(function(){
53124 v.headersDisabled = false;
53130 * Ext JS Library 1.1.1
53131 * Copyright(c) 2006-2007, Ext JS, LLC.
53133 * Originally Released Under LGPL - original licence link has changed is not relivant.
53136 * <script type="text/javascript">
53139 // This is a support class used internally by the Grid components
53140 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
53142 this.view = grid.getView();
53143 // split the proxies so they don't interfere with mouse events
53144 this.proxyTop = Roo.DomHelper.append(document.body, {
53145 cls:"col-move-top", html:" "
53147 this.proxyBottom = Roo.DomHelper.append(document.body, {
53148 cls:"col-move-bottom", html:" "
53150 this.proxyTop.hide = this.proxyBottom.hide = function(){
53151 this.setLeftTop(-100,-100);
53152 this.setStyle("visibility", "hidden");
53154 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
53155 // temporarily disabled
53156 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
53157 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
53159 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
53160 proxyOffsets : [-4, -9],
53161 fly: Roo.Element.fly,
53163 getTargetFromEvent : function(e){
53164 var t = Roo.lib.Event.getTarget(e);
53165 var cindex = this.view.findCellIndex(t);
53166 if(cindex !== false){
53167 return this.view.getHeaderCell(cindex);
53172 nextVisible : function(h){
53173 var v = this.view, cm = this.grid.colModel;
53176 if(!cm.isHidden(v.getCellIndex(h))){
53184 prevVisible : function(h){
53185 var v = this.view, cm = this.grid.colModel;
53188 if(!cm.isHidden(v.getCellIndex(h))){
53196 positionIndicator : function(h, n, e){
53197 var x = Roo.lib.Event.getPageX(e);
53198 var r = Roo.lib.Dom.getRegion(n.firstChild);
53199 var px, pt, py = r.top + this.proxyOffsets[1];
53200 if((r.right - x) <= (r.right-r.left)/2){
53201 px = r.right+this.view.borderWidth;
53207 var oldIndex = this.view.getCellIndex(h);
53208 var newIndex = this.view.getCellIndex(n);
53210 if(this.grid.colModel.isFixed(newIndex)){
53214 var locked = this.grid.colModel.isLocked(newIndex);
53219 if(oldIndex < newIndex){
53222 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
53225 px += this.proxyOffsets[0];
53226 this.proxyTop.setLeftTop(px, py);
53227 this.proxyTop.show();
53228 if(!this.bottomOffset){
53229 this.bottomOffset = this.view.mainHd.getHeight();
53231 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
53232 this.proxyBottom.show();
53236 onNodeEnter : function(n, dd, e, data){
53237 if(data.header != n){
53238 this.positionIndicator(data.header, n, e);
53242 onNodeOver : function(n, dd, e, data){
53243 var result = false;
53244 if(data.header != n){
53245 result = this.positionIndicator(data.header, n, e);
53248 this.proxyTop.hide();
53249 this.proxyBottom.hide();
53251 return result ? this.dropAllowed : this.dropNotAllowed;
53254 onNodeOut : function(n, dd, e, data){
53255 this.proxyTop.hide();
53256 this.proxyBottom.hide();
53259 onNodeDrop : function(n, dd, e, data){
53260 var h = data.header;
53262 var cm = this.grid.colModel;
53263 var x = Roo.lib.Event.getPageX(e);
53264 var r = Roo.lib.Dom.getRegion(n.firstChild);
53265 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
53266 var oldIndex = this.view.getCellIndex(h);
53267 var newIndex = this.view.getCellIndex(n);
53268 var locked = cm.isLocked(newIndex);
53272 if(oldIndex < newIndex){
53275 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
53278 cm.setLocked(oldIndex, locked, true);
53279 cm.moveColumn(oldIndex, newIndex);
53280 this.grid.fireEvent("columnmove", oldIndex, newIndex);
53288 * Ext JS Library 1.1.1
53289 * Copyright(c) 2006-2007, Ext JS, LLC.
53291 * Originally Released Under LGPL - original licence link has changed is not relivant.
53294 * <script type="text/javascript">
53298 * @class Roo.grid.GridView
53299 * @extends Roo.util.Observable
53302 * @param {Object} config
53304 Roo.grid.GridView = function(config){
53305 Roo.grid.GridView.superclass.constructor.call(this);
53308 Roo.apply(this, config);
53311 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
53313 unselectable : 'unselectable="on"',
53314 unselectableCls : 'x-unselectable',
53317 rowClass : "x-grid-row",
53319 cellClass : "x-grid-col",
53321 tdClass : "x-grid-td",
53323 hdClass : "x-grid-hd",
53325 splitClass : "x-grid-split",
53327 sortClasses : ["sort-asc", "sort-desc"],
53329 enableMoveAnim : false,
53333 dh : Roo.DomHelper,
53335 fly : Roo.Element.fly,
53337 css : Roo.util.CSS,
53343 scrollIncrement : 22,
53345 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
53347 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
53349 bind : function(ds, cm){
53351 this.ds.un("load", this.onLoad, this);
53352 this.ds.un("datachanged", this.onDataChange, this);
53353 this.ds.un("add", this.onAdd, this);
53354 this.ds.un("remove", this.onRemove, this);
53355 this.ds.un("update", this.onUpdate, this);
53356 this.ds.un("clear", this.onClear, this);
53359 ds.on("load", this.onLoad, this);
53360 ds.on("datachanged", this.onDataChange, this);
53361 ds.on("add", this.onAdd, this);
53362 ds.on("remove", this.onRemove, this);
53363 ds.on("update", this.onUpdate, this);
53364 ds.on("clear", this.onClear, this);
53369 this.cm.un("widthchange", this.onColWidthChange, this);
53370 this.cm.un("headerchange", this.onHeaderChange, this);
53371 this.cm.un("hiddenchange", this.onHiddenChange, this);
53372 this.cm.un("columnmoved", this.onColumnMove, this);
53373 this.cm.un("columnlockchange", this.onColumnLock, this);
53376 this.generateRules(cm);
53377 cm.on("widthchange", this.onColWidthChange, this);
53378 cm.on("headerchange", this.onHeaderChange, this);
53379 cm.on("hiddenchange", this.onHiddenChange, this);
53380 cm.on("columnmoved", this.onColumnMove, this);
53381 cm.on("columnlockchange", this.onColumnLock, this);
53386 init: function(grid){
53387 Roo.grid.GridView.superclass.init.call(this, grid);
53389 this.bind(grid.dataSource, grid.colModel);
53391 grid.on("headerclick", this.handleHeaderClick, this);
53393 if(grid.trackMouseOver){
53394 grid.on("mouseover", this.onRowOver, this);
53395 grid.on("mouseout", this.onRowOut, this);
53397 grid.cancelTextSelection = function(){};
53398 this.gridId = grid.id;
53400 var tpls = this.templates || {};
53403 tpls.master = new Roo.Template(
53404 '<div class="x-grid" hidefocus="true">',
53405 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
53406 '<div class="x-grid-topbar"></div>',
53407 '<div class="x-grid-scroller"><div></div></div>',
53408 '<div class="x-grid-locked">',
53409 '<div class="x-grid-header">{lockedHeader}</div>',
53410 '<div class="x-grid-body">{lockedBody}</div>',
53412 '<div class="x-grid-viewport">',
53413 '<div class="x-grid-header">{header}</div>',
53414 '<div class="x-grid-body">{body}</div>',
53416 '<div class="x-grid-bottombar"></div>',
53418 '<div class="x-grid-resize-proxy"> </div>',
53421 tpls.master.disableformats = true;
53425 tpls.header = new Roo.Template(
53426 '<table border="0" cellspacing="0" cellpadding="0">',
53427 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
53430 tpls.header.disableformats = true;
53432 tpls.header.compile();
53435 tpls.hcell = new Roo.Template(
53436 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
53437 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
53440 tpls.hcell.disableFormats = true;
53442 tpls.hcell.compile();
53445 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
53446 this.unselectableCls + '" ' + this.unselectable +'> </div>');
53447 tpls.hsplit.disableFormats = true;
53449 tpls.hsplit.compile();
53452 tpls.body = new Roo.Template(
53453 '<table border="0" cellspacing="0" cellpadding="0">',
53454 "<tbody>{rows}</tbody>",
53457 tpls.body.disableFormats = true;
53459 tpls.body.compile();
53462 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
53463 tpls.row.disableFormats = true;
53465 tpls.row.compile();
53468 tpls.cell = new Roo.Template(
53469 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
53470 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
53471 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
53474 tpls.cell.disableFormats = true;
53476 tpls.cell.compile();
53478 this.templates = tpls;
53481 // remap these for backwards compat
53482 onColWidthChange : function(){
53483 this.updateColumns.apply(this, arguments);
53485 onHeaderChange : function(){
53486 this.updateHeaders.apply(this, arguments);
53488 onHiddenChange : function(){
53489 this.handleHiddenChange.apply(this, arguments);
53491 onColumnMove : function(){
53492 this.handleColumnMove.apply(this, arguments);
53494 onColumnLock : function(){
53495 this.handleLockChange.apply(this, arguments);
53498 onDataChange : function(){
53500 this.updateHeaderSortState();
53503 onClear : function(){
53507 onUpdate : function(ds, record){
53508 this.refreshRow(record);
53511 refreshRow : function(record){
53512 var ds = this.ds, index;
53513 if(typeof record == 'number'){
53515 record = ds.getAt(index);
53517 index = ds.indexOf(record);
53519 this.insertRows(ds, index, index, true);
53520 this.onRemove(ds, record, index+1, true);
53521 this.syncRowHeights(index, index);
53523 this.fireEvent("rowupdated", this, index, record);
53526 onAdd : function(ds, records, index){
53527 this.insertRows(ds, index, index + (records.length-1));
53530 onRemove : function(ds, record, index, isUpdate){
53531 if(isUpdate !== true){
53532 this.fireEvent("beforerowremoved", this, index, record);
53534 var bt = this.getBodyTable(), lt = this.getLockedTable();
53535 if(bt.rows[index]){
53536 bt.firstChild.removeChild(bt.rows[index]);
53538 if(lt.rows[index]){
53539 lt.firstChild.removeChild(lt.rows[index]);
53541 if(isUpdate !== true){
53542 this.stripeRows(index);
53543 this.syncRowHeights(index, index);
53545 this.fireEvent("rowremoved", this, index, record);
53549 onLoad : function(){
53550 this.scrollToTop();
53554 * Scrolls the grid to the top
53556 scrollToTop : function(){
53558 this.scroller.dom.scrollTop = 0;
53564 * Gets a panel in the header of the grid that can be used for toolbars etc.
53565 * After modifying the contents of this panel a call to grid.autoSize() may be
53566 * required to register any changes in size.
53567 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
53568 * @return Roo.Element
53570 getHeaderPanel : function(doShow){
53572 this.headerPanel.show();
53574 return this.headerPanel;
53578 * Gets a panel in the footer of the grid that can be used for toolbars etc.
53579 * After modifying the contents of this panel a call to grid.autoSize() may be
53580 * required to register any changes in size.
53581 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
53582 * @return Roo.Element
53584 getFooterPanel : function(doShow){
53586 this.footerPanel.show();
53588 return this.footerPanel;
53591 initElements : function(){
53592 var E = Roo.Element;
53593 var el = this.grid.getGridEl().dom.firstChild;
53594 var cs = el.childNodes;
53596 this.el = new E(el);
53598 this.focusEl = new E(el.firstChild);
53599 this.focusEl.swallowEvent("click", true);
53601 this.headerPanel = new E(cs[1]);
53602 this.headerPanel.enableDisplayMode("block");
53604 this.scroller = new E(cs[2]);
53605 this.scrollSizer = new E(this.scroller.dom.firstChild);
53607 this.lockedWrap = new E(cs[3]);
53608 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
53609 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
53611 this.mainWrap = new E(cs[4]);
53612 this.mainHd = new E(this.mainWrap.dom.firstChild);
53613 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
53615 this.footerPanel = new E(cs[5]);
53616 this.footerPanel.enableDisplayMode("block");
53618 this.resizeProxy = new E(cs[6]);
53620 this.headerSelector = String.format(
53621 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
53622 this.lockedHd.id, this.mainHd.id
53625 this.splitterSelector = String.format(
53626 '#{0} div.x-grid-split, #{1} div.x-grid-split',
53627 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
53630 idToCssName : function(s)
53632 return s.replace(/[^a-z0-9]+/ig, '-');
53635 getHeaderCell : function(index){
53636 return Roo.DomQuery.select(this.headerSelector)[index];
53639 getHeaderCellMeasure : function(index){
53640 return this.getHeaderCell(index).firstChild;
53643 getHeaderCellText : function(index){
53644 return this.getHeaderCell(index).firstChild.firstChild;
53647 getLockedTable : function(){
53648 return this.lockedBody.dom.firstChild;
53651 getBodyTable : function(){
53652 return this.mainBody.dom.firstChild;
53655 getLockedRow : function(index){
53656 return this.getLockedTable().rows[index];
53659 getRow : function(index){
53660 return this.getBodyTable().rows[index];
53663 getRowComposite : function(index){
53665 this.rowEl = new Roo.CompositeElementLite();
53667 var els = [], lrow, mrow;
53668 if(lrow = this.getLockedRow(index)){
53671 if(mrow = this.getRow(index)){
53674 this.rowEl.elements = els;
53678 * Gets the 'td' of the cell
53680 * @param {Integer} rowIndex row to select
53681 * @param {Integer} colIndex column to select
53685 getCell : function(rowIndex, colIndex){
53686 var locked = this.cm.getLockedCount();
53688 if(colIndex < locked){
53689 source = this.lockedBody.dom.firstChild;
53691 source = this.mainBody.dom.firstChild;
53692 colIndex -= locked;
53694 return source.rows[rowIndex].childNodes[colIndex];
53697 getCellText : function(rowIndex, colIndex){
53698 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
53701 getCellBox : function(cell){
53702 var b = this.fly(cell).getBox();
53703 if(Roo.isOpera){ // opera fails to report the Y
53704 b.y = cell.offsetTop + this.mainBody.getY();
53709 getCellIndex : function(cell){
53710 var id = String(cell.className).match(this.cellRE);
53712 return parseInt(id[1], 10);
53717 findHeaderIndex : function(n){
53718 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
53719 return r ? this.getCellIndex(r) : false;
53722 findHeaderCell : function(n){
53723 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
53724 return r ? r : false;
53727 findRowIndex : function(n){
53731 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
53732 return r ? r.rowIndex : false;
53735 findCellIndex : function(node){
53736 var stop = this.el.dom;
53737 while(node && node != stop){
53738 if(this.findRE.test(node.className)){
53739 return this.getCellIndex(node);
53741 node = node.parentNode;
53746 getColumnId : function(index){
53747 return this.cm.getColumnId(index);
53750 getSplitters : function()
53752 if(this.splitterSelector){
53753 return Roo.DomQuery.select(this.splitterSelector);
53759 getSplitter : function(index){
53760 return this.getSplitters()[index];
53763 onRowOver : function(e, t){
53765 if((row = this.findRowIndex(t)) !== false){
53766 this.getRowComposite(row).addClass("x-grid-row-over");
53770 onRowOut : function(e, t){
53772 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
53773 this.getRowComposite(row).removeClass("x-grid-row-over");
53777 renderHeaders : function(){
53779 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
53780 var cb = [], lb = [], sb = [], lsb = [], p = {};
53781 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53782 p.cellId = "x-grid-hd-0-" + i;
53783 p.splitId = "x-grid-csplit-0-" + i;
53784 p.id = cm.getColumnId(i);
53785 p.title = cm.getColumnTooltip(i) || "";
53786 p.value = cm.getColumnHeader(i) || "";
53787 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
53788 if(!cm.isLocked(i)){
53789 cb[cb.length] = ct.apply(p);
53790 sb[sb.length] = st.apply(p);
53792 lb[lb.length] = ct.apply(p);
53793 lsb[lsb.length] = st.apply(p);
53796 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
53797 ht.apply({cells: cb.join(""), splits:sb.join("")})];
53800 updateHeaders : function(){
53801 var html = this.renderHeaders();
53802 this.lockedHd.update(html[0]);
53803 this.mainHd.update(html[1]);
53807 * Focuses the specified row.
53808 * @param {Number} row The row index
53810 focusRow : function(row)
53812 //Roo.log('GridView.focusRow');
53813 var x = this.scroller.dom.scrollLeft;
53814 this.focusCell(row, 0, false);
53815 this.scroller.dom.scrollLeft = x;
53819 * Focuses the specified cell.
53820 * @param {Number} row The row index
53821 * @param {Number} col The column index
53822 * @param {Boolean} hscroll false to disable horizontal scrolling
53824 focusCell : function(row, col, hscroll)
53826 //Roo.log('GridView.focusCell');
53827 var el = this.ensureVisible(row, col, hscroll);
53828 this.focusEl.alignTo(el, "tl-tl");
53830 this.focusEl.focus();
53832 this.focusEl.focus.defer(1, this.focusEl);
53837 * Scrolls the specified cell into view
53838 * @param {Number} row The row index
53839 * @param {Number} col The column index
53840 * @param {Boolean} hscroll false to disable horizontal scrolling
53842 ensureVisible : function(row, col, hscroll)
53844 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
53845 //return null; //disable for testing.
53846 if(typeof row != "number"){
53847 row = row.rowIndex;
53849 if(row < 0 && row >= this.ds.getCount()){
53852 col = (col !== undefined ? col : 0);
53853 var cm = this.grid.colModel;
53854 while(cm.isHidden(col)){
53858 var el = this.getCell(row, col);
53862 var c = this.scroller.dom;
53864 var ctop = parseInt(el.offsetTop, 10);
53865 var cleft = parseInt(el.offsetLeft, 10);
53866 var cbot = ctop + el.offsetHeight;
53867 var cright = cleft + el.offsetWidth;
53869 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
53870 var stop = parseInt(c.scrollTop, 10);
53871 var sleft = parseInt(c.scrollLeft, 10);
53872 var sbot = stop + ch;
53873 var sright = sleft + c.clientWidth;
53875 Roo.log('GridView.ensureVisible:' +
53877 ' c.clientHeight:' + c.clientHeight +
53878 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
53886 c.scrollTop = ctop;
53887 //Roo.log("set scrolltop to ctop DISABLE?");
53888 }else if(cbot > sbot){
53889 //Roo.log("set scrolltop to cbot-ch");
53890 c.scrollTop = cbot-ch;
53893 if(hscroll !== false){
53895 c.scrollLeft = cleft;
53896 }else if(cright > sright){
53897 c.scrollLeft = cright-c.clientWidth;
53904 updateColumns : function(){
53905 this.grid.stopEditing();
53906 var cm = this.grid.colModel, colIds = this.getColumnIds();
53907 //var totalWidth = cm.getTotalWidth();
53909 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53910 //if(cm.isHidden(i)) continue;
53911 var w = cm.getColumnWidth(i);
53912 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
53913 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
53915 this.updateSplitters();
53918 generateRules : function(cm){
53919 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
53920 Roo.util.CSS.removeStyleSheet(rulesId);
53921 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53922 var cid = cm.getColumnId(i);
53924 if(cm.config[i].align){
53925 align = 'text-align:'+cm.config[i].align+';';
53928 if(cm.isHidden(i)){
53929 hidden = 'display:none;';
53931 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
53933 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
53934 this.hdSelector, cid, " {\n", align, width, "}\n",
53935 this.tdSelector, cid, " {\n",hidden,"\n}\n",
53936 this.splitSelector, cid, " {\n", hidden , "\n}\n");
53938 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
53941 updateSplitters : function(){
53942 var cm = this.cm, s = this.getSplitters();
53943 if(s){ // splitters not created yet
53944 var pos = 0, locked = true;
53945 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53946 if(cm.isHidden(i)) continue;
53947 var w = cm.getColumnWidth(i); // make sure it's a number
53948 if(!cm.isLocked(i) && locked){
53953 s[i].style.left = (pos-this.splitOffset) + "px";
53958 handleHiddenChange : function(colModel, colIndex, hidden){
53960 this.hideColumn(colIndex);
53962 this.unhideColumn(colIndex);
53966 hideColumn : function(colIndex){
53967 var cid = this.getColumnId(colIndex);
53968 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
53969 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
53971 this.updateHeaders();
53973 this.updateSplitters();
53977 unhideColumn : function(colIndex){
53978 var cid = this.getColumnId(colIndex);
53979 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
53980 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
53983 this.updateHeaders();
53985 this.updateSplitters();
53989 insertRows : function(dm, firstRow, lastRow, isUpdate){
53990 if(firstRow == 0 && lastRow == dm.getCount()-1){
53994 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
53996 var s = this.getScrollState();
53997 var markup = this.renderRows(firstRow, lastRow);
53998 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
53999 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
54000 this.restoreScroll(s);
54002 this.fireEvent("rowsinserted", this, firstRow, lastRow);
54003 this.syncRowHeights(firstRow, lastRow);
54004 this.stripeRows(firstRow);
54010 bufferRows : function(markup, target, index){
54011 var before = null, trows = target.rows, tbody = target.tBodies[0];
54012 if(index < trows.length){
54013 before = trows[index];
54015 var b = document.createElement("div");
54016 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
54017 var rows = b.firstChild.rows;
54018 for(var i = 0, len = rows.length; i < len; i++){
54020 tbody.insertBefore(rows[0], before);
54022 tbody.appendChild(rows[0]);
54029 deleteRows : function(dm, firstRow, lastRow){
54030 if(dm.getRowCount()<1){
54031 this.fireEvent("beforerefresh", this);
54032 this.mainBody.update("");
54033 this.lockedBody.update("");
54034 this.fireEvent("refresh", this);
54036 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
54037 var bt = this.getBodyTable();
54038 var tbody = bt.firstChild;
54039 var rows = bt.rows;
54040 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
54041 tbody.removeChild(rows[firstRow]);
54043 this.stripeRows(firstRow);
54044 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
54048 updateRows : function(dataSource, firstRow, lastRow){
54049 var s = this.getScrollState();
54051 this.restoreScroll(s);
54054 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
54058 this.updateHeaderSortState();
54061 getScrollState : function(){
54063 var sb = this.scroller.dom;
54064 return {left: sb.scrollLeft, top: sb.scrollTop};
54067 stripeRows : function(startRow){
54068 if(!this.grid.stripeRows || this.ds.getCount() < 1){
54071 startRow = startRow || 0;
54072 var rows = this.getBodyTable().rows;
54073 var lrows = this.getLockedTable().rows;
54074 var cls = ' x-grid-row-alt ';
54075 for(var i = startRow, len = rows.length; i < len; i++){
54076 var row = rows[i], lrow = lrows[i];
54077 var isAlt = ((i+1) % 2 == 0);
54078 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
54079 if(isAlt == hasAlt){
54083 row.className += " x-grid-row-alt";
54085 row.className = row.className.replace("x-grid-row-alt", "");
54088 lrow.className = row.className;
54093 restoreScroll : function(state){
54094 //Roo.log('GridView.restoreScroll');
54095 var sb = this.scroller.dom;
54096 sb.scrollLeft = state.left;
54097 sb.scrollTop = state.top;
54101 syncScroll : function(){
54102 //Roo.log('GridView.syncScroll');
54103 var sb = this.scroller.dom;
54104 var sh = this.mainHd.dom;
54105 var bs = this.mainBody.dom;
54106 var lv = this.lockedBody.dom;
54107 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
54108 lv.scrollTop = bs.scrollTop = sb.scrollTop;
54111 handleScroll : function(e){
54113 var sb = this.scroller.dom;
54114 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
54118 handleWheel : function(e){
54119 var d = e.getWheelDelta();
54120 this.scroller.dom.scrollTop -= d*22;
54121 // set this here to prevent jumpy scrolling on large tables
54122 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
54126 renderRows : function(startRow, endRow){
54127 // pull in all the crap needed to render rows
54128 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
54129 var colCount = cm.getColumnCount();
54131 if(ds.getCount() < 1){
54135 // build a map for all the columns
54137 for(var i = 0; i < colCount; i++){
54138 var name = cm.getDataIndex(i);
54140 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
54141 renderer : cm.getRenderer(i),
54142 id : cm.getColumnId(i),
54143 locked : cm.isLocked(i)
54147 startRow = startRow || 0;
54148 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
54150 // records to render
54151 var rs = ds.getRange(startRow, endRow);
54153 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
54156 // As much as I hate to duplicate code, this was branched because FireFox really hates
54157 // [].join("") on strings. The performance difference was substantial enough to
54158 // branch this function
54159 doRender : Roo.isGecko ?
54160 function(cs, rs, ds, startRow, colCount, stripe){
54161 var ts = this.templates, ct = ts.cell, rt = ts.row;
54163 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
54165 var hasListener = this.grid.hasListener('rowclass');
54167 for(var j = 0, len = rs.length; j < len; j++){
54168 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
54169 for(var i = 0; i < colCount; i++){
54171 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
54173 p.css = p.attr = "";
54174 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
54175 if(p.value == undefined || p.value === "") p.value = " ";
54176 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
54177 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
54179 var markup = ct.apply(p);
54187 if(stripe && ((rowIndex+1) % 2 == 0)){
54188 alt.push("x-grid-row-alt")
54191 alt.push( " x-grid-dirty-row");
54194 if(this.getRowClass){
54195 alt.push(this.getRowClass(r, rowIndex));
54201 rowIndex : rowIndex,
54204 this.grid.fireEvent('rowclass', this, rowcfg);
54205 alt.push(rowcfg.rowClass);
54207 rp.alt = alt.join(" ");
54208 lbuf+= rt.apply(rp);
54210 buf+= rt.apply(rp);
54212 return [lbuf, buf];
54214 function(cs, rs, ds, startRow, colCount, stripe){
54215 var ts = this.templates, ct = ts.cell, rt = ts.row;
54217 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
54218 var hasListener = this.grid.hasListener('rowclass');
54221 for(var j = 0, len = rs.length; j < len; j++){
54222 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
54223 for(var i = 0; i < colCount; i++){
54225 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
54227 p.css = p.attr = "";
54228 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
54229 if(p.value == undefined || p.value === "") p.value = " ";
54230 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
54231 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
54234 var markup = ct.apply(p);
54236 cb[cb.length] = markup;
54238 lcb[lcb.length] = markup;
54242 if(stripe && ((rowIndex+1) % 2 == 0)){
54243 alt.push( "x-grid-row-alt");
54246 alt.push(" x-grid-dirty-row");
54249 if(this.getRowClass){
54250 alt.push( this.getRowClass(r, rowIndex));
54256 rowIndex : rowIndex,
54259 this.grid.fireEvent('rowclass', this, rowcfg);
54260 alt.push(rowcfg.rowClass);
54262 rp.alt = alt.join(" ");
54263 rp.cells = lcb.join("");
54264 lbuf[lbuf.length] = rt.apply(rp);
54265 rp.cells = cb.join("");
54266 buf[buf.length] = rt.apply(rp);
54268 return [lbuf.join(""), buf.join("")];
54271 renderBody : function(){
54272 var markup = this.renderRows();
54273 var bt = this.templates.body;
54274 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
54278 * Refreshes the grid
54279 * @param {Boolean} headersToo
54281 refresh : function(headersToo){
54282 this.fireEvent("beforerefresh", this);
54283 this.grid.stopEditing();
54284 var result = this.renderBody();
54285 this.lockedBody.update(result[0]);
54286 this.mainBody.update(result[1]);
54287 if(headersToo === true){
54288 this.updateHeaders();
54289 this.updateColumns();
54290 this.updateSplitters();
54291 this.updateHeaderSortState();
54293 this.syncRowHeights();
54295 this.fireEvent("refresh", this);
54298 handleColumnMove : function(cm, oldIndex, newIndex){
54299 this.indexMap = null;
54300 var s = this.getScrollState();
54301 this.refresh(true);
54302 this.restoreScroll(s);
54303 this.afterMove(newIndex);
54306 afterMove : function(colIndex){
54307 if(this.enableMoveAnim && Roo.enableFx){
54308 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
54310 // if multisort - fix sortOrder, and reload..
54311 if (this.grid.dataSource.multiSort) {
54312 // the we can call sort again..
54313 var dm = this.grid.dataSource;
54314 var cm = this.grid.colModel;
54316 for(var i = 0; i < cm.config.length; i++ ) {
54318 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
54319 continue; // dont' bother, it's not in sort list or being set.
54322 so.push(cm.config[i].dataIndex);
54325 dm.load(dm.lastOptions);
54332 updateCell : function(dm, rowIndex, dataIndex){
54333 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
54334 if(typeof colIndex == "undefined"){ // not present in grid
54337 var cm = this.grid.colModel;
54338 var cell = this.getCell(rowIndex, colIndex);
54339 var cellText = this.getCellText(rowIndex, colIndex);
54342 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
54343 id : cm.getColumnId(colIndex),
54344 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
54346 var renderer = cm.getRenderer(colIndex);
54347 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
54348 if(typeof val == "undefined" || val === "") val = " ";
54349 cellText.innerHTML = val;
54350 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
54351 this.syncRowHeights(rowIndex, rowIndex);
54354 calcColumnWidth : function(colIndex, maxRowsToMeasure){
54356 if(this.grid.autoSizeHeaders){
54357 var h = this.getHeaderCellMeasure(colIndex);
54358 maxWidth = Math.max(maxWidth, h.scrollWidth);
54361 if(this.cm.isLocked(colIndex)){
54362 tb = this.getLockedTable();
54365 tb = this.getBodyTable();
54366 index = colIndex - this.cm.getLockedCount();
54369 var rows = tb.rows;
54370 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
54371 for(var i = 0; i < stopIndex; i++){
54372 var cell = rows[i].childNodes[index].firstChild;
54373 maxWidth = Math.max(maxWidth, cell.scrollWidth);
54376 return maxWidth + /*margin for error in IE*/ 5;
54379 * Autofit a column to its content.
54380 * @param {Number} colIndex
54381 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
54383 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
54384 if(this.cm.isHidden(colIndex)){
54385 return; // can't calc a hidden column
54388 var cid = this.cm.getColumnId(colIndex);
54389 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
54390 if(this.grid.autoSizeHeaders){
54391 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
54394 var newWidth = this.calcColumnWidth(colIndex);
54395 this.cm.setColumnWidth(colIndex,
54396 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
54397 if(!suppressEvent){
54398 this.grid.fireEvent("columnresize", colIndex, newWidth);
54403 * Autofits all columns to their content and then expands to fit any extra space in the grid
54405 autoSizeColumns : function(){
54406 var cm = this.grid.colModel;
54407 var colCount = cm.getColumnCount();
54408 for(var i = 0; i < colCount; i++){
54409 this.autoSizeColumn(i, true, true);
54411 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
54414 this.updateColumns();
54420 * Autofits all columns to the grid's width proportionate with their current size
54421 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
54423 fitColumns : function(reserveScrollSpace){
54424 var cm = this.grid.colModel;
54425 var colCount = cm.getColumnCount();
54429 for (i = 0; i < colCount; i++){
54430 if(!cm.isHidden(i) && !cm.isFixed(i)){
54431 w = cm.getColumnWidth(i);
54437 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
54438 if(reserveScrollSpace){
54441 var frac = (avail - cm.getTotalWidth())/width;
54442 while (cols.length){
54445 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
54447 this.updateColumns();
54451 onRowSelect : function(rowIndex){
54452 var row = this.getRowComposite(rowIndex);
54453 row.addClass("x-grid-row-selected");
54456 onRowDeselect : function(rowIndex){
54457 var row = this.getRowComposite(rowIndex);
54458 row.removeClass("x-grid-row-selected");
54461 onCellSelect : function(row, col){
54462 var cell = this.getCell(row, col);
54464 Roo.fly(cell).addClass("x-grid-cell-selected");
54468 onCellDeselect : function(row, col){
54469 var cell = this.getCell(row, col);
54471 Roo.fly(cell).removeClass("x-grid-cell-selected");
54475 updateHeaderSortState : function(){
54477 // sort state can be single { field: xxx, direction : yyy}
54478 // or { xxx=>ASC , yyy : DESC ..... }
54481 if (!this.ds.multiSort) {
54482 var state = this.ds.getSortState();
54486 mstate[state.field] = state.direction;
54487 // FIXME... - this is not used here.. but might be elsewhere..
54488 this.sortState = state;
54491 mstate = this.ds.sortToggle;
54493 //remove existing sort classes..
54495 var sc = this.sortClasses;
54496 var hds = this.el.select(this.headerSelector).removeClass(sc);
54498 for(var f in mstate) {
54500 var sortColumn = this.cm.findColumnIndex(f);
54502 if(sortColumn != -1){
54503 var sortDir = mstate[f];
54504 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
54513 handleHeaderClick : function(g, index,e){
54515 Roo.log("header click");
54518 // touch events on header are handled by context
54519 this.handleHdCtx(g,index,e);
54524 if(this.headersDisabled){
54527 var dm = g.dataSource, cm = g.colModel;
54528 if(!cm.isSortable(index)){
54533 if (dm.multiSort) {
54534 // update the sortOrder
54536 for(var i = 0; i < cm.config.length; i++ ) {
54538 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
54539 continue; // dont' bother, it's not in sort list or being set.
54542 so.push(cm.config[i].dataIndex);
54548 dm.sort(cm.getDataIndex(index));
54552 destroy : function(){
54554 this.colMenu.removeAll();
54555 Roo.menu.MenuMgr.unregister(this.colMenu);
54556 this.colMenu.getEl().remove();
54557 delete this.colMenu;
54560 this.hmenu.removeAll();
54561 Roo.menu.MenuMgr.unregister(this.hmenu);
54562 this.hmenu.getEl().remove();
54565 if(this.grid.enableColumnMove){
54566 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
54568 for(var dd in dds){
54569 if(!dds[dd].config.isTarget && dds[dd].dragElId){
54570 var elid = dds[dd].dragElId;
54572 Roo.get(elid).remove();
54573 } else if(dds[dd].config.isTarget){
54574 dds[dd].proxyTop.remove();
54575 dds[dd].proxyBottom.remove();
54578 if(Roo.dd.DDM.locationCache[dd]){
54579 delete Roo.dd.DDM.locationCache[dd];
54582 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
54585 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
54586 this.bind(null, null);
54587 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
54590 handleLockChange : function(){
54591 this.refresh(true);
54594 onDenyColumnLock : function(){
54598 onDenyColumnHide : function(){
54602 handleHdMenuClick : function(item){
54603 var index = this.hdCtxIndex;
54604 var cm = this.cm, ds = this.ds;
54607 ds.sort(cm.getDataIndex(index), "ASC");
54610 ds.sort(cm.getDataIndex(index), "DESC");
54613 var lc = cm.getLockedCount();
54614 if(cm.getColumnCount(true) <= lc+1){
54615 this.onDenyColumnLock();
54619 cm.setLocked(index, true, true);
54620 cm.moveColumn(index, lc);
54621 this.grid.fireEvent("columnmove", index, lc);
54623 cm.setLocked(index, true);
54627 var lc = cm.getLockedCount();
54628 if((lc-1) != index){
54629 cm.setLocked(index, false, true);
54630 cm.moveColumn(index, lc-1);
54631 this.grid.fireEvent("columnmove", index, lc-1);
54633 cm.setLocked(index, false);
54636 case 'wider': // used to expand cols on touch..
54638 var cw = cm.getColumnWidth(index);
54639 cw += (item.id == 'wider' ? 1 : -1) * 50;
54640 cw = Math.max(0, cw);
54641 cw = Math.min(cw,4000);
54642 cm.setColumnWidth(index, cw);
54646 index = cm.getIndexById(item.id.substr(4));
54648 if(item.checked && cm.getColumnCount(true) <= 1){
54649 this.onDenyColumnHide();
54652 cm.setHidden(index, item.checked);
54658 beforeColMenuShow : function(){
54659 var cm = this.cm, colCount = cm.getColumnCount();
54660 this.colMenu.removeAll();
54661 for(var i = 0; i < colCount; i++){
54662 this.colMenu.add(new Roo.menu.CheckItem({
54663 id: "col-"+cm.getColumnId(i),
54664 text: cm.getColumnHeader(i),
54665 checked: !cm.isHidden(i),
54671 handleHdCtx : function(g, index, e){
54673 var hd = this.getHeaderCell(index);
54674 this.hdCtxIndex = index;
54675 var ms = this.hmenu.items, cm = this.cm;
54676 ms.get("asc").setDisabled(!cm.isSortable(index));
54677 ms.get("desc").setDisabled(!cm.isSortable(index));
54678 if(this.grid.enableColLock !== false){
54679 ms.get("lock").setDisabled(cm.isLocked(index));
54680 ms.get("unlock").setDisabled(!cm.isLocked(index));
54682 this.hmenu.show(hd, "tl-bl");
54685 handleHdOver : function(e){
54686 var hd = this.findHeaderCell(e.getTarget());
54687 if(hd && !this.headersDisabled){
54688 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
54689 this.fly(hd).addClass("x-grid-hd-over");
54694 handleHdOut : function(e){
54695 var hd = this.findHeaderCell(e.getTarget());
54697 this.fly(hd).removeClass("x-grid-hd-over");
54701 handleSplitDblClick : function(e, t){
54702 var i = this.getCellIndex(t);
54703 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
54704 this.autoSizeColumn(i, true);
54709 render : function(){
54712 var colCount = cm.getColumnCount();
54714 if(this.grid.monitorWindowResize === true){
54715 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
54717 var header = this.renderHeaders();
54718 var body = this.templates.body.apply({rows:""});
54719 var html = this.templates.master.apply({
54722 lockedHeader: header[0],
54726 //this.updateColumns();
54728 this.grid.getGridEl().dom.innerHTML = html;
54730 this.initElements();
54732 // a kludge to fix the random scolling effect in webkit
54733 this.el.on("scroll", function() {
54734 this.el.dom.scrollTop=0; // hopefully not recursive..
54737 this.scroller.on("scroll", this.handleScroll, this);
54738 this.lockedBody.on("mousewheel", this.handleWheel, this);
54739 this.mainBody.on("mousewheel", this.handleWheel, this);
54741 this.mainHd.on("mouseover", this.handleHdOver, this);
54742 this.mainHd.on("mouseout", this.handleHdOut, this);
54743 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
54744 {delegate: "."+this.splitClass});
54746 this.lockedHd.on("mouseover", this.handleHdOver, this);
54747 this.lockedHd.on("mouseout", this.handleHdOut, this);
54748 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
54749 {delegate: "."+this.splitClass});
54751 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
54752 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54755 this.updateSplitters();
54757 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
54758 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54759 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54762 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
54763 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
54765 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
54766 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
54768 if(this.grid.enableColLock !== false){
54769 this.hmenu.add('-',
54770 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
54771 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
54775 this.hmenu.add('-',
54776 {id:"wider", text: this.columnsWiderText},
54777 {id:"narrow", text: this.columnsNarrowText }
54783 if(this.grid.enableColumnHide !== false){
54785 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
54786 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
54787 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
54789 this.hmenu.add('-',
54790 {id:"columns", text: this.columnsText, menu: this.colMenu}
54793 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
54795 this.grid.on("headercontextmenu", this.handleHdCtx, this);
54798 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
54799 this.dd = new Roo.grid.GridDragZone(this.grid, {
54800 ddGroup : this.grid.ddGroup || 'GridDD'
54806 for(var i = 0; i < colCount; i++){
54807 if(cm.isHidden(i)){
54808 this.hideColumn(i);
54810 if(cm.config[i].align){
54811 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
54812 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
54816 this.updateHeaderSortState();
54818 this.beforeInitialResize();
54821 // two part rendering gives faster view to the user
54822 this.renderPhase2.defer(1, this);
54825 renderPhase2 : function(){
54826 // render the rows now
54828 if(this.grid.autoSizeColumns){
54829 this.autoSizeColumns();
54833 beforeInitialResize : function(){
54837 onColumnSplitterMoved : function(i, w){
54838 this.userResized = true;
54839 var cm = this.grid.colModel;
54840 cm.setColumnWidth(i, w, true);
54841 var cid = cm.getColumnId(i);
54842 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
54843 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
54844 this.updateSplitters();
54846 this.grid.fireEvent("columnresize", i, w);
54849 syncRowHeights : function(startIndex, endIndex){
54850 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
54851 startIndex = startIndex || 0;
54852 var mrows = this.getBodyTable().rows;
54853 var lrows = this.getLockedTable().rows;
54854 var len = mrows.length-1;
54855 endIndex = Math.min(endIndex || len, len);
54856 for(var i = startIndex; i <= endIndex; i++){
54857 var m = mrows[i], l = lrows[i];
54858 var h = Math.max(m.offsetHeight, l.offsetHeight);
54859 m.style.height = l.style.height = h + "px";
54864 layout : function(initialRender, is2ndPass){
54866 var auto = g.autoHeight;
54867 var scrollOffset = 16;
54868 var c = g.getGridEl(), cm = this.cm,
54869 expandCol = g.autoExpandColumn,
54871 //c.beginMeasure();
54873 if(!c.dom.offsetWidth){ // display:none?
54875 this.lockedWrap.show();
54876 this.mainWrap.show();
54881 var hasLock = this.cm.isLocked(0);
54883 var tbh = this.headerPanel.getHeight();
54884 var bbh = this.footerPanel.getHeight();
54887 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
54888 var newHeight = ch + c.getBorderWidth("tb");
54890 newHeight = Math.min(g.maxHeight, newHeight);
54892 c.setHeight(newHeight);
54896 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
54899 var s = this.scroller;
54901 var csize = c.getSize(true);
54903 this.el.setSize(csize.width, csize.height);
54905 this.headerPanel.setWidth(csize.width);
54906 this.footerPanel.setWidth(csize.width);
54908 var hdHeight = this.mainHd.getHeight();
54909 var vw = csize.width;
54910 var vh = csize.height - (tbh + bbh);
54914 var bt = this.getBodyTable();
54915 var ltWidth = hasLock ?
54916 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
54918 var scrollHeight = bt.offsetHeight;
54919 var scrollWidth = ltWidth + bt.offsetWidth;
54920 var vscroll = false, hscroll = false;
54922 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
54924 var lw = this.lockedWrap, mw = this.mainWrap;
54925 var lb = this.lockedBody, mb = this.mainBody;
54927 setTimeout(function(){
54928 var t = s.dom.offsetTop;
54929 var w = s.dom.clientWidth,
54930 h = s.dom.clientHeight;
54933 lw.setSize(ltWidth, h);
54935 mw.setLeftTop(ltWidth, t);
54936 mw.setSize(w-ltWidth, h);
54938 lb.setHeight(h-hdHeight);
54939 mb.setHeight(h-hdHeight);
54941 if(is2ndPass !== true && !gv.userResized && expandCol){
54942 // high speed resize without full column calculation
54944 var ci = cm.getIndexById(expandCol);
54946 ci = cm.findColumnIndex(expandCol);
54948 ci = Math.max(0, ci); // make sure it's got at least the first col.
54949 var expandId = cm.getColumnId(ci);
54950 var tw = cm.getTotalWidth(false);
54951 var currentWidth = cm.getColumnWidth(ci);
54952 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
54953 if(currentWidth != cw){
54954 cm.setColumnWidth(ci, cw, true);
54955 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
54956 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
54957 gv.updateSplitters();
54958 gv.layout(false, true);
54970 onWindowResize : function(){
54971 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
54977 appendFooter : function(parentEl){
54981 sortAscText : "Sort Ascending",
54982 sortDescText : "Sort Descending",
54983 lockText : "Lock Column",
54984 unlockText : "Unlock Column",
54985 columnsText : "Columns",
54987 columnsWiderText : "Wider",
54988 columnsNarrowText : "Thinner"
54992 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
54993 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
54994 this.proxy.el.addClass('x-grid3-col-dd');
54997 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
54998 handleMouseDown : function(e){
55002 callHandleMouseDown : function(e){
55003 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
55008 * Ext JS Library 1.1.1
55009 * Copyright(c) 2006-2007, Ext JS, LLC.
55011 * Originally Released Under LGPL - original licence link has changed is not relivant.
55014 * <script type="text/javascript">
55018 // This is a support class used internally by the Grid components
55019 Roo.grid.SplitDragZone = function(grid, hd, hd2){
55021 this.view = grid.getView();
55022 this.proxy = this.view.resizeProxy;
55023 Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
55024 "gridSplitters" + this.grid.getGridEl().id, {
55025 dragElId : Roo.id(this.proxy.dom), resizeFrame:false
55027 this.setHandleElId(Roo.id(hd));
55028 this.setOuterHandleElId(Roo.id(hd2));
55029 this.scroll = false;
55031 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
55032 fly: Roo.Element.fly,
55034 b4StartDrag : function(x, y){
55035 this.view.headersDisabled = true;
55036 this.proxy.setHeight(this.view.mainWrap.getHeight());
55037 var w = this.cm.getColumnWidth(this.cellIndex);
55038 var minw = Math.max(w-this.grid.minColumnWidth, 0);
55039 this.resetConstraints();
55040 this.setXConstraint(minw, 1000);
55041 this.setYConstraint(0, 0);
55042 this.minX = x - minw;
55043 this.maxX = x + 1000;
55045 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
55049 handleMouseDown : function(e){
55050 ev = Roo.EventObject.setEvent(e);
55051 var t = this.fly(ev.getTarget());
55052 if(t.hasClass("x-grid-split")){
55053 this.cellIndex = this.view.getCellIndex(t.dom);
55054 this.split = t.dom;
55055 this.cm = this.grid.colModel;
55056 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
55057 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
55062 endDrag : function(e){
55063 this.view.headersDisabled = false;
55064 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
55065 var diff = endX - this.startPos;
55066 this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
55069 autoOffset : function(){
55070 this.setDelta(0,0);
55074 * Ext JS Library 1.1.1
55075 * Copyright(c) 2006-2007, Ext JS, LLC.
55077 * Originally Released Under LGPL - original licence link has changed is not relivant.
55080 * <script type="text/javascript">
55084 // This is a support class used internally by the Grid components
55085 Roo.grid.GridDragZone = function(grid, config){
55086 this.view = grid.getView();
55087 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
55088 if(this.view.lockedBody){
55089 this.setHandleElId(Roo.id(this.view.mainBody.dom));
55090 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
55092 this.scroll = false;
55094 this.ddel = document.createElement('div');
55095 this.ddel.className = 'x-grid-dd-wrap';
55098 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
55099 ddGroup : "GridDD",
55101 getDragData : function(e){
55102 var t = Roo.lib.Event.getTarget(e);
55103 var rowIndex = this.view.findRowIndex(t);
55104 var sm = this.grid.selModel;
55106 //Roo.log(rowIndex);
55108 if (sm.getSelectedCell) {
55109 // cell selection..
55110 if (!sm.getSelectedCell()) {
55113 if (rowIndex != sm.getSelectedCell()[0]) {
55119 if(rowIndex !== false){
55124 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
55126 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
55129 if (e.hasModifier()){
55130 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
55133 Roo.log("getDragData");
55138 rowIndex: rowIndex,
55139 selections:sm.getSelections ? sm.getSelections() : (
55140 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
55147 onInitDrag : function(e){
55148 var data = this.dragData;
55149 this.ddel.innerHTML = this.grid.getDragDropText();
55150 this.proxy.update(this.ddel);
55151 // fire start drag?
55154 afterRepair : function(){
55155 this.dragging = false;
55158 getRepairXY : function(e, data){
55162 onEndDrag : function(data, e){
55166 onValidDrop : function(dd, e, id){
55171 beforeInvalidDrop : function(e, id){
55176 * Ext JS Library 1.1.1
55177 * Copyright(c) 2006-2007, Ext JS, LLC.
55179 * Originally Released Under LGPL - original licence link has changed is not relivant.
55182 * <script type="text/javascript">
55187 * @class Roo.grid.ColumnModel
55188 * @extends Roo.util.Observable
55189 * This is the default implementation of a ColumnModel used by the Grid. It defines
55190 * the columns in the grid.
55193 var colModel = new Roo.grid.ColumnModel([
55194 {header: "Ticker", width: 60, sortable: true, locked: true},
55195 {header: "Company Name", width: 150, sortable: true},
55196 {header: "Market Cap.", width: 100, sortable: true},
55197 {header: "$ Sales", width: 100, sortable: true, renderer: money},
55198 {header: "Employees", width: 100, sortable: true, resizable: false}
55203 * The config options listed for this class are options which may appear in each
55204 * individual column definition.
55205 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
55207 * @param {Object} config An Array of column config objects. See this class's
55208 * config objects for details.
55210 Roo.grid.ColumnModel = function(config){
55212 * The config passed into the constructor
55214 this.config = config;
55217 // if no id, create one
55218 // if the column does not have a dataIndex mapping,
55219 // map it to the order it is in the config
55220 for(var i = 0, len = config.length; i < len; i++){
55222 if(typeof c.dataIndex == "undefined"){
55225 if(typeof c.renderer == "string"){
55226 c.renderer = Roo.util.Format[c.renderer];
55228 if(typeof c.id == "undefined"){
55231 if(c.editor && c.editor.xtype){
55232 c.editor = Roo.factory(c.editor, Roo.grid);
55234 if(c.editor && c.editor.isFormField){
55235 c.editor = new Roo.grid.GridEditor(c.editor);
55237 this.lookup[c.id] = c;
55241 * The width of columns which have no width specified (defaults to 100)
55244 this.defaultWidth = 100;
55247 * Default sortable of columns which have no sortable specified (defaults to false)
55250 this.defaultSortable = false;
55254 * @event widthchange
55255 * Fires when the width of a column changes.
55256 * @param {ColumnModel} this
55257 * @param {Number} columnIndex The column index
55258 * @param {Number} newWidth The new width
55260 "widthchange": true,
55262 * @event headerchange
55263 * Fires when the text of a header changes.
55264 * @param {ColumnModel} this
55265 * @param {Number} columnIndex The column index
55266 * @param {Number} newText The new header text
55268 "headerchange": true,
55270 * @event hiddenchange
55271 * Fires when a column is hidden or "unhidden".
55272 * @param {ColumnModel} this
55273 * @param {Number} columnIndex The column index
55274 * @param {Boolean} hidden true if hidden, false otherwise
55276 "hiddenchange": true,
55278 * @event columnmoved
55279 * Fires when a column is moved.
55280 * @param {ColumnModel} this
55281 * @param {Number} oldIndex
55282 * @param {Number} newIndex
55284 "columnmoved" : true,
55286 * @event columlockchange
55287 * Fires when a column's locked state is changed
55288 * @param {ColumnModel} this
55289 * @param {Number} colIndex
55290 * @param {Boolean} locked true if locked
55292 "columnlockchange" : true
55294 Roo.grid.ColumnModel.superclass.constructor.call(this);
55296 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
55298 * @cfg {String} header The header text to display in the Grid view.
55301 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
55302 * {@link Roo.data.Record} definition from which to draw the column's value. If not
55303 * specified, the column's index is used as an index into the Record's data Array.
55306 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
55307 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
55310 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
55311 * Defaults to the value of the {@link #defaultSortable} property.
55312 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
55315 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
55318 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
55321 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
55324 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
55327 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
55328 * given the cell's data value. See {@link #setRenderer}. If not specified, the
55329 * default renderer uses the raw data value. If an object is returned (bootstrap only)
55330 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
55333 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
55336 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
55339 * @cfg {String} cursor (Optional)
55342 * @cfg {String} tooltip (Optional)
55345 * Returns the id of the column at the specified index.
55346 * @param {Number} index The column index
55347 * @return {String} the id
55349 getColumnId : function(index){
55350 return this.config[index].id;
55354 * Returns the column for a specified id.
55355 * @param {String} id The column id
55356 * @return {Object} the column
55358 getColumnById : function(id){
55359 return this.lookup[id];
55364 * Returns the column for a specified dataIndex.
55365 * @param {String} dataIndex The column dataIndex
55366 * @return {Object|Boolean} the column or false if not found
55368 getColumnByDataIndex: function(dataIndex){
55369 var index = this.findColumnIndex(dataIndex);
55370 return index > -1 ? this.config[index] : false;
55374 * Returns the index for a specified column id.
55375 * @param {String} id The column id
55376 * @return {Number} the index, or -1 if not found
55378 getIndexById : function(id){
55379 for(var i = 0, len = this.config.length; i < len; i++){
55380 if(this.config[i].id == id){
55388 * Returns the index for a specified column dataIndex.
55389 * @param {String} dataIndex The column dataIndex
55390 * @return {Number} the index, or -1 if not found
55393 findColumnIndex : function(dataIndex){
55394 for(var i = 0, len = this.config.length; i < len; i++){
55395 if(this.config[i].dataIndex == dataIndex){
55403 moveColumn : function(oldIndex, newIndex){
55404 var c = this.config[oldIndex];
55405 this.config.splice(oldIndex, 1);
55406 this.config.splice(newIndex, 0, c);
55407 this.dataMap = null;
55408 this.fireEvent("columnmoved", this, oldIndex, newIndex);
55411 isLocked : function(colIndex){
55412 return this.config[colIndex].locked === true;
55415 setLocked : function(colIndex, value, suppressEvent){
55416 if(this.isLocked(colIndex) == value){
55419 this.config[colIndex].locked = value;
55420 if(!suppressEvent){
55421 this.fireEvent("columnlockchange", this, colIndex, value);
55425 getTotalLockedWidth : function(){
55426 var totalWidth = 0;
55427 for(var i = 0; i < this.config.length; i++){
55428 if(this.isLocked(i) && !this.isHidden(i)){
55429 this.totalWidth += this.getColumnWidth(i);
55435 getLockedCount : function(){
55436 for(var i = 0, len = this.config.length; i < len; i++){
55437 if(!this.isLocked(i)){
55444 * Returns the number of columns.
55447 getColumnCount : function(visibleOnly){
55448 if(visibleOnly === true){
55450 for(var i = 0, len = this.config.length; i < len; i++){
55451 if(!this.isHidden(i)){
55457 return this.config.length;
55461 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
55462 * @param {Function} fn
55463 * @param {Object} scope (optional)
55464 * @return {Array} result
55466 getColumnsBy : function(fn, scope){
55468 for(var i = 0, len = this.config.length; i < len; i++){
55469 var c = this.config[i];
55470 if(fn.call(scope||this, c, i) === true){
55478 * Returns true if the specified column is sortable.
55479 * @param {Number} col The column index
55480 * @return {Boolean}
55482 isSortable : function(col){
55483 if(typeof this.config[col].sortable == "undefined"){
55484 return this.defaultSortable;
55486 return this.config[col].sortable;
55490 * Returns the rendering (formatting) function defined for the column.
55491 * @param {Number} col The column index.
55492 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
55494 getRenderer : function(col){
55495 if(!this.config[col].renderer){
55496 return Roo.grid.ColumnModel.defaultRenderer;
55498 return this.config[col].renderer;
55502 * Sets the rendering (formatting) function for a column.
55503 * @param {Number} col The column index
55504 * @param {Function} fn The function to use to process the cell's raw data
55505 * to return HTML markup for the grid view. The render function is called with
55506 * the following parameters:<ul>
55507 * <li>Data value.</li>
55508 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
55509 * <li>css A CSS style string to apply to the table cell.</li>
55510 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
55511 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
55512 * <li>Row index</li>
55513 * <li>Column index</li>
55514 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
55516 setRenderer : function(col, fn){
55517 this.config[col].renderer = fn;
55521 * Returns the width for the specified column.
55522 * @param {Number} col The column index
55525 getColumnWidth : function(col){
55526 return this.config[col].width * 1 || this.defaultWidth;
55530 * Sets the width for a column.
55531 * @param {Number} col The column index
55532 * @param {Number} width The new width
55534 setColumnWidth : function(col, width, suppressEvent){
55535 this.config[col].width = width;
55536 this.totalWidth = null;
55537 if(!suppressEvent){
55538 this.fireEvent("widthchange", this, col, width);
55543 * Returns the total width of all columns.
55544 * @param {Boolean} includeHidden True to include hidden column widths
55547 getTotalWidth : function(includeHidden){
55548 if(!this.totalWidth){
55549 this.totalWidth = 0;
55550 for(var i = 0, len = this.config.length; i < len; i++){
55551 if(includeHidden || !this.isHidden(i)){
55552 this.totalWidth += this.getColumnWidth(i);
55556 return this.totalWidth;
55560 * Returns the header for the specified column.
55561 * @param {Number} col The column index
55564 getColumnHeader : function(col){
55565 return this.config[col].header;
55569 * Sets the header for a column.
55570 * @param {Number} col The column index
55571 * @param {String} header The new header
55573 setColumnHeader : function(col, header){
55574 this.config[col].header = header;
55575 this.fireEvent("headerchange", this, col, header);
55579 * Returns the tooltip for the specified column.
55580 * @param {Number} col The column index
55583 getColumnTooltip : function(col){
55584 return this.config[col].tooltip;
55587 * Sets the tooltip for a column.
55588 * @param {Number} col The column index
55589 * @param {String} tooltip The new tooltip
55591 setColumnTooltip : function(col, tooltip){
55592 this.config[col].tooltip = tooltip;
55596 * Returns the dataIndex for the specified column.
55597 * @param {Number} col The column index
55600 getDataIndex : function(col){
55601 return this.config[col].dataIndex;
55605 * Sets the dataIndex for a column.
55606 * @param {Number} col The column index
55607 * @param {Number} dataIndex The new dataIndex
55609 setDataIndex : function(col, dataIndex){
55610 this.config[col].dataIndex = dataIndex;
55616 * Returns true if the cell is editable.
55617 * @param {Number} colIndex The column index
55618 * @param {Number} rowIndex The row index
55619 * @return {Boolean}
55621 isCellEditable : function(colIndex, rowIndex){
55622 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
55626 * Returns the editor defined for the cell/column.
55627 * return false or null to disable editing.
55628 * @param {Number} colIndex The column index
55629 * @param {Number} rowIndex The row index
55632 getCellEditor : function(colIndex, rowIndex){
55633 return this.config[colIndex].editor;
55637 * Sets if a column is editable.
55638 * @param {Number} col The column index
55639 * @param {Boolean} editable True if the column is editable
55641 setEditable : function(col, editable){
55642 this.config[col].editable = editable;
55647 * Returns true if the column is hidden.
55648 * @param {Number} colIndex The column index
55649 * @return {Boolean}
55651 isHidden : function(colIndex){
55652 return this.config[colIndex].hidden;
55657 * Returns true if the column width cannot be changed
55659 isFixed : function(colIndex){
55660 return this.config[colIndex].fixed;
55664 * Returns true if the column can be resized
55665 * @return {Boolean}
55667 isResizable : function(colIndex){
55668 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
55671 * Sets if a column is hidden.
55672 * @param {Number} colIndex The column index
55673 * @param {Boolean} hidden True if the column is hidden
55675 setHidden : function(colIndex, hidden){
55676 this.config[colIndex].hidden = hidden;
55677 this.totalWidth = null;
55678 this.fireEvent("hiddenchange", this, colIndex, hidden);
55682 * Sets the editor for a column.
55683 * @param {Number} col The column index
55684 * @param {Object} editor The editor object
55686 setEditor : function(col, editor){
55687 this.config[col].editor = editor;
55691 Roo.grid.ColumnModel.defaultRenderer = function(value){
55692 if(typeof value == "string" && value.length < 1){
55698 // Alias for backwards compatibility
55699 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
55702 * Ext JS Library 1.1.1
55703 * Copyright(c) 2006-2007, Ext JS, LLC.
55705 * Originally Released Under LGPL - original licence link has changed is not relivant.
55708 * <script type="text/javascript">
55712 * @class Roo.grid.AbstractSelectionModel
55713 * @extends Roo.util.Observable
55714 * Abstract base class for grid SelectionModels. It provides the interface that should be
55715 * implemented by descendant classes. This class should not be directly instantiated.
55718 Roo.grid.AbstractSelectionModel = function(){
55719 this.locked = false;
55720 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
55723 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
55724 /** @ignore Called by the grid automatically. Do not call directly. */
55725 init : function(grid){
55731 * Locks the selections.
55734 this.locked = true;
55738 * Unlocks the selections.
55740 unlock : function(){
55741 this.locked = false;
55745 * Returns true if the selections are locked.
55746 * @return {Boolean}
55748 isLocked : function(){
55749 return this.locked;
55753 * Ext JS Library 1.1.1
55754 * Copyright(c) 2006-2007, Ext JS, LLC.
55756 * Originally Released Under LGPL - original licence link has changed is not relivant.
55759 * <script type="text/javascript">
55762 * @extends Roo.grid.AbstractSelectionModel
55763 * @class Roo.grid.RowSelectionModel
55764 * The default SelectionModel used by {@link Roo.grid.Grid}.
55765 * It supports multiple selections and keyboard selection/navigation.
55767 * @param {Object} config
55769 Roo.grid.RowSelectionModel = function(config){
55770 Roo.apply(this, config);
55771 this.selections = new Roo.util.MixedCollection(false, function(o){
55776 this.lastActive = false;
55780 * @event selectionchange
55781 * Fires when the selection changes
55782 * @param {SelectionModel} this
55784 "selectionchange" : true,
55786 * @event afterselectionchange
55787 * Fires after the selection changes (eg. by key press or clicking)
55788 * @param {SelectionModel} this
55790 "afterselectionchange" : true,
55792 * @event beforerowselect
55793 * Fires when a row is selected being selected, return false to cancel.
55794 * @param {SelectionModel} this
55795 * @param {Number} rowIndex The selected index
55796 * @param {Boolean} keepExisting False if other selections will be cleared
55798 "beforerowselect" : true,
55801 * Fires when a row is selected.
55802 * @param {SelectionModel} this
55803 * @param {Number} rowIndex The selected index
55804 * @param {Roo.data.Record} r The record
55806 "rowselect" : true,
55808 * @event rowdeselect
55809 * Fires when a row is deselected.
55810 * @param {SelectionModel} this
55811 * @param {Number} rowIndex The selected index
55813 "rowdeselect" : true
55815 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
55816 this.locked = false;
55819 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
55821 * @cfg {Boolean} singleSelect
55822 * True to allow selection of only one row at a time (defaults to false)
55824 singleSelect : false,
55827 initEvents : function(){
55829 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
55830 this.grid.on("mousedown", this.handleMouseDown, this);
55831 }else{ // allow click to work like normal
55832 this.grid.on("rowclick", this.handleDragableRowClick, this);
55835 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
55836 "up" : function(e){
55838 this.selectPrevious(e.shiftKey);
55839 }else if(this.last !== false && this.lastActive !== false){
55840 var last = this.last;
55841 this.selectRange(this.last, this.lastActive-1);
55842 this.grid.getView().focusRow(this.lastActive);
55843 if(last !== false){
55847 this.selectFirstRow();
55849 this.fireEvent("afterselectionchange", this);
55851 "down" : function(e){
55853 this.selectNext(e.shiftKey);
55854 }else if(this.last !== false && this.lastActive !== false){
55855 var last = this.last;
55856 this.selectRange(this.last, this.lastActive+1);
55857 this.grid.getView().focusRow(this.lastActive);
55858 if(last !== false){
55862 this.selectFirstRow();
55864 this.fireEvent("afterselectionchange", this);
55869 var view = this.grid.view;
55870 view.on("refresh", this.onRefresh, this);
55871 view.on("rowupdated", this.onRowUpdated, this);
55872 view.on("rowremoved", this.onRemove, this);
55876 onRefresh : function(){
55877 var ds = this.grid.dataSource, i, v = this.grid.view;
55878 var s = this.selections;
55879 s.each(function(r){
55880 if((i = ds.indexOfId(r.id)) != -1){
55889 onRemove : function(v, index, r){
55890 this.selections.remove(r);
55894 onRowUpdated : function(v, index, r){
55895 if(this.isSelected(r)){
55896 v.onRowSelect(index);
55902 * @param {Array} records The records to select
55903 * @param {Boolean} keepExisting (optional) True to keep existing selections
55905 selectRecords : function(records, keepExisting){
55907 this.clearSelections();
55909 var ds = this.grid.dataSource;
55910 for(var i = 0, len = records.length; i < len; i++){
55911 this.selectRow(ds.indexOf(records[i]), true);
55916 * Gets the number of selected rows.
55919 getCount : function(){
55920 return this.selections.length;
55924 * Selects the first row in the grid.
55926 selectFirstRow : function(){
55931 * Select the last row.
55932 * @param {Boolean} keepExisting (optional) True to keep existing selections
55934 selectLastRow : function(keepExisting){
55935 this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
55939 * Selects the row immediately following the last selected row.
55940 * @param {Boolean} keepExisting (optional) True to keep existing selections
55942 selectNext : function(keepExisting){
55943 if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
55944 this.selectRow(this.last+1, keepExisting);
55945 this.grid.getView().focusRow(this.last);
55950 * Selects the row that precedes the last selected row.
55951 * @param {Boolean} keepExisting (optional) True to keep existing selections
55953 selectPrevious : function(keepExisting){
55955 this.selectRow(this.last-1, keepExisting);
55956 this.grid.getView().focusRow(this.last);
55961 * Returns the selected records
55962 * @return {Array} Array of selected records
55964 getSelections : function(){
55965 return [].concat(this.selections.items);
55969 * Returns the first selected record.
55972 getSelected : function(){
55973 return this.selections.itemAt(0);
55978 * Clears all selections.
55980 clearSelections : function(fast){
55981 if(this.locked) return;
55983 var ds = this.grid.dataSource;
55984 var s = this.selections;
55985 s.each(function(r){
55986 this.deselectRow(ds.indexOfId(r.id));
55990 this.selections.clear();
55997 * Selects all rows.
55999 selectAll : function(){
56000 if(this.locked) return;
56001 this.selections.clear();
56002 for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
56003 this.selectRow(i, true);
56008 * Returns True if there is a selection.
56009 * @return {Boolean}
56011 hasSelection : function(){
56012 return this.selections.length > 0;
56016 * Returns True if the specified row is selected.
56017 * @param {Number/Record} record The record or index of the record to check
56018 * @return {Boolean}
56020 isSelected : function(index){
56021 var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
56022 return (r && this.selections.key(r.id) ? true : false);
56026 * Returns True if the specified record id is selected.
56027 * @param {String} id The id of record to check
56028 * @return {Boolean}
56030 isIdSelected : function(id){
56031 return (this.selections.key(id) ? true : false);
56035 handleMouseDown : function(e, t){
56036 var view = this.grid.getView(), rowIndex;
56037 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
56040 if(e.shiftKey && this.last !== false){
56041 var last = this.last;
56042 this.selectRange(last, rowIndex, e.ctrlKey);
56043 this.last = last; // reset the last
56044 view.focusRow(rowIndex);
56046 var isSelected = this.isSelected(rowIndex);
56047 if(e.button !== 0 && isSelected){
56048 view.focusRow(rowIndex);
56049 }else if(e.ctrlKey && isSelected){
56050 this.deselectRow(rowIndex);
56051 }else if(!isSelected){
56052 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
56053 view.focusRow(rowIndex);
56056 this.fireEvent("afterselectionchange", this);
56059 handleDragableRowClick : function(grid, rowIndex, e)
56061 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
56062 this.selectRow(rowIndex, false);
56063 grid.view.focusRow(rowIndex);
56064 this.fireEvent("afterselectionchange", this);
56069 * Selects multiple rows.
56070 * @param {Array} rows Array of the indexes of the row to select
56071 * @param {Boolean} keepExisting (optional) True to keep existing selections
56073 selectRows : function(rows, keepExisting){
56075 this.clearSelections();
56077 for(var i = 0, len = rows.length; i < len; i++){
56078 this.selectRow(rows[i], true);
56083 * Selects a range of rows. All rows in between startRow and endRow are also selected.
56084 * @param {Number} startRow The index of the first row in the range
56085 * @param {Number} endRow The index of the last row in the range
56086 * @param {Boolean} keepExisting (optional) True to retain existing selections
56088 selectRange : function(startRow, endRow, keepExisting){
56089 if(this.locked) return;
56091 this.clearSelections();
56093 if(startRow <= endRow){
56094 for(var i = startRow; i <= endRow; i++){
56095 this.selectRow(i, true);
56098 for(var i = startRow; i >= endRow; i--){
56099 this.selectRow(i, true);
56105 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
56106 * @param {Number} startRow The index of the first row in the range
56107 * @param {Number} endRow The index of the last row in the range
56109 deselectRange : function(startRow, endRow, preventViewNotify){
56110 if(this.locked) return;
56111 for(var i = startRow; i <= endRow; i++){
56112 this.deselectRow(i, preventViewNotify);
56118 * @param {Number} row The index of the row to select
56119 * @param {Boolean} keepExisting (optional) True to keep existing selections
56121 selectRow : function(index, keepExisting, preventViewNotify){
56122 if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
56123 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
56124 if(!keepExisting || this.singleSelect){
56125 this.clearSelections();
56127 var r = this.grid.dataSource.getAt(index);
56128 this.selections.add(r);
56129 this.last = this.lastActive = index;
56130 if(!preventViewNotify){
56131 this.grid.getView().onRowSelect(index);
56133 this.fireEvent("rowselect", this, index, r);
56134 this.fireEvent("selectionchange", this);
56140 * @param {Number} row The index of the row to deselect
56142 deselectRow : function(index, preventViewNotify){
56143 if(this.locked) return;
56144 if(this.last == index){
56147 if(this.lastActive == index){
56148 this.lastActive = false;
56150 var r = this.grid.dataSource.getAt(index);
56151 this.selections.remove(r);
56152 if(!preventViewNotify){
56153 this.grid.getView().onRowDeselect(index);
56155 this.fireEvent("rowdeselect", this, index);
56156 this.fireEvent("selectionchange", this);
56160 restoreLast : function(){
56162 this.last = this._last;
56167 acceptsNav : function(row, col, cm){
56168 return !cm.isHidden(col) && cm.isCellEditable(col, row);
56172 onEditorKey : function(field, e){
56173 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
56178 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
56180 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56182 }else if(k == e.ENTER && !e.ctrlKey){
56186 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
56188 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
56190 }else if(k == e.ESC){
56194 g.startEditing(newCell[0], newCell[1]);
56199 * Ext JS Library 1.1.1
56200 * Copyright(c) 2006-2007, Ext JS, LLC.
56202 * Originally Released Under LGPL - original licence link has changed is not relivant.
56205 * <script type="text/javascript">
56208 * @class Roo.grid.CellSelectionModel
56209 * @extends Roo.grid.AbstractSelectionModel
56210 * This class provides the basic implementation for cell selection in a grid.
56212 * @param {Object} config The object containing the configuration of this model.
56213 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
56215 Roo.grid.CellSelectionModel = function(config){
56216 Roo.apply(this, config);
56218 this.selection = null;
56222 * @event beforerowselect
56223 * Fires before a cell is selected.
56224 * @param {SelectionModel} this
56225 * @param {Number} rowIndex The selected row index
56226 * @param {Number} colIndex The selected cell index
56228 "beforecellselect" : true,
56230 * @event cellselect
56231 * Fires when a cell is selected.
56232 * @param {SelectionModel} this
56233 * @param {Number} rowIndex The selected row index
56234 * @param {Number} colIndex The selected cell index
56236 "cellselect" : true,
56238 * @event selectionchange
56239 * Fires when the active selection changes.
56240 * @param {SelectionModel} this
56241 * @param {Object} selection null for no selection or an object (o) with two properties
56243 <li>o.record: the record object for the row the selection is in</li>
56244 <li>o.cell: An array of [rowIndex, columnIndex]</li>
56247 "selectionchange" : true,
56250 * Fires when the tab (or enter) was pressed on the last editable cell
56251 * You can use this to trigger add new row.
56252 * @param {SelectionModel} this
56256 * @event beforeeditnext
56257 * Fires before the next editable sell is made active
56258 * You can use this to skip to another cell or fire the tabend
56259 * if you set cell to false
56260 * @param {Object} eventdata object : { cell : [ row, col ] }
56262 "beforeeditnext" : true
56264 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
56267 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
56269 enter_is_tab: false,
56272 initEvents : function(){
56273 this.grid.on("mousedown", this.handleMouseDown, this);
56274 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
56275 var view = this.grid.view;
56276 view.on("refresh", this.onViewChange, this);
56277 view.on("rowupdated", this.onRowUpdated, this);
56278 view.on("beforerowremoved", this.clearSelections, this);
56279 view.on("beforerowsinserted", this.clearSelections, this);
56280 if(this.grid.isEditor){
56281 this.grid.on("beforeedit", this.beforeEdit, this);
56286 beforeEdit : function(e){
56287 this.select(e.row, e.column, false, true, e.record);
56291 onRowUpdated : function(v, index, r){
56292 if(this.selection && this.selection.record == r){
56293 v.onCellSelect(index, this.selection.cell[1]);
56298 onViewChange : function(){
56299 this.clearSelections(true);
56303 * Returns the currently selected cell,.
56304 * @return {Array} The selected cell (row, column) or null if none selected.
56306 getSelectedCell : function(){
56307 return this.selection ? this.selection.cell : null;
56311 * Clears all selections.
56312 * @param {Boolean} true to prevent the gridview from being notified about the change.
56314 clearSelections : function(preventNotify){
56315 var s = this.selection;
56317 if(preventNotify !== true){
56318 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
56320 this.selection = null;
56321 this.fireEvent("selectionchange", this, null);
56326 * Returns true if there is a selection.
56327 * @return {Boolean}
56329 hasSelection : function(){
56330 return this.selection ? true : false;
56334 handleMouseDown : function(e, t){
56335 var v = this.grid.getView();
56336 if(this.isLocked()){
56339 var row = v.findRowIndex(t);
56340 var cell = v.findCellIndex(t);
56341 if(row !== false && cell !== false){
56342 this.select(row, cell);
56348 * @param {Number} rowIndex
56349 * @param {Number} collIndex
56351 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
56352 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
56353 this.clearSelections();
56354 r = r || this.grid.dataSource.getAt(rowIndex);
56357 cell : [rowIndex, colIndex]
56359 if(!preventViewNotify){
56360 var v = this.grid.getView();
56361 v.onCellSelect(rowIndex, colIndex);
56362 if(preventFocus !== true){
56363 v.focusCell(rowIndex, colIndex);
56366 this.fireEvent("cellselect", this, rowIndex, colIndex);
56367 this.fireEvent("selectionchange", this, this.selection);
56372 isSelectable : function(rowIndex, colIndex, cm){
56373 return !cm.isHidden(colIndex);
56377 handleKeyDown : function(e){
56378 //Roo.log('Cell Sel Model handleKeyDown');
56379 if(!e.isNavKeyPress()){
56382 var g = this.grid, s = this.selection;
56385 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
56387 this.select(cell[0], cell[1]);
56392 var walk = function(row, col, step){
56393 return g.walkCells(row, col, step, sm.isSelectable, sm);
56395 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
56402 // handled by onEditorKey
56403 if (g.isEditor && g.editing) {
56407 newCell = walk(r, c-1, -1);
56409 newCell = walk(r, c+1, 1);
56414 newCell = walk(r+1, c, 1);
56418 newCell = walk(r-1, c, -1);
56422 newCell = walk(r, c+1, 1);
56426 newCell = walk(r, c-1, -1);
56431 if(g.isEditor && !g.editing){
56432 g.startEditing(r, c);
56441 this.select(newCell[0], newCell[1]);
56447 acceptsNav : function(row, col, cm){
56448 return !cm.isHidden(col) && cm.isCellEditable(col, row);
56452 * @param {Number} field (not used) - as it's normally used as a listener
56453 * @param {Number} e - event - fake it by using
56455 * var e = Roo.EventObjectImpl.prototype;
56456 * e.keyCode = e.TAB
56460 onEditorKey : function(field, e){
56462 var k = e.getKey(),
56465 ed = g.activeEditor,
56467 ///Roo.log('onEditorKey' + k);
56470 if (this.enter_is_tab && k == e.ENTER) {
56476 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
56478 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56484 } else if(k == e.ENTER && !e.ctrlKey){
56487 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56489 } else if(k == e.ESC){
56494 var ecall = { cell : newCell, forward : forward };
56495 this.fireEvent('beforeeditnext', ecall );
56496 newCell = ecall.cell;
56497 forward = ecall.forward;
56501 //Roo.log('next cell after edit');
56502 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
56503 } else if (forward) {
56504 // tabbed past last
56505 this.fireEvent.defer(100, this, ['tabend',this]);
56510 * Ext JS Library 1.1.1
56511 * Copyright(c) 2006-2007, Ext JS, LLC.
56513 * Originally Released Under LGPL - original licence link has changed is not relivant.
56516 * <script type="text/javascript">
56520 * @class Roo.grid.EditorGrid
56521 * @extends Roo.grid.Grid
56522 * Class for creating and editable grid.
56523 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
56524 * The container MUST have some type of size defined for the grid to fill. The container will be
56525 * automatically set to position relative if it isn't already.
56526 * @param {Object} dataSource The data model to bind to
56527 * @param {Object} colModel The column model with info about this grid's columns
56529 Roo.grid.EditorGrid = function(container, config){
56530 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
56531 this.getGridEl().addClass("xedit-grid");
56533 if(!this.selModel){
56534 this.selModel = new Roo.grid.CellSelectionModel();
56537 this.activeEditor = null;
56541 * @event beforeedit
56542 * Fires before cell editing is triggered. The edit event object has the following properties <br />
56543 * <ul style="padding:5px;padding-left:16px;">
56544 * <li>grid - This grid</li>
56545 * <li>record - The record being edited</li>
56546 * <li>field - The field name being edited</li>
56547 * <li>value - The value for the field being edited.</li>
56548 * <li>row - The grid row index</li>
56549 * <li>column - The grid column index</li>
56550 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
56552 * @param {Object} e An edit event (see above for description)
56554 "beforeedit" : true,
56557 * Fires after a cell is edited. <br />
56558 * <ul style="padding:5px;padding-left:16px;">
56559 * <li>grid - This grid</li>
56560 * <li>record - The record being edited</li>
56561 * <li>field - The field name being edited</li>
56562 * <li>value - The value being set</li>
56563 * <li>originalValue - The original value for the field, before the edit.</li>
56564 * <li>row - The grid row index</li>
56565 * <li>column - The grid column index</li>
56567 * @param {Object} e An edit event (see above for description)
56569 "afteredit" : true,
56571 * @event validateedit
56572 * Fires after a cell is edited, but before the value is set in the record.
56573 * You can use this to modify the value being set in the field, Return false
56574 * to cancel the change. The edit event object has the following properties <br />
56575 * <ul style="padding:5px;padding-left:16px;">
56576 * <li>editor - This editor</li>
56577 * <li>grid - This grid</li>
56578 * <li>record - The record being edited</li>
56579 * <li>field - The field name being edited</li>
56580 * <li>value - The value being set</li>
56581 * <li>originalValue - The original value for the field, before the edit.</li>
56582 * <li>row - The grid row index</li>
56583 * <li>column - The grid column index</li>
56584 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
56586 * @param {Object} e An edit event (see above for description)
56588 "validateedit" : true
56590 this.on("bodyscroll", this.stopEditing, this);
56591 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
56594 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
56596 * @cfg {Number} clicksToEdit
56597 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
56604 trackMouseOver: false, // causes very odd FF errors
56606 onCellDblClick : function(g, row, col){
56607 this.startEditing(row, col);
56610 onEditComplete : function(ed, value, startValue){
56611 this.editing = false;
56612 this.activeEditor = null;
56613 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
56615 var field = this.colModel.getDataIndex(ed.col);
56620 originalValue: startValue,
56627 var cell = Roo.get(this.view.getCell(ed.row,ed.col))
56630 if(String(value) !== String(startValue)){
56632 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
56633 r.set(field, e.value);
56634 // if we are dealing with a combo box..
56635 // then we also set the 'name' colum to be the displayField
56636 if (ed.field.displayField && ed.field.name) {
56637 r.set(ed.field.name, ed.field.el.dom.value);
56640 delete e.cancel; //?? why!!!
56641 this.fireEvent("afteredit", e);
56644 this.fireEvent("afteredit", e); // always fire it!
56646 this.view.focusCell(ed.row, ed.col);
56650 * Starts editing the specified for the specified row/column
56651 * @param {Number} rowIndex
56652 * @param {Number} colIndex
56654 startEditing : function(row, col){
56655 this.stopEditing();
56656 if(this.colModel.isCellEditable(col, row)){
56657 this.view.ensureVisible(row, col, true);
56659 var r = this.dataSource.getAt(row);
56660 var field = this.colModel.getDataIndex(col);
56661 var cell = Roo.get(this.view.getCell(row,col));
56666 value: r.data[field],
56671 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
56672 this.editing = true;
56673 var ed = this.colModel.getCellEditor(col, row);
56679 ed.render(ed.parentEl || document.body);
56685 (function(){ // complex but required for focus issues in safari, ie and opera
56689 ed.on("complete", this.onEditComplete, this, {single: true});
56690 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
56691 this.activeEditor = ed;
56692 var v = r.data[field];
56693 ed.startEdit(this.view.getCell(row, col), v);
56694 // combo's with 'displayField and name set
56695 if (ed.field.displayField && ed.field.name) {
56696 ed.field.el.dom.value = r.data[ed.field.name];
56700 }).defer(50, this);
56706 * Stops any active editing
56708 stopEditing : function(){
56709 if(this.activeEditor){
56710 this.activeEditor.completeEdit();
56712 this.activeEditor = null;
56716 * Called to get grid's drag proxy text, by default returns this.ddText.
56719 getDragDropText : function(){
56720 var count = this.selModel.getSelectedCell() ? 1 : 0;
56721 return String.format(this.ddText, count, count == 1 ? '' : 's');
56726 * Ext JS Library 1.1.1
56727 * Copyright(c) 2006-2007, Ext JS, LLC.
56729 * Originally Released Under LGPL - original licence link has changed is not relivant.
56732 * <script type="text/javascript">
56735 // private - not really -- you end up using it !
56736 // This is a support class used internally by the Grid components
56739 * @class Roo.grid.GridEditor
56740 * @extends Roo.Editor
56741 * Class for creating and editable grid elements.
56742 * @param {Object} config any settings (must include field)
56744 Roo.grid.GridEditor = function(field, config){
56745 if (!config && field.field) {
56747 field = Roo.factory(config.field, Roo.form);
56749 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
56750 field.monitorTab = false;
56753 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
56756 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
56759 alignment: "tl-tl",
56762 cls: "x-small-editor x-grid-editor",
56767 * Ext JS Library 1.1.1
56768 * Copyright(c) 2006-2007, Ext JS, LLC.
56770 * Originally Released Under LGPL - original licence link has changed is not relivant.
56773 * <script type="text/javascript">
56778 Roo.grid.PropertyRecord = Roo.data.Record.create([
56779 {name:'name',type:'string'}, 'value'
56783 Roo.grid.PropertyStore = function(grid, source){
56785 this.store = new Roo.data.Store({
56786 recordType : Roo.grid.PropertyRecord
56788 this.store.on('update', this.onUpdate, this);
56790 this.setSource(source);
56792 Roo.grid.PropertyStore.superclass.constructor.call(this);
56797 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
56798 setSource : function(o){
56800 this.store.removeAll();
56803 if(this.isEditableValue(o[k])){
56804 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
56807 this.store.loadRecords({records: data}, {}, true);
56810 onUpdate : function(ds, record, type){
56811 if(type == Roo.data.Record.EDIT){
56812 var v = record.data['value'];
56813 var oldValue = record.modified['value'];
56814 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
56815 this.source[record.id] = v;
56817 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
56824 getProperty : function(row){
56825 return this.store.getAt(row);
56828 isEditableValue: function(val){
56829 if(val && val instanceof Date){
56831 }else if(typeof val == 'object' || typeof val == 'function'){
56837 setValue : function(prop, value){
56838 this.source[prop] = value;
56839 this.store.getById(prop).set('value', value);
56842 getSource : function(){
56843 return this.source;
56847 Roo.grid.PropertyColumnModel = function(grid, store){
56850 g.PropertyColumnModel.superclass.constructor.call(this, [
56851 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
56852 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
56854 this.store = store;
56855 this.bselect = Roo.DomHelper.append(document.body, {
56856 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
56857 {tag: 'option', value: 'true', html: 'true'},
56858 {tag: 'option', value: 'false', html: 'false'}
56861 Roo.id(this.bselect);
56864 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
56865 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
56866 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
56867 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
56868 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
56870 this.renderCellDelegate = this.renderCell.createDelegate(this);
56871 this.renderPropDelegate = this.renderProp.createDelegate(this);
56874 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
56878 valueText : 'Value',
56880 dateFormat : 'm/j/Y',
56883 renderDate : function(dateVal){
56884 return dateVal.dateFormat(this.dateFormat);
56887 renderBool : function(bVal){
56888 return bVal ? 'true' : 'false';
56891 isCellEditable : function(colIndex, rowIndex){
56892 return colIndex == 1;
56895 getRenderer : function(col){
56897 this.renderCellDelegate : this.renderPropDelegate;
56900 renderProp : function(v){
56901 return this.getPropertyName(v);
56904 renderCell : function(val){
56906 if(val instanceof Date){
56907 rv = this.renderDate(val);
56908 }else if(typeof val == 'boolean'){
56909 rv = this.renderBool(val);
56911 return Roo.util.Format.htmlEncode(rv);
56914 getPropertyName : function(name){
56915 var pn = this.grid.propertyNames;
56916 return pn && pn[name] ? pn[name] : name;
56919 getCellEditor : function(colIndex, rowIndex){
56920 var p = this.store.getProperty(rowIndex);
56921 var n = p.data['name'], val = p.data['value'];
56923 if(typeof(this.grid.customEditors[n]) == 'string'){
56924 return this.editors[this.grid.customEditors[n]];
56926 if(typeof(this.grid.customEditors[n]) != 'undefined'){
56927 return this.grid.customEditors[n];
56929 if(val instanceof Date){
56930 return this.editors['date'];
56931 }else if(typeof val == 'number'){
56932 return this.editors['number'];
56933 }else if(typeof val == 'boolean'){
56934 return this.editors['boolean'];
56936 return this.editors['string'];
56942 * @class Roo.grid.PropertyGrid
56943 * @extends Roo.grid.EditorGrid
56944 * This class represents the interface of a component based property grid control.
56945 * <br><br>Usage:<pre><code>
56946 var grid = new Roo.grid.PropertyGrid("my-container-id", {
56954 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
56955 * The container MUST have some type of size defined for the grid to fill. The container will be
56956 * automatically set to position relative if it isn't already.
56957 * @param {Object} config A config object that sets properties on this grid.
56959 Roo.grid.PropertyGrid = function(container, config){
56960 config = config || {};
56961 var store = new Roo.grid.PropertyStore(this);
56962 this.store = store;
56963 var cm = new Roo.grid.PropertyColumnModel(this, store);
56964 store.store.sort('name', 'ASC');
56965 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
56968 enableColLock:false,
56969 enableColumnMove:false,
56971 trackMouseOver: false,
56974 this.getGridEl().addClass('x-props-grid');
56975 this.lastEditRow = null;
56976 this.on('columnresize', this.onColumnResize, this);
56979 * @event beforepropertychange
56980 * Fires before a property changes (return false to stop?)
56981 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
56982 * @param {String} id Record Id
56983 * @param {String} newval New Value
56984 * @param {String} oldval Old Value
56986 "beforepropertychange": true,
56988 * @event propertychange
56989 * Fires after a property changes
56990 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
56991 * @param {String} id Record Id
56992 * @param {String} newval New Value
56993 * @param {String} oldval Old Value
56995 "propertychange": true
56997 this.customEditors = this.customEditors || {};
56999 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
57002 * @cfg {Object} customEditors map of colnames=> custom editors.
57003 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
57004 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
57005 * false disables editing of the field.
57009 * @cfg {Object} propertyNames map of property Names to their displayed value
57012 render : function(){
57013 Roo.grid.PropertyGrid.superclass.render.call(this);
57014 this.autoSize.defer(100, this);
57017 autoSize : function(){
57018 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
57020 this.view.fitColumns();
57024 onColumnResize : function(){
57025 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
57029 * Sets the data for the Grid
57030 * accepts a Key => Value object of all the elements avaiable.
57031 * @param {Object} data to appear in grid.
57033 setSource : function(source){
57034 this.store.setSource(source);
57038 * Gets all the data from the grid.
57039 * @return {Object} data data stored in grid
57041 getSource : function(){
57042 return this.store.getSource();
57051 * @class Roo.grid.Calendar
57052 * @extends Roo.util.Grid
57053 * This class extends the Grid to provide a calendar widget
57054 * <br><br>Usage:<pre><code>
57055 var grid = new Roo.grid.Calendar("my-container-id", {
57058 selModel: mySelectionModel,
57059 autoSizeColumns: true,
57060 monitorWindowResize: false,
57061 trackMouseOver: true
57062 eventstore : real data store..
57068 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
57069 * The container MUST have some type of size defined for the grid to fill. The container will be
57070 * automatically set to position relative if it isn't already.
57071 * @param {Object} config A config object that sets properties on this grid.
57073 Roo.grid.Calendar = function(container, config){
57074 // initialize the container
57075 this.container = Roo.get(container);
57076 this.container.update("");
57077 this.container.setStyle("overflow", "hidden");
57078 this.container.addClass('x-grid-container');
57080 this.id = this.container.id;
57082 Roo.apply(this, config);
57083 // check and correct shorthanded configs
57087 for (var r = 0;r < 6;r++) {
57090 for (var c =0;c < 7;c++) {
57094 if (this.eventStore) {
57095 this.eventStore= Roo.factory(this.eventStore, Roo.data);
57096 this.eventStore.on('load',this.onLoad, this);
57097 this.eventStore.on('beforeload',this.clearEvents, this);
57101 this.dataSource = new Roo.data.Store({
57102 proxy: new Roo.data.MemoryProxy(rows),
57103 reader: new Roo.data.ArrayReader({}, [
57104 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
57107 this.dataSource.load();
57108 this.ds = this.dataSource;
57109 this.ds.xmodule = this.xmodule || false;
57112 var cellRender = function(v,x,r)
57114 return String.format(
57115 '<div class="fc-day fc-widget-content"><div>' +
57116 '<div class="fc-event-container"></div>' +
57117 '<div class="fc-day-number">{0}</div>'+
57119 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
57120 '</div></div>', v);
57125 this.colModel = new Roo.grid.ColumnModel( [
57127 xtype: 'ColumnModel',
57129 dataIndex : 'weekday0',
57131 renderer : cellRender
57134 xtype: 'ColumnModel',
57136 dataIndex : 'weekday1',
57138 renderer : cellRender
57141 xtype: 'ColumnModel',
57143 dataIndex : 'weekday2',
57144 header : 'Tuesday',
57145 renderer : cellRender
57148 xtype: 'ColumnModel',
57150 dataIndex : 'weekday3',
57151 header : 'Wednesday',
57152 renderer : cellRender
57155 xtype: 'ColumnModel',
57157 dataIndex : 'weekday4',
57158 header : 'Thursday',
57159 renderer : cellRender
57162 xtype: 'ColumnModel',
57164 dataIndex : 'weekday5',
57166 renderer : cellRender
57169 xtype: 'ColumnModel',
57171 dataIndex : 'weekday6',
57172 header : 'Saturday',
57173 renderer : cellRender
57176 this.cm = this.colModel;
57177 this.cm.xmodule = this.xmodule || false;
57181 //this.selModel = new Roo.grid.CellSelectionModel();
57182 //this.sm = this.selModel;
57183 //this.selModel.init(this);
57187 this.container.setWidth(this.width);
57191 this.container.setHeight(this.height);
57198 * The raw click event for the entire grid.
57199 * @param {Roo.EventObject} e
57204 * The raw dblclick event for the entire grid.
57205 * @param {Roo.EventObject} e
57209 * @event contextmenu
57210 * The raw contextmenu event for the entire grid.
57211 * @param {Roo.EventObject} e
57213 "contextmenu" : true,
57216 * The raw mousedown event for the entire grid.
57217 * @param {Roo.EventObject} e
57219 "mousedown" : true,
57222 * The raw mouseup event for the entire grid.
57223 * @param {Roo.EventObject} e
57228 * The raw mouseover event for the entire grid.
57229 * @param {Roo.EventObject} e
57231 "mouseover" : true,
57234 * The raw mouseout event for the entire grid.
57235 * @param {Roo.EventObject} e
57240 * The raw keypress event for the entire grid.
57241 * @param {Roo.EventObject} e
57246 * The raw keydown event for the entire grid.
57247 * @param {Roo.EventObject} e
57255 * Fires when a cell is clicked
57256 * @param {Grid} this
57257 * @param {Number} rowIndex
57258 * @param {Number} columnIndex
57259 * @param {Roo.EventObject} e
57261 "cellclick" : true,
57263 * @event celldblclick
57264 * Fires when a cell is double clicked
57265 * @param {Grid} this
57266 * @param {Number} rowIndex
57267 * @param {Number} columnIndex
57268 * @param {Roo.EventObject} e
57270 "celldblclick" : true,
57273 * Fires when a row is clicked
57274 * @param {Grid} this
57275 * @param {Number} rowIndex
57276 * @param {Roo.EventObject} e
57280 * @event rowdblclick
57281 * Fires when a row is double clicked
57282 * @param {Grid} this
57283 * @param {Number} rowIndex
57284 * @param {Roo.EventObject} e
57286 "rowdblclick" : true,
57288 * @event headerclick
57289 * Fires when a header is clicked
57290 * @param {Grid} this
57291 * @param {Number} columnIndex
57292 * @param {Roo.EventObject} e
57294 "headerclick" : true,
57296 * @event headerdblclick
57297 * Fires when a header cell is double clicked
57298 * @param {Grid} this
57299 * @param {Number} columnIndex
57300 * @param {Roo.EventObject} e
57302 "headerdblclick" : true,
57304 * @event rowcontextmenu
57305 * Fires when a row is right clicked
57306 * @param {Grid} this
57307 * @param {Number} rowIndex
57308 * @param {Roo.EventObject} e
57310 "rowcontextmenu" : true,
57312 * @event cellcontextmenu
57313 * Fires when a cell is right clicked
57314 * @param {Grid} this
57315 * @param {Number} rowIndex
57316 * @param {Number} cellIndex
57317 * @param {Roo.EventObject} e
57319 "cellcontextmenu" : true,
57321 * @event headercontextmenu
57322 * Fires when a header is right clicked
57323 * @param {Grid} this
57324 * @param {Number} columnIndex
57325 * @param {Roo.EventObject} e
57327 "headercontextmenu" : true,
57329 * @event bodyscroll
57330 * Fires when the body element is scrolled
57331 * @param {Number} scrollLeft
57332 * @param {Number} scrollTop
57334 "bodyscroll" : true,
57336 * @event columnresize
57337 * Fires when the user resizes a column
57338 * @param {Number} columnIndex
57339 * @param {Number} newSize
57341 "columnresize" : true,
57343 * @event columnmove
57344 * Fires when the user moves a column
57345 * @param {Number} oldIndex
57346 * @param {Number} newIndex
57348 "columnmove" : true,
57351 * Fires when row(s) start being dragged
57352 * @param {Grid} this
57353 * @param {Roo.GridDD} dd The drag drop object
57354 * @param {event} e The raw browser event
57356 "startdrag" : true,
57359 * Fires when a drag operation is complete
57360 * @param {Grid} this
57361 * @param {Roo.GridDD} dd The drag drop object
57362 * @param {event} e The raw browser event
57367 * Fires when dragged row(s) are dropped on a valid DD target
57368 * @param {Grid} this
57369 * @param {Roo.GridDD} dd The drag drop object
57370 * @param {String} targetId The target drag drop object
57371 * @param {event} e The raw browser event
57376 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
57377 * @param {Grid} this
57378 * @param {Roo.GridDD} dd The drag drop object
57379 * @param {String} targetId The target drag drop object
57380 * @param {event} e The raw browser event
57385 * Fires when the dragged row(s) first cross another DD target while being dragged
57386 * @param {Grid} this
57387 * @param {Roo.GridDD} dd The drag drop object
57388 * @param {String} targetId The target drag drop object
57389 * @param {event} e The raw browser event
57391 "dragenter" : true,
57394 * Fires when the dragged row(s) leave another DD target while being dragged
57395 * @param {Grid} this
57396 * @param {Roo.GridDD} dd The drag drop object
57397 * @param {String} targetId The target drag drop object
57398 * @param {event} e The raw browser event
57403 * Fires when a row is rendered, so you can change add a style to it.
57404 * @param {GridView} gridview The grid view
57405 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
57411 * Fires when the grid is rendered
57412 * @param {Grid} grid
57417 * Fires when a date is selected
57418 * @param {DatePicker} this
57419 * @param {Date} date The selected date
57423 * @event monthchange
57424 * Fires when the displayed month changes
57425 * @param {DatePicker} this
57426 * @param {Date} date The selected month
57428 'monthchange': true,
57430 * @event evententer
57431 * Fires when mouse over an event
57432 * @param {Calendar} this
57433 * @param {event} Event
57435 'evententer': true,
57437 * @event eventleave
57438 * Fires when the mouse leaves an
57439 * @param {Calendar} this
57442 'eventleave': true,
57444 * @event eventclick
57445 * Fires when the mouse click an
57446 * @param {Calendar} this
57449 'eventclick': true,
57451 * @event eventrender
57452 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
57453 * @param {Calendar} this
57454 * @param {data} data to be modified
57456 'eventrender': true
57460 Roo.grid.Grid.superclass.constructor.call(this);
57461 this.on('render', function() {
57462 this.view.el.addClass('x-grid-cal');
57464 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
57468 if (!Roo.grid.Calendar.style) {
57469 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
57472 '.x-grid-cal .x-grid-col' : {
57473 height: 'auto !important',
57474 'vertical-align': 'top'
57476 '.x-grid-cal .fc-event-hori' : {
57487 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
57489 * @cfg {Store} eventStore The store that loads events.
57494 activeDate : false,
57497 monitorWindowResize : false,
57500 resizeColumns : function() {
57501 var col = (this.view.el.getWidth() / 7) - 3;
57502 // loop through cols, and setWidth
57503 for(var i =0 ; i < 7 ; i++){
57504 this.cm.setColumnWidth(i, col);
57507 setDate :function(date) {
57509 Roo.log('setDate?');
57511 this.resizeColumns();
57512 var vd = this.activeDate;
57513 this.activeDate = date;
57514 // if(vd && this.el){
57515 // var t = date.getTime();
57516 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
57517 // Roo.log('using add remove');
57519 // this.fireEvent('monthchange', this, date);
57521 // this.cells.removeClass("fc-state-highlight");
57522 // this.cells.each(function(c){
57523 // if(c.dateValue == t){
57524 // c.addClass("fc-state-highlight");
57525 // setTimeout(function(){
57526 // try{c.dom.firstChild.focus();}catch(e){}
57536 var days = date.getDaysInMonth();
57538 var firstOfMonth = date.getFirstDateOfMonth();
57539 var startingPos = firstOfMonth.getDay()-this.startDay;
57541 if(startingPos < this.startDay){
57545 var pm = date.add(Date.MONTH, -1);
57546 var prevStart = pm.getDaysInMonth()-startingPos;
57550 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
57552 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
57553 //this.cells.addClassOnOver('fc-state-hover');
57555 var cells = this.cells.elements;
57556 var textEls = this.textNodes;
57558 //Roo.each(cells, function(cell){
57559 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
57562 days += startingPos;
57564 // convert everything to numbers so it's fast
57565 var day = 86400000;
57566 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
57569 //Roo.log(prevStart);
57571 var today = new Date().clearTime().getTime();
57572 var sel = date.clearTime().getTime();
57573 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
57574 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
57575 var ddMatch = this.disabledDatesRE;
57576 var ddText = this.disabledDatesText;
57577 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
57578 var ddaysText = this.disabledDaysText;
57579 var format = this.format;
57581 var setCellClass = function(cal, cell){
57583 //Roo.log('set Cell Class');
57585 var t = d.getTime();
57590 cell.dateValue = t;
57592 cell.className += " fc-today";
57593 cell.className += " fc-state-highlight";
57594 cell.title = cal.todayText;
57597 // disable highlight in other month..
57598 cell.className += " fc-state-highlight";
57603 //cell.className = " fc-state-disabled";
57604 cell.title = cal.minText;
57608 //cell.className = " fc-state-disabled";
57609 cell.title = cal.maxText;
57613 if(ddays.indexOf(d.getDay()) != -1){
57614 // cell.title = ddaysText;
57615 // cell.className = " fc-state-disabled";
57618 if(ddMatch && format){
57619 var fvalue = d.dateFormat(format);
57620 if(ddMatch.test(fvalue)){
57621 cell.title = ddText.replace("%0", fvalue);
57622 cell.className = " fc-state-disabled";
57626 if (!cell.initialClassName) {
57627 cell.initialClassName = cell.dom.className;
57630 cell.dom.className = cell.initialClassName + ' ' + cell.className;
57635 for(; i < startingPos; i++) {
57636 cells[i].dayName = (++prevStart);
57637 Roo.log(textEls[i]);
57638 d.setDate(d.getDate()+1);
57640 //cells[i].className = "fc-past fc-other-month";
57641 setCellClass(this, cells[i]);
57646 for(; i < days; i++){
57647 intDay = i - startingPos + 1;
57648 cells[i].dayName = (intDay);
57649 d.setDate(d.getDate()+1);
57651 cells[i].className = ''; // "x-date-active";
57652 setCellClass(this, cells[i]);
57656 for(; i < 42; i++) {
57657 //textEls[i].innerHTML = (++extraDays);
57659 d.setDate(d.getDate()+1);
57660 cells[i].dayName = (++extraDays);
57661 cells[i].className = "fc-future fc-other-month";
57662 setCellClass(this, cells[i]);
57665 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
57667 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
57669 // this will cause all the cells to mis
57672 for (var r = 0;r < 6;r++) {
57673 for (var c =0;c < 7;c++) {
57674 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
57678 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
57679 for(i=0;i<cells.length;i++) {
57681 this.cells.elements[i].dayName = cells[i].dayName ;
57682 this.cells.elements[i].className = cells[i].className;
57683 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
57684 this.cells.elements[i].title = cells[i].title ;
57685 this.cells.elements[i].dateValue = cells[i].dateValue ;
57691 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
57692 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
57694 ////if(totalRows != 6){
57695 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
57696 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
57699 this.fireEvent('monthchange', this, date);
57704 * Returns the grid's SelectionModel.
57705 * @return {SelectionModel}
57707 getSelectionModel : function(){
57708 if(!this.selModel){
57709 this.selModel = new Roo.grid.CellSelectionModel();
57711 return this.selModel;
57715 this.eventStore.load()
57721 findCell : function(dt) {
57722 dt = dt.clearTime().getTime();
57724 this.cells.each(function(c){
57725 //Roo.log("check " +c.dateValue + '?=' + dt);
57726 if(c.dateValue == dt){
57736 findCells : function(rec) {
57737 var s = rec.data.start_dt.clone().clearTime().getTime();
57739 var e= rec.data.end_dt.clone().clearTime().getTime();
57742 this.cells.each(function(c){
57743 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
57745 if(c.dateValue > e){
57748 if(c.dateValue < s){
57757 findBestRow: function(cells)
57761 for (var i =0 ; i < cells.length;i++) {
57762 ret = Math.max(cells[i].rows || 0,ret);
57769 addItem : function(rec)
57771 // look for vertical location slot in
57772 var cells = this.findCells(rec);
57774 rec.row = this.findBestRow(cells);
57776 // work out the location.
57780 for(var i =0; i < cells.length; i++) {
57788 if (crow.start.getY() == cells[i].getY()) {
57790 crow.end = cells[i];
57806 for (var i = 0; i < cells.length;i++) {
57807 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
57814 clearEvents: function() {
57816 if (!this.eventStore.getCount()) {
57819 // reset number of rows in cells.
57820 Roo.each(this.cells.elements, function(c){
57824 this.eventStore.each(function(e) {
57825 this.clearEvent(e);
57830 clearEvent : function(ev)
57833 Roo.each(ev.els, function(el) {
57834 el.un('mouseenter' ,this.onEventEnter, this);
57835 el.un('mouseleave' ,this.onEventLeave, this);
57843 renderEvent : function(ev,ctr) {
57845 ctr = this.view.el.select('.fc-event-container',true).first();
57849 this.clearEvent(ev);
57855 var cells = ev.cells;
57856 var rows = ev.rows;
57857 this.fireEvent('eventrender', this, ev);
57859 for(var i =0; i < rows.length; i++) {
57863 cls += ' fc-event-start';
57865 if ((i+1) == rows.length) {
57866 cls += ' fc-event-end';
57869 //Roo.log(ev.data);
57870 // how many rows should it span..
57871 var cg = this.eventTmpl.append(ctr,Roo.apply({
57874 }, ev.data) , true);
57877 cg.on('mouseenter' ,this.onEventEnter, this, ev);
57878 cg.on('mouseleave' ,this.onEventLeave, this, ev);
57879 cg.on('click', this.onEventClick, this, ev);
57883 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
57884 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
57887 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
57888 cg.setWidth(ebox.right - sbox.x -2);
57892 renderEvents: function()
57894 // first make sure there is enough space..
57896 if (!this.eventTmpl) {
57897 this.eventTmpl = new Roo.Template(
57898 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
57899 '<div class="fc-event-inner">' +
57900 '<span class="fc-event-time">{time}</span>' +
57901 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
57903 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
57911 this.cells.each(function(c) {
57912 //Roo.log(c.select('.fc-day-content div',true).first());
57913 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
57916 var ctr = this.view.el.select('.fc-event-container',true).first();
57919 this.eventStore.each(function(ev){
57921 this.renderEvent(ev);
57925 this.view.layout();
57929 onEventEnter: function (e, el,event,d) {
57930 this.fireEvent('evententer', this, el, event);
57933 onEventLeave: function (e, el,event,d) {
57934 this.fireEvent('eventleave', this, el, event);
57937 onEventClick: function (e, el,event,d) {
57938 this.fireEvent('eventclick', this, el, event);
57941 onMonthChange: function () {
57945 onLoad: function () {
57947 //Roo.log('calendar onload');
57949 if(this.eventStore.getCount() > 0){
57953 this.eventStore.each(function(d){
57958 if (typeof(add.end_dt) == 'undefined') {
57959 Roo.log("Missing End time in calendar data: ");
57963 if (typeof(add.start_dt) == 'undefined') {
57964 Roo.log("Missing Start time in calendar data: ");
57968 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
57969 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
57970 add.id = add.id || d.id;
57971 add.title = add.title || '??';
57979 this.renderEvents();
57989 render : function ()
57993 if (!this.view.el.hasClass('course-timesheet')) {
57994 this.view.el.addClass('course-timesheet');
57996 if (this.tsStyle) {
58001 Roo.log(_this.grid.view.el.getWidth());
58004 this.tsStyle = Roo.util.CSS.createStyleSheet({
58005 '.course-timesheet .x-grid-row' : {
58008 '.x-grid-row td' : {
58009 'vertical-align' : 0
58011 '.course-edit-link' : {
58013 'text-overflow' : 'ellipsis',
58014 'overflow' : 'hidden',
58015 'white-space' : 'nowrap',
58016 'cursor' : 'pointer'
58021 '.de-act-sup-link' : {
58022 'color' : 'purple',
58023 'text-decoration' : 'line-through'
58027 'text-decoration' : 'line-through'
58029 '.course-timesheet .course-highlight' : {
58030 'border-top-style': 'dashed !important',
58031 'border-bottom-bottom': 'dashed !important'
58033 '.course-timesheet .course-item' : {
58034 'font-family' : 'tahoma, arial, helvetica',
58035 'font-size' : '11px',
58036 'overflow' : 'hidden',
58037 'padding-left' : '10px',
58038 'padding-right' : '10px',
58039 'padding-top' : '10px'
58047 monitorWindowResize : false,
58048 cellrenderer : function(v,x,r)
58053 xtype: 'CellSelectionModel',
58060 beforeload : function (_self, options)
58062 options.params = options.params || {};
58063 options.params._month = _this.monthField.getValue();
58064 options.params.limit = 9999;
58065 options.params['sort'] = 'when_dt';
58066 options.params['dir'] = 'ASC';
58067 this.proxy.loadResponse = this.loadResponse;
58069 //this.addColumns();
58071 load : function (_self, records, options)
58073 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
58074 // if you click on the translation.. you can edit it...
58075 var el = Roo.get(this);
58076 var id = el.dom.getAttribute('data-id');
58077 var d = el.dom.getAttribute('data-date');
58078 var t = el.dom.getAttribute('data-time');
58079 //var id = this.child('span').dom.textContent;
58082 Pman.Dialog.CourseCalendar.show({
58086 productitem_active : id ? 1 : 0
58088 _this.grid.ds.load({});
58093 _this.panel.fireEvent('resize', [ '', '' ]);
58096 loadResponse : function(o, success, response){
58097 // this is overridden on before load..
58099 Roo.log("our code?");
58100 //Roo.log(success);
58101 //Roo.log(response)
58102 delete this.activeRequest;
58104 this.fireEvent("loadexception", this, o, response);
58105 o.request.callback.call(o.request.scope, null, o.request.arg, false);
58110 result = o.reader.read(response);
58112 Roo.log("load exception?");
58113 this.fireEvent("loadexception", this, o, response, e);
58114 o.request.callback.call(o.request.scope, null, o.request.arg, false);
58117 Roo.log("ready...");
58118 // loop through result.records;
58119 // and set this.tdate[date] = [] << array of records..
58121 Roo.each(result.records, function(r){
58123 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
58124 _this.tdata[r.data.when_dt.format('j')] = [];
58126 _this.tdata[r.data.when_dt.format('j')].push(r.data);
58129 //Roo.log(_this.tdata);
58131 result.records = [];
58132 result.totalRecords = 6;
58134 // let's generate some duumy records for the rows.
58135 //var st = _this.dateField.getValue();
58137 // work out monday..
58138 //st = st.add(Date.DAY, -1 * st.format('w'));
58140 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58142 var firstOfMonth = date.getFirstDayOfMonth();
58143 var days = date.getDaysInMonth();
58145 var firstAdded = false;
58146 for (var i = 0; i < result.totalRecords ; i++) {
58147 //var d= st.add(Date.DAY, i);
58150 for(var w = 0 ; w < 7 ; w++){
58151 if(!firstAdded && firstOfMonth != w){
58158 var dd = (d > 0 && d < 10) ? "0"+d : d;
58159 row['weekday'+w] = String.format(
58160 '<span style="font-size: 16px;"><b>{0}</b></span>'+
58161 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
58163 date.format('Y-m-')+dd
58166 if(typeof(_this.tdata[d]) != 'undefined'){
58167 Roo.each(_this.tdata[d], function(r){
58171 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
58172 if(r.parent_id*1>0){
58173 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
58176 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
58177 deactive = 'de-act-link';
58180 row['weekday'+w] += String.format(
58181 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
58183 r.product_id_name, //1
58184 r.when_dt.format('h:ia'), //2
58194 // only do this if something added..
58196 result.records.push(_this.grid.dataSource.reader.newRow(row));
58200 // push it twice. (second one with an hour..
58204 this.fireEvent("load", this, o, o.request.arg);
58205 o.request.callback.call(o.request.scope, result, o.request.arg, true);
58207 sortInfo : {field: 'when_dt', direction : 'ASC' },
58209 xtype: 'HttpProxy',
58212 url : baseURL + '/Roo/Shop_course.php'
58215 xtype: 'JsonReader',
58232 'name': 'parent_id',
58236 'name': 'product_id',
58240 'name': 'productitem_id',
58258 click : function (_self, e)
58260 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58261 sd.setMonth(sd.getMonth()-1);
58262 _this.monthField.setValue(sd.format('Y-m-d'));
58263 _this.grid.ds.load({});
58269 xtype: 'Separator',
58273 xtype: 'MonthField',
58276 render : function (_self)
58278 _this.monthField = _self;
58279 // _this.monthField.set today
58281 select : function (combo, date)
58283 _this.grid.ds.load({});
58286 value : (function() { return new Date(); })()
58289 xtype: 'Separator',
58295 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
58305 click : function (_self, e)
58307 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58308 sd.setMonth(sd.getMonth()+1);
58309 _this.monthField.setValue(sd.format('Y-m-d'));
58310 _this.grid.ds.load({});
58323 * Ext JS Library 1.1.1
58324 * Copyright(c) 2006-2007, Ext JS, LLC.
58326 * Originally Released Under LGPL - original licence link has changed is not relivant.
58329 * <script type="text/javascript">
58333 * @class Roo.LoadMask
58334 * A simple utility class for generically masking elements while loading data. If the element being masked has
58335 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
58336 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
58337 * element's UpdateManager load indicator and will be destroyed after the initial load.
58339 * Create a new LoadMask
58340 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
58341 * @param {Object} config The config object
58343 Roo.LoadMask = function(el, config){
58344 this.el = Roo.get(el);
58345 Roo.apply(this, config);
58347 this.store.on('beforeload', this.onBeforeLoad, this);
58348 this.store.on('load', this.onLoad, this);
58349 this.store.on('loadexception', this.onLoadException, this);
58350 this.removeMask = false;
58352 var um = this.el.getUpdateManager();
58353 um.showLoadIndicator = false; // disable the default indicator
58354 um.on('beforeupdate', this.onBeforeLoad, this);
58355 um.on('update', this.onLoad, this);
58356 um.on('failure', this.onLoad, this);
58357 this.removeMask = true;
58361 Roo.LoadMask.prototype = {
58363 * @cfg {Boolean} removeMask
58364 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
58365 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
58368 * @cfg {String} msg
58369 * The text to display in a centered loading message box (defaults to 'Loading...')
58371 msg : 'Loading...',
58373 * @cfg {String} msgCls
58374 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
58376 msgCls : 'x-mask-loading',
58379 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
58385 * Disables the mask to prevent it from being displayed
58387 disable : function(){
58388 this.disabled = true;
58392 * Enables the mask so that it can be displayed
58394 enable : function(){
58395 this.disabled = false;
58398 onLoadException : function()
58400 Roo.log(arguments);
58402 if (typeof(arguments[3]) != 'undefined') {
58403 Roo.MessageBox.alert("Error loading",arguments[3]);
58407 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
58408 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
58417 this.el.unmask(this.removeMask);
58420 onLoad : function()
58422 this.el.unmask(this.removeMask);
58426 onBeforeLoad : function(){
58427 if(!this.disabled){
58428 this.el.mask(this.msg, this.msgCls);
58433 destroy : function(){
58435 this.store.un('beforeload', this.onBeforeLoad, this);
58436 this.store.un('load', this.onLoad, this);
58437 this.store.un('loadexception', this.onLoadException, this);
58439 var um = this.el.getUpdateManager();
58440 um.un('beforeupdate', this.onBeforeLoad, this);
58441 um.un('update', this.onLoad, this);
58442 um.un('failure', this.onLoad, this);
58447 * Ext JS Library 1.1.1
58448 * Copyright(c) 2006-2007, Ext JS, LLC.
58450 * Originally Released Under LGPL - original licence link has changed is not relivant.
58453 * <script type="text/javascript">
58458 * @class Roo.XTemplate
58459 * @extends Roo.Template
58460 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
58462 var t = new Roo.XTemplate(
58463 '<select name="{name}">',
58464 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
58468 // then append, applying the master template values
58471 * Supported features:
58476 {a_variable} - output encoded.
58477 {a_variable.format:("Y-m-d")} - call a method on the variable
58478 {a_variable:raw} - unencoded output
58479 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
58480 {a_variable:this.method_on_template(...)} - call a method on the template object.
58485 <tpl for="a_variable or condition.."></tpl>
58486 <tpl if="a_variable or condition"></tpl>
58487 <tpl exec="some javascript"></tpl>
58488 <tpl name="named_template"></tpl> (experimental)
58490 <tpl for="."></tpl> - just iterate the property..
58491 <tpl for=".."></tpl> - iterates with the parent (probably the template)
58495 Roo.XTemplate = function()
58497 Roo.XTemplate.superclass.constructor.apply(this, arguments);
58504 Roo.extend(Roo.XTemplate, Roo.Template, {
58507 * The various sub templates
58512 * basic tag replacing syntax
58515 * // you can fake an object call by doing this
58519 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
58522 * compile the template
58524 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
58527 compile: function()
58531 s = ['<tpl>', s, '</tpl>'].join('');
58533 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
58534 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
58535 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
58536 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
58537 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
58542 while(true == !!(m = s.match(re))){
58543 var forMatch = m[0].match(nameRe),
58544 ifMatch = m[0].match(ifRe),
58545 execMatch = m[0].match(execRe),
58546 namedMatch = m[0].match(namedRe),
58551 name = forMatch && forMatch[1] ? forMatch[1] : '';
58554 // if - puts fn into test..
58555 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
58557 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
58562 // exec - calls a function... returns empty if true is returned.
58563 exp = execMatch && execMatch[1] ? execMatch[1] : null;
58565 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
58573 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
58574 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
58575 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
58578 var uid = namedMatch ? namedMatch[1] : id;
58582 id: namedMatch ? namedMatch[1] : id,
58589 s = s.replace(m[0], '');
58591 s = s.replace(m[0], '{xtpl'+ id + '}');
58596 for(var i = tpls.length-1; i >= 0; --i){
58597 this.compileTpl(tpls[i]);
58598 this.tpls[tpls[i].id] = tpls[i];
58600 this.master = tpls[tpls.length-1];
58604 * same as applyTemplate, except it's done to one of the subTemplates
58605 * when using named templates, you can do:
58607 * var str = pl.applySubTemplate('your-name', values);
58610 * @param {Number} id of the template
58611 * @param {Object} values to apply to template
58612 * @param {Object} parent (normaly the instance of this object)
58614 applySubTemplate : function(id, values, parent)
58618 var t = this.tpls[id];
58622 if(t.test && !t.test.call(this, values, parent)){
58626 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
58627 Roo.log(e.toString());
58633 if(t.exec && t.exec.call(this, values, parent)){
58637 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
58638 Roo.log(e.toString());
58643 var vs = t.target ? t.target.call(this, values, parent) : values;
58644 parent = t.target ? values : parent;
58645 if(t.target && vs instanceof Array){
58647 for(var i = 0, len = vs.length; i < len; i++){
58648 buf[buf.length] = t.compiled.call(this, vs[i], parent);
58650 return buf.join('');
58652 return t.compiled.call(this, vs, parent);
58654 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
58655 Roo.log(e.toString());
58656 Roo.log(t.compiled);
58661 compileTpl : function(tpl)
58663 var fm = Roo.util.Format;
58664 var useF = this.disableFormats !== true;
58665 var sep = Roo.isGecko ? "+" : ",";
58666 var undef = function(str) {
58667 Roo.log("Property not found :" + str);
58671 var fn = function(m, name, format, args)
58673 //Roo.log(arguments);
58674 args = args ? args.replace(/\\'/g,"'") : args;
58675 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
58676 if (typeof(format) == 'undefined') {
58677 format= 'htmlEncode';
58679 if (format == 'raw' ) {
58683 if(name.substr(0, 4) == 'xtpl'){
58684 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
58687 // build an array of options to determine if value is undefined..
58689 // basically get 'xxxx.yyyy' then do
58690 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
58691 // (function () { Roo.log("Property not found"); return ''; })() :
58696 Roo.each(name.split('.'), function(st) {
58697 lookfor += (lookfor.length ? '.': '') + st;
58698 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
58701 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
58704 if(format && useF){
58706 args = args ? ',' + args : "";
58708 if(format.substr(0, 5) != "this."){
58709 format = "fm." + format + '(';
58711 format = 'this.call("'+ format.substr(5) + '", ';
58715 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
58719 // called with xxyx.yuu:(test,test)
58721 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
58723 // raw.. - :raw modifier..
58724 return "'"+ sep + udef_st + name + ")"+sep+"'";
58728 // branched to use + in gecko and [].join() in others
58730 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
58731 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
58734 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
58735 body.push(tpl.body.replace(/(\r\n|\n)/g,
58736 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
58737 body.push("'].join('');};};");
58738 body = body.join('');
58741 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
58743 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
58749 applyTemplate : function(values){
58750 return this.master.compiled.call(this, values, {});
58751 //var s = this.subs;
58754 apply : function(){
58755 return this.applyTemplate.apply(this, arguments);
58760 Roo.XTemplate.from = function(el){
58761 el = Roo.getDom(el);
58762 return new Roo.XTemplate(el.value || el.innerHTML);