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 = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
65 // remove css image flicker
68 document.execCommand("BackgroundImageCache", false, true);
74 * True if the browser is in strict mode
79 * True if the page is running over SSL
84 * True when the document is fully initialized and ready for action
89 * Turn on debugging output (currently only the factory uses this)
96 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
99 enableGarbageCollector : true,
102 * True to automatically purge event listeners after uncaching an element (defaults to false).
103 * Note: this only happens if enableGarbageCollector is true.
106 enableListenerCollection:false,
109 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
110 * the IE insecure content warning (defaults to javascript:false).
113 SSL_SECURE_URL : "javascript:false",
116 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
117 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
120 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
122 emptyFn : function(){},
125 * Copies all the properties of config to obj if they don't already exist.
126 * @param {Object} obj The receiver of the properties
127 * @param {Object} config The source of the properties
128 * @return {Object} returns obj
130 applyIf : function(o, c){
133 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
140 * Applies event listeners to elements by selectors when the document is ready.
141 * The event name is specified with an @ suffix.
144 // add a listener for click on all anchors in element with id foo
145 '#foo a@click' : function(e, t){
149 // add the same listener to multiple selectors (separated by comma BEFORE the @)
150 '#foo a, #bar span.some-class@mouseover' : function(){
155 * @param {Object} obj The list of behaviors to apply
157 addBehaviors : function(o){
159 Roo.onReady(function(){
164 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
166 var parts = b.split('@');
167 if(parts[1]){ // for Object prototype breakers
170 cache[s] = Roo.select(s);
172 cache[s].on(parts[1], o[b]);
179 * Generates unique ids. If the element already has an id, it is unchanged
180 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
181 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
182 * @return {String} The generated Id.
184 id : function(el, prefix){
185 prefix = prefix || "roo-gen";
187 var id = prefix + (++idSeed);
188 return el ? (el.id ? el.id : (el.id = id)) : id;
193 * Extends one class with another class and optionally overrides members with the passed literal. This class
194 * also adds the function "override()" to the class that can be used to override
195 * members on an instance.
196 * @param {Object} subclass The class inheriting the functionality
197 * @param {Object} superclass The class being extended
198 * @param {Object} overrides (optional) A literal with members
203 var io = function(o){
208 return function(sb, sp, overrides){
209 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
212 sb = function(){sp.apply(this, arguments);};
214 var F = function(){}, sbp, spp = sp.prototype;
216 sbp = sb.prototype = new F();
220 if(spp.constructor == Object.prototype.constructor){
225 sb.override = function(o){
229 Roo.override(sb, overrides);
235 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
237 Roo.override(MyClass, {
238 newMethod1: function(){
241 newMethod2: function(foo){
246 * @param {Object} origclass The class to override
247 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
248 * containing one or more methods.
251 override : function(origclass, overrides){
253 var p = origclass.prototype;
254 for(var method in overrides){
255 p[method] = overrides[method];
260 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
262 Roo.namespace('Company', 'Company.data');
263 Company.Widget = function() { ... }
264 Company.data.CustomStore = function(config) { ... }
266 * @param {String} namespace1
267 * @param {String} namespace2
268 * @param {String} etc
271 namespace : function(){
272 var a=arguments, o=null, i, j, d, rt;
273 for (i=0; i<a.length; ++i) {
277 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
278 for (j=1; j<d.length; ++j) {
279 o[d[j]]=o[d[j]] || {};
285 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
287 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
288 Roo.factory(conf, Roo.data);
290 * @param {String} classname
291 * @param {String} namespace (optional)
295 factory : function(c, ns)
297 // no xtype, no ns or c.xns - or forced off by c.xns
298 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
301 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
302 if (c.constructor == ns[c.xtype]) {// already created...
306 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
307 var ret = new ns[c.xtype](c);
311 c.xns = false; // prevent recursion..
315 * Logs to console if it can.
317 * @param {String|Object} string
322 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
329 * 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.
333 urlEncode : function(o){
339 var ov = o[key], k = Roo.encodeURIComponent(key);
340 var type = typeof ov;
341 if(type == 'undefined'){
343 }else if(type != "function" && type != "object"){
344 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
345 }else if(ov instanceof Array){
347 for(var i = 0, len = ov.length; i < len; i++) {
348 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
359 * Safe version of encodeURIComponent
360 * @param {String} data
364 encodeURIComponent : function (data)
367 return encodeURIComponent(data);
368 } catch(e) {} // should be an uri encode error.
370 if (data == '' || data == null){
373 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
374 function nibble_to_hex(nibble){
375 var chars = '0123456789ABCDEF';
376 return chars.charAt(nibble);
378 data = data.toString();
380 for(var i=0; i<data.length; i++){
381 var c = data.charCodeAt(i);
382 var bs = new Array();
385 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
386 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
387 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
388 bs[3] = 0x80 | (c & 0x3F);
389 }else if (c > 0x800){
391 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
392 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
393 bs[2] = 0x80 | (c & 0x3F);
396 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
397 bs[1] = 0x80 | (c & 0x3F);
402 for(var j=0; j<bs.length; j++){
404 var hex = nibble_to_hex((b & 0xF0) >>> 4)
405 + nibble_to_hex(b &0x0F);
414 * 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]}.
415 * @param {String} string
416 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
417 * @return {Object} A literal with members
419 urlDecode : function(string, overwrite){
420 if(!string || !string.length){
424 var pairs = string.split('&');
425 var pair, name, value;
426 for(var i = 0, len = pairs.length; i < len; i++){
427 pair = pairs[i].split('=');
428 name = decodeURIComponent(pair[0]);
429 value = decodeURIComponent(pair[1]);
430 if(overwrite !== true){
431 if(typeof obj[name] == "undefined"){
433 }else if(typeof obj[name] == "string"){
434 obj[name] = [obj[name]];
435 obj[name].push(value);
437 obj[name].push(value);
447 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
448 * passed array is not really an array, your function is called once with it.
449 * The supplied function is called with (Object item, Number index, Array allItems).
450 * @param {Array/NodeList/Mixed} array
451 * @param {Function} fn
452 * @param {Object} scope
454 each : function(array, fn, scope){
455 if(typeof array.length == "undefined" || typeof array == "string"){
458 for(var i = 0, len = array.length; i < len; i++){
459 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
464 combine : function(){
465 var as = arguments, l = as.length, r = [];
466 for(var i = 0; i < l; i++){
468 if(a instanceof Array){
470 }else if(a.length !== undefined && !a.substr){
471 r = r.concat(Array.prototype.slice.call(a, 0));
480 * Escapes the passed string for use in a regular expression
481 * @param {String} str
484 escapeRe : function(s) {
485 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
489 callback : function(cb, scope, args, delay){
490 if(typeof cb == "function"){
492 cb.defer(delay, scope, args || []);
494 cb.apply(scope, args || []);
500 * Return the dom node for the passed string (id), dom node, or Roo.Element
501 * @param {String/HTMLElement/Roo.Element} el
502 * @return HTMLElement
504 getDom : function(el){
508 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
512 * Shorthand for {@link Roo.ComponentMgr#get}
514 * @return Roo.Component
516 getCmp : function(id){
517 return Roo.ComponentMgr.get(id);
520 num : function(v, defaultValue){
521 if(typeof v != 'number'){
527 destroy : function(){
528 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
532 as.removeAllListeners();
536 if(typeof as.purgeListeners == 'function'){
539 if(typeof as.destroy == 'function'){
546 // inpired by a similar function in mootools library
548 * Returns the type of object that is passed in. If the object passed in is null or undefined it
549 * return false otherwise it returns one of the following values:<ul>
550 * <li><b>string</b>: If the object passed is a string</li>
551 * <li><b>number</b>: If the object passed is a number</li>
552 * <li><b>boolean</b>: If the object passed is a boolean value</li>
553 * <li><b>function</b>: If the object passed is a function reference</li>
554 * <li><b>object</b>: If the object passed is an object</li>
555 * <li><b>array</b>: If the object passed is an array</li>
556 * <li><b>regexp</b>: If the object passed is a regular expression</li>
557 * <li><b>element</b>: If the object passed is a DOM Element</li>
558 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
559 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
560 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
561 * @param {Mixed} object
565 if(o === undefined || o === null){
572 if(t == 'object' && o.nodeName) {
574 case 1: return 'element';
575 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
578 if(t == 'object' || t == 'function') {
579 switch(o.constructor) {
580 case Array: return 'array';
581 case RegExp: return 'regexp';
583 if(typeof o.length == 'number' && typeof o.item == 'function') {
591 * Returns true if the passed value is null, undefined or an empty string (optional).
592 * @param {Mixed} value The value to test
593 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
596 isEmpty : function(v, allowBlank){
597 return v === null || v === undefined || (!allowBlank ? v === '' : false);
611 isBorderBox : isBorderBox,
613 isWindows : isWindows,
622 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
623 * you may want to set this to true.
626 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
631 * Selects a single element as a Roo Element
632 * This is about as close as you can get to jQuery's $('do crazy stuff')
633 * @param {String} selector The selector/xpath query
634 * @param {Node} root (optional) The start of the query (defaults to document).
635 * @return {Roo.Element}
637 selectNode : function(selector, root)
639 var node = Roo.DomQuery.selectNode(selector,root);
640 return node ? Roo.get(node) : new Roo.Element(false);
648 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
649 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");
652 * Ext JS Library 1.1.1
653 * Copyright(c) 2006-2007, Ext JS, LLC.
655 * Originally Released Under LGPL - original licence link has changed is not relivant.
658 * <script type="text/javascript">
662 // wrappedn so fnCleanup is not in global scope...
664 function fnCleanUp() {
665 var p = Function.prototype;
666 delete p.createSequence;
668 delete p.createDelegate;
669 delete p.createCallback;
670 delete p.createInterceptor;
672 window.detachEvent("onunload", fnCleanUp);
674 window.attachEvent("onunload", fnCleanUp);
681 * These functions are available on every Function object (any JavaScript function).
683 Roo.apply(Function.prototype, {
685 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
686 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
687 * Will create a function that is bound to those 2 args.
688 * @return {Function} The new function
690 createCallback : function(/*args...*/){
691 // make args available, in function below
692 var args = arguments;
695 return method.apply(window, args);
700 * Creates a delegate (callback) that sets the scope to obj.
701 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
702 * Will create a function that is automatically scoped to this.
703 * @param {Object} obj (optional) The object for which the scope is set
704 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
705 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
706 * if a number the args are inserted at the specified position
707 * @return {Function} The new function
709 createDelegate : function(obj, args, appendArgs){
712 var callArgs = args || arguments;
713 if(appendArgs === true){
714 callArgs = Array.prototype.slice.call(arguments, 0);
715 callArgs = callArgs.concat(args);
716 }else if(typeof appendArgs == "number"){
717 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
718 var applyArgs = [appendArgs, 0].concat(args); // create method call params
719 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
721 return method.apply(obj || window, callArgs);
726 * Calls this function after the number of millseconds specified.
727 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
728 * @param {Object} obj (optional) The object for which the scope is set
729 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
730 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
731 * if a number the args are inserted at the specified position
732 * @return {Number} The timeout id that can be used with clearTimeout
734 defer : function(millis, obj, args, appendArgs){
735 var fn = this.createDelegate(obj, args, appendArgs);
737 return setTimeout(fn, millis);
743 * Create a combined function call sequence of the original function + the passed function.
744 * The resulting function returns the results of the original function.
745 * The passed fcn is called with the parameters of the original function
746 * @param {Function} fcn The function to sequence
747 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
748 * @return {Function} The new function
750 createSequence : function(fcn, scope){
751 if(typeof fcn != "function"){
756 var retval = method.apply(this || window, arguments);
757 fcn.apply(scope || this || window, arguments);
763 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
764 * The resulting function returns the results of the original function.
765 * The passed fcn is called with the parameters of the original function.
767 * @param {Function} fcn The function to call before the original
768 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
769 * @return {Function} The new function
771 createInterceptor : function(fcn, scope){
772 if(typeof fcn != "function"){
779 if(fcn.apply(scope || this || window, arguments) === false){
782 return method.apply(this || window, arguments);
788 * Ext JS Library 1.1.1
789 * Copyright(c) 2006-2007, Ext JS, LLC.
791 * Originally Released Under LGPL - original licence link has changed is not relivant.
794 * <script type="text/javascript">
797 Roo.applyIf(String, {
802 * Escapes the passed string for ' and \
803 * @param {String} string The string to escape
804 * @return {String} The escaped string
807 escape : function(string) {
808 return string.replace(/('|\\)/g, "\\$1");
812 * Pads the left side of a string with a specified character. This is especially useful
813 * for normalizing number and date strings. Example usage:
815 var s = String.leftPad('123', 5, '0');
816 // s now contains the string: '00123'
818 * @param {String} string The original string
819 * @param {Number} size The total length of the output string
820 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
821 * @return {String} The padded string
824 leftPad : function (val, size, ch) {
825 var result = new String(val);
826 if(ch === null || ch === undefined || ch === '') {
829 while (result.length < size) {
830 result = ch + result;
836 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
837 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
839 var cls = 'my-class', text = 'Some text';
840 var s = String.format('<div class="{0}">{1}</div>', cls, text);
841 // s now contains the string: '<div class="my-class">Some text</div>'
843 * @param {String} string The tokenized string to be formatted
844 * @param {String} value1 The value to replace token {0}
845 * @param {String} value2 Etc...
846 * @return {String} The formatted string
849 format : function(format){
850 var args = Array.prototype.slice.call(arguments, 1);
851 return format.replace(/\{(\d+)\}/g, function(m, i){
852 return Roo.util.Format.htmlEncode(args[i]);
858 * Utility function that allows you to easily switch a string between two alternating values. The passed value
859 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
860 * they are already different, the first value passed in is returned. Note that this method returns the new value
861 * but does not change the current string.
863 // alternate sort directions
864 sort = sort.toggle('ASC', 'DESC');
866 // instead of conditional logic:
867 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
869 * @param {String} value The value to compare to the current string
870 * @param {String} other The new value to use if the string already equals the first value passed in
871 * @return {String} The new value
874 String.prototype.toggle = function(value, other){
875 return this == value ? other : value;
878 * Ext JS Library 1.1.1
879 * Copyright(c) 2006-2007, Ext JS, LLC.
881 * Originally Released Under LGPL - original licence link has changed is not relivant.
884 * <script type="text/javascript">
890 Roo.applyIf(Number.prototype, {
892 * Checks whether or not the current number is within a desired range. If the number is already within the
893 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
894 * exceeded. Note that this method returns the constrained value but does not change the current number.
895 * @param {Number} min The minimum number in the range
896 * @param {Number} max The maximum number in the range
897 * @return {Number} The constrained value if outside the range, otherwise the current value
899 constrain : function(min, max){
900 return Math.min(Math.max(this, min), max);
904 * Ext JS Library 1.1.1
905 * Copyright(c) 2006-2007, Ext JS, LLC.
907 * Originally Released Under LGPL - original licence link has changed is not relivant.
910 * <script type="text/javascript">
915 Roo.applyIf(Array.prototype, {
917 * Checks whether or not the specified object exists in the array.
918 * @param {Object} o The object to check for
919 * @return {Number} The index of o in the array (or -1 if it is not found)
921 indexOf : function(o){
922 for (var i = 0, len = this.length; i < len; i++){
923 if(this[i] == o) return i;
929 * Removes the specified object from the array. If the object is not found nothing happens.
930 * @param {Object} o The object to remove
932 remove : function(o){
933 var index = this.indexOf(o);
935 this.splice(index, 1);
939 * Map (JS 1.6 compatibility)
940 * @param {Function} function to call
944 var len = this.length >>> 0;
945 if (typeof fun != "function")
946 throw new TypeError();
948 var res = new Array(len);
949 var thisp = arguments[1];
950 for (var i = 0; i < len; i++)
953 res[i] = fun.call(thisp, this[i], i, this);
964 * Ext JS Library 1.1.1
965 * Copyright(c) 2006-2007, Ext JS, LLC.
967 * Originally Released Under LGPL - original licence link has changed is not relivant.
970 * <script type="text/javascript">
976 * The date parsing and format syntax is a subset of
977 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
978 * supported will provide results equivalent to their PHP versions.
980 * Following is the list of all currently supported formats:
983 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
985 Format Output Description
986 ------ ---------- --------------------------------------------------------------
987 d 10 Day of the month, 2 digits with leading zeros
988 D Wed A textual representation of a day, three letters
989 j 10 Day of the month without leading zeros
990 l Wednesday A full textual representation of the day of the week
991 S th English ordinal day of month suffix, 2 chars (use with j)
992 w 3 Numeric representation of the day of the week
993 z 9 The julian date, or day of the year (0-365)
994 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
995 F January A full textual representation of the month
996 m 01 Numeric representation of a month, with leading zeros
997 M Jan Month name abbreviation, three letters
998 n 1 Numeric representation of a month, without leading zeros
999 t 31 Number of days in the given month
1000 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1001 Y 2007 A full numeric representation of a year, 4 digits
1002 y 07 A two digit representation of a year
1003 a pm Lowercase Ante meridiem and Post meridiem
1004 A PM Uppercase Ante meridiem and Post meridiem
1005 g 3 12-hour format of an hour without leading zeros
1006 G 15 24-hour format of an hour without leading zeros
1007 h 03 12-hour format of an hour with leading zeros
1008 H 15 24-hour format of an hour with leading zeros
1009 i 05 Minutes with leading zeros
1010 s 01 Seconds, with leading zeros
1011 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1012 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1013 T CST Timezone setting of the machine running the code
1014 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1017 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1019 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1020 document.write(dt.format('Y-m-d')); //2007-01-10
1021 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1022 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
1025 * Here are some standard date/time patterns that you might find helpful. They
1026 * are not part of the source of Date.js, but to use them you can simply copy this
1027 * block of code into any script that is included after Date.js and they will also become
1028 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1031 ISO8601Long:"Y-m-d H:i:s",
1032 ISO8601Short:"Y-m-d",
1034 LongDate: "l, F d, Y",
1035 FullDateTime: "l, F d, Y g:i:s A",
1038 LongTime: "g:i:s A",
1039 SortableDateTime: "Y-m-d\\TH:i:s",
1040 UniversalSortableDateTime: "Y-m-d H:i:sO",
1047 var dt = new Date();
1048 document.write(dt.format(Date.patterns.ShortDate));
1053 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1054 * They generate precompiled functions from date formats instead of parsing and
1055 * processing the pattern every time you format a date. These functions are available
1056 * on every Date object (any javascript function).
1058 * The original article and download are here:
1059 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1066 Returns the number of milliseconds between this date and date
1067 @param {Date} date (optional) Defaults to now
1068 @return {Number} The diff in milliseconds
1069 @member Date getElapsed
1071 Date.prototype.getElapsed = function(date) {
1072 return Math.abs((date || new Date()).getTime()-this.getTime());
1074 // was in date file..
1078 Date.parseFunctions = {count:0};
1080 Date.parseRegexes = [];
1082 Date.formatFunctions = {count:0};
1085 Date.prototype.dateFormat = function(format) {
1086 if (Date.formatFunctions[format] == null) {
1087 Date.createNewFormat(format);
1089 var func = Date.formatFunctions[format];
1090 return this[func]();
1095 * Formats a date given the supplied format string
1096 * @param {String} format The format string
1097 * @return {String} The formatted date
1100 Date.prototype.format = Date.prototype.dateFormat;
1103 Date.createNewFormat = function(format) {
1104 var funcName = "format" + Date.formatFunctions.count++;
1105 Date.formatFunctions[format] = funcName;
1106 var code = "Date.prototype." + funcName + " = function(){return ";
1107 var special = false;
1109 for (var i = 0; i < format.length; ++i) {
1110 ch = format.charAt(i);
1111 if (!special && ch == "\\") {
1116 code += "'" + String.escape(ch) + "' + ";
1119 code += Date.getFormatCode(ch);
1122 /** eval:var:zzzzzzzzzzzzz */
1123 eval(code.substring(0, code.length - 3) + ";}");
1127 Date.getFormatCode = function(character) {
1128 switch (character) {
1130 return "String.leftPad(this.getDate(), 2, '0') + ";
1132 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1134 return "this.getDate() + ";
1136 return "Date.dayNames[this.getDay()] + ";
1138 return "this.getSuffix() + ";
1140 return "this.getDay() + ";
1142 return "this.getDayOfYear() + ";
1144 return "this.getWeekOfYear() + ";
1146 return "Date.monthNames[this.getMonth()] + ";
1148 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1150 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1152 return "(this.getMonth() + 1) + ";
1154 return "this.getDaysInMonth() + ";
1156 return "(this.isLeapYear() ? 1 : 0) + ";
1158 return "this.getFullYear() + ";
1160 return "('' + this.getFullYear()).substring(2, 4) + ";
1162 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1164 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1166 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1168 return "this.getHours() + ";
1170 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1172 return "String.leftPad(this.getHours(), 2, '0') + ";
1174 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1176 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1178 return "this.getGMTOffset() + ";
1180 return "this.getGMTColonOffset() + ";
1182 return "this.getTimezone() + ";
1184 return "(this.getTimezoneOffset() * -60) + ";
1186 return "'" + String.escape(character) + "' + ";
1191 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1192 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1193 * the date format that is not specified will default to the current date value for that part. Time parts can also
1194 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1195 * string or the parse operation will fail.
1198 //dt = Fri May 25 2007 (current date)
1199 var dt = new Date();
1201 //dt = Thu May 25 2006 (today's month/day in 2006)
1202 dt = Date.parseDate("2006", "Y");
1204 //dt = Sun Jan 15 2006 (all date parts specified)
1205 dt = Date.parseDate("2006-1-15", "Y-m-d");
1207 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1208 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1210 * @param {String} input The unparsed date as a string
1211 * @param {String} format The format the date is in
1212 * @return {Date} The parsed date
1215 Date.parseDate = function(input, format) {
1216 if (Date.parseFunctions[format] == null) {
1217 Date.createParser(format);
1219 var func = Date.parseFunctions[format];
1220 return Date[func](input);
1225 Date.createParser = function(format) {
1226 var funcName = "parse" + Date.parseFunctions.count++;
1227 var regexNum = Date.parseRegexes.length;
1228 var currentGroup = 1;
1229 Date.parseFunctions[format] = funcName;
1231 var code = "Date." + funcName + " = function(input){\n"
1232 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1233 + "var d = new Date();\n"
1234 + "y = d.getFullYear();\n"
1235 + "m = d.getMonth();\n"
1236 + "d = d.getDate();\n"
1237 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1238 + "if (results && results.length > 0) {";
1241 var special = false;
1243 for (var i = 0; i < format.length; ++i) {
1244 ch = format.charAt(i);
1245 if (!special && ch == "\\") {
1250 regex += String.escape(ch);
1253 var obj = Date.formatCodeToRegex(ch, currentGroup);
1254 currentGroup += obj.g;
1256 if (obj.g && obj.c) {
1262 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1263 + "{v = new Date(y, m, d, h, i, s);}\n"
1264 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1265 + "{v = new Date(y, m, d, h, i);}\n"
1266 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1267 + "{v = new Date(y, m, d, h);}\n"
1268 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1269 + "{v = new Date(y, m, d);}\n"
1270 + "else if (y >= 0 && m >= 0)\n"
1271 + "{v = new Date(y, m);}\n"
1272 + "else if (y >= 0)\n"
1273 + "{v = new Date(y);}\n"
1274 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1275 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1276 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1279 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1280 /** eval:var:zzzzzzzzzzzzz */
1285 Date.formatCodeToRegex = function(character, currentGroup) {
1286 switch (character) {
1290 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1293 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1294 s:"(\\d{1,2})"}; // day of month without leading zeroes
1297 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1298 s:"(\\d{2})"}; // day of month with leading zeroes
1302 s:"(?:" + Date.dayNames.join("|") + ")"};
1306 s:"(?:st|nd|rd|th)"};
1321 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1322 s:"(" + Date.monthNames.join("|") + ")"};
1325 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1326 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1329 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1330 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1333 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1334 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1345 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1349 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1350 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1354 c:"if (results[" + currentGroup + "] == 'am') {\n"
1355 + "if (h == 12) { h = 0; }\n"
1356 + "} else { if (h < 12) { h += 12; }}",
1360 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1361 + "if (h == 12) { h = 0; }\n"
1362 + "} else { if (h < 12) { h += 12; }}",
1367 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1368 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1372 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1373 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1376 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1380 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1385 "o = results[", currentGroup, "];\n",
1386 "var sn = o.substring(0,1);\n", // get + / - sign
1387 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1388 "var mn = o.substring(3,5) % 60;\n", // get minutes
1389 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1390 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1392 s:"([+\-]\\d{2,4})"};
1398 "o = results[", currentGroup, "];\n",
1399 "var sn = o.substring(0,1);\n",
1400 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1401 "var mn = o.substring(4,6) % 60;\n",
1402 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1403 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1409 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1412 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1413 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1414 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1418 s:String.escape(character)};
1423 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1424 * @return {String} The abbreviated timezone name (e.g. 'CST')
1426 Date.prototype.getTimezone = function() {
1427 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1431 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1432 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1434 Date.prototype.getGMTOffset = function() {
1435 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1436 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1437 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1441 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1442 * @return {String} 2-characters representing hours and 2-characters representing minutes
1443 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1445 Date.prototype.getGMTColonOffset = function() {
1446 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1447 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1449 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1453 * Get the numeric day number of the year, adjusted for leap year.
1454 * @return {Number} 0 through 364 (365 in leap years)
1456 Date.prototype.getDayOfYear = function() {
1458 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1459 for (var i = 0; i < this.getMonth(); ++i) {
1460 num += Date.daysInMonth[i];
1462 return num + this.getDate() - 1;
1466 * Get the string representation of the numeric week number of the year
1467 * (equivalent to the format specifier 'W').
1468 * @return {String} '00' through '52'
1470 Date.prototype.getWeekOfYear = function() {
1471 // Skip to Thursday of this week
1472 var now = this.getDayOfYear() + (4 - this.getDay());
1473 // Find the first Thursday of the year
1474 var jan1 = new Date(this.getFullYear(), 0, 1);
1475 var then = (7 - jan1.getDay() + 4);
1476 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1480 * Whether or not the current date is in a leap year.
1481 * @return {Boolean} True if the current date is in a leap year, else false
1483 Date.prototype.isLeapYear = function() {
1484 var year = this.getFullYear();
1485 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1489 * Get the first day of the current month, adjusted for leap year. The returned value
1490 * is the numeric day index within the week (0-6) which can be used in conjunction with
1491 * the {@link #monthNames} array to retrieve the textual day name.
1494 var dt = new Date('1/10/2007');
1495 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1497 * @return {Number} The day number (0-6)
1499 Date.prototype.getFirstDayOfMonth = function() {
1500 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1501 return (day < 0) ? (day + 7) : day;
1505 * Get the last day of the current month, adjusted for leap year. The returned value
1506 * is the numeric day index within the week (0-6) which can be used in conjunction with
1507 * the {@link #monthNames} array to retrieve the textual day name.
1510 var dt = new Date('1/10/2007');
1511 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1513 * @return {Number} The day number (0-6)
1515 Date.prototype.getLastDayOfMonth = function() {
1516 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1517 return (day < 0) ? (day + 7) : day;
1522 * Get the first date of this date's month
1525 Date.prototype.getFirstDateOfMonth = function() {
1526 return new Date(this.getFullYear(), this.getMonth(), 1);
1530 * Get the last date of this date's month
1533 Date.prototype.getLastDateOfMonth = function() {
1534 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1537 * Get the number of days in the current month, adjusted for leap year.
1538 * @return {Number} The number of days in the month
1540 Date.prototype.getDaysInMonth = function() {
1541 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1542 return Date.daysInMonth[this.getMonth()];
1546 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1547 * @return {String} 'st, 'nd', 'rd' or 'th'
1549 Date.prototype.getSuffix = function() {
1550 switch (this.getDate()) {
1567 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1570 * An array of textual month names.
1571 * Override these values for international dates, for example...
1572 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1591 * An array of textual day names.
1592 * Override these values for international dates, for example...
1593 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1609 Date.monthNumbers = {
1624 * Creates and returns a new Date instance with the exact same date value as the called instance.
1625 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1626 * variable will also be changed. When the intention is to create a new variable that will not
1627 * modify the original instance, you should create a clone.
1629 * Example of correctly cloning a date:
1632 var orig = new Date('10/1/2006');
1635 document.write(orig); //returns 'Thu Oct 05 2006'!
1638 var orig = new Date('10/1/2006');
1639 var copy = orig.clone();
1641 document.write(orig); //returns 'Thu Oct 01 2006'
1643 * @return {Date} The new Date instance
1645 Date.prototype.clone = function() {
1646 return new Date(this.getTime());
1650 * Clears any time information from this date
1651 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1652 @return {Date} this or the clone
1654 Date.prototype.clearTime = function(clone){
1656 return this.clone().clearTime();
1661 this.setMilliseconds(0);
1666 // safari setMonth is broken
1668 Date.brokenSetMonth = Date.prototype.setMonth;
1669 Date.prototype.setMonth = function(num){
1671 var n = Math.ceil(-num);
1672 var back_year = Math.ceil(n/12);
1673 var month = (n % 12) ? 12 - n % 12 : 0 ;
1674 this.setFullYear(this.getFullYear() - back_year);
1675 return Date.brokenSetMonth.call(this, month);
1677 return Date.brokenSetMonth.apply(this, arguments);
1682 /** Date interval constant
1686 /** Date interval constant
1690 /** Date interval constant
1694 /** Date interval constant
1698 /** Date interval constant
1702 /** Date interval constant
1706 /** Date interval constant
1712 * Provides a convenient method of performing basic date arithmetic. This method
1713 * does not modify the Date instance being called - it creates and returns
1714 * a new Date instance containing the resulting date value.
1719 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1720 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1722 //Negative values will subtract correctly:
1723 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1724 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1726 //You can even chain several calls together in one line!
1727 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1728 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1731 * @param {String} interval A valid date interval enum value
1732 * @param {Number} value The amount to add to the current date
1733 * @return {Date} The new Date instance
1735 Date.prototype.add = function(interval, value){
1736 var d = this.clone();
1737 if (!interval || value === 0) return d;
1738 switch(interval.toLowerCase()){
1740 d.setMilliseconds(this.getMilliseconds() + value);
1743 d.setSeconds(this.getSeconds() + value);
1746 d.setMinutes(this.getMinutes() + value);
1749 d.setHours(this.getHours() + value);
1752 d.setDate(this.getDate() + value);
1755 var day = this.getDate();
1757 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1760 d.setMonth(this.getMonth() + value);
1763 d.setFullYear(this.getFullYear() + value);
1770 * Ext JS Library 1.1.1
1771 * Copyright(c) 2006-2007, Ext JS, LLC.
1773 * Originally Released Under LGPL - original licence link has changed is not relivant.
1776 * <script type="text/javascript">
1780 * @class Roo.lib.Dom
1783 * Dom utils (from YIU afaik)
1788 * Get the view width
1789 * @param {Boolean} full True will get the full document, otherwise it's the view width
1790 * @return {Number} The width
1793 getViewWidth : function(full) {
1794 return full ? this.getDocumentWidth() : this.getViewportWidth();
1797 * Get the view height
1798 * @param {Boolean} full True will get the full document, otherwise it's the view height
1799 * @return {Number} The height
1801 getViewHeight : function(full) {
1802 return full ? this.getDocumentHeight() : this.getViewportHeight();
1805 getDocumentHeight: function() {
1806 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1807 return Math.max(scrollHeight, this.getViewportHeight());
1810 getDocumentWidth: function() {
1811 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1812 return Math.max(scrollWidth, this.getViewportWidth());
1815 getViewportHeight: function() {
1816 var height = self.innerHeight;
1817 var mode = document.compatMode;
1819 if ((mode || Roo.isIE) && !Roo.isOpera) {
1820 height = (mode == "CSS1Compat") ?
1821 document.documentElement.clientHeight :
1822 document.body.clientHeight;
1828 getViewportWidth: function() {
1829 var width = self.innerWidth;
1830 var mode = document.compatMode;
1832 if (mode || Roo.isIE) {
1833 width = (mode == "CSS1Compat") ?
1834 document.documentElement.clientWidth :
1835 document.body.clientWidth;
1840 isAncestor : function(p, c) {
1847 if (p.contains && !Roo.isSafari) {
1848 return p.contains(c);
1849 } else if (p.compareDocumentPosition) {
1850 return !!(p.compareDocumentPosition(c) & 16);
1852 var parent = c.parentNode;
1857 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1860 parent = parent.parentNode;
1866 getRegion : function(el) {
1867 return Roo.lib.Region.getRegion(el);
1870 getY : function(el) {
1871 return this.getXY(el)[1];
1874 getX : function(el) {
1875 return this.getXY(el)[0];
1878 getXY : function(el) {
1879 var p, pe, b, scroll, bd = document.body;
1880 el = Roo.getDom(el);
1881 var fly = Roo.lib.AnimBase.fly;
1882 if (el.getBoundingClientRect) {
1883 b = el.getBoundingClientRect();
1884 scroll = fly(document).getScroll();
1885 return [b.left + scroll.left, b.top + scroll.top];
1891 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1898 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1905 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1906 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1913 if (p != el && pe.getStyle('overflow') != 'visible') {
1921 if (Roo.isSafari && hasAbsolute) {
1926 if (Roo.isGecko && !hasAbsolute) {
1928 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1929 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1933 while (p && p != bd) {
1934 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1946 setXY : function(el, xy) {
1947 el = Roo.fly(el, '_setXY');
1949 var pts = el.translatePoints(xy);
1950 if (xy[0] !== false) {
1951 el.dom.style.left = pts.left + "px";
1953 if (xy[1] !== false) {
1954 el.dom.style.top = pts.top + "px";
1958 setX : function(el, x) {
1959 this.setXY(el, [x, false]);
1962 setY : function(el, y) {
1963 this.setXY(el, [false, y]);
1967 * Portions of this file are based on pieces of Yahoo User Interface Library
1968 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1969 * YUI licensed under the BSD License:
1970 * http://developer.yahoo.net/yui/license.txt
1971 * <script type="text/javascript">
1975 Roo.lib.Event = function() {
1976 var loadComplete = false;
1978 var unloadListeners = [];
1980 var onAvailStack = [];
1982 var lastError = null;
1995 startInterval: function() {
1996 if (!this._interval) {
1998 var callback = function() {
1999 self._tryPreloadAttach();
2001 this._interval = setInterval(callback, this.POLL_INTERVAL);
2006 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2007 onAvailStack.push({ id: p_id,
2010 override: p_override,
2011 checkReady: false });
2013 retryCount = this.POLL_RETRYS;
2014 this.startInterval();
2018 addListener: function(el, eventName, fn) {
2019 el = Roo.getDom(el);
2024 if ("unload" == eventName) {
2025 unloadListeners[unloadListeners.length] =
2026 [el, eventName, fn];
2030 var wrappedFn = function(e) {
2031 return fn(Roo.lib.Event.getEvent(e));
2034 var li = [el, eventName, fn, wrappedFn];
2036 var index = listeners.length;
2037 listeners[index] = li;
2039 this.doAdd(el, eventName, wrappedFn, false);
2045 removeListener: function(el, eventName, fn) {
2048 el = Roo.getDom(el);
2051 return this.purgeElement(el, false, eventName);
2055 if ("unload" == eventName) {
2057 for (i = 0,len = unloadListeners.length; i < len; i++) {
2058 var li = unloadListeners[i];
2061 li[1] == eventName &&
2063 unloadListeners.splice(i, 1);
2071 var cacheItem = null;
2074 var index = arguments[3];
2076 if ("undefined" == typeof index) {
2077 index = this._getCacheIndex(el, eventName, fn);
2081 cacheItem = listeners[index];
2084 if (!el || !cacheItem) {
2088 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2090 delete listeners[index][this.WFN];
2091 delete listeners[index][this.FN];
2092 listeners.splice(index, 1);
2099 getTarget: function(ev, resolveTextNode) {
2100 ev = ev.browserEvent || ev;
2101 var t = ev.target || ev.srcElement;
2102 return this.resolveTextNode(t);
2106 resolveTextNode: function(node) {
2107 if (Roo.isSafari && node && 3 == node.nodeType) {
2108 return node.parentNode;
2115 getPageX: function(ev) {
2116 ev = ev.browserEvent || ev;
2118 if (!x && 0 !== x) {
2119 x = ev.clientX || 0;
2122 x += this.getScroll()[1];
2130 getPageY: function(ev) {
2131 ev = ev.browserEvent || ev;
2133 if (!y && 0 !== y) {
2134 y = ev.clientY || 0;
2137 y += this.getScroll()[0];
2146 getXY: function(ev) {
2147 ev = ev.browserEvent || ev;
2148 return [this.getPageX(ev), this.getPageY(ev)];
2152 getRelatedTarget: function(ev) {
2153 ev = ev.browserEvent || ev;
2154 var t = ev.relatedTarget;
2156 if (ev.type == "mouseout") {
2158 } else if (ev.type == "mouseover") {
2163 return this.resolveTextNode(t);
2167 getTime: function(ev) {
2168 ev = ev.browserEvent || ev;
2170 var t = new Date().getTime();
2174 this.lastError = ex;
2183 stopEvent: function(ev) {
2184 this.stopPropagation(ev);
2185 this.preventDefault(ev);
2189 stopPropagation: function(ev) {
2190 ev = ev.browserEvent || ev;
2191 if (ev.stopPropagation) {
2192 ev.stopPropagation();
2194 ev.cancelBubble = true;
2199 preventDefault: function(ev) {
2200 ev = ev.browserEvent || ev;
2201 if(ev.preventDefault) {
2202 ev.preventDefault();
2204 ev.returnValue = false;
2209 getEvent: function(e) {
2210 var ev = e || window.event;
2212 var c = this.getEvent.caller;
2214 ev = c.arguments[0];
2215 if (ev && Event == ev.constructor) {
2225 getCharCode: function(ev) {
2226 ev = ev.browserEvent || ev;
2227 return ev.charCode || ev.keyCode || 0;
2231 _getCacheIndex: function(el, eventName, fn) {
2232 for (var i = 0,len = listeners.length; i < len; ++i) {
2233 var li = listeners[i];
2235 li[this.FN] == fn &&
2236 li[this.EL] == el &&
2237 li[this.TYPE] == eventName) {
2249 getEl: function(id) {
2250 return document.getElementById(id);
2254 clearCache: function() {
2258 _load: function(e) {
2259 loadComplete = true;
2260 var EU = Roo.lib.Event;
2264 EU.doRemove(window, "load", EU._load);
2269 _tryPreloadAttach: function() {
2278 var tryAgain = !loadComplete;
2280 tryAgain = (retryCount > 0);
2285 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2286 var item = onAvailStack[i];
2288 var el = this.getEl(item.id);
2291 if (!item.checkReady ||
2294 (document && document.body)) {
2297 if (item.override) {
2298 if (item.override === true) {
2301 scope = item.override;
2304 item.fn.call(scope, item.obj);
2305 onAvailStack[i] = null;
2308 notAvail.push(item);
2313 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2317 this.startInterval();
2319 clearInterval(this._interval);
2320 this._interval = null;
2323 this.locked = false;
2330 purgeElement: function(el, recurse, eventName) {
2331 var elListeners = this.getListeners(el, eventName);
2333 for (var i = 0,len = elListeners.length; i < len; ++i) {
2334 var l = elListeners[i];
2335 this.removeListener(el, l.type, l.fn);
2339 if (recurse && el && el.childNodes) {
2340 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2341 this.purgeElement(el.childNodes[i], recurse, eventName);
2347 getListeners: function(el, eventName) {
2348 var results = [], searchLists;
2350 searchLists = [listeners, unloadListeners];
2351 } else if (eventName == "unload") {
2352 searchLists = [unloadListeners];
2354 searchLists = [listeners];
2357 for (var j = 0; j < searchLists.length; ++j) {
2358 var searchList = searchLists[j];
2359 if (searchList && searchList.length > 0) {
2360 for (var i = 0,len = searchList.length; i < len; ++i) {
2361 var l = searchList[i];
2362 if (l && l[this.EL] === el &&
2363 (!eventName || eventName === l[this.TYPE])) {
2368 adjust: l[this.ADJ_SCOPE],
2376 return (results.length) ? results : null;
2380 _unload: function(e) {
2382 var EU = Roo.lib.Event, i, j, l, len, index;
2384 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2385 l = unloadListeners[i];
2388 if (l[EU.ADJ_SCOPE]) {
2389 if (l[EU.ADJ_SCOPE] === true) {
2392 scope = l[EU.ADJ_SCOPE];
2395 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2396 unloadListeners[i] = null;
2402 unloadListeners = null;
2404 if (listeners && listeners.length > 0) {
2405 j = listeners.length;
2408 l = listeners[index];
2410 EU.removeListener(l[EU.EL], l[EU.TYPE],
2420 EU.doRemove(window, "unload", EU._unload);
2425 getScroll: function() {
2426 var dd = document.documentElement, db = document.body;
2427 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2428 return [dd.scrollTop, dd.scrollLeft];
2430 return [db.scrollTop, db.scrollLeft];
2437 doAdd: function () {
2438 if (window.addEventListener) {
2439 return function(el, eventName, fn, capture) {
2440 el.addEventListener(eventName, fn, (capture));
2442 } else if (window.attachEvent) {
2443 return function(el, eventName, fn, capture) {
2444 el.attachEvent("on" + eventName, fn);
2453 doRemove: function() {
2454 if (window.removeEventListener) {
2455 return function (el, eventName, fn, capture) {
2456 el.removeEventListener(eventName, fn, (capture));
2458 } else if (window.detachEvent) {
2459 return function (el, eventName, fn) {
2460 el.detachEvent("on" + eventName, fn);
2472 var E = Roo.lib.Event;
2473 E.on = E.addListener;
2474 E.un = E.removeListener;
2476 if (document && document.body) {
2479 E.doAdd(window, "load", E._load);
2481 E.doAdd(window, "unload", E._unload);
2482 E._tryPreloadAttach();
2486 * Portions of this file are based on pieces of Yahoo User Interface Library
2487 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2488 * YUI licensed under the BSD License:
2489 * http://developer.yahoo.net/yui/license.txt
2490 * <script type="text/javascript">
2496 * @class Roo.lib.Ajax
2503 request : function(method, uri, cb, data, options) {
2505 var hs = options.headers;
2508 if(hs.hasOwnProperty(h)){
2509 this.initHeader(h, hs[h], false);
2513 if(options.xmlData){
2514 this.initHeader('Content-Type', 'text/xml', false);
2516 data = options.xmlData;
2520 return this.asyncRequest(method, uri, cb, data);
2523 serializeForm : function(form) {
2524 if(typeof form == 'string') {
2525 form = (document.getElementById(form) || document.forms[form]);
2528 var el, name, val, disabled, data = '', hasSubmit = false;
2529 for (var i = 0; i < form.elements.length; i++) {
2530 el = form.elements[i];
2531 disabled = form.elements[i].disabled;
2532 name = form.elements[i].name;
2533 val = form.elements[i].value;
2535 if (!disabled && name){
2539 case 'select-multiple':
2540 for (var j = 0; j < el.options.length; j++) {
2541 if (el.options[j].selected) {
2543 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2546 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2554 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2567 if(hasSubmit == false) {
2568 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2573 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2578 data = data.substr(0, data.length - 1);
2586 useDefaultHeader:true,
2588 defaultPostHeader:'application/x-www-form-urlencoded',
2590 useDefaultXhrHeader:true,
2592 defaultXhrHeader:'XMLHttpRequest',
2594 hasDefaultHeaders:true,
2606 setProgId:function(id)
2608 this.activeX.unshift(id);
2611 setDefaultPostHeader:function(b)
2613 this.useDefaultHeader = b;
2616 setDefaultXhrHeader:function(b)
2618 this.useDefaultXhrHeader = b;
2621 setPollingInterval:function(i)
2623 if (typeof i == 'number' && isFinite(i)) {
2624 this.pollInterval = i;
2628 createXhrObject:function(transactionId)
2634 http = new XMLHttpRequest();
2636 obj = { conn:http, tId:transactionId };
2640 for (var i = 0; i < this.activeX.length; ++i) {
2644 http = new ActiveXObject(this.activeX[i]);
2646 obj = { conn:http, tId:transactionId };
2659 getConnectionObject:function()
2662 var tId = this.transactionId;
2666 o = this.createXhrObject(tId);
2668 this.transactionId++;
2679 asyncRequest:function(method, uri, callback, postData)
2681 var o = this.getConnectionObject();
2687 o.conn.open(method, uri, true);
2689 if (this.useDefaultXhrHeader) {
2690 if (!this.defaultHeaders['X-Requested-With']) {
2691 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2695 if(postData && this.useDefaultHeader){
2696 this.initHeader('Content-Type', this.defaultPostHeader);
2699 if (this.hasDefaultHeaders || this.hasHeaders) {
2703 this.handleReadyState(o, callback);
2704 o.conn.send(postData || null);
2710 handleReadyState:function(o, callback)
2714 if (callback && callback.timeout) {
2716 this.timeout[o.tId] = window.setTimeout(function() {
2717 oConn.abort(o, callback, true);
2718 }, callback.timeout);
2721 this.poll[o.tId] = window.setInterval(
2723 if (o.conn && o.conn.readyState == 4) {
2724 window.clearInterval(oConn.poll[o.tId]);
2725 delete oConn.poll[o.tId];
2727 if(callback && callback.timeout) {
2728 window.clearTimeout(oConn.timeout[o.tId]);
2729 delete oConn.timeout[o.tId];
2732 oConn.handleTransactionResponse(o, callback);
2735 , this.pollInterval);
2738 handleTransactionResponse:function(o, callback, isAbort)
2742 this.releaseObject(o);
2746 var httpStatus, responseObject;
2750 if (o.conn.status !== undefined && o.conn.status != 0) {
2751 httpStatus = o.conn.status;
2763 if (httpStatus >= 200 && httpStatus < 300) {
2764 responseObject = this.createResponseObject(o, callback.argument);
2765 if (callback.success) {
2766 if (!callback.scope) {
2767 callback.success(responseObject);
2772 callback.success.apply(callback.scope, [responseObject]);
2777 switch (httpStatus) {
2785 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2786 if (callback.failure) {
2787 if (!callback.scope) {
2788 callback.failure(responseObject);
2791 callback.failure.apply(callback.scope, [responseObject]);
2796 responseObject = this.createResponseObject(o, callback.argument);
2797 if (callback.failure) {
2798 if (!callback.scope) {
2799 callback.failure(responseObject);
2802 callback.failure.apply(callback.scope, [responseObject]);
2808 this.releaseObject(o);
2809 responseObject = null;
2812 createResponseObject:function(o, callbackArg)
2819 var headerStr = o.conn.getAllResponseHeaders();
2820 var header = headerStr.split('\n');
2821 for (var i = 0; i < header.length; i++) {
2822 var delimitPos = header[i].indexOf(':');
2823 if (delimitPos != -1) {
2824 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2832 obj.status = o.conn.status;
2833 obj.statusText = o.conn.statusText;
2834 obj.getResponseHeader = headerObj;
2835 obj.getAllResponseHeaders = headerStr;
2836 obj.responseText = o.conn.responseText;
2837 obj.responseXML = o.conn.responseXML;
2839 if (typeof callbackArg !== undefined) {
2840 obj.argument = callbackArg;
2846 createExceptionObject:function(tId, callbackArg, isAbort)
2849 var COMM_ERROR = 'communication failure';
2850 var ABORT_CODE = -1;
2851 var ABORT_ERROR = 'transaction aborted';
2857 obj.status = ABORT_CODE;
2858 obj.statusText = ABORT_ERROR;
2861 obj.status = COMM_CODE;
2862 obj.statusText = COMM_ERROR;
2866 obj.argument = callbackArg;
2872 initHeader:function(label, value, isDefault)
2874 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2876 if (headerObj[label] === undefined) {
2877 headerObj[label] = value;
2882 headerObj[label] = value + "," + headerObj[label];
2886 this.hasDefaultHeaders = true;
2889 this.hasHeaders = true;
2894 setHeader:function(o)
2896 if (this.hasDefaultHeaders) {
2897 for (var prop in this.defaultHeaders) {
2898 if (this.defaultHeaders.hasOwnProperty(prop)) {
2899 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2904 if (this.hasHeaders) {
2905 for (var prop in this.headers) {
2906 if (this.headers.hasOwnProperty(prop)) {
2907 o.conn.setRequestHeader(prop, this.headers[prop]);
2911 this.hasHeaders = false;
2915 resetDefaultHeaders:function() {
2916 delete this.defaultHeaders;
2917 this.defaultHeaders = {};
2918 this.hasDefaultHeaders = false;
2921 abort:function(o, callback, isTimeout)
2923 if(this.isCallInProgress(o)) {
2925 window.clearInterval(this.poll[o.tId]);
2926 delete this.poll[o.tId];
2928 delete this.timeout[o.tId];
2931 this.handleTransactionResponse(o, callback, true);
2941 isCallInProgress:function(o)
2944 return o.conn.readyState != 4 && o.conn.readyState != 0;
2953 releaseObject:function(o)
2962 'MSXML2.XMLHTTP.3.0',
2970 * Portions of this file are based on pieces of Yahoo User Interface Library
2971 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2972 * YUI licensed under the BSD License:
2973 * http://developer.yahoo.net/yui/license.txt
2974 * <script type="text/javascript">
2978 Roo.lib.Region = function(t, r, b, l) {
2988 Roo.lib.Region.prototype = {
2989 contains : function(region) {
2990 return ( region.left >= this.left &&
2991 region.right <= this.right &&
2992 region.top >= this.top &&
2993 region.bottom <= this.bottom );
2997 getArea : function() {
2998 return ( (this.bottom - this.top) * (this.right - this.left) );
3001 intersect : function(region) {
3002 var t = Math.max(this.top, region.top);
3003 var r = Math.min(this.right, region.right);
3004 var b = Math.min(this.bottom, region.bottom);
3005 var l = Math.max(this.left, region.left);
3007 if (b >= t && r >= l) {
3008 return new Roo.lib.Region(t, r, b, l);
3013 union : function(region) {
3014 var t = Math.min(this.top, region.top);
3015 var r = Math.max(this.right, region.right);
3016 var b = Math.max(this.bottom, region.bottom);
3017 var l = Math.min(this.left, region.left);
3019 return new Roo.lib.Region(t, r, b, l);
3022 adjust : function(t, l, b, r) {
3031 Roo.lib.Region.getRegion = function(el) {
3032 var p = Roo.lib.Dom.getXY(el);
3035 var r = p[0] + el.offsetWidth;
3036 var b = p[1] + el.offsetHeight;
3039 return new Roo.lib.Region(t, r, b, l);
3042 * Portions of this file are based on pieces of Yahoo User Interface Library
3043 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3044 * YUI licensed under the BSD License:
3045 * http://developer.yahoo.net/yui/license.txt
3046 * <script type="text/javascript">
3049 //@@dep Roo.lib.Region
3052 Roo.lib.Point = function(x, y) {
3053 if (x instanceof Array) {
3057 this.x = this.right = this.left = this[0] = x;
3058 this.y = this.top = this.bottom = this[1] = y;
3061 Roo.lib.Point.prototype = new Roo.lib.Region();
3063 * Portions of this file are based on pieces of Yahoo User Interface Library
3064 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3065 * YUI licensed under the BSD License:
3066 * http://developer.yahoo.net/yui/license.txt
3067 * <script type="text/javascript">
3074 scroll : function(el, args, duration, easing, cb, scope) {
3075 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3078 motion : function(el, args, duration, easing, cb, scope) {
3079 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3082 color : function(el, args, duration, easing, cb, scope) {
3083 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3086 run : function(el, args, duration, easing, cb, scope, type) {
3087 type = type || Roo.lib.AnimBase;
3088 if (typeof easing == "string") {
3089 easing = Roo.lib.Easing[easing];
3091 var anim = new type(el, args, duration, easing);
3092 anim.animateX(function() {
3093 Roo.callback(cb, scope);
3099 * Portions of this file are based on pieces of Yahoo User Interface Library
3100 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3101 * YUI licensed under the BSD License:
3102 * http://developer.yahoo.net/yui/license.txt
3103 * <script type="text/javascript">
3111 if (!libFlyweight) {
3112 libFlyweight = new Roo.Element.Flyweight();
3114 libFlyweight.dom = el;
3115 return libFlyweight;
3118 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3122 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3124 this.init(el, attributes, duration, method);
3128 Roo.lib.AnimBase.fly = fly;
3132 Roo.lib.AnimBase.prototype = {
3134 toString: function() {
3135 var el = this.getEl();
3136 var id = el.id || el.tagName;
3137 return ("Anim " + id);
3141 noNegatives: /width|height|opacity|padding/i,
3142 offsetAttribute: /^((width|height)|(top|left))$/,
3143 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3144 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3148 doMethod: function(attr, start, end) {
3149 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3153 setAttribute: function(attr, val, unit) {
3154 if (this.patterns.noNegatives.test(attr)) {
3155 val = (val > 0) ? val : 0;
3158 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3162 getAttribute: function(attr) {
3163 var el = this.getEl();
3164 var val = fly(el).getStyle(attr);
3166 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3167 return parseFloat(val);
3170 var a = this.patterns.offsetAttribute.exec(attr) || [];
3171 var pos = !!( a[3] );
3172 var box = !!( a[2] );
3175 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3176 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3185 getDefaultUnit: function(attr) {
3186 if (this.patterns.defaultUnit.test(attr)) {
3193 animateX : function(callback, scope) {
3194 var f = function() {
3195 this.onComplete.removeListener(f);
3196 if (typeof callback == "function") {
3197 callback.call(scope || this, this);
3200 this.onComplete.addListener(f, this);
3205 setRuntimeAttribute: function(attr) {
3208 var attributes = this.attributes;
3210 this.runtimeAttributes[attr] = {};
3212 var isset = function(prop) {
3213 return (typeof prop !== 'undefined');
3216 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3220 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3223 if (isset(attributes[attr]['to'])) {
3224 end = attributes[attr]['to'];
3225 } else if (isset(attributes[attr]['by'])) {
3226 if (start.constructor == Array) {
3228 for (var i = 0, len = start.length; i < len; ++i) {
3229 end[i] = start[i] + attributes[attr]['by'][i];
3232 end = start + attributes[attr]['by'];
3236 this.runtimeAttributes[attr].start = start;
3237 this.runtimeAttributes[attr].end = end;
3240 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3244 init: function(el, attributes, duration, method) {
3246 var isAnimated = false;
3249 var startTime = null;
3252 var actualFrames = 0;
3255 el = Roo.getDom(el);
3258 this.attributes = attributes || {};
3261 this.duration = duration || 1;
3264 this.method = method || Roo.lib.Easing.easeNone;
3267 this.useSeconds = true;
3270 this.currentFrame = 0;
3273 this.totalFrames = Roo.lib.AnimMgr.fps;
3276 this.getEl = function() {
3281 this.isAnimated = function() {
3286 this.getStartTime = function() {
3290 this.runtimeAttributes = {};
3293 this.animate = function() {
3294 if (this.isAnimated()) {
3298 this.currentFrame = 0;
3300 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3302 Roo.lib.AnimMgr.registerElement(this);
3306 this.stop = function(finish) {
3308 this.currentFrame = this.totalFrames;
3309 this._onTween.fire();
3311 Roo.lib.AnimMgr.stop(this);
3314 var onStart = function() {
3315 this.onStart.fire();
3317 this.runtimeAttributes = {};
3318 for (var attr in this.attributes) {
3319 this.setRuntimeAttribute(attr);
3324 startTime = new Date();
3328 var onTween = function() {
3330 duration: new Date() - this.getStartTime(),
3331 currentFrame: this.currentFrame
3334 data.toString = function() {
3336 'duration: ' + data.duration +
3337 ', currentFrame: ' + data.currentFrame
3341 this.onTween.fire(data);
3343 var runtimeAttributes = this.runtimeAttributes;
3345 for (var attr in runtimeAttributes) {
3346 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3352 var onComplete = function() {
3353 var actual_duration = (new Date() - startTime) / 1000 ;
3356 duration: actual_duration,
3357 frames: actualFrames,
3358 fps: actualFrames / actual_duration
3361 data.toString = function() {
3363 'duration: ' + data.duration +
3364 ', frames: ' + data.frames +
3365 ', fps: ' + data.fps
3371 this.onComplete.fire(data);
3375 this._onStart = new Roo.util.Event(this);
3376 this.onStart = new Roo.util.Event(this);
3377 this.onTween = new Roo.util.Event(this);
3378 this._onTween = new Roo.util.Event(this);
3379 this.onComplete = new Roo.util.Event(this);
3380 this._onComplete = new Roo.util.Event(this);
3381 this._onStart.addListener(onStart);
3382 this._onTween.addListener(onTween);
3383 this._onComplete.addListener(onComplete);
3388 * Portions of this file are based on pieces of Yahoo User Interface Library
3389 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3390 * YUI licensed under the BSD License:
3391 * http://developer.yahoo.net/yui/license.txt
3392 * <script type="text/javascript">
3396 Roo.lib.AnimMgr = new function() {
3413 this.registerElement = function(tween) {
3414 queue[queue.length] = tween;
3416 tween._onStart.fire();
3421 this.unRegister = function(tween, index) {
3422 tween._onComplete.fire();
3423 index = index || getIndex(tween);
3425 queue.splice(index, 1);
3429 if (tweenCount <= 0) {
3435 this.start = function() {
3436 if (thread === null) {
3437 thread = setInterval(this.run, this.delay);
3442 this.stop = function(tween) {
3444 clearInterval(thread);
3446 for (var i = 0, len = queue.length; i < len; ++i) {
3447 if (queue[0].isAnimated()) {
3448 this.unRegister(queue[0], 0);
3457 this.unRegister(tween);
3462 this.run = function() {
3463 for (var i = 0, len = queue.length; i < len; ++i) {
3464 var tween = queue[i];
3465 if (!tween || !tween.isAnimated()) {
3469 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3471 tween.currentFrame += 1;
3473 if (tween.useSeconds) {
3474 correctFrame(tween);
3476 tween._onTween.fire();
3479 Roo.lib.AnimMgr.stop(tween, i);
3484 var getIndex = function(anim) {
3485 for (var i = 0, len = queue.length; i < len; ++i) {
3486 if (queue[i] == anim) {
3494 var correctFrame = function(tween) {
3495 var frames = tween.totalFrames;
3496 var frame = tween.currentFrame;
3497 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3498 var elapsed = (new Date() - tween.getStartTime());
3501 if (elapsed < tween.duration * 1000) {
3502 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3504 tweak = frames - (frame + 1);
3506 if (tweak > 0 && isFinite(tweak)) {
3507 if (tween.currentFrame + tweak >= frames) {
3508 tweak = frames - (frame + 1);
3511 tween.currentFrame += tweak;
3515 * Portions of this file are based on pieces of Yahoo User Interface Library
3516 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3517 * YUI licensed under the BSD License:
3518 * http://developer.yahoo.net/yui/license.txt
3519 * <script type="text/javascript">
3522 Roo.lib.Bezier = new function() {
3524 this.getPosition = function(points, t) {
3525 var n = points.length;
3528 for (var i = 0; i < n; ++i) {
3529 tmp[i] = [points[i][0], points[i][1]];
3532 for (var j = 1; j < n; ++j) {
3533 for (i = 0; i < n - j; ++i) {
3534 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3535 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3539 return [ tmp[0][0], tmp[0][1] ];
3543 * Portions of this file are based on pieces of Yahoo User Interface Library
3544 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3545 * YUI licensed under the BSD License:
3546 * http://developer.yahoo.net/yui/license.txt
3547 * <script type="text/javascript">
3552 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3553 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3556 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3558 var fly = Roo.lib.AnimBase.fly;
3560 var superclass = Y.ColorAnim.superclass;
3561 var proto = Y.ColorAnim.prototype;
3563 proto.toString = function() {
3564 var el = this.getEl();
3565 var id = el.id || el.tagName;
3566 return ("ColorAnim " + id);
3569 proto.patterns.color = /color$/i;
3570 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3571 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3572 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3573 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3576 proto.parseColor = function(s) {
3577 if (s.length == 3) {
3581 var c = this.patterns.hex.exec(s);
3582 if (c && c.length == 4) {
3583 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3586 c = this.patterns.rgb.exec(s);
3587 if (c && c.length == 4) {
3588 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3591 c = this.patterns.hex3.exec(s);
3592 if (c && c.length == 4) {
3593 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3598 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3599 proto.getAttribute = function(attr) {
3600 var el = this.getEl();
3601 if (this.patterns.color.test(attr)) {
3602 var val = fly(el).getStyle(attr);
3604 if (this.patterns.transparent.test(val)) {
3605 var parent = el.parentNode;
3606 val = fly(parent).getStyle(attr);
3608 while (parent && this.patterns.transparent.test(val)) {
3609 parent = parent.parentNode;
3610 val = fly(parent).getStyle(attr);
3611 if (parent.tagName.toUpperCase() == 'HTML') {
3617 val = superclass.getAttribute.call(this, attr);
3622 proto.getAttribute = function(attr) {
3623 var el = this.getEl();
3624 if (this.patterns.color.test(attr)) {
3625 var val = fly(el).getStyle(attr);
3627 if (this.patterns.transparent.test(val)) {
3628 var parent = el.parentNode;
3629 val = fly(parent).getStyle(attr);
3631 while (parent && this.patterns.transparent.test(val)) {
3632 parent = parent.parentNode;
3633 val = fly(parent).getStyle(attr);
3634 if (parent.tagName.toUpperCase() == 'HTML') {
3640 val = superclass.getAttribute.call(this, attr);
3646 proto.doMethod = function(attr, start, end) {
3649 if (this.patterns.color.test(attr)) {
3651 for (var i = 0, len = start.length; i < len; ++i) {
3652 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3655 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3658 val = superclass.doMethod.call(this, attr, start, end);
3664 proto.setRuntimeAttribute = function(attr) {
3665 superclass.setRuntimeAttribute.call(this, attr);
3667 if (this.patterns.color.test(attr)) {
3668 var attributes = this.attributes;
3669 var start = this.parseColor(this.runtimeAttributes[attr].start);
3670 var end = this.parseColor(this.runtimeAttributes[attr].end);
3672 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3673 end = this.parseColor(attributes[attr].by);
3675 for (var i = 0, len = start.length; i < len; ++i) {
3676 end[i] = start[i] + end[i];
3680 this.runtimeAttributes[attr].start = start;
3681 this.runtimeAttributes[attr].end = end;
3687 * Portions of this file are based on pieces of Yahoo User Interface Library
3688 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3689 * YUI licensed under the BSD License:
3690 * http://developer.yahoo.net/yui/license.txt
3691 * <script type="text/javascript">
3697 easeNone: function (t, b, c, d) {
3698 return c * t / d + b;
3702 easeIn: function (t, b, c, d) {
3703 return c * (t /= d) * t + b;
3707 easeOut: function (t, b, c, d) {
3708 return -c * (t /= d) * (t - 2) + b;
3712 easeBoth: function (t, b, c, d) {
3713 if ((t /= d / 2) < 1) {
3714 return c / 2 * t * t + b;
3717 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3721 easeInStrong: function (t, b, c, d) {
3722 return c * (t /= d) * t * t * t + b;
3726 easeOutStrong: function (t, b, c, d) {
3727 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3731 easeBothStrong: function (t, b, c, d) {
3732 if ((t /= d / 2) < 1) {
3733 return c / 2 * t * t * t * t + b;
3736 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3741 elasticIn: function (t, b, c, d, a, p) {
3745 if ((t /= d) == 1) {
3752 if (!a || a < Math.abs(c)) {
3757 var s = p / (2 * Math.PI) * Math.asin(c / a);
3760 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3764 elasticOut: function (t, b, c, d, a, p) {
3768 if ((t /= d) == 1) {
3775 if (!a || a < Math.abs(c)) {
3780 var s = p / (2 * Math.PI) * Math.asin(c / a);
3783 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3787 elasticBoth: function (t, b, c, d, a, p) {
3792 if ((t /= d / 2) == 2) {
3800 if (!a || a < Math.abs(c)) {
3805 var s = p / (2 * Math.PI) * Math.asin(c / a);
3809 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3810 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3812 return a * Math.pow(2, -10 * (t -= 1)) *
3813 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3818 backIn: function (t, b, c, d, s) {
3819 if (typeof s == 'undefined') {
3822 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3826 backOut: function (t, b, c, d, s) {
3827 if (typeof s == 'undefined') {
3830 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3834 backBoth: function (t, b, c, d, s) {
3835 if (typeof s == 'undefined') {
3839 if ((t /= d / 2 ) < 1) {
3840 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3842 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3846 bounceIn: function (t, b, c, d) {
3847 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3851 bounceOut: function (t, b, c, d) {
3852 if ((t /= d) < (1 / 2.75)) {
3853 return c * (7.5625 * t * t) + b;
3854 } else if (t < (2 / 2.75)) {
3855 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3856 } else if (t < (2.5 / 2.75)) {
3857 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3859 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3863 bounceBoth: function (t, b, c, d) {
3865 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3867 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3870 * Portions of this file are based on pieces of Yahoo User Interface Library
3871 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3872 * YUI licensed under the BSD License:
3873 * http://developer.yahoo.net/yui/license.txt
3874 * <script type="text/javascript">
3878 Roo.lib.Motion = function(el, attributes, duration, method) {
3880 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3884 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3888 var superclass = Y.Motion.superclass;
3889 var proto = Y.Motion.prototype;
3891 proto.toString = function() {
3892 var el = this.getEl();
3893 var id = el.id || el.tagName;
3894 return ("Motion " + id);
3897 proto.patterns.points = /^points$/i;
3899 proto.setAttribute = function(attr, val, unit) {
3900 if (this.patterns.points.test(attr)) {
3901 unit = unit || 'px';
3902 superclass.setAttribute.call(this, 'left', val[0], unit);
3903 superclass.setAttribute.call(this, 'top', val[1], unit);
3905 superclass.setAttribute.call(this, attr, val, unit);
3909 proto.getAttribute = function(attr) {
3910 if (this.patterns.points.test(attr)) {
3912 superclass.getAttribute.call(this, 'left'),
3913 superclass.getAttribute.call(this, 'top')
3916 val = superclass.getAttribute.call(this, attr);
3922 proto.doMethod = function(attr, start, end) {
3925 if (this.patterns.points.test(attr)) {
3926 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3927 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3929 val = superclass.doMethod.call(this, attr, start, end);
3934 proto.setRuntimeAttribute = function(attr) {
3935 if (this.patterns.points.test(attr)) {
3936 var el = this.getEl();
3937 var attributes = this.attributes;
3939 var control = attributes['points']['control'] || [];
3943 if (control.length > 0 && !(control[0] instanceof Array)) {
3944 control = [control];
3947 for (i = 0,len = control.length; i < len; ++i) {
3948 tmp[i] = control[i];
3953 Roo.fly(el).position();
3955 if (isset(attributes['points']['from'])) {
3956 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3959 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3962 start = this.getAttribute('points');
3965 if (isset(attributes['points']['to'])) {
3966 end = translateValues.call(this, attributes['points']['to'], start);
3968 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3969 for (i = 0,len = control.length; i < len; ++i) {
3970 control[i] = translateValues.call(this, control[i], start);
3974 } else if (isset(attributes['points']['by'])) {
3975 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
3977 for (i = 0,len = control.length; i < len; ++i) {
3978 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
3982 this.runtimeAttributes[attr] = [start];
3984 if (control.length > 0) {
3985 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
3988 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
3991 superclass.setRuntimeAttribute.call(this, attr);
3995 var translateValues = function(val, start) {
3996 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3997 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4002 var isset = function(prop) {
4003 return (typeof prop !== 'undefined');
4007 * Portions of this file are based on pieces of Yahoo User Interface Library
4008 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4009 * YUI licensed under the BSD License:
4010 * http://developer.yahoo.net/yui/license.txt
4011 * <script type="text/javascript">
4015 Roo.lib.Scroll = function(el, attributes, duration, method) {
4017 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4021 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4025 var superclass = Y.Scroll.superclass;
4026 var proto = Y.Scroll.prototype;
4028 proto.toString = function() {
4029 var el = this.getEl();
4030 var id = el.id || el.tagName;
4031 return ("Scroll " + id);
4034 proto.doMethod = function(attr, start, end) {
4037 if (attr == 'scroll') {
4039 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4040 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4044 val = superclass.doMethod.call(this, attr, start, end);
4049 proto.getAttribute = function(attr) {
4051 var el = this.getEl();
4053 if (attr == 'scroll') {
4054 val = [ el.scrollLeft, el.scrollTop ];
4056 val = superclass.getAttribute.call(this, attr);
4062 proto.setAttribute = function(attr, val, unit) {
4063 var el = this.getEl();
4065 if (attr == 'scroll') {
4066 el.scrollLeft = val[0];
4067 el.scrollTop = val[1];
4069 superclass.setAttribute.call(this, attr, val, unit);
4075 * Ext JS Library 1.1.1
4076 * Copyright(c) 2006-2007, Ext JS, LLC.
4078 * Originally Released Under LGPL - original licence link has changed is not relivant.
4081 * <script type="text/javascript">
4085 // nasty IE9 hack - what a pile of crap that is..
4087 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4088 Range.prototype.createContextualFragment = function (html) {
4089 var doc = window.document;
4090 var container = doc.createElement("div");
4091 container.innerHTML = html;
4092 var frag = doc.createDocumentFragment(), n;
4093 while ((n = container.firstChild)) {
4094 frag.appendChild(n);
4101 * @class Roo.DomHelper
4102 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4103 * 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>.
4106 Roo.DomHelper = function(){
4107 var tempTableEl = null;
4108 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4109 var tableRe = /^table|tbody|tr|td$/i;
4111 // build as innerHTML where available
4113 var createHtml = function(o){
4114 if(typeof o == 'string'){
4123 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4124 if(attr == "style"){
4126 if(typeof s == "function"){
4129 if(typeof s == "string"){
4130 b += ' style="' + s + '"';
4131 }else if(typeof s == "object"){
4134 if(typeof s[key] != "function"){
4135 b += key + ":" + s[key] + ";";
4142 b += ' class="' + o["cls"] + '"';
4143 }else if(attr == "htmlFor"){
4144 b += ' for="' + o["htmlFor"] + '"';
4146 b += " " + attr + '="' + o[attr] + '"';
4150 if(emptyTags.test(o.tag)){
4154 var cn = o.children || o.cn;
4156 //http://bugs.kde.org/show_bug.cgi?id=71506
4157 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4158 for(var i = 0, len = cn.length; i < len; i++) {
4159 b += createHtml(cn[i], b);
4162 b += createHtml(cn, b);
4168 b += "</" + o.tag + ">";
4175 var createDom = function(o, parentNode){
4177 // defininition craeted..
4179 if (o.ns && o.ns != 'html') {
4181 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4182 xmlns[o.ns] = o.xmlns;
4185 if (typeof(xmlns[o.ns]) == 'undefined') {
4186 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4192 if (typeof(o) == 'string') {
4193 return parentNode.appendChild(document.createTextNode(o));
4195 o.tag = o.tag || div;
4196 if (o.ns && Roo.isIE) {
4198 o.tag = o.ns + ':' + o.tag;
4201 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4202 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4205 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4206 attr == "style" || typeof o[attr] == "function") continue;
4208 if(attr=="cls" && Roo.isIE){
4209 el.className = o["cls"];
4211 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4212 else el[attr] = o[attr];
4215 Roo.DomHelper.applyStyles(el, o.style);
4216 var cn = o.children || o.cn;
4218 //http://bugs.kde.org/show_bug.cgi?id=71506
4219 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4220 for(var i = 0, len = cn.length; i < len; i++) {
4221 createDom(cn[i], el);
4228 el.innerHTML = o.html;
4231 parentNode.appendChild(el);
4236 var ieTable = function(depth, s, h, e){
4237 tempTableEl.innerHTML = [s, h, e].join('');
4238 var i = -1, el = tempTableEl;
4245 // kill repeat to save bytes
4249 tbe = '</tbody>'+te,
4255 * Nasty code for IE's broken table implementation
4257 var insertIntoTable = function(tag, where, el, html){
4259 tempTableEl = document.createElement('div');
4264 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4267 if(where == 'beforebegin'){
4271 before = el.nextSibling;
4274 node = ieTable(4, trs, html, tre);
4276 else if(tag == 'tr'){
4277 if(where == 'beforebegin'){
4280 node = ieTable(3, tbs, html, tbe);
4281 } else if(where == 'afterend'){
4282 before = el.nextSibling;
4284 node = ieTable(3, tbs, html, tbe);
4285 } else{ // INTO a TR
4286 if(where == 'afterbegin'){
4287 before = el.firstChild;
4289 node = ieTable(4, trs, html, tre);
4291 } else if(tag == 'tbody'){
4292 if(where == 'beforebegin'){
4295 node = ieTable(2, ts, html, te);
4296 } else if(where == 'afterend'){
4297 before = el.nextSibling;
4299 node = ieTable(2, ts, html, te);
4301 if(where == 'afterbegin'){
4302 before = el.firstChild;
4304 node = ieTable(3, tbs, html, tbe);
4307 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4310 if(where == 'afterbegin'){
4311 before = el.firstChild;
4313 node = ieTable(2, ts, html, te);
4315 el.insertBefore(node, before);
4320 /** True to force the use of DOM instead of html fragments @type Boolean */
4324 * Returns the markup for the passed Element(s) config
4325 * @param {Object} o The Dom object spec (and children)
4328 markup : function(o){
4329 return createHtml(o);
4333 * Applies a style specification to an element
4334 * @param {String/HTMLElement} el The element to apply styles to
4335 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4336 * a function which returns such a specification.
4338 applyStyles : function(el, styles){
4341 if(typeof styles == "string"){
4342 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4344 while ((matches = re.exec(styles)) != null){
4345 el.setStyle(matches[1], matches[2]);
4347 }else if (typeof styles == "object"){
4348 for (var style in styles){
4349 el.setStyle(style, styles[style]);
4351 }else if (typeof styles == "function"){
4352 Roo.DomHelper.applyStyles(el, styles.call());
4358 * Inserts an HTML fragment into the Dom
4359 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4360 * @param {HTMLElement} el The context element
4361 * @param {String} html The HTML fragmenet
4362 * @return {HTMLElement} The new node
4364 insertHtml : function(where, el, html){
4365 where = where.toLowerCase();
4366 if(el.insertAdjacentHTML){
4367 if(tableRe.test(el.tagName)){
4369 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4375 el.insertAdjacentHTML('BeforeBegin', html);
4376 return el.previousSibling;
4378 el.insertAdjacentHTML('AfterBegin', html);
4379 return el.firstChild;
4381 el.insertAdjacentHTML('BeforeEnd', html);
4382 return el.lastChild;
4384 el.insertAdjacentHTML('AfterEnd', html);
4385 return el.nextSibling;
4387 throw 'Illegal insertion point -> "' + where + '"';
4389 var range = el.ownerDocument.createRange();
4393 range.setStartBefore(el);
4394 frag = range.createContextualFragment(html);
4395 el.parentNode.insertBefore(frag, el);
4396 return el.previousSibling;
4399 range.setStartBefore(el.firstChild);
4400 frag = range.createContextualFragment(html);
4401 el.insertBefore(frag, el.firstChild);
4402 return el.firstChild;
4404 el.innerHTML = html;
4405 return el.firstChild;
4409 range.setStartAfter(el.lastChild);
4410 frag = range.createContextualFragment(html);
4411 el.appendChild(frag);
4412 return el.lastChild;
4414 el.innerHTML = html;
4415 return el.lastChild;
4418 range.setStartAfter(el);
4419 frag = range.createContextualFragment(html);
4420 el.parentNode.insertBefore(frag, el.nextSibling);
4421 return el.nextSibling;
4423 throw 'Illegal insertion point -> "' + where + '"';
4427 * Creates new Dom element(s) and inserts them before el
4428 * @param {String/HTMLElement/Element} el The context element
4429 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4430 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4431 * @return {HTMLElement/Roo.Element} The new node
4433 insertBefore : function(el, o, returnElement){
4434 return this.doInsert(el, o, returnElement, "beforeBegin");
4438 * Creates new Dom element(s) and inserts them after el
4439 * @param {String/HTMLElement/Element} el The context element
4440 * @param {Object} o The Dom object spec (and children)
4441 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4442 * @return {HTMLElement/Roo.Element} The new node
4444 insertAfter : function(el, o, returnElement){
4445 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4449 * Creates new Dom element(s) and inserts them as the first child of 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 insertFirst : function(el, o, returnElement){
4456 return this.doInsert(el, o, returnElement, "afterBegin");
4460 doInsert : function(el, o, returnElement, pos, sibling){
4461 el = Roo.getDom(el);
4463 if(this.useDom || o.ns){
4464 newNode = createDom(o, null);
4465 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4467 var html = createHtml(o);
4468 newNode = this.insertHtml(pos, el, html);
4470 return returnElement ? Roo.get(newNode, true) : newNode;
4474 * Creates new Dom element(s) and appends them to el
4475 * @param {String/HTMLElement/Element} el The context element
4476 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4477 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4478 * @return {HTMLElement/Roo.Element} The new node
4480 append : function(el, o, returnElement){
4481 el = Roo.getDom(el);
4483 if(this.useDom || o.ns){
4484 newNode = createDom(o, null);
4485 el.appendChild(newNode);
4487 var html = createHtml(o);
4488 newNode = this.insertHtml("beforeEnd", el, html);
4490 return returnElement ? Roo.get(newNode, true) : newNode;
4494 * Creates new Dom element(s) and overwrites the contents of el with them
4495 * @param {String/HTMLElement/Element} el The context element
4496 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4497 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4498 * @return {HTMLElement/Roo.Element} The new node
4500 overwrite : function(el, o, returnElement){
4501 el = Roo.getDom(el);
4504 while (el.childNodes.length) {
4505 el.removeChild(el.firstChild);
4509 el.innerHTML = createHtml(o);
4512 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4516 * Creates a new Roo.DomHelper.Template from the Dom object spec
4517 * @param {Object} o The Dom object spec (and children)
4518 * @return {Roo.DomHelper.Template} The new template
4520 createTemplate : function(o){
4521 var html = createHtml(o);
4522 return new Roo.Template(html);
4528 * Ext JS Library 1.1.1
4529 * Copyright(c) 2006-2007, Ext JS, LLC.
4531 * Originally Released Under LGPL - original licence link has changed is not relivant.
4534 * <script type="text/javascript">
4538 * @class Roo.Template
4539 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4540 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4543 var t = new Roo.Template({
4544 html : '<div name="{id}">' +
4545 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4547 myformat: function (value, allValues) {
4548 return 'XX' + value;
4551 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4553 * For more information see this blog post with examples:
4554 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4555 - Create Elements using DOM, HTML fragments and Templates</a>.
4557 * @param {Object} cfg - Configuration object.
4559 Roo.Template = function(cfg){
4561 if(cfg instanceof Array){
4563 }else if(arguments.length > 1){
4564 cfg = Array.prototype.join.call(arguments, "");
4568 if (typeof(cfg) == 'object') {
4579 Roo.Template.prototype = {
4582 * @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..
4583 * it should be fixed so that template is observable...
4587 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4591 * Returns an HTML fragment of this template with the specified values applied.
4592 * @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'})
4593 * @return {String} The HTML fragment
4595 applyTemplate : function(values){
4599 return this.compiled(values);
4601 var useF = this.disableFormats !== true;
4602 var fm = Roo.util.Format, tpl = this;
4603 var fn = function(m, name, format, args){
4605 if(format.substr(0, 5) == "this."){
4606 return tpl.call(format.substr(5), values[name], values);
4609 // quoted values are required for strings in compiled templates,
4610 // but for non compiled we need to strip them
4611 // quoted reversed for jsmin
4612 var re = /^\s*['"](.*)["']\s*$/;
4613 args = args.split(',');
4614 for(var i = 0, len = args.length; i < len; i++){
4615 args[i] = args[i].replace(re, "$1");
4617 args = [values[name]].concat(args);
4619 args = [values[name]];
4621 return fm[format].apply(fm, args);
4624 return values[name] !== undefined ? values[name] : "";
4627 return this.html.replace(this.re, fn);
4645 this.loading = true;
4646 this.compiled = false;
4648 var cx = new Roo.data.Connection();
4652 success : function (response) {
4654 _t.html = response.responseText;
4658 failure : function(response) {
4659 Roo.log("Template failed to load from " + _t.url);
4666 * Sets the HTML used as the template and optionally compiles it.
4667 * @param {String} html
4668 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4669 * @return {Roo.Template} this
4671 set : function(html, compile){
4673 this.compiled = null;
4681 * True to disable format functions (defaults to false)
4684 disableFormats : false,
4687 * The regular expression used to match template variables
4691 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4694 * Compiles the template into an internal function, eliminating the RegEx overhead.
4695 * @return {Roo.Template} this
4697 compile : function(){
4698 var fm = Roo.util.Format;
4699 var useF = this.disableFormats !== true;
4700 var sep = Roo.isGecko ? "+" : ",";
4701 var fn = function(m, name, format, args){
4703 args = args ? ',' + args : "";
4704 if(format.substr(0, 5) != "this."){
4705 format = "fm." + format + '(';
4707 format = 'this.call("'+ format.substr(5) + '", ';
4711 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4713 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4716 // branched to use + in gecko and [].join() in others
4718 body = "this.compiled = function(values){ return '" +
4719 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4722 body = ["this.compiled = function(values){ return ['"];
4723 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4724 body.push("'].join('');};");
4725 body = body.join('');
4735 // private function used to call members
4736 call : function(fnName, value, allValues){
4737 return this[fnName](value, allValues);
4741 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4742 * @param {String/HTMLElement/Roo.Element} el The context element
4743 * @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'})
4744 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4745 * @return {HTMLElement/Roo.Element} The new node or Element
4747 insertFirst: function(el, values, returnElement){
4748 return this.doInsert('afterBegin', el, values, returnElement);
4752 * Applies the supplied values to the template and inserts the new node(s) before el.
4753 * @param {String/HTMLElement/Roo.Element} el The context element
4754 * @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'})
4755 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4756 * @return {HTMLElement/Roo.Element} The new node or Element
4758 insertBefore: function(el, values, returnElement){
4759 return this.doInsert('beforeBegin', el, values, returnElement);
4763 * Applies the supplied values to the template and inserts the new node(s) after 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 insertAfter : function(el, values, returnElement){
4770 return this.doInsert('afterEnd', el, values, returnElement);
4774 * Applies the supplied values to the template and appends the new node(s) to 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 append : function(el, values, returnElement){
4781 return this.doInsert('beforeEnd', el, values, returnElement);
4784 doInsert : function(where, el, values, returnEl){
4785 el = Roo.getDom(el);
4786 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4787 return returnEl ? Roo.get(newNode, true) : newNode;
4791 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4792 * @param {String/HTMLElement/Roo.Element} el The context element
4793 * @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'})
4794 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4795 * @return {HTMLElement/Roo.Element} The new node or Element
4797 overwrite : function(el, values, returnElement){
4798 el = Roo.getDom(el);
4799 el.innerHTML = this.applyTemplate(values);
4800 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4804 * Alias for {@link #applyTemplate}
4807 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4810 Roo.DomHelper.Template = Roo.Template;
4813 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4814 * @param {String/HTMLElement} el A DOM element or its id
4815 * @returns {Roo.Template} The created template
4818 Roo.Template.from = function(el){
4819 el = Roo.getDom(el);
4820 return new Roo.Template(el.value || el.innerHTML);
4823 * Ext JS Library 1.1.1
4824 * Copyright(c) 2006-2007, Ext JS, LLC.
4826 * Originally Released Under LGPL - original licence link has changed is not relivant.
4829 * <script type="text/javascript">
4834 * This is code is also distributed under MIT license for use
4835 * with jQuery and prototype JavaScript libraries.
4838 * @class Roo.DomQuery
4839 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).
4841 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>
4844 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.
4846 <h4>Element Selectors:</h4>
4848 <li> <b>*</b> any element</li>
4849 <li> <b>E</b> an element with the tag E</li>
4850 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4851 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4852 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4853 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4855 <h4>Attribute Selectors:</h4>
4856 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4858 <li> <b>E[foo]</b> has an attribute "foo"</li>
4859 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4860 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4861 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4862 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4863 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4864 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4866 <h4>Pseudo Classes:</h4>
4868 <li> <b>E:first-child</b> E is the first child of its parent</li>
4869 <li> <b>E:last-child</b> E is the last child of its parent</li>
4870 <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>
4871 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4872 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4873 <li> <b>E:only-child</b> E is the only child of its parent</li>
4874 <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>
4875 <li> <b>E:first</b> the first E in the resultset</li>
4876 <li> <b>E:last</b> the last E in the resultset</li>
4877 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4878 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4879 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4880 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4881 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4882 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4883 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4884 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4885 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4887 <h4>CSS Value Selectors:</h4>
4889 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4890 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4891 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4892 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4893 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4894 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4898 Roo.DomQuery = function(){
4899 var cache = {}, simpleCache = {}, valueCache = {};
4900 var nonSpace = /\S/;
4901 var trimRe = /^\s+|\s+$/g;
4902 var tplRe = /\{(\d+)\}/g;
4903 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4904 var tagTokenRe = /^(#)?([\w-\*]+)/;
4905 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4907 function child(p, index){
4909 var n = p.firstChild;
4911 if(n.nodeType == 1){
4922 while((n = n.nextSibling) && n.nodeType != 1);
4927 while((n = n.previousSibling) && n.nodeType != 1);
4931 function children(d){
4932 var n = d.firstChild, ni = -1;
4934 var nx = n.nextSibling;
4935 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4945 function byClassName(c, a, v){
4949 var r = [], ri = -1, cn;
4950 for(var i = 0, ci; ci = c[i]; i++){
4951 if((' '+ci.className+' ').indexOf(v) != -1){
4958 function attrValue(n, attr){
4959 if(!n.tagName && typeof n.length != "undefined"){
4968 if(attr == "class" || attr == "className"){
4971 return n.getAttribute(attr) || n[attr];
4975 function getNodes(ns, mode, tagName){
4976 var result = [], ri = -1, cs;
4980 tagName = tagName || "*";
4981 if(typeof ns.getElementsByTagName != "undefined"){
4985 for(var i = 0, ni; ni = ns[i]; i++){
4986 cs = ni.getElementsByTagName(tagName);
4987 for(var j = 0, ci; ci = cs[j]; j++){
4991 }else if(mode == "/" || mode == ">"){
4992 var utag = tagName.toUpperCase();
4993 for(var i = 0, ni, cn; ni = ns[i]; i++){
4994 cn = ni.children || ni.childNodes;
4995 for(var j = 0, cj; cj = cn[j]; j++){
4996 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5001 }else if(mode == "+"){
5002 var utag = tagName.toUpperCase();
5003 for(var i = 0, n; n = ns[i]; i++){
5004 while((n = n.nextSibling) && n.nodeType != 1);
5005 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5009 }else if(mode == "~"){
5010 for(var i = 0, n; n = ns[i]; i++){
5011 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5020 function concat(a, b){
5024 for(var i = 0, l = b.length; i < l; i++){
5030 function byTag(cs, tagName){
5031 if(cs.tagName || cs == document){
5037 var r = [], ri = -1;
5038 tagName = tagName.toLowerCase();
5039 for(var i = 0, ci; ci = cs[i]; i++){
5040 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5047 function byId(cs, attr, id){
5048 if(cs.tagName || cs == document){
5054 var r = [], ri = -1;
5055 for(var i = 0,ci; ci = cs[i]; i++){
5056 if(ci && ci.id == id){
5064 function byAttribute(cs, attr, value, op, custom){
5065 var r = [], ri = -1, st = custom=="{";
5066 var f = Roo.DomQuery.operators[op];
5067 for(var i = 0, ci; ci = cs[i]; i++){
5070 a = Roo.DomQuery.getStyle(ci, attr);
5072 else if(attr == "class" || attr == "className"){
5074 }else if(attr == "for"){
5076 }else if(attr == "href"){
5077 a = ci.getAttribute("href", 2);
5079 a = ci.getAttribute(attr);
5081 if((f && f(a, value)) || (!f && a)){
5088 function byPseudo(cs, name, value){
5089 return Roo.DomQuery.pseudos[name](cs, value);
5092 // This is for IE MSXML which does not support expandos.
5093 // IE runs the same speed using setAttribute, however FF slows way down
5094 // and Safari completely fails so they need to continue to use expandos.
5095 var isIE = window.ActiveXObject ? true : false;
5097 // this eval is stop the compressor from
5098 // renaming the variable to something shorter
5100 /** eval:var:batch */
5105 function nodupIEXml(cs){
5107 cs[0].setAttribute("_nodup", d);
5109 for(var i = 1, len = cs.length; i < len; i++){
5111 if(!c.getAttribute("_nodup") != d){
5112 c.setAttribute("_nodup", d);
5116 for(var i = 0, len = cs.length; i < len; i++){
5117 cs[i].removeAttribute("_nodup");
5126 var len = cs.length, c, i, r = cs, cj, ri = -1;
5127 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5130 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5131 return nodupIEXml(cs);
5135 for(i = 1; c = cs[i]; i++){
5140 for(var j = 0; j < i; j++){
5143 for(j = i+1; cj = cs[j]; j++){
5155 function quickDiffIEXml(c1, c2){
5157 for(var i = 0, len = c1.length; i < len; i++){
5158 c1[i].setAttribute("_qdiff", d);
5161 for(var i = 0, len = c2.length; i < len; i++){
5162 if(c2[i].getAttribute("_qdiff") != d){
5163 r[r.length] = c2[i];
5166 for(var i = 0, len = c1.length; i < len; i++){
5167 c1[i].removeAttribute("_qdiff");
5172 function quickDiff(c1, c2){
5173 var len1 = c1.length;
5177 if(isIE && c1[0].selectSingleNode){
5178 return quickDiffIEXml(c1, c2);
5181 for(var i = 0; i < len1; i++){
5185 for(var i = 0, len = c2.length; i < len; i++){
5186 if(c2[i]._qdiff != d){
5187 r[r.length] = c2[i];
5193 function quickId(ns, mode, root, id){
5195 var d = root.ownerDocument || root;
5196 return d.getElementById(id);
5198 ns = getNodes(ns, mode, "*");
5199 return byId(ns, null, id);
5203 getStyle : function(el, name){
5204 return Roo.fly(el).getStyle(name);
5207 * Compiles a selector/xpath query into a reusable function. The returned function
5208 * takes one parameter "root" (optional), which is the context node from where the query should start.
5209 * @param {String} selector The selector/xpath query
5210 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5211 * @return {Function}
5213 compile : function(path, type){
5214 type = type || "select";
5216 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5217 var q = path, mode, lq;
5218 var tk = Roo.DomQuery.matchers;
5219 var tklen = tk.length;
5222 // accept leading mode switch
5223 var lmode = q.match(modeRe);
5224 if(lmode && lmode[1]){
5225 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5226 q = q.replace(lmode[1], "");
5228 // strip leading slashes
5229 while(path.substr(0, 1)=="/"){
5230 path = path.substr(1);
5233 while(q && lq != q){
5235 var tm = q.match(tagTokenRe);
5236 if(type == "select"){
5239 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5241 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5243 q = q.replace(tm[0], "");
5244 }else if(q.substr(0, 1) != '@'){
5245 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5250 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5252 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5254 q = q.replace(tm[0], "");
5257 while(!(mm = q.match(modeRe))){
5258 var matched = false;
5259 for(var j = 0; j < tklen; j++){
5261 var m = q.match(t.re);
5263 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5266 q = q.replace(m[0], "");
5271 // prevent infinite loop on bad selector
5273 throw 'Error parsing selector, parsing failed at "' + q + '"';
5277 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5278 q = q.replace(mm[1], "");
5281 fn[fn.length] = "return nodup(n);\n}";
5284 * list of variables that need from compression as they are used by eval.
5294 * eval:var:byClassName
5296 * eval:var:byAttribute
5297 * eval:var:attrValue
5305 * Selects a group of elements.
5306 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5307 * @param {Node} root (optional) The start of the query (defaults to document).
5310 select : function(path, root, type){
5311 if(!root || root == document){
5314 if(typeof root == "string"){
5315 root = document.getElementById(root);
5317 var paths = path.split(",");
5319 for(var i = 0, len = paths.length; i < len; i++){
5320 var p = paths[i].replace(trimRe, "");
5322 cache[p] = Roo.DomQuery.compile(p);
5324 throw p + " is not a valid selector";
5327 var result = cache[p](root);
5328 if(result && result != document){
5329 results = results.concat(result);
5332 if(paths.length > 1){
5333 return nodup(results);
5339 * Selects a single element.
5340 * @param {String} selector The selector/xpath query
5341 * @param {Node} root (optional) The start of the query (defaults to document).
5344 selectNode : function(path, root){
5345 return Roo.DomQuery.select(path, root)[0];
5349 * Selects the value of a node, optionally replacing null with the defaultValue.
5350 * @param {String} selector The selector/xpath query
5351 * @param {Node} root (optional) The start of the query (defaults to document).
5352 * @param {String} defaultValue
5354 selectValue : function(path, root, defaultValue){
5355 path = path.replace(trimRe, "");
5356 if(!valueCache[path]){
5357 valueCache[path] = Roo.DomQuery.compile(path, "select");
5359 var n = valueCache[path](root);
5360 n = n[0] ? n[0] : n;
5361 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5362 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5366 * Selects the value of a node, parsing integers and floats.
5367 * @param {String} selector The selector/xpath query
5368 * @param {Node} root (optional) The start of the query (defaults to document).
5369 * @param {Number} defaultValue
5372 selectNumber : function(path, root, defaultValue){
5373 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5374 return parseFloat(v);
5378 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5379 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5380 * @param {String} selector The simple selector to test
5383 is : function(el, ss){
5384 if(typeof el == "string"){
5385 el = document.getElementById(el);
5387 var isArray = (el instanceof Array);
5388 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5389 return isArray ? (result.length == el.length) : (result.length > 0);
5393 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5394 * @param {Array} el An array of elements to filter
5395 * @param {String} selector The simple selector to test
5396 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5397 * the selector instead of the ones that match
5400 filter : function(els, ss, nonMatches){
5401 ss = ss.replace(trimRe, "");
5402 if(!simpleCache[ss]){
5403 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5405 var result = simpleCache[ss](els);
5406 return nonMatches ? quickDiff(result, els) : result;
5410 * Collection of matching regular expressions and code snippets.
5414 select: 'n = byClassName(n, null, " {1} ");'
5416 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5417 select: 'n = byPseudo(n, "{1}", "{2}");'
5419 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5420 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5423 select: 'n = byId(n, null, "{1}");'
5426 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5431 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5432 * 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, > <.
5435 "=" : function(a, v){
5438 "!=" : function(a, v){
5441 "^=" : function(a, v){
5442 return a && a.substr(0, v.length) == v;
5444 "$=" : function(a, v){
5445 return a && a.substr(a.length-v.length) == v;
5447 "*=" : function(a, v){
5448 return a && a.indexOf(v) !== -1;
5450 "%=" : function(a, v){
5451 return (a % v) == 0;
5453 "|=" : function(a, v){
5454 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5456 "~=" : function(a, v){
5457 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5462 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5463 * and the argument (if any) supplied in the selector.
5466 "first-child" : function(c){
5467 var r = [], ri = -1, n;
5468 for(var i = 0, ci; ci = n = c[i]; i++){
5469 while((n = n.previousSibling) && n.nodeType != 1);
5477 "last-child" : function(c){
5478 var r = [], ri = -1, n;
5479 for(var i = 0, ci; ci = n = c[i]; i++){
5480 while((n = n.nextSibling) && n.nodeType != 1);
5488 "nth-child" : function(c, a) {
5489 var r = [], ri = -1;
5490 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5491 var f = (m[1] || 1) - 0, l = m[2] - 0;
5492 for(var i = 0, n; n = c[i]; i++){
5493 var pn = n.parentNode;
5494 if (batch != pn._batch) {
5496 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5497 if(cn.nodeType == 1){
5504 if (l == 0 || n.nodeIndex == l){
5507 } else if ((n.nodeIndex + l) % f == 0){
5515 "only-child" : function(c){
5516 var r = [], ri = -1;;
5517 for(var i = 0, ci; ci = c[i]; i++){
5518 if(!prev(ci) && !next(ci)){
5525 "empty" : function(c){
5526 var r = [], ri = -1;
5527 for(var i = 0, ci; ci = c[i]; i++){
5528 var cns = ci.childNodes, j = 0, cn, empty = true;
5531 if(cn.nodeType == 1 || cn.nodeType == 3){
5543 "contains" : function(c, v){
5544 var r = [], ri = -1;
5545 for(var i = 0, ci; ci = c[i]; i++){
5546 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5553 "nodeValue" : function(c, v){
5554 var r = [], ri = -1;
5555 for(var i = 0, ci; ci = c[i]; i++){
5556 if(ci.firstChild && ci.firstChild.nodeValue == v){
5563 "checked" : function(c){
5564 var r = [], ri = -1;
5565 for(var i = 0, ci; ci = c[i]; i++){
5566 if(ci.checked == true){
5573 "not" : function(c, ss){
5574 return Roo.DomQuery.filter(c, ss, true);
5577 "odd" : function(c){
5578 return this["nth-child"](c, "odd");
5581 "even" : function(c){
5582 return this["nth-child"](c, "even");
5585 "nth" : function(c, a){
5586 return c[a-1] || [];
5589 "first" : function(c){
5593 "last" : function(c){
5594 return c[c.length-1] || [];
5597 "has" : function(c, ss){
5598 var s = Roo.DomQuery.select;
5599 var r = [], ri = -1;
5600 for(var i = 0, ci; ci = c[i]; i++){
5601 if(s(ss, ci).length > 0){
5608 "next" : function(c, ss){
5609 var is = Roo.DomQuery.is;
5610 var r = [], ri = -1;
5611 for(var i = 0, ci; ci = c[i]; i++){
5620 "prev" : function(c, ss){
5621 var is = Roo.DomQuery.is;
5622 var r = [], ri = -1;
5623 for(var i = 0, ci; ci = c[i]; i++){
5636 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5637 * @param {String} path The selector/xpath query
5638 * @param {Node} root (optional) The start of the query (defaults to document).
5643 Roo.query = Roo.DomQuery.select;
5646 * Ext JS Library 1.1.1
5647 * Copyright(c) 2006-2007, Ext JS, LLC.
5649 * Originally Released Under LGPL - original licence link has changed is not relivant.
5652 * <script type="text/javascript">
5656 * @class Roo.util.Observable
5657 * Base class that provides a common interface for publishing events. Subclasses are expected to
5658 * to have a property "events" with all the events defined.<br>
5661 Employee = function(name){
5668 Roo.extend(Employee, Roo.util.Observable);
5670 * @param {Object} config properties to use (incuding events / listeners)
5673 Roo.util.Observable = function(cfg){
5676 this.addEvents(cfg.events || {});
5678 delete cfg.events; // make sure
5681 Roo.apply(this, cfg);
5684 this.on(this.listeners);
5685 delete this.listeners;
5688 Roo.util.Observable.prototype = {
5690 * @cfg {Object} listeners list of events and functions to call for this object,
5694 'click' : function(e) {
5704 * Fires the specified event with the passed parameters (minus the event name).
5705 * @param {String} eventName
5706 * @param {Object...} args Variable number of parameters are passed to handlers
5707 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5709 fireEvent : function(){
5710 var ce = this.events[arguments[0].toLowerCase()];
5711 if(typeof ce == "object"){
5712 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5719 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5722 * Appends an event handler to this component
5723 * @param {String} eventName The type of event to listen for
5724 * @param {Function} handler The method the event invokes
5725 * @param {Object} scope (optional) The scope in which to execute the handler
5726 * function. The handler function's "this" context.
5727 * @param {Object} options (optional) An object containing handler configuration
5728 * properties. This may contain any of the following properties:<ul>
5729 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5730 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5731 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5732 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5733 * by the specified number of milliseconds. If the event fires again within that time, the original
5734 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5737 * <b>Combining Options</b><br>
5738 * Using the options argument, it is possible to combine different types of listeners:<br>
5740 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5742 el.on('click', this.onClick, this, {
5749 * <b>Attaching multiple handlers in 1 call</b><br>
5750 * The method also allows for a single argument to be passed which is a config object containing properties
5751 * which specify multiple handlers.
5760 fn: this.onMouseOver,
5764 fn: this.onMouseOut,
5770 * Or a shorthand syntax which passes the same scope object to all handlers:
5773 'click': this.onClick,
5774 'mouseover': this.onMouseOver,
5775 'mouseout': this.onMouseOut,
5780 addListener : function(eventName, fn, scope, o){
5781 if(typeof eventName == "object"){
5784 if(this.filterOptRe.test(e)){
5787 if(typeof o[e] == "function"){
5789 this.addListener(e, o[e], o.scope, o);
5791 // individual options
5792 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5797 o = (!o || typeof o == "boolean") ? {} : o;
5798 eventName = eventName.toLowerCase();
5799 var ce = this.events[eventName] || true;
5800 if(typeof ce == "boolean"){
5801 ce = new Roo.util.Event(this, eventName);
5802 this.events[eventName] = ce;
5804 ce.addListener(fn, scope, o);
5808 * Removes a listener
5809 * @param {String} eventName The type of event to listen for
5810 * @param {Function} handler The handler to remove
5811 * @param {Object} scope (optional) The scope (this object) for the handler
5813 removeListener : function(eventName, fn, scope){
5814 var ce = this.events[eventName.toLowerCase()];
5815 if(typeof ce == "object"){
5816 ce.removeListener(fn, scope);
5821 * Removes all listeners for this object
5823 purgeListeners : function(){
5824 for(var evt in this.events){
5825 if(typeof this.events[evt] == "object"){
5826 this.events[evt].clearListeners();
5831 relayEvents : function(o, events){
5832 var createHandler = function(ename){
5834 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5837 for(var i = 0, len = events.length; i < len; i++){
5838 var ename = events[i];
5839 if(!this.events[ename]){ this.events[ename] = true; };
5840 o.on(ename, createHandler(ename), this);
5845 * Used to define events on this Observable
5846 * @param {Object} object The object with the events defined
5848 addEvents : function(o){
5852 Roo.applyIf(this.events, o);
5856 * Checks to see if this object has any listeners for a specified event
5857 * @param {String} eventName The name of the event to check for
5858 * @return {Boolean} True if the event is being listened for, else false
5860 hasListener : function(eventName){
5861 var e = this.events[eventName];
5862 return typeof e == "object" && e.listeners.length > 0;
5866 * Appends an event handler to this element (shorthand for addListener)
5867 * @param {String} eventName The type of event to listen for
5868 * @param {Function} handler The method the event invokes
5869 * @param {Object} scope (optional) The scope in which to execute the handler
5870 * function. The handler function's "this" context.
5871 * @param {Object} options (optional)
5874 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5876 * Removes a listener (shorthand for removeListener)
5877 * @param {String} eventName The type of event to listen for
5878 * @param {Function} handler The handler to remove
5879 * @param {Object} scope (optional) The scope (this object) for the handler
5882 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5885 * Starts capture on the specified Observable. All events will be passed
5886 * to the supplied function with the event name + standard signature of the event
5887 * <b>before</b> the event is fired. If the supplied function returns false,
5888 * the event will not fire.
5889 * @param {Observable} o The Observable to capture
5890 * @param {Function} fn The function to call
5891 * @param {Object} scope (optional) The scope (this object) for the fn
5894 Roo.util.Observable.capture = function(o, fn, scope){
5895 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5899 * Removes <b>all</b> added captures from the Observable.
5900 * @param {Observable} o The Observable to release
5903 Roo.util.Observable.releaseCapture = function(o){
5904 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5909 var createBuffered = function(h, o, scope){
5910 var task = new Roo.util.DelayedTask();
5912 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5916 var createSingle = function(h, e, fn, scope){
5918 e.removeListener(fn, scope);
5919 return h.apply(scope, arguments);
5923 var createDelayed = function(h, o, scope){
5925 var args = Array.prototype.slice.call(arguments, 0);
5926 setTimeout(function(){
5927 h.apply(scope, args);
5932 Roo.util.Event = function(obj, name){
5935 this.listeners = [];
5938 Roo.util.Event.prototype = {
5939 addListener : function(fn, scope, options){
5940 var o = options || {};
5941 scope = scope || this.obj;
5942 if(!this.isListening(fn, scope)){
5943 var l = {fn: fn, scope: scope, options: o};
5946 h = createDelayed(h, o, scope);
5949 h = createSingle(h, this, fn, scope);
5952 h = createBuffered(h, o, scope);
5955 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5956 this.listeners.push(l);
5958 this.listeners = this.listeners.slice(0);
5959 this.listeners.push(l);
5964 findListener : function(fn, scope){
5965 scope = scope || this.obj;
5966 var ls = this.listeners;
5967 for(var i = 0, len = ls.length; i < len; i++){
5969 if(l.fn == fn && l.scope == scope){
5976 isListening : function(fn, scope){
5977 return this.findListener(fn, scope) != -1;
5980 removeListener : function(fn, scope){
5982 if((index = this.findListener(fn, scope)) != -1){
5984 this.listeners.splice(index, 1);
5986 this.listeners = this.listeners.slice(0);
5987 this.listeners.splice(index, 1);
5994 clearListeners : function(){
5995 this.listeners = [];
5999 var ls = this.listeners, scope, len = ls.length;
6002 var args = Array.prototype.slice.call(arguments, 0);
6003 for(var i = 0; i < len; i++){
6005 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
6006 this.firing = false;
6010 this.firing = false;
6017 * Ext JS Library 1.1.1
6018 * Copyright(c) 2006-2007, Ext JS, LLC.
6020 * Originally Released Under LGPL - original licence link has changed is not relivant.
6023 * <script type="text/javascript">
6027 * @class Roo.EventManager
6028 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6029 * several useful events directly.
6030 * See {@link Roo.EventObject} for more details on normalized event objects.
6033 Roo.EventManager = function(){
6034 var docReadyEvent, docReadyProcId, docReadyState = false;
6035 var resizeEvent, resizeTask, textEvent, textSize;
6036 var E = Roo.lib.Event;
6037 var D = Roo.lib.Dom;
6040 var fireDocReady = function(){
6042 docReadyState = true;
6045 clearInterval(docReadyProcId);
6047 if(Roo.isGecko || Roo.isOpera) {
6048 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6051 var defer = document.getElementById("ie-deferred-loader");
6053 defer.onreadystatechange = null;
6054 defer.parentNode.removeChild(defer);
6058 docReadyEvent.fire();
6059 docReadyEvent.clearListeners();
6064 var initDocReady = function(){
6065 docReadyEvent = new Roo.util.Event();
6066 if(Roo.isGecko || Roo.isOpera) {
6067 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6069 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6070 var defer = document.getElementById("ie-deferred-loader");
6071 defer.onreadystatechange = function(){
6072 if(this.readyState == "complete"){
6076 }else if(Roo.isSafari){
6077 docReadyProcId = setInterval(function(){
6078 var rs = document.readyState;
6079 if(rs == "complete") {
6084 // no matter what, make sure it fires on load
6085 E.on(window, "load", fireDocReady);
6088 var createBuffered = function(h, o){
6089 var task = new Roo.util.DelayedTask(h);
6091 // create new event object impl so new events don't wipe out properties
6092 e = new Roo.EventObjectImpl(e);
6093 task.delay(o.buffer, h, null, [e]);
6097 var createSingle = function(h, el, ename, fn){
6099 Roo.EventManager.removeListener(el, ename, fn);
6104 var createDelayed = function(h, o){
6106 // create new event object impl so new events don't wipe out properties
6107 e = new Roo.EventObjectImpl(e);
6108 setTimeout(function(){
6114 var listen = function(element, ename, opt, fn, scope){
6115 var o = (!opt || typeof opt == "boolean") ? {} : opt;
6116 fn = fn || o.fn; scope = scope || o.scope;
6117 var el = Roo.getDom(element);
6119 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6121 var h = function(e){
6122 e = Roo.EventObject.setEvent(e);
6125 t = e.getTarget(o.delegate, el);
6132 if(o.stopEvent === true){
6135 if(o.preventDefault === true){
6138 if(o.stopPropagation === true){
6139 e.stopPropagation();
6142 if(o.normalized === false){
6146 fn.call(scope || el, e, t, o);
6149 h = createDelayed(h, o);
6152 h = createSingle(h, el, ename, fn);
6155 h = createBuffered(h, o);
6157 fn._handlers = fn._handlers || [];
6158 fn._handlers.push([Roo.id(el), ename, h]);
6161 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6162 el.addEventListener("DOMMouseScroll", h, false);
6163 E.on(window, 'unload', function(){
6164 el.removeEventListener("DOMMouseScroll", h, false);
6167 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6168 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6173 var stopListening = function(el, ename, fn){
6174 var id = Roo.id(el), hds = fn._handlers, hd = fn;
6176 for(var i = 0, len = hds.length; i < len; i++){
6178 if(h[0] == id && h[1] == ename){
6185 E.un(el, ename, hd);
6186 el = Roo.getDom(el);
6187 if(ename == "mousewheel" && el.addEventListener){
6188 el.removeEventListener("DOMMouseScroll", hd, false);
6190 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6191 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6195 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6202 * @scope Roo.EventManager
6207 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6208 * object with a Roo.EventObject
6209 * @param {Function} fn The method the event invokes
6210 * @param {Object} scope An object that becomes the scope of the handler
6211 * @param {boolean} override If true, the obj passed in becomes
6212 * the execution scope of the listener
6213 * @return {Function} The wrapped function
6216 wrap : function(fn, scope, override){
6218 Roo.EventObject.setEvent(e);
6219 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6224 * Appends an event handler to an element (shorthand for addListener)
6225 * @param {String/HTMLElement} element The html element or id to assign the
6226 * @param {String} eventName The type of event to listen for
6227 * @param {Function} handler The method the event invokes
6228 * @param {Object} scope (optional) The scope in which to execute the handler
6229 * function. The handler function's "this" context.
6230 * @param {Object} options (optional) An object containing handler configuration
6231 * properties. This may contain any of the following properties:<ul>
6232 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6233 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6234 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6235 * <li>preventDefault {Boolean} True to prevent the default action</li>
6236 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6237 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6238 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6239 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6240 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6241 * by the specified number of milliseconds. If the event fires again within that time, the original
6242 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6245 * <b>Combining Options</b><br>
6246 * Using the options argument, it is possible to combine different types of listeners:<br>
6248 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6250 el.on('click', this.onClick, this, {
6257 * <b>Attaching multiple handlers in 1 call</b><br>
6258 * The method also allows for a single argument to be passed which is a config object containing properties
6259 * which specify multiple handlers.
6269 fn: this.onMouseOver
6278 * Or a shorthand syntax:<br>
6281 'click' : this.onClick,
6282 'mouseover' : this.onMouseOver,
6283 'mouseout' : this.onMouseOut
6287 addListener : function(element, eventName, fn, scope, options){
6288 if(typeof eventName == "object"){
6294 if(typeof o[e] == "function"){
6296 listen(element, e, o, o[e], o.scope);
6298 // individual options
6299 listen(element, e, o[e]);
6304 return listen(element, eventName, options, fn, scope);
6308 * Removes an event handler
6310 * @param {String/HTMLElement} element The id or html element to remove the
6312 * @param {String} eventName The type of event
6313 * @param {Function} fn
6314 * @return {Boolean} True if a listener was actually removed
6316 removeListener : function(element, eventName, fn){
6317 return stopListening(element, eventName, fn);
6321 * Fires when the document is ready (before onload and before images are loaded). Can be
6322 * accessed shorthanded Roo.onReady().
6323 * @param {Function} fn The method the event invokes
6324 * @param {Object} scope An object that becomes the scope of the handler
6325 * @param {boolean} options
6327 onDocumentReady : function(fn, scope, options){
6328 if(docReadyState){ // if it already fired
6329 docReadyEvent.addListener(fn, scope, options);
6330 docReadyEvent.fire();
6331 docReadyEvent.clearListeners();
6337 docReadyEvent.addListener(fn, scope, options);
6341 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6342 * @param {Function} fn The method the event invokes
6343 * @param {Object} scope An object that becomes the scope of the handler
6344 * @param {boolean} options
6346 onWindowResize : function(fn, scope, options){
6348 resizeEvent = new Roo.util.Event();
6349 resizeTask = new Roo.util.DelayedTask(function(){
6350 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6352 E.on(window, "resize", function(){
6354 resizeTask.delay(50);
6356 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6360 resizeEvent.addListener(fn, scope, options);
6364 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6365 * @param {Function} fn The method the event invokes
6366 * @param {Object} scope An object that becomes the scope of the handler
6367 * @param {boolean} options
6369 onTextResize : function(fn, scope, options){
6371 textEvent = new Roo.util.Event();
6372 var textEl = new Roo.Element(document.createElement('div'));
6373 textEl.dom.className = 'x-text-resize';
6374 textEl.dom.innerHTML = 'X';
6375 textEl.appendTo(document.body);
6376 textSize = textEl.dom.offsetHeight;
6377 setInterval(function(){
6378 if(textEl.dom.offsetHeight != textSize){
6379 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6381 }, this.textResizeInterval);
6383 textEvent.addListener(fn, scope, options);
6387 * Removes the passed window resize listener.
6388 * @param {Function} fn The method the event invokes
6389 * @param {Object} scope The scope of handler
6391 removeResizeListener : function(fn, scope){
6393 resizeEvent.removeListener(fn, scope);
6398 fireResize : function(){
6400 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6404 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6408 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6410 textResizeInterval : 50
6415 * @scopeAlias pub=Roo.EventManager
6419 * Appends an event handler to an element (shorthand for addListener)
6420 * @param {String/HTMLElement} element The html element or id to assign the
6421 * @param {String} eventName The type of event to listen for
6422 * @param {Function} handler The method the event invokes
6423 * @param {Object} scope (optional) The scope in which to execute the handler
6424 * function. The handler function's "this" context.
6425 * @param {Object} options (optional) An object containing handler configuration
6426 * properties. This may contain any of the following properties:<ul>
6427 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6428 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6429 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6430 * <li>preventDefault {Boolean} True to prevent the default action</li>
6431 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6432 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6433 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6434 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6435 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6436 * by the specified number of milliseconds. If the event fires again within that time, the original
6437 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6440 * <b>Combining Options</b><br>
6441 * Using the options argument, it is possible to combine different types of listeners:<br>
6443 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6445 el.on('click', this.onClick, this, {
6452 * <b>Attaching multiple handlers in 1 call</b><br>
6453 * The method also allows for a single argument to be passed which is a config object containing properties
6454 * which specify multiple handlers.
6464 fn: this.onMouseOver
6473 * Or a shorthand syntax:<br>
6476 'click' : this.onClick,
6477 'mouseover' : this.onMouseOver,
6478 'mouseout' : this.onMouseOut
6482 pub.on = pub.addListener;
6483 pub.un = pub.removeListener;
6485 pub.stoppedMouseDownEvent = new Roo.util.Event();
6489 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6490 * @param {Function} fn The method the event invokes
6491 * @param {Object} scope An object that becomes the scope of the handler
6492 * @param {boolean} override If true, the obj passed in becomes
6493 * the execution scope of the listener
6497 Roo.onReady = Roo.EventManager.onDocumentReady;
6499 Roo.onReady(function(){
6500 var bd = Roo.get(document.body);
6505 : Roo.isGecko ? "roo-gecko"
6506 : Roo.isOpera ? "roo-opera"
6507 : Roo.isSafari ? "roo-safari" : ""];
6510 cls.push("roo-mac");
6513 cls.push("roo-linux");
6515 if(Roo.isBorderBox){
6516 cls.push('roo-border-box');
6518 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6519 var p = bd.dom.parentNode;
6521 p.className += ' roo-strict';
6524 bd.addClass(cls.join(' '));
6528 * @class Roo.EventObject
6529 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6530 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6533 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6535 var target = e.getTarget();
6538 var myDiv = Roo.get("myDiv");
6539 myDiv.on("click", handleClick);
6541 Roo.EventManager.on("myDiv", 'click', handleClick);
6542 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6546 Roo.EventObject = function(){
6548 var E = Roo.lib.Event;
6550 // safari keypress events for special keys return bad keycodes
6553 63235 : 39, // right
6556 63276 : 33, // page up
6557 63277 : 34, // page down
6558 63272 : 46, // delete
6563 // normalize button clicks
6564 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6565 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6567 Roo.EventObjectImpl = function(e){
6569 this.setEvent(e.browserEvent || e);
6572 Roo.EventObjectImpl.prototype = {
6574 * Used to fix doc tools.
6575 * @scope Roo.EventObject.prototype
6581 /** The normal browser event */
6582 browserEvent : null,
6583 /** The button pressed in a mouse event */
6585 /** True if the shift key was down during the event */
6587 /** True if the control key was down during the event */
6589 /** True if the alt key was down during the event */
6648 setEvent : function(e){
6649 if(e == this || (e && e.browserEvent)){ // already wrapped
6652 this.browserEvent = e;
6654 // normalize buttons
6655 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6656 if(e.type == 'click' && this.button == -1){
6660 this.shiftKey = e.shiftKey;
6661 // mac metaKey behaves like ctrlKey
6662 this.ctrlKey = e.ctrlKey || e.metaKey;
6663 this.altKey = e.altKey;
6664 // in getKey these will be normalized for the mac
6665 this.keyCode = e.keyCode;
6666 // keyup warnings on firefox.
6667 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6668 // cache the target for the delayed and or buffered events
6669 this.target = E.getTarget(e);
6671 this.xy = E.getXY(e);
6674 this.shiftKey = false;
6675 this.ctrlKey = false;
6676 this.altKey = false;
6686 * Stop the event (preventDefault and stopPropagation)
6688 stopEvent : function(){
6689 if(this.browserEvent){
6690 if(this.browserEvent.type == 'mousedown'){
6691 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6693 E.stopEvent(this.browserEvent);
6698 * Prevents the browsers default handling of the event.
6700 preventDefault : function(){
6701 if(this.browserEvent){
6702 E.preventDefault(this.browserEvent);
6707 isNavKeyPress : function(){
6708 var k = this.keyCode;
6709 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6710 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6713 isSpecialKey : function(){
6714 var k = this.keyCode;
6715 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6716 (k == 16) || (k == 17) ||
6717 (k >= 18 && k <= 20) ||
6718 (k >= 33 && k <= 35) ||
6719 (k >= 36 && k <= 39) ||
6720 (k >= 44 && k <= 45);
6723 * Cancels bubbling of the event.
6725 stopPropagation : function(){
6726 if(this.browserEvent){
6727 if(this.type == 'mousedown'){
6728 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6730 E.stopPropagation(this.browserEvent);
6735 * Gets the key code for the event.
6738 getCharCode : function(){
6739 return this.charCode || this.keyCode;
6743 * Returns a normalized keyCode for the event.
6744 * @return {Number} The key code
6746 getKey : function(){
6747 var k = this.keyCode || this.charCode;
6748 return Roo.isSafari ? (safariKeys[k] || k) : k;
6752 * Gets the x coordinate of the event.
6755 getPageX : function(){
6760 * Gets the y coordinate of the event.
6763 getPageY : function(){
6768 * Gets the time of the event.
6771 getTime : function(){
6772 if(this.browserEvent){
6773 return E.getTime(this.browserEvent);
6779 * Gets the page coordinates of the event.
6780 * @return {Array} The xy values like [x, y]
6787 * Gets the target for the event.
6788 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6789 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6790 search as a number or element (defaults to 10 || document.body)
6791 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6792 * @return {HTMLelement}
6794 getTarget : function(selector, maxDepth, returnEl){
6795 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6798 * Gets the related target.
6799 * @return {HTMLElement}
6801 getRelatedTarget : function(){
6802 if(this.browserEvent){
6803 return E.getRelatedTarget(this.browserEvent);
6809 * Normalizes mouse wheel delta across browsers
6810 * @return {Number} The delta
6812 getWheelDelta : function(){
6813 var e = this.browserEvent;
6815 if(e.wheelDelta){ /* IE/Opera. */
6816 delta = e.wheelDelta/120;
6817 }else if(e.detail){ /* Mozilla case. */
6818 delta = -e.detail/3;
6824 * Returns true if the control, meta, shift or alt key was pressed during this event.
6827 hasModifier : function(){
6828 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6832 * Returns true if the target of this event equals el or is a child of el
6833 * @param {String/HTMLElement/Element} el
6834 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6837 within : function(el, related){
6838 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6839 return t && Roo.fly(el).contains(t);
6842 getPoint : function(){
6843 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6847 return new Roo.EventObjectImpl();
6852 * Ext JS Library 1.1.1
6853 * Copyright(c) 2006-2007, Ext JS, LLC.
6855 * Originally Released Under LGPL - original licence link has changed is not relivant.
6858 * <script type="text/javascript">
6862 // was in Composite Element!??!?!
6865 var D = Roo.lib.Dom;
6866 var E = Roo.lib.Event;
6867 var A = Roo.lib.Anim;
6869 // local style camelizing for speed
6871 var camelRe = /(-[a-z])/gi;
6872 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6873 var view = document.defaultView;
6876 * @class Roo.Element
6877 * Represents an Element in the DOM.<br><br>
6880 var el = Roo.get("my-div");
6883 var el = getEl("my-div");
6885 // or with a DOM element
6886 var el = Roo.get(myDivElement);
6888 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6889 * each call instead of constructing a new one.<br><br>
6890 * <b>Animations</b><br />
6891 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6892 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6894 Option Default Description
6895 --------- -------- ---------------------------------------------
6896 duration .35 The duration of the animation in seconds
6897 easing easeOut The YUI easing method
6898 callback none A function to execute when the anim completes
6899 scope this The scope (this) of the callback function
6901 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6902 * manipulate the animation. Here's an example:
6904 var el = Roo.get("my-div");
6909 // default animation
6910 el.setWidth(100, true);
6912 // animation with some options set
6919 // using the "anim" property to get the Anim object
6925 el.setWidth(100, opt);
6927 if(opt.anim.isAnimated()){
6931 * <b> Composite (Collections of) Elements</b><br />
6932 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
6933 * @constructor Create a new Element directly.
6934 * @param {String/HTMLElement} element
6935 * @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).
6937 Roo.Element = function(element, forceNew){
6938 var dom = typeof element == "string" ?
6939 document.getElementById(element) : element;
6940 if(!dom){ // invalid id/element
6944 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
6945 return Roo.Element.cache[id];
6955 * The DOM element ID
6958 this.id = id || Roo.id(dom);
6961 var El = Roo.Element;
6965 * The element's default display mode (defaults to "")
6968 originalDisplay : "",
6972 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
6977 * Sets the element's visibility mode. When setVisible() is called it
6978 * will use this to determine whether to set the visibility or the display property.
6979 * @param visMode Element.VISIBILITY or Element.DISPLAY
6980 * @return {Roo.Element} this
6982 setVisibilityMode : function(visMode){
6983 this.visibilityMode = visMode;
6987 * Convenience method for setVisibilityMode(Element.DISPLAY)
6988 * @param {String} display (optional) What to set display to when visible
6989 * @return {Roo.Element} this
6991 enableDisplayMode : function(display){
6992 this.setVisibilityMode(El.DISPLAY);
6993 if(typeof display != "undefined") this.originalDisplay = display;
6998 * 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)
6999 * @param {String} selector The simple selector to test
7000 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7001 search as a number or element (defaults to 10 || document.body)
7002 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7003 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7005 findParent : function(simpleSelector, maxDepth, returnEl){
7006 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7007 maxDepth = maxDepth || 50;
7008 if(typeof maxDepth != "number"){
7009 stopEl = Roo.getDom(maxDepth);
7012 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7013 if(dq.is(p, simpleSelector)){
7014 return returnEl ? Roo.get(p) : p;
7024 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7025 * @param {String} selector The simple selector to test
7026 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7027 search as a number or element (defaults to 10 || document.body)
7028 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7029 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7031 findParentNode : function(simpleSelector, maxDepth, returnEl){
7032 var p = Roo.fly(this.dom.parentNode, '_internal');
7033 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7037 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
7038 * This is a shortcut for findParentNode() that always returns an Roo.Element.
7039 * @param {String} selector The simple selector to test
7040 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7041 search as a number or element (defaults to 10 || document.body)
7042 * @return {Roo.Element} The matching DOM node (or null if no match was found)
7044 up : function(simpleSelector, maxDepth){
7045 return this.findParentNode(simpleSelector, maxDepth, true);
7051 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
7052 * @param {String} selector The simple selector to test
7053 * @return {Boolean} True if this element matches the selector, else false
7055 is : function(simpleSelector){
7056 return Roo.DomQuery.is(this.dom, simpleSelector);
7060 * Perform animation on this element.
7061 * @param {Object} args The YUI animation control args
7062 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
7063 * @param {Function} onComplete (optional) Function to call when animation completes
7064 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
7065 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
7066 * @return {Roo.Element} this
7068 animate : function(args, duration, onComplete, easing, animType){
7069 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7074 * @private Internal animation call
7076 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7077 animType = animType || 'run';
7079 var anim = Roo.lib.Anim[animType](
7081 (opt.duration || defaultDur) || .35,
7082 (opt.easing || defaultEase) || 'easeOut',
7084 Roo.callback(cb, this);
7085 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7093 // private legacy anim prep
7094 preanim : function(a, i){
7095 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7099 * Removes worthless text nodes
7100 * @param {Boolean} forceReclean (optional) By default the element
7101 * keeps track if it has been cleaned already so
7102 * you can call this over and over. However, if you update the element and
7103 * need to force a reclean, you can pass true.
7105 clean : function(forceReclean){
7106 if(this.isCleaned && forceReclean !== true){
7110 var d = this.dom, n = d.firstChild, ni = -1;
7112 var nx = n.nextSibling;
7113 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7120 this.isCleaned = true;
7125 calcOffsetsTo : function(el){
7128 var restorePos = false;
7129 if(el.getStyle('position') == 'static'){
7130 el.position('relative');
7135 while(op && op != d && op.tagName != 'HTML'){
7138 op = op.offsetParent;
7141 el.position('static');
7147 * Scrolls this element into view within the passed container.
7148 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7149 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7150 * @return {Roo.Element} this
7152 scrollIntoView : function(container, hscroll){
7153 var c = Roo.getDom(container) || document.body;
7156 var o = this.calcOffsetsTo(c),
7159 b = t+el.offsetHeight,
7160 r = l+el.offsetWidth;
7162 var ch = c.clientHeight;
7163 var ct = parseInt(c.scrollTop, 10);
7164 var cl = parseInt(c.scrollLeft, 10);
7166 var cr = cl + c.clientWidth;
7174 if(hscroll !== false){
7178 c.scrollLeft = r-c.clientWidth;
7185 scrollChildIntoView : function(child, hscroll){
7186 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7190 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7191 * the new height may not be available immediately.
7192 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7193 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7194 * @param {Function} onComplete (optional) Function to call when animation completes
7195 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7196 * @return {Roo.Element} this
7198 autoHeight : function(animate, duration, onComplete, easing){
7199 var oldHeight = this.getHeight();
7201 this.setHeight(1); // force clipping
7202 setTimeout(function(){
7203 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7205 this.setHeight(height);
7207 if(typeof onComplete == "function"){
7211 this.setHeight(oldHeight); // restore original height
7212 this.setHeight(height, animate, duration, function(){
7214 if(typeof onComplete == "function") onComplete();
7215 }.createDelegate(this), easing);
7217 }.createDelegate(this), 0);
7222 * Returns true if this element is an ancestor of the passed element
7223 * @param {HTMLElement/String} el The element to check
7224 * @return {Boolean} True if this element is an ancestor of el, else false
7226 contains : function(el){
7227 if(!el){return false;}
7228 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7232 * Checks whether the element is currently visible using both visibility and display properties.
7233 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7234 * @return {Boolean} True if the element is currently visible, else false
7236 isVisible : function(deep) {
7237 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7238 if(deep !== true || !vis){
7241 var p = this.dom.parentNode;
7242 while(p && p.tagName.toLowerCase() != "body"){
7243 if(!Roo.fly(p, '_isVisible').isVisible()){
7252 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7253 * @param {String} selector The CSS selector
7254 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7255 * @return {CompositeElement/CompositeElementLite} The composite element
7257 select : function(selector, unique){
7258 return El.select(selector, unique, this.dom);
7262 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7263 * @param {String} selector The CSS selector
7264 * @return {Array} An array of the matched nodes
7266 query : function(selector, unique){
7267 return Roo.DomQuery.select(selector, this.dom);
7271 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7272 * @param {String} selector The CSS selector
7273 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7274 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7276 child : function(selector, returnDom){
7277 var n = Roo.DomQuery.selectNode(selector, this.dom);
7278 return returnDom ? n : Roo.get(n);
7282 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7283 * @param {String} selector The CSS selector
7284 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7285 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7287 down : function(selector, returnDom){
7288 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7289 return returnDom ? n : Roo.get(n);
7293 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7294 * @param {String} group The group the DD object is member of
7295 * @param {Object} config The DD config object
7296 * @param {Object} overrides An object containing methods to override/implement on the DD object
7297 * @return {Roo.dd.DD} The DD object
7299 initDD : function(group, config, overrides){
7300 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7301 return Roo.apply(dd, overrides);
7305 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7306 * @param {String} group The group the DDProxy object is member of
7307 * @param {Object} config The DDProxy config object
7308 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7309 * @return {Roo.dd.DDProxy} The DDProxy object
7311 initDDProxy : function(group, config, overrides){
7312 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7313 return Roo.apply(dd, overrides);
7317 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7318 * @param {String} group The group the DDTarget object is member of
7319 * @param {Object} config The DDTarget config object
7320 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7321 * @return {Roo.dd.DDTarget} The DDTarget object
7323 initDDTarget : function(group, config, overrides){
7324 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7325 return Roo.apply(dd, overrides);
7329 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7330 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7331 * @param {Boolean} visible Whether the element is visible
7332 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7333 * @return {Roo.Element} this
7335 setVisible : function(visible, animate){
7337 if(this.visibilityMode == El.DISPLAY){
7338 this.setDisplayed(visible);
7341 this.dom.style.visibility = visible ? "visible" : "hidden";
7344 // closure for composites
7346 var visMode = this.visibilityMode;
7348 this.setOpacity(.01);
7349 this.setVisible(true);
7351 this.anim({opacity: { to: (visible?1:0) }},
7352 this.preanim(arguments, 1),
7353 null, .35, 'easeIn', function(){
7355 if(visMode == El.DISPLAY){
7356 dom.style.display = "none";
7358 dom.style.visibility = "hidden";
7360 Roo.get(dom).setOpacity(1);
7368 * Returns true if display is not "none"
7371 isDisplayed : function() {
7372 return this.getStyle("display") != "none";
7376 * Toggles the element's visibility or display, depending on visibility mode.
7377 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7378 * @return {Roo.Element} this
7380 toggle : function(animate){
7381 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7386 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7387 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7388 * @return {Roo.Element} this
7390 setDisplayed : function(value) {
7391 if(typeof value == "boolean"){
7392 value = value ? this.originalDisplay : "none";
7394 this.setStyle("display", value);
7399 * Tries to focus the element. Any exceptions are caught and ignored.
7400 * @return {Roo.Element} this
7402 focus : function() {
7410 * Tries to blur the element. Any exceptions are caught and ignored.
7411 * @return {Roo.Element} this
7421 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7422 * @param {String/Array} className The CSS class to add, or an array of classes
7423 * @return {Roo.Element} this
7425 addClass : function(className){
7426 if(className instanceof Array){
7427 for(var i = 0, len = className.length; i < len; i++) {
7428 this.addClass(className[i]);
7431 if(className && !this.hasClass(className)){
7432 this.dom.className = this.dom.className + " " + className;
7439 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7440 * @param {String/Array} className The CSS class to add, or an array of classes
7441 * @return {Roo.Element} this
7443 radioClass : function(className){
7444 var siblings = this.dom.parentNode.childNodes;
7445 for(var i = 0; i < siblings.length; i++) {
7446 var s = siblings[i];
7447 if(s.nodeType == 1){
7448 Roo.get(s).removeClass(className);
7451 this.addClass(className);
7456 * Removes one or more CSS classes from the element.
7457 * @param {String/Array} className The CSS class to remove, or an array of classes
7458 * @return {Roo.Element} this
7460 removeClass : function(className){
7461 if(!className || !this.dom.className){
7464 if(className instanceof Array){
7465 for(var i = 0, len = className.length; i < len; i++) {
7466 this.removeClass(className[i]);
7469 if(this.hasClass(className)){
7470 var re = this.classReCache[className];
7472 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7473 this.classReCache[className] = re;
7475 this.dom.className =
7476 this.dom.className.replace(re, " ");
7486 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7487 * @param {String} className The CSS class to toggle
7488 * @return {Roo.Element} this
7490 toggleClass : function(className){
7491 if(this.hasClass(className)){
7492 this.removeClass(className);
7494 this.addClass(className);
7500 * Checks if the specified CSS class exists on this element's DOM node.
7501 * @param {String} className The CSS class to check for
7502 * @return {Boolean} True if the class exists, else false
7504 hasClass : function(className){
7505 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7509 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7510 * @param {String} oldClassName The CSS class to replace
7511 * @param {String} newClassName The replacement CSS class
7512 * @return {Roo.Element} this
7514 replaceClass : function(oldClassName, newClassName){
7515 this.removeClass(oldClassName);
7516 this.addClass(newClassName);
7521 * Returns an object with properties matching the styles requested.
7522 * For example, el.getStyles('color', 'font-size', 'width') might return
7523 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7524 * @param {String} style1 A style name
7525 * @param {String} style2 A style name
7526 * @param {String} etc.
7527 * @return {Object} The style object
7529 getStyles : function(){
7530 var a = arguments, len = a.length, r = {};
7531 for(var i = 0; i < len; i++){
7532 r[a[i]] = this.getStyle(a[i]);
7538 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7539 * @param {String} property The style property whose value is returned.
7540 * @return {String} The current value of the style property for this element.
7542 getStyle : function(){
7543 return view && view.getComputedStyle ?
7545 var el = this.dom, v, cs, camel;
7546 if(prop == 'float'){
7549 if(el.style && (v = el.style[prop])){
7552 if(cs = view.getComputedStyle(el, "")){
7553 if(!(camel = propCache[prop])){
7554 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7561 var el = this.dom, v, cs, camel;
7562 if(prop == 'opacity'){
7563 if(typeof el.style.filter == 'string'){
7564 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7566 var fv = parseFloat(m[1]);
7568 return fv ? fv / 100 : 0;
7573 }else if(prop == 'float'){
7574 prop = "styleFloat";
7576 if(!(camel = propCache[prop])){
7577 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7579 if(v = el.style[camel]){
7582 if(cs = el.currentStyle){
7590 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7591 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7592 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7593 * @return {Roo.Element} this
7595 setStyle : function(prop, value){
7596 if(typeof prop == "string"){
7598 if (prop == 'float') {
7599 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7604 if(!(camel = propCache[prop])){
7605 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7608 if(camel == 'opacity') {
7609 this.setOpacity(value);
7611 this.dom.style[camel] = value;
7614 for(var style in prop){
7615 if(typeof prop[style] != "function"){
7616 this.setStyle(style, prop[style]);
7624 * More flexible version of {@link #setStyle} for setting style properties.
7625 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7626 * a function which returns such a specification.
7627 * @return {Roo.Element} this
7629 applyStyles : function(style){
7630 Roo.DomHelper.applyStyles(this.dom, style);
7635 * 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).
7636 * @return {Number} The X position of the element
7639 return D.getX(this.dom);
7643 * 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).
7644 * @return {Number} The Y position of the element
7647 return D.getY(this.dom);
7651 * 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).
7652 * @return {Array} The XY position of the element
7655 return D.getXY(this.dom);
7659 * 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).
7660 * @param {Number} The X position of the element
7661 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7662 * @return {Roo.Element} this
7664 setX : function(x, animate){
7666 D.setX(this.dom, x);
7668 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7674 * 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).
7675 * @param {Number} The Y position of the element
7676 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7677 * @return {Roo.Element} this
7679 setY : function(y, animate){
7681 D.setY(this.dom, y);
7683 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7689 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7690 * @param {String} left The left CSS property value
7691 * @return {Roo.Element} this
7693 setLeft : function(left){
7694 this.setStyle("left", this.addUnits(left));
7699 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7700 * @param {String} top The top CSS property value
7701 * @return {Roo.Element} this
7703 setTop : function(top){
7704 this.setStyle("top", this.addUnits(top));
7709 * Sets the element's CSS right style.
7710 * @param {String} right The right CSS property value
7711 * @return {Roo.Element} this
7713 setRight : function(right){
7714 this.setStyle("right", this.addUnits(right));
7719 * Sets the element's CSS bottom style.
7720 * @param {String} bottom The bottom CSS property value
7721 * @return {Roo.Element} this
7723 setBottom : function(bottom){
7724 this.setStyle("bottom", this.addUnits(bottom));
7729 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7730 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7731 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7732 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7733 * @return {Roo.Element} this
7735 setXY : function(pos, animate){
7737 D.setXY(this.dom, pos);
7739 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7745 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7746 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7747 * @param {Number} x X value for new position (coordinates are page-based)
7748 * @param {Number} y Y value for new position (coordinates are page-based)
7749 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7750 * @return {Roo.Element} this
7752 setLocation : function(x, y, animate){
7753 this.setXY([x, y], this.preanim(arguments, 2));
7758 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7759 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7760 * @param {Number} x X value for new position (coordinates are page-based)
7761 * @param {Number} y Y value for new position (coordinates are page-based)
7762 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7763 * @return {Roo.Element} this
7765 moveTo : function(x, y, animate){
7766 this.setXY([x, y], this.preanim(arguments, 2));
7771 * Returns the region of the given element.
7772 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7773 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7775 getRegion : function(){
7776 return D.getRegion(this.dom);
7780 * Returns the offset height of the element
7781 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7782 * @return {Number} The element's height
7784 getHeight : function(contentHeight){
7785 var h = this.dom.offsetHeight || 0;
7786 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7790 * Returns the offset width of the element
7791 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7792 * @return {Number} The element's width
7794 getWidth : function(contentWidth){
7795 var w = this.dom.offsetWidth || 0;
7796 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7800 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7801 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7802 * if a height has not been set using CSS.
7805 getComputedHeight : function(){
7806 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7808 h = parseInt(this.getStyle('height'), 10) || 0;
7809 if(!this.isBorderBox()){
7810 h += this.getFrameWidth('tb');
7817 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7818 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7819 * if a width has not been set using CSS.
7822 getComputedWidth : function(){
7823 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7825 w = parseInt(this.getStyle('width'), 10) || 0;
7826 if(!this.isBorderBox()){
7827 w += this.getFrameWidth('lr');
7834 * Returns the size of the element.
7835 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7836 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7838 getSize : function(contentSize){
7839 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7843 * Returns the width and height of the viewport.
7844 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7846 getViewSize : function(){
7847 var d = this.dom, doc = document, aw = 0, ah = 0;
7848 if(d == doc || d == doc.body){
7849 return {width : D.getViewWidth(), height: D.getViewHeight()};
7852 width : d.clientWidth,
7853 height: d.clientHeight
7859 * Returns the value of the "value" attribute
7860 * @param {Boolean} asNumber true to parse the value as a number
7861 * @return {String/Number}
7863 getValue : function(asNumber){
7864 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7868 adjustWidth : function(width){
7869 if(typeof width == "number"){
7870 if(this.autoBoxAdjust && !this.isBorderBox()){
7871 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7881 adjustHeight : function(height){
7882 if(typeof height == "number"){
7883 if(this.autoBoxAdjust && !this.isBorderBox()){
7884 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7894 * Set the width of the element
7895 * @param {Number} width The new width
7896 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7897 * @return {Roo.Element} this
7899 setWidth : function(width, animate){
7900 width = this.adjustWidth(width);
7902 this.dom.style.width = this.addUnits(width);
7904 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7910 * Set the height of the element
7911 * @param {Number} height The new height
7912 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7913 * @return {Roo.Element} this
7915 setHeight : function(height, animate){
7916 height = this.adjustHeight(height);
7918 this.dom.style.height = this.addUnits(height);
7920 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7926 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7927 * @param {Number} width The new width
7928 * @param {Number} height The new height
7929 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7930 * @return {Roo.Element} this
7932 setSize : function(width, height, animate){
7933 if(typeof width == "object"){ // in case of object from getSize()
7934 height = width.height; width = width.width;
7936 width = this.adjustWidth(width); height = this.adjustHeight(height);
7938 this.dom.style.width = this.addUnits(width);
7939 this.dom.style.height = this.addUnits(height);
7941 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
7947 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
7948 * @param {Number} x X value for new position (coordinates are page-based)
7949 * @param {Number} y Y value for new position (coordinates are page-based)
7950 * @param {Number} width The new width
7951 * @param {Number} height The new height
7952 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7953 * @return {Roo.Element} this
7955 setBounds : function(x, y, width, height, animate){
7957 this.setSize(width, height);
7958 this.setLocation(x, y);
7960 width = this.adjustWidth(width); height = this.adjustHeight(height);
7961 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
7962 this.preanim(arguments, 4), 'motion');
7968 * 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.
7969 * @param {Roo.lib.Region} region The region to fill
7970 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7971 * @return {Roo.Element} this
7973 setRegion : function(region, animate){
7974 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
7979 * Appends an event handler
7981 * @param {String} eventName The type of event to append
7982 * @param {Function} fn The method the event invokes
7983 * @param {Object} scope (optional) The scope (this object) of the fn
7984 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
7986 addListener : function(eventName, fn, scope, options){
7988 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
7993 * Removes an event handler from this element
7994 * @param {String} eventName the type of event to remove
7995 * @param {Function} fn the method the event invokes
7996 * @return {Roo.Element} this
7998 removeListener : function(eventName, fn){
7999 Roo.EventManager.removeListener(this.dom, eventName, fn);
8004 * Removes all previous added listeners from this element
8005 * @return {Roo.Element} this
8007 removeAllListeners : function(){
8008 E.purgeElement(this.dom);
8012 relayEvent : function(eventName, observable){
8013 this.on(eventName, function(e){
8014 observable.fireEvent(eventName, e);
8019 * Set the opacity of the element
8020 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
8021 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8022 * @return {Roo.Element} this
8024 setOpacity : function(opacity, animate){
8026 var s = this.dom.style;
8029 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
8030 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
8032 s.opacity = opacity;
8035 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
8041 * Gets the left X coordinate
8042 * @param {Boolean} local True to get the local css position instead of page coordinate
8045 getLeft : function(local){
8049 return parseInt(this.getStyle("left"), 10) || 0;
8054 * Gets the right X coordinate of the element (element X position + element width)
8055 * @param {Boolean} local True to get the local css position instead of page coordinate
8058 getRight : function(local){
8060 return this.getX() + this.getWidth();
8062 return (this.getLeft(true) + this.getWidth()) || 0;
8067 * Gets the top Y coordinate
8068 * @param {Boolean} local True to get the local css position instead of page coordinate
8071 getTop : function(local) {
8075 return parseInt(this.getStyle("top"), 10) || 0;
8080 * Gets the bottom Y coordinate of the element (element Y position + element height)
8081 * @param {Boolean} local True to get the local css position instead of page coordinate
8084 getBottom : function(local){
8086 return this.getY() + this.getHeight();
8088 return (this.getTop(true) + this.getHeight()) || 0;
8093 * Initializes positioning on this element. If a desired position is not passed, it will make the
8094 * the element positioned relative IF it is not already positioned.
8095 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8096 * @param {Number} zIndex (optional) The zIndex to apply
8097 * @param {Number} x (optional) Set the page X position
8098 * @param {Number} y (optional) Set the page Y position
8100 position : function(pos, zIndex, x, y){
8102 if(this.getStyle('position') == 'static'){
8103 this.setStyle('position', 'relative');
8106 this.setStyle("position", pos);
8109 this.setStyle("z-index", zIndex);
8111 if(x !== undefined && y !== undefined){
8113 }else if(x !== undefined){
8115 }else if(y !== undefined){
8121 * Clear positioning back to the default when the document was loaded
8122 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8123 * @return {Roo.Element} this
8125 clearPositioning : function(value){
8133 "position" : "static"
8139 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8140 * snapshot before performing an update and then restoring the element.
8143 getPositioning : function(){
8144 var l = this.getStyle("left");
8145 var t = this.getStyle("top");
8147 "position" : this.getStyle("position"),
8149 "right" : l ? "" : this.getStyle("right"),
8151 "bottom" : t ? "" : this.getStyle("bottom"),
8152 "z-index" : this.getStyle("z-index")
8157 * Gets the width of the border(s) for the specified side(s)
8158 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8159 * passing lr would get the border (l)eft width + the border (r)ight width.
8160 * @return {Number} The width of the sides passed added together
8162 getBorderWidth : function(side){
8163 return this.addStyles(side, El.borders);
8167 * Gets the width of the padding(s) for the specified side(s)
8168 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8169 * passing lr would get the padding (l)eft + the padding (r)ight.
8170 * @return {Number} The padding of the sides passed added together
8172 getPadding : function(side){
8173 return this.addStyles(side, El.paddings);
8177 * Set positioning with an object returned by getPositioning().
8178 * @param {Object} posCfg
8179 * @return {Roo.Element} this
8181 setPositioning : function(pc){
8182 this.applyStyles(pc);
8183 if(pc.right == "auto"){
8184 this.dom.style.right = "";
8186 if(pc.bottom == "auto"){
8187 this.dom.style.bottom = "";
8193 fixDisplay : function(){
8194 if(this.getStyle("display") == "none"){
8195 this.setStyle("visibility", "hidden");
8196 this.setStyle("display", this.originalDisplay); // first try reverting to default
8197 if(this.getStyle("display") == "none"){ // if that fails, default to block
8198 this.setStyle("display", "block");
8204 * Quick set left and top adding default units
8205 * @param {String} left The left CSS property value
8206 * @param {String} top The top CSS property value
8207 * @return {Roo.Element} this
8209 setLeftTop : function(left, top){
8210 this.dom.style.left = this.addUnits(left);
8211 this.dom.style.top = this.addUnits(top);
8216 * Move this element relative to its current position.
8217 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8218 * @param {Number} distance How far to move the element in pixels
8219 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8220 * @return {Roo.Element} this
8222 move : function(direction, distance, animate){
8223 var xy = this.getXY();
8224 direction = direction.toLowerCase();
8228 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8232 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8237 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8242 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8249 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8250 * @return {Roo.Element} this
8253 if(!this.isClipped){
8254 this.isClipped = true;
8255 this.originalClip = {
8256 "o": this.getStyle("overflow"),
8257 "x": this.getStyle("overflow-x"),
8258 "y": this.getStyle("overflow-y")
8260 this.setStyle("overflow", "hidden");
8261 this.setStyle("overflow-x", "hidden");
8262 this.setStyle("overflow-y", "hidden");
8268 * Return clipping (overflow) to original clipping before clip() was called
8269 * @return {Roo.Element} this
8271 unclip : function(){
8273 this.isClipped = false;
8274 var o = this.originalClip;
8275 if(o.o){this.setStyle("overflow", o.o);}
8276 if(o.x){this.setStyle("overflow-x", o.x);}
8277 if(o.y){this.setStyle("overflow-y", o.y);}
8284 * Gets the x,y coordinates specified by the anchor position on the element.
8285 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8286 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8287 * {width: (target width), height: (target height)} (defaults to the element's current size)
8288 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8289 * @return {Array} [x, y] An array containing the element's x and y coordinates
8291 getAnchorXY : function(anchor, local, s){
8292 //Passing a different size is useful for pre-calculating anchors,
8293 //especially for anchored animations that change the el size.
8295 var w, h, vp = false;
8298 if(d == document.body || d == document){
8300 w = D.getViewWidth(); h = D.getViewHeight();
8302 w = this.getWidth(); h = this.getHeight();
8305 w = s.width; h = s.height;
8307 var x = 0, y = 0, r = Math.round;
8308 switch((anchor || "tl").toLowerCase()){
8350 var sc = this.getScroll();
8351 return [x + sc.left, y + sc.top];
8353 //Add the element's offset xy
8354 var o = this.getXY();
8355 return [x+o[0], y+o[1]];
8359 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8360 * supported position values.
8361 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8362 * @param {String} position The position to align to.
8363 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8364 * @return {Array} [x, y]
8366 getAlignToXY : function(el, p, o){
8370 throw "Element.alignTo with an element that doesn't exist";
8372 var c = false; //constrain to viewport
8373 var p1 = "", p2 = "";
8380 }else if(p.indexOf("-") == -1){
8383 p = p.toLowerCase();
8384 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8386 throw "Element.alignTo with an invalid alignment " + p;
8388 p1 = m[1]; p2 = m[2]; c = !!m[3];
8390 //Subtract the aligned el's internal xy from the target's offset xy
8391 //plus custom offset to get the aligned el's new offset xy
8392 var a1 = this.getAnchorXY(p1, true);
8393 var a2 = el.getAnchorXY(p2, false);
8394 var x = a2[0] - a1[0] + o[0];
8395 var y = a2[1] - a1[1] + o[1];
8397 //constrain the aligned el to viewport if necessary
8398 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8399 // 5px of margin for ie
8400 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8402 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8403 //perpendicular to the vp border, allow the aligned el to slide on that border,
8404 //otherwise swap the aligned el to the opposite border of the target.
8405 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8406 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8407 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8408 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8411 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8412 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8414 if((x+w) > dw + scrollX){
8415 x = swapX ? r.left-w : dw+scrollX-w;
8418 x = swapX ? r.right : scrollX;
8420 if((y+h) > dh + scrollY){
8421 y = swapY ? r.top-h : dh+scrollY-h;
8424 y = swapY ? r.bottom : scrollY;
8431 getConstrainToXY : function(){
8432 var os = {top:0, left:0, bottom:0, right: 0};
8434 return function(el, local, offsets, proposedXY){
8436 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8438 var vw, vh, vx = 0, vy = 0;
8439 if(el.dom == document.body || el.dom == document){
8440 vw = Roo.lib.Dom.getViewWidth();
8441 vh = Roo.lib.Dom.getViewHeight();
8443 vw = el.dom.clientWidth;
8444 vh = el.dom.clientHeight;
8446 var vxy = el.getXY();
8452 var s = el.getScroll();
8454 vx += offsets.left + s.left;
8455 vy += offsets.top + s.top;
8457 vw -= offsets.right;
8458 vh -= offsets.bottom;
8463 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8464 var x = xy[0], y = xy[1];
8465 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8467 // only move it if it needs it
8470 // first validate right/bottom
8479 // then make sure top/left isn't negative
8488 return moved ? [x, y] : false;
8493 adjustForConstraints : function(xy, parent, offsets){
8494 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8498 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8499 * document it aligns it to the viewport.
8500 * The position parameter is optional, and can be specified in any one of the following formats:
8502 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8503 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8504 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8505 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8506 * <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
8507 * element's anchor point, and the second value is used as the target's anchor point.</li>
8509 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8510 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8511 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8512 * that specified in order to enforce the viewport constraints.
8513 * Following are all of the supported anchor positions:
8516 ----- -----------------------------
8517 tl The top left corner (default)
8518 t The center of the top edge
8519 tr The top right corner
8520 l The center of the left edge
8521 c In the center of the element
8522 r The center of the right edge
8523 bl The bottom left corner
8524 b The center of the bottom edge
8525 br The bottom right corner
8529 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8530 el.alignTo("other-el");
8532 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8533 el.alignTo("other-el", "tr?");
8535 // align the bottom right corner of el with the center left edge of other-el
8536 el.alignTo("other-el", "br-l?");
8538 // align the center of el with the bottom left corner of other-el and
8539 // adjust the x position by -6 pixels (and the y position by 0)
8540 el.alignTo("other-el", "c-bl", [-6, 0]);
8542 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8543 * @param {String} position The position to align to.
8544 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8545 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8546 * @return {Roo.Element} this
8548 alignTo : function(element, position, offsets, animate){
8549 var xy = this.getAlignToXY(element, position, offsets);
8550 this.setXY(xy, this.preanim(arguments, 3));
8555 * Anchors an element to another element and realigns it when the window is resized.
8556 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8557 * @param {String} position The position to align to.
8558 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8559 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8560 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8561 * is a number, it is used as the buffer delay (defaults to 50ms).
8562 * @param {Function} callback The function to call after the animation finishes
8563 * @return {Roo.Element} this
8565 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8566 var action = function(){
8567 this.alignTo(el, alignment, offsets, animate);
8568 Roo.callback(callback, this);
8570 Roo.EventManager.onWindowResize(action, this);
8571 var tm = typeof monitorScroll;
8572 if(tm != 'undefined'){
8573 Roo.EventManager.on(window, 'scroll', action, this,
8574 {buffer: tm == 'number' ? monitorScroll : 50});
8576 action.call(this); // align immediately
8580 * Clears any opacity settings from this element. Required in some cases for IE.
8581 * @return {Roo.Element} this
8583 clearOpacity : function(){
8584 if (window.ActiveXObject) {
8585 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8586 this.dom.style.filter = "";
8589 this.dom.style.opacity = "";
8590 this.dom.style["-moz-opacity"] = "";
8591 this.dom.style["-khtml-opacity"] = "";
8597 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8598 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8599 * @return {Roo.Element} this
8601 hide : function(animate){
8602 this.setVisible(false, this.preanim(arguments, 0));
8607 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8608 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8609 * @return {Roo.Element} this
8611 show : function(animate){
8612 this.setVisible(true, this.preanim(arguments, 0));
8617 * @private Test if size has a unit, otherwise appends the default
8619 addUnits : function(size){
8620 return Roo.Element.addUnits(size, this.defaultUnit);
8624 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8625 * @return {Roo.Element} this
8627 beginMeasure : function(){
8629 if(el.offsetWidth || el.offsetHeight){
8630 return this; // offsets work already
8633 var p = this.dom, b = document.body; // start with this element
8634 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8635 var pe = Roo.get(p);
8636 if(pe.getStyle('display') == 'none'){
8637 changed.push({el: p, visibility: pe.getStyle("visibility")});
8638 p.style.visibility = "hidden";
8639 p.style.display = "block";
8643 this._measureChanged = changed;
8649 * Restores displays to before beginMeasure was called
8650 * @return {Roo.Element} this
8652 endMeasure : function(){
8653 var changed = this._measureChanged;
8655 for(var i = 0, len = changed.length; i < len; i++) {
8657 r.el.style.visibility = r.visibility;
8658 r.el.style.display = "none";
8660 this._measureChanged = null;
8666 * Update the innerHTML of this element, optionally searching for and processing scripts
8667 * @param {String} html The new HTML
8668 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8669 * @param {Function} callback For async script loading you can be noticed when the update completes
8670 * @return {Roo.Element} this
8672 update : function(html, loadScripts, callback){
8673 if(typeof html == "undefined"){
8676 if(loadScripts !== true){
8677 this.dom.innerHTML = html;
8678 if(typeof callback == "function"){
8686 html += '<span id="' + id + '"></span>';
8688 E.onAvailable(id, function(){
8689 var hd = document.getElementsByTagName("head")[0];
8690 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8691 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8692 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8695 while(match = re.exec(html)){
8696 var attrs = match[1];
8697 var srcMatch = attrs ? attrs.match(srcRe) : false;
8698 if(srcMatch && srcMatch[2]){
8699 var s = document.createElement("script");
8700 s.src = srcMatch[2];
8701 var typeMatch = attrs.match(typeRe);
8702 if(typeMatch && typeMatch[2]){
8703 s.type = typeMatch[2];
8706 }else if(match[2] && match[2].length > 0){
8707 if(window.execScript) {
8708 window.execScript(match[2]);
8716 window.eval(match[2]);
8720 var el = document.getElementById(id);
8721 if(el){el.parentNode.removeChild(el);}
8722 if(typeof callback == "function"){
8726 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8731 * Direct access to the UpdateManager update() method (takes the same parameters).
8732 * @param {String/Function} url The url for this request or a function to call to get the url
8733 * @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}
8734 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8735 * @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.
8736 * @return {Roo.Element} this
8739 var um = this.getUpdateManager();
8740 um.update.apply(um, arguments);
8745 * Gets this element's UpdateManager
8746 * @return {Roo.UpdateManager} The UpdateManager
8748 getUpdateManager : function(){
8749 if(!this.updateManager){
8750 this.updateManager = new Roo.UpdateManager(this);
8752 return this.updateManager;
8756 * Disables text selection for this element (normalized across browsers)
8757 * @return {Roo.Element} this
8759 unselectable : function(){
8760 this.dom.unselectable = "on";
8761 this.swallowEvent("selectstart", true);
8762 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8763 this.addClass("x-unselectable");
8768 * Calculates the x, y to center this element on the screen
8769 * @return {Array} The x, y values [x, y]
8771 getCenterXY : function(){
8772 return this.getAlignToXY(document, 'c-c');
8776 * Centers the Element in either the viewport, or another Element.
8777 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8779 center : function(centerIn){
8780 this.alignTo(centerIn || document, 'c-c');
8785 * Tests various css rules/browsers to determine if this element uses a border box
8788 isBorderBox : function(){
8789 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8793 * Return a box {x, y, width, height} that can be used to set another elements
8794 * size/location to match this element.
8795 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8796 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8797 * @return {Object} box An object in the format {x, y, width, height}
8799 getBox : function(contentBox, local){
8804 var left = parseInt(this.getStyle("left"), 10) || 0;
8805 var top = parseInt(this.getStyle("top"), 10) || 0;
8808 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8810 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8812 var l = this.getBorderWidth("l")+this.getPadding("l");
8813 var r = this.getBorderWidth("r")+this.getPadding("r");
8814 var t = this.getBorderWidth("t")+this.getPadding("t");
8815 var b = this.getBorderWidth("b")+this.getPadding("b");
8816 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)};
8818 bx.right = bx.x + bx.width;
8819 bx.bottom = bx.y + bx.height;
8824 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8825 for more information about the sides.
8826 * @param {String} sides
8829 getFrameWidth : function(sides, onlyContentBox){
8830 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8834 * 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.
8835 * @param {Object} box The box to fill {x, y, width, height}
8836 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8837 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8838 * @return {Roo.Element} this
8840 setBox : function(box, adjust, animate){
8841 var w = box.width, h = box.height;
8842 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8843 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8844 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8846 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8851 * Forces the browser to repaint this element
8852 * @return {Roo.Element} this
8854 repaint : function(){
8856 this.addClass("x-repaint");
8857 setTimeout(function(){
8858 Roo.get(dom).removeClass("x-repaint");
8864 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8865 * then it returns the calculated width of the sides (see getPadding)
8866 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8867 * @return {Object/Number}
8869 getMargins : function(side){
8872 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8873 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8874 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8875 right: parseInt(this.getStyle("margin-right"), 10) || 0
8878 return this.addStyles(side, El.margins);
8883 addStyles : function(sides, styles){
8885 for(var i = 0, len = sides.length; i < len; i++){
8886 v = this.getStyle(styles[sides.charAt(i)]);
8888 w = parseInt(v, 10);
8896 * Creates a proxy element of this element
8897 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8898 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8899 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8900 * @return {Roo.Element} The new proxy element
8902 createProxy : function(config, renderTo, matchBox){
8904 renderTo = Roo.getDom(renderTo);
8906 renderTo = document.body;
8908 config = typeof config == "object" ?
8909 config : {tag : "div", cls: config};
8910 var proxy = Roo.DomHelper.append(renderTo, config, true);
8912 proxy.setBox(this.getBox());
8918 * Puts a mask over this element to disable user interaction. Requires core.css.
8919 * This method can only be applied to elements which accept child nodes.
8920 * @param {String} msg (optional) A message to display in the mask
8921 * @param {String} msgCls (optional) A css class to apply to the msg element
8922 * @return {Element} The mask element
8924 mask : function(msg, msgCls)
8926 if(this.getStyle("position") == "static"){
8927 this.setStyle("position", "relative");
8930 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
8932 this.addClass("x-masked");
8933 this._mask.setDisplayed(true);
8938 while (dom && dom.style) {
8939 if (!isNaN(parseInt(dom.style.zIndex))) {
8940 z = Math.max(z, parseInt(dom.style.zIndex));
8942 dom = dom.parentNode;
8944 // if we are masking the body - then it hides everything..
8945 if (this.dom == document.body) {
8947 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
8948 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
8951 if(typeof msg == 'string'){
8953 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
8955 var mm = this._maskMsg;
8956 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
8957 mm.dom.firstChild.innerHTML = msg;
8958 mm.setDisplayed(true);
8960 mm.setStyle('z-index', z + 102);
8962 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
8963 this._mask.setHeight(this.getHeight());
8965 this._mask.setStyle('z-index', z + 100);
8971 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
8972 * it is cached for reuse.
8974 unmask : function(removeEl){
8976 if(removeEl === true){
8977 this._mask.remove();
8980 this._maskMsg.remove();
8981 delete this._maskMsg;
8984 this._mask.setDisplayed(false);
8986 this._maskMsg.setDisplayed(false);
8990 this.removeClass("x-masked");
8994 * Returns true if this element is masked
8997 isMasked : function(){
8998 return this._mask && this._mask.isVisible();
9002 * Creates an iframe shim for this element to keep selects and other windowed objects from
9004 * @return {Roo.Element} The new shim element
9006 createShim : function(){
9007 var el = document.createElement('iframe');
9008 el.frameBorder = 'no';
9009 el.className = 'roo-shim';
9010 if(Roo.isIE && Roo.isSecure){
9011 el.src = Roo.SSL_SECURE_URL;
9013 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
9014 shim.autoBoxAdjust = false;
9019 * Removes this element from the DOM and deletes it from the cache
9021 remove : function(){
9022 if(this.dom.parentNode){
9023 this.dom.parentNode.removeChild(this.dom);
9025 delete El.cache[this.dom.id];
9029 * Sets up event handlers to add and remove a css class when the mouse is over this element
9030 * @param {String} className
9031 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
9032 * mouseout events for children elements
9033 * @return {Roo.Element} this
9035 addClassOnOver : function(className, preventFlicker){
9036 this.on("mouseover", function(){
9037 Roo.fly(this, '_internal').addClass(className);
9039 var removeFn = function(e){
9040 if(preventFlicker !== true || !e.within(this, true)){
9041 Roo.fly(this, '_internal').removeClass(className);
9044 this.on("mouseout", removeFn, this.dom);
9049 * Sets up event handlers to add and remove a css class when this element has the focus
9050 * @param {String} className
9051 * @return {Roo.Element} this
9053 addClassOnFocus : function(className){
9054 this.on("focus", function(){
9055 Roo.fly(this, '_internal').addClass(className);
9057 this.on("blur", function(){
9058 Roo.fly(this, '_internal').removeClass(className);
9063 * 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)
9064 * @param {String} className
9065 * @return {Roo.Element} this
9067 addClassOnClick : function(className){
9069 this.on("mousedown", function(){
9070 Roo.fly(dom, '_internal').addClass(className);
9071 var d = Roo.get(document);
9072 var fn = function(){
9073 Roo.fly(dom, '_internal').removeClass(className);
9074 d.removeListener("mouseup", fn);
9076 d.on("mouseup", fn);
9082 * Stops the specified event from bubbling and optionally prevents the default action
9083 * @param {String} eventName
9084 * @param {Boolean} preventDefault (optional) true to prevent the default action too
9085 * @return {Roo.Element} this
9087 swallowEvent : function(eventName, preventDefault){
9088 var fn = function(e){
9089 e.stopPropagation();
9094 if(eventName instanceof Array){
9095 for(var i = 0, len = eventName.length; i < len; i++){
9096 this.on(eventName[i], fn);
9100 this.on(eventName, fn);
9107 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9110 * Sizes this element to its parent element's dimensions performing
9111 * neccessary box adjustments.
9112 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9113 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9114 * @return {Roo.Element} this
9116 fitToParent : function(monitorResize, targetParent) {
9117 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9118 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9119 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9122 var p = Roo.get(targetParent || this.dom.parentNode);
9123 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9124 if (monitorResize === true) {
9125 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9126 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9132 * Gets the next sibling, skipping text nodes
9133 * @return {HTMLElement} The next sibling or null
9135 getNextSibling : function(){
9136 var n = this.dom.nextSibling;
9137 while(n && n.nodeType != 1){
9144 * Gets the previous sibling, skipping text nodes
9145 * @return {HTMLElement} The previous sibling or null
9147 getPrevSibling : function(){
9148 var n = this.dom.previousSibling;
9149 while(n && n.nodeType != 1){
9150 n = n.previousSibling;
9157 * Appends the passed element(s) to this element
9158 * @param {String/HTMLElement/Array/Element/CompositeElement} el
9159 * @return {Roo.Element} this
9161 appendChild: function(el){
9168 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9169 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
9170 * automatically generated with the specified attributes.
9171 * @param {HTMLElement} insertBefore (optional) a child element of this element
9172 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9173 * @return {Roo.Element} The new child element
9175 createChild: function(config, insertBefore, returnDom){
9176 config = config || {tag:'div'};
9178 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9180 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
9184 * Appends this element to the passed element
9185 * @param {String/HTMLElement/Element} el The new parent element
9186 * @return {Roo.Element} this
9188 appendTo: function(el){
9189 el = Roo.getDom(el);
9190 el.appendChild(this.dom);
9195 * Inserts this element before the passed element in the DOM
9196 * @param {String/HTMLElement/Element} el The element to insert before
9197 * @return {Roo.Element} this
9199 insertBefore: function(el){
9200 el = Roo.getDom(el);
9201 el.parentNode.insertBefore(this.dom, el);
9206 * Inserts this element after the passed element in the DOM
9207 * @param {String/HTMLElement/Element} el The element to insert after
9208 * @return {Roo.Element} this
9210 insertAfter: function(el){
9211 el = Roo.getDom(el);
9212 el.parentNode.insertBefore(this.dom, el.nextSibling);
9217 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9218 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9219 * @return {Roo.Element} The new child
9221 insertFirst: function(el, returnDom){
9223 if(typeof el == 'object' && !el.nodeType){ // dh config
9224 return this.createChild(el, this.dom.firstChild, returnDom);
9226 el = Roo.getDom(el);
9227 this.dom.insertBefore(el, this.dom.firstChild);
9228 return !returnDom ? Roo.get(el) : el;
9233 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9234 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9235 * @param {String} where (optional) 'before' or 'after' defaults to before
9236 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9237 * @return {Roo.Element} the inserted Element
9239 insertSibling: function(el, where, returnDom){
9240 where = where ? where.toLowerCase() : 'before';
9242 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9244 if(typeof el == 'object' && !el.nodeType){ // dh config
9245 if(where == 'after' && !this.dom.nextSibling){
9246 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9248 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9252 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9253 where == 'before' ? this.dom : this.dom.nextSibling);
9262 * Creates and wraps this element with another element
9263 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9264 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9265 * @return {HTMLElement/Element} The newly created wrapper element
9267 wrap: function(config, returnDom){
9269 config = {tag: "div"};
9271 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9272 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9277 * Replaces the passed element with this element
9278 * @param {String/HTMLElement/Element} el The element to replace
9279 * @return {Roo.Element} this
9281 replace: function(el){
9283 this.insertBefore(el);
9289 * Inserts an html fragment into this element
9290 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9291 * @param {String} html The HTML fragment
9292 * @param {Boolean} returnEl True to return an Roo.Element
9293 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9295 insertHtml : function(where, html, returnEl){
9296 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9297 return returnEl ? Roo.get(el) : el;
9301 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9302 * @param {Object} o The object with the attributes
9303 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9304 * @return {Roo.Element} this
9306 set : function(o, useSet){
9308 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9310 if(attr == "style" || typeof o[attr] == "function") continue;
9312 el.className = o["cls"];
9314 if(useSet) el.setAttribute(attr, o[attr]);
9315 else el[attr] = o[attr];
9319 Roo.DomHelper.applyStyles(el, o.style);
9325 * Convenience method for constructing a KeyMap
9326 * @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:
9327 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9328 * @param {Function} fn The function to call
9329 * @param {Object} scope (optional) The scope of the function
9330 * @return {Roo.KeyMap} The KeyMap created
9332 addKeyListener : function(key, fn, scope){
9334 if(typeof key != "object" || key instanceof Array){
9350 return new Roo.KeyMap(this, config);
9354 * Creates a KeyMap for this element
9355 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9356 * @return {Roo.KeyMap} The KeyMap created
9358 addKeyMap : function(config){
9359 return new Roo.KeyMap(this, config);
9363 * Returns true if this element is scrollable.
9366 isScrollable : function(){
9368 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9372 * 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().
9373 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9374 * @param {Number} value The new scroll value
9375 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9376 * @return {Element} this
9379 scrollTo : function(side, value, animate){
9380 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9382 this.dom[prop] = value;
9384 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9385 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9391 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9392 * within this element's scrollable range.
9393 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9394 * @param {Number} distance How far to scroll the element in pixels
9395 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9396 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9397 * was scrolled as far as it could go.
9399 scroll : function(direction, distance, animate){
9400 if(!this.isScrollable()){
9404 var l = el.scrollLeft, t = el.scrollTop;
9405 var w = el.scrollWidth, h = el.scrollHeight;
9406 var cw = el.clientWidth, ch = el.clientHeight;
9407 direction = direction.toLowerCase();
9408 var scrolled = false;
9409 var a = this.preanim(arguments, 2);
9414 var v = Math.min(l + distance, w-cw);
9415 this.scrollTo("left", v, a);
9422 var v = Math.max(l - distance, 0);
9423 this.scrollTo("left", v, a);
9431 var v = Math.max(t - distance, 0);
9432 this.scrollTo("top", v, a);
9440 var v = Math.min(t + distance, h-ch);
9441 this.scrollTo("top", v, a);
9450 * Translates the passed page coordinates into left/top css values for this element
9451 * @param {Number/Array} x The page x or an array containing [x, y]
9452 * @param {Number} y The page y
9453 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9455 translatePoints : function(x, y){
9456 if(typeof x == 'object' || x instanceof Array){
9459 var p = this.getStyle('position');
9460 var o = this.getXY();
9462 var l = parseInt(this.getStyle('left'), 10);
9463 var t = parseInt(this.getStyle('top'), 10);
9466 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9469 t = (p == "relative") ? 0 : this.dom.offsetTop;
9472 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9476 * Returns the current scroll position of the element.
9477 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9479 getScroll : function(){
9480 var d = this.dom, doc = document;
9481 if(d == doc || d == doc.body){
9482 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9483 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9484 return {left: l, top: t};
9486 return {left: d.scrollLeft, top: d.scrollTop};
9491 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9492 * are convert to standard 6 digit hex color.
9493 * @param {String} attr The css attribute
9494 * @param {String} defaultValue The default value to use when a valid color isn't found
9495 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9498 getColor : function(attr, defaultValue, prefix){
9499 var v = this.getStyle(attr);
9500 if(!v || v == "transparent" || v == "inherit") {
9501 return defaultValue;
9503 var color = typeof prefix == "undefined" ? "#" : prefix;
9504 if(v.substr(0, 4) == "rgb("){
9505 var rvs = v.slice(4, v.length -1).split(",");
9506 for(var i = 0; i < 3; i++){
9507 var h = parseInt(rvs[i]).toString(16);
9514 if(v.substr(0, 1) == "#"){
9516 for(var i = 1; i < 4; i++){
9517 var c = v.charAt(i);
9520 }else if(v.length == 7){
9521 color += v.substr(1);
9525 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9529 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9530 * gradient background, rounded corners and a 4-way shadow.
9531 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9532 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9533 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9534 * @return {Roo.Element} this
9536 boxWrap : function(cls){
9537 cls = cls || 'x-box';
9538 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9539 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9544 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9545 * @param {String} namespace The namespace in which to look for the attribute
9546 * @param {String} name The attribute name
9547 * @return {String} The attribute value
9549 getAttributeNS : Roo.isIE ? function(ns, name){
9551 var type = typeof d[ns+":"+name];
9552 if(type != 'undefined' && type != 'unknown'){
9553 return d[ns+":"+name];
9556 } : function(ns, name){
9558 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9563 * Sets or Returns the value the dom attribute value
9564 * @param {String} name The attribute name
9565 * @param {String} value (optional) The value to set the attribute to
9566 * @return {String} The attribute value
9568 attr : function(name){
9569 if (arguments.length > 1) {
9570 this.dom.setAttribute(name, arguments[1]);
9571 return arguments[1];
9573 if (!this.dom.hasAttribute(name)) {
9576 return this.dom.getAttribute(name);
9583 var ep = El.prototype;
9586 * Appends an event handler (Shorthand for addListener)
9587 * @param {String} eventName The type of event to append
9588 * @param {Function} fn The method the event invokes
9589 * @param {Object} scope (optional) The scope (this object) of the fn
9590 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9593 ep.on = ep.addListener;
9595 ep.mon = ep.addListener;
9598 * Removes an event handler from this element (shorthand for removeListener)
9599 * @param {String} eventName the type of event to remove
9600 * @param {Function} fn the method the event invokes
9601 * @return {Roo.Element} this
9604 ep.un = ep.removeListener;
9607 * true to automatically adjust width and height settings for box-model issues (default to true)
9609 ep.autoBoxAdjust = true;
9612 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9615 El.addUnits = function(v, defaultUnit){
9616 if(v === "" || v == "auto"){
9619 if(v === undefined){
9622 if(typeof v == "number" || !El.unitPattern.test(v)){
9623 return v + (defaultUnit || 'px');
9628 // special markup used throughout Roo when box wrapping elements
9629 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>';
9631 * Visibility mode constant - Use visibility to hide element
9637 * Visibility mode constant - Use display to hide element
9643 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9644 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9645 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9657 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9658 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9659 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9660 * @return {Element} The Element object
9663 El.get = function(el){
9665 if(!el){ return null; }
9666 if(typeof el == "string"){ // element id
9667 if(!(elm = document.getElementById(el))){
9670 if(ex = El.cache[el]){
9673 ex = El.cache[el] = new El(elm);
9676 }else if(el.tagName){ // dom element
9680 if(ex = El.cache[id]){
9683 ex = El.cache[id] = new El(el);
9686 }else if(el instanceof El){
9688 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9689 // catch case where it hasn't been appended
9690 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9693 }else if(el.isComposite){
9695 }else if(el instanceof Array){
9696 return El.select(el);
9697 }else if(el == document){
9698 // create a bogus element object representing the document object
9700 var f = function(){};
9701 f.prototype = El.prototype;
9703 docEl.dom = document;
9711 El.uncache = function(el){
9712 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9714 delete El.cache[a[i].id || a[i]];
9720 // Garbage collection - uncache elements/purge listeners on orphaned elements
9721 // so we don't hold a reference and cause the browser to retain them
9722 El.garbageCollect = function(){
9723 if(!Roo.enableGarbageCollector){
9724 clearInterval(El.collectorThread);
9727 for(var eid in El.cache){
9728 var el = El.cache[eid], d = el.dom;
9729 // -------------------------------------------------------
9730 // Determining what is garbage:
9731 // -------------------------------------------------------
9733 // dom node is null, definitely garbage
9734 // -------------------------------------------------------
9736 // no parentNode == direct orphan, definitely garbage
9737 // -------------------------------------------------------
9738 // !d.offsetParent && !document.getElementById(eid)
9739 // display none elements have no offsetParent so we will
9740 // also try to look it up by it's id. However, check
9741 // offsetParent first so we don't do unneeded lookups.
9742 // This enables collection of elements that are not orphans
9743 // directly, but somewhere up the line they have an orphan
9745 // -------------------------------------------------------
9746 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9747 delete El.cache[eid];
9748 if(d && Roo.enableListenerCollection){
9754 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9758 El.Flyweight = function(dom){
9761 El.Flyweight.prototype = El.prototype;
9763 El._flyweights = {};
9765 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9766 * the dom node can be overwritten by other code.
9767 * @param {String/HTMLElement} el The dom node or id
9768 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9769 * prevent conflicts (e.g. internally Roo uses "_internal")
9771 * @return {Element} The shared Element object
9773 El.fly = function(el, named){
9774 named = named || '_global';
9775 el = Roo.getDom(el);
9779 if(!El._flyweights[named]){
9780 El._flyweights[named] = new El.Flyweight();
9782 El._flyweights[named].dom = el;
9783 return El._flyweights[named];
9787 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9788 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9789 * Shorthand of {@link Roo.Element#get}
9790 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9791 * @return {Element} The Element object
9797 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9798 * the dom node can be overwritten by other code.
9799 * Shorthand of {@link Roo.Element#fly}
9800 * @param {String/HTMLElement} el The dom node or id
9801 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9802 * prevent conflicts (e.g. internally Roo uses "_internal")
9804 * @return {Element} The shared Element object
9810 // speedy lookup for elements never to box adjust
9811 var noBoxAdjust = Roo.isStrict ? {
9814 input:1, select:1, textarea:1
9816 if(Roo.isIE || Roo.isGecko){
9817 noBoxAdjust['button'] = 1;
9821 Roo.EventManager.on(window, 'unload', function(){
9823 delete El._flyweights;
9831 Roo.Element.selectorFunction = Roo.DomQuery.select;
9834 Roo.Element.select = function(selector, unique, root){
9836 if(typeof selector == "string"){
9837 els = Roo.Element.selectorFunction(selector, root);
9838 }else if(selector.length !== undefined){
9841 throw "Invalid selector";
9843 if(unique === true){
9844 return new Roo.CompositeElement(els);
9846 return new Roo.CompositeElementLite(els);
9850 * Selects elements based on the passed CSS selector to enable working on them as 1.
9851 * @param {String/Array} selector The CSS selector or an array of elements
9852 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9853 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9854 * @return {CompositeElementLite/CompositeElement}
9858 Roo.select = Roo.Element.select;
9875 * Ext JS Library 1.1.1
9876 * Copyright(c) 2006-2007, Ext JS, LLC.
9878 * Originally Released Under LGPL - original licence link has changed is not relivant.
9881 * <script type="text/javascript">
9886 //Notifies Element that fx methods are available
9887 Roo.enableFx = true;
9891 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9892 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9893 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9894 * Element effects to work.</p><br/>
9896 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9897 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9898 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9899 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
9900 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9901 * expected results and should be done with care.</p><br/>
9903 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9904 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
9907 ----- -----------------------------
9908 tl The top left corner
9909 t The center of the top edge
9910 tr The top right corner
9911 l The center of the left edge
9912 r The center of the right edge
9913 bl The bottom left corner
9914 b The center of the bottom edge
9915 br The bottom right corner
9917 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9918 * below are common options that can be passed to any Fx method.</b>
9919 * @cfg {Function} callback A function called when the effect is finished
9920 * @cfg {Object} scope The scope of the effect function
9921 * @cfg {String} easing A valid Easing value for the effect
9922 * @cfg {String} afterCls A css class to apply after the effect
9923 * @cfg {Number} duration The length of time (in seconds) that the effect should last
9924 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
9925 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
9926 * effects that end with the element being visually hidden, ignored otherwise)
9927 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
9928 * a function which returns such a specification that will be applied to the Element after the effect finishes
9929 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
9930 * @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
9931 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
9935 * Slides the element into view. An anchor point can be optionally passed to set the point of
9936 * origin for the slide effect. This function automatically handles wrapping the element with
9937 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
9940 // default: slide the element in from the top
9943 // custom: slide the element in from the right with a 2-second duration
9944 el.slideIn('r', { duration: 2 });
9946 // common config options shown with default values
9952 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9953 * @param {Object} options (optional) Object literal with any of the Fx config options
9954 * @return {Roo.Element} The Element
9956 slideIn : function(anchor, o){
9957 var el = this.getFxEl();
9960 el.queueFx(o, function(){
9962 anchor = anchor || "t";
9964 // fix display to visibility
9967 // restore values after effect
9968 var r = this.getFxRestore();
9969 var b = this.getBox();
9970 // fixed size for slide
9974 var wrap = this.fxWrap(r.pos, o, "hidden");
9976 var st = this.dom.style;
9977 st.visibility = "visible";
9978 st.position = "absolute";
9980 // clear out temp styles after slide and unwrap
9981 var after = function(){
9982 el.fxUnwrap(wrap, r.pos, o);
9984 st.height = r.height;
9987 // time to calc the positions
9988 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
9990 switch(anchor.toLowerCase()){
9992 wrap.setSize(b.width, 0);
9993 st.left = st.bottom = "0";
9997 wrap.setSize(0, b.height);
9998 st.right = st.top = "0";
10002 wrap.setSize(0, b.height);
10003 wrap.setX(b.right);
10004 st.left = st.top = "0";
10005 a = {width: bw, points: pt};
10008 wrap.setSize(b.width, 0);
10009 wrap.setY(b.bottom);
10010 st.left = st.top = "0";
10011 a = {height: bh, points: pt};
10014 wrap.setSize(0, 0);
10015 st.right = st.bottom = "0";
10016 a = {width: bw, height: bh};
10019 wrap.setSize(0, 0);
10020 wrap.setY(b.y+b.height);
10021 st.right = st.top = "0";
10022 a = {width: bw, height: bh, points: pt};
10025 wrap.setSize(0, 0);
10026 wrap.setXY([b.right, b.bottom]);
10027 st.left = st.top = "0";
10028 a = {width: bw, height: bh, points: pt};
10031 wrap.setSize(0, 0);
10032 wrap.setX(b.x+b.width);
10033 st.left = st.bottom = "0";
10034 a = {width: bw, height: bh, points: pt};
10037 this.dom.style.visibility = "visible";
10040 arguments.callee.anim = wrap.fxanim(a,
10050 * Slides the element out of view. An anchor point can be optionally passed to set the end point
10051 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
10052 * 'hidden') but block elements will still take up space in the document. The element must be removed
10053 * from the DOM using the 'remove' config option if desired. This function automatically handles
10054 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10057 // default: slide the element out to the top
10060 // custom: slide the element out to the right with a 2-second duration
10061 el.slideOut('r', { duration: 2 });
10063 // common config options shown with default values
10071 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10072 * @param {Object} options (optional) Object literal with any of the Fx config options
10073 * @return {Roo.Element} The Element
10075 slideOut : function(anchor, o){
10076 var el = this.getFxEl();
10079 el.queueFx(o, function(){
10081 anchor = anchor || "t";
10083 // restore values after effect
10084 var r = this.getFxRestore();
10086 var b = this.getBox();
10087 // fixed size for slide
10091 var wrap = this.fxWrap(r.pos, o, "visible");
10093 var st = this.dom.style;
10094 st.visibility = "visible";
10095 st.position = "absolute";
10099 var after = function(){
10101 el.setDisplayed(false);
10106 el.fxUnwrap(wrap, r.pos, o);
10108 st.width = r.width;
10109 st.height = r.height;
10114 var a, zero = {to: 0};
10115 switch(anchor.toLowerCase()){
10117 st.left = st.bottom = "0";
10118 a = {height: zero};
10121 st.right = st.top = "0";
10125 st.left = st.top = "0";
10126 a = {width: zero, points: {to:[b.right, b.y]}};
10129 st.left = st.top = "0";
10130 a = {height: zero, points: {to:[b.x, b.bottom]}};
10133 st.right = st.bottom = "0";
10134 a = {width: zero, height: zero};
10137 st.right = st.top = "0";
10138 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10141 st.left = st.top = "0";
10142 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10145 st.left = st.bottom = "0";
10146 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10150 arguments.callee.anim = wrap.fxanim(a,
10160 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
10161 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
10162 * The element must be removed from the DOM using the 'remove' config option if desired.
10168 // common config options shown with default values
10176 * @param {Object} options (optional) Object literal with any of the Fx config options
10177 * @return {Roo.Element} The Element
10179 puff : function(o){
10180 var el = this.getFxEl();
10183 el.queueFx(o, function(){
10184 this.clearOpacity();
10187 // restore values after effect
10188 var r = this.getFxRestore();
10189 var st = this.dom.style;
10191 var after = function(){
10193 el.setDisplayed(false);
10200 el.setPositioning(r.pos);
10201 st.width = r.width;
10202 st.height = r.height;
10207 var width = this.getWidth();
10208 var height = this.getHeight();
10210 arguments.callee.anim = this.fxanim({
10211 width : {to: this.adjustWidth(width * 2)},
10212 height : {to: this.adjustHeight(height * 2)},
10213 points : {by: [-(width * .5), -(height * .5)]},
10215 fontSize: {to:200, unit: "%"}
10226 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10227 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10228 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10234 // all config options shown with default values
10242 * @param {Object} options (optional) Object literal with any of the Fx config options
10243 * @return {Roo.Element} The Element
10245 switchOff : function(o){
10246 var el = this.getFxEl();
10249 el.queueFx(o, function(){
10250 this.clearOpacity();
10253 // restore values after effect
10254 var r = this.getFxRestore();
10255 var st = this.dom.style;
10257 var after = function(){
10259 el.setDisplayed(false);
10265 el.setPositioning(r.pos);
10266 st.width = r.width;
10267 st.height = r.height;
10272 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10273 this.clearOpacity();
10277 points:{by:[0, this.getHeight() * .5]}
10278 }, o, 'motion', 0.3, 'easeIn', after);
10279 }).defer(100, this);
10286 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10287 * changed using the "attr" config option) and then fading back to the original color. If no original
10288 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10291 // default: highlight background to yellow
10294 // custom: highlight foreground text to blue for 2 seconds
10295 el.highlight("0000ff", { attr: 'color', duration: 2 });
10297 // common config options shown with default values
10298 el.highlight("ffff9c", {
10299 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10300 endColor: (current color) or "ffffff",
10305 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10306 * @param {Object} options (optional) Object literal with any of the Fx config options
10307 * @return {Roo.Element} The Element
10309 highlight : function(color, o){
10310 var el = this.getFxEl();
10313 el.queueFx(o, function(){
10314 color = color || "ffff9c";
10315 attr = o.attr || "backgroundColor";
10317 this.clearOpacity();
10320 var origColor = this.getColor(attr);
10321 var restoreColor = this.dom.style[attr];
10322 endColor = (o.endColor || origColor) || "ffffff";
10324 var after = function(){
10325 el.dom.style[attr] = restoreColor;
10330 a[attr] = {from: color, to: endColor};
10331 arguments.callee.anim = this.fxanim(a,
10341 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10344 // default: a single light blue ripple
10347 // custom: 3 red ripples lasting 3 seconds total
10348 el.frame("ff0000", 3, { duration: 3 });
10350 // common config options shown with default values
10351 el.frame("C3DAF9", 1, {
10352 duration: 1 //duration of entire animation (not each individual ripple)
10353 // Note: Easing is not configurable and will be ignored if included
10356 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10357 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10358 * @param {Object} options (optional) Object literal with any of the Fx config options
10359 * @return {Roo.Element} The Element
10361 frame : function(color, count, o){
10362 var el = this.getFxEl();
10365 el.queueFx(o, function(){
10366 color = color || "#C3DAF9";
10367 if(color.length == 6){
10368 color = "#" + color;
10370 count = count || 1;
10371 duration = o.duration || 1;
10374 var b = this.getBox();
10375 var animFn = function(){
10376 var proxy = this.createProxy({
10379 visbility:"hidden",
10380 position:"absolute",
10381 "z-index":"35000", // yee haw
10382 border:"0px solid " + color
10385 var scale = Roo.isBorderBox ? 2 : 1;
10387 top:{from:b.y, to:b.y - 20},
10388 left:{from:b.x, to:b.x - 20},
10389 borderWidth:{from:0, to:10},
10390 opacity:{from:1, to:0},
10391 height:{from:b.height, to:(b.height + (20*scale))},
10392 width:{from:b.width, to:(b.width + (20*scale))}
10393 }, duration, function(){
10397 animFn.defer((duration/2)*1000, this);
10408 * Creates a pause before any subsequent queued effects begin. If there are
10409 * no effects queued after the pause it will have no effect.
10414 * @param {Number} seconds The length of time to pause (in seconds)
10415 * @return {Roo.Element} The Element
10417 pause : function(seconds){
10418 var el = this.getFxEl();
10421 el.queueFx(o, function(){
10422 setTimeout(function(){
10424 }, seconds * 1000);
10430 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10431 * using the "endOpacity" config option.
10434 // default: fade in from opacity 0 to 100%
10437 // custom: fade in from opacity 0 to 75% over 2 seconds
10438 el.fadeIn({ endOpacity: .75, duration: 2});
10440 // common config options shown with default values
10442 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10447 * @param {Object} options (optional) Object literal with any of the Fx config options
10448 * @return {Roo.Element} The Element
10450 fadeIn : function(o){
10451 var el = this.getFxEl();
10453 el.queueFx(o, function(){
10454 this.setOpacity(0);
10456 this.dom.style.visibility = 'visible';
10457 var to = o.endOpacity || 1;
10458 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10459 o, null, .5, "easeOut", function(){
10461 this.clearOpacity();
10470 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10471 * using the "endOpacity" config option.
10474 // default: fade out from the element's current opacity to 0
10477 // custom: fade out from the element's current opacity to 25% over 2 seconds
10478 el.fadeOut({ endOpacity: .25, duration: 2});
10480 // common config options shown with default values
10482 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10489 * @param {Object} options (optional) Object literal with any of the Fx config options
10490 * @return {Roo.Element} The Element
10492 fadeOut : function(o){
10493 var el = this.getFxEl();
10495 el.queueFx(o, function(){
10496 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10497 o, null, .5, "easeOut", function(){
10498 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10499 this.dom.style.display = "none";
10501 this.dom.style.visibility = "hidden";
10503 this.clearOpacity();
10511 * Animates the transition of an element's dimensions from a starting height/width
10512 * to an ending height/width.
10515 // change height and width to 100x100 pixels
10516 el.scale(100, 100);
10518 // common config options shown with default values. The height and width will default to
10519 // the element's existing values if passed as null.
10522 [element's height], {
10527 * @param {Number} width The new width (pass undefined to keep the original width)
10528 * @param {Number} height The new height (pass undefined to keep the original height)
10529 * @param {Object} options (optional) Object literal with any of the Fx config options
10530 * @return {Roo.Element} The Element
10532 scale : function(w, h, o){
10533 this.shift(Roo.apply({}, o, {
10541 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10542 * Any of these properties not specified in the config object will not be changed. This effect
10543 * requires that at least one new dimension, position or opacity setting must be passed in on
10544 * the config object in order for the function to have any effect.
10547 // slide the element horizontally to x position 200 while changing the height and opacity
10548 el.shift({ x: 200, height: 50, opacity: .8 });
10550 // common config options shown with default values.
10552 width: [element's width],
10553 height: [element's height],
10554 x: [element's x position],
10555 y: [element's y position],
10556 opacity: [element's opacity],
10561 * @param {Object} options Object literal with any of the Fx config options
10562 * @return {Roo.Element} The Element
10564 shift : function(o){
10565 var el = this.getFxEl();
10567 el.queueFx(o, function(){
10568 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10569 if(w !== undefined){
10570 a.width = {to: this.adjustWidth(w)};
10572 if(h !== undefined){
10573 a.height = {to: this.adjustHeight(h)};
10575 if(x !== undefined || y !== undefined){
10577 x !== undefined ? x : this.getX(),
10578 y !== undefined ? y : this.getY()
10581 if(op !== undefined){
10582 a.opacity = {to: op};
10584 if(o.xy !== undefined){
10585 a.points = {to: o.xy};
10587 arguments.callee.anim = this.fxanim(a,
10588 o, 'motion', .35, "easeOut", function(){
10596 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10597 * ending point of the effect.
10600 // default: slide the element downward while fading out
10603 // custom: slide the element out to the right with a 2-second duration
10604 el.ghost('r', { duration: 2 });
10606 // common config options shown with default values
10614 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10615 * @param {Object} options (optional) Object literal with any of the Fx config options
10616 * @return {Roo.Element} The Element
10618 ghost : function(anchor, o){
10619 var el = this.getFxEl();
10622 el.queueFx(o, function(){
10623 anchor = anchor || "b";
10625 // restore values after effect
10626 var r = this.getFxRestore();
10627 var w = this.getWidth(),
10628 h = this.getHeight();
10630 var st = this.dom.style;
10632 var after = function(){
10634 el.setDisplayed(false);
10640 el.setPositioning(r.pos);
10641 st.width = r.width;
10642 st.height = r.height;
10647 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10648 switch(anchor.toLowerCase()){
10675 arguments.callee.anim = this.fxanim(a,
10685 * Ensures that all effects queued after syncFx is called on the element are
10686 * run concurrently. This is the opposite of {@link #sequenceFx}.
10687 * @return {Roo.Element} The Element
10689 syncFx : function(){
10690 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10699 * Ensures that all effects queued after sequenceFx is called on the element are
10700 * run in sequence. This is the opposite of {@link #syncFx}.
10701 * @return {Roo.Element} The Element
10703 sequenceFx : function(){
10704 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10706 concurrent : false,
10713 nextFx : function(){
10714 var ef = this.fxQueue[0];
10721 * Returns true if the element has any effects actively running or queued, else returns false.
10722 * @return {Boolean} True if element has active effects, else false
10724 hasActiveFx : function(){
10725 return this.fxQueue && this.fxQueue[0];
10729 * Stops any running effects and clears the element's internal effects queue if it contains
10730 * any additional effects that haven't started yet.
10731 * @return {Roo.Element} The Element
10733 stopFx : function(){
10734 if(this.hasActiveFx()){
10735 var cur = this.fxQueue[0];
10736 if(cur && cur.anim && cur.anim.isAnimated()){
10737 this.fxQueue = [cur]; // clear out others
10738 cur.anim.stop(true);
10745 beforeFx : function(o){
10746 if(this.hasActiveFx() && !o.concurrent){
10757 * Returns true if the element is currently blocking so that no other effect can be queued
10758 * until this effect is finished, else returns false if blocking is not set. This is commonly
10759 * used to ensure that an effect initiated by a user action runs to completion prior to the
10760 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10761 * @return {Boolean} True if blocking, else false
10763 hasFxBlock : function(){
10764 var q = this.fxQueue;
10765 return q && q[0] && q[0].block;
10769 queueFx : function(o, fn){
10773 if(!this.hasFxBlock()){
10774 Roo.applyIf(o, this.fxDefaults);
10776 var run = this.beforeFx(o);
10777 fn.block = o.block;
10778 this.fxQueue.push(fn);
10790 fxWrap : function(pos, o, vis){
10792 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10795 wrapXY = this.getXY();
10797 var div = document.createElement("div");
10798 div.style.visibility = vis;
10799 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10800 wrap.setPositioning(pos);
10801 if(wrap.getStyle("position") == "static"){
10802 wrap.position("relative");
10804 this.clearPositioning('auto');
10806 wrap.dom.appendChild(this.dom);
10808 wrap.setXY(wrapXY);
10815 fxUnwrap : function(wrap, pos, o){
10816 this.clearPositioning();
10817 this.setPositioning(pos);
10819 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10825 getFxRestore : function(){
10826 var st = this.dom.style;
10827 return {pos: this.getPositioning(), width: st.width, height : st.height};
10831 afterFx : function(o){
10833 this.applyStyles(o.afterStyle);
10836 this.addClass(o.afterCls);
10838 if(o.remove === true){
10841 Roo.callback(o.callback, o.scope, [this]);
10843 this.fxQueue.shift();
10849 getFxEl : function(){ // support for composite element fx
10850 return Roo.get(this.dom);
10854 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10855 animType = animType || 'run';
10857 var anim = Roo.lib.Anim[animType](
10859 (opt.duration || defaultDur) || .35,
10860 (opt.easing || defaultEase) || 'easeOut',
10862 Roo.callback(cb, this);
10871 // backwords compat
10872 Roo.Fx.resize = Roo.Fx.scale;
10874 //When included, Roo.Fx is automatically applied to Element so that all basic
10875 //effects are available directly via the Element API
10876 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10878 * Ext JS Library 1.1.1
10879 * Copyright(c) 2006-2007, Ext JS, LLC.
10881 * Originally Released Under LGPL - original licence link has changed is not relivant.
10884 * <script type="text/javascript">
10889 * @class Roo.CompositeElement
10890 * Standard composite class. Creates a Roo.Element for every element in the collection.
10892 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10893 * actions will be performed on all the elements in this collection.</b>
10895 * All methods return <i>this</i> and can be chained.
10897 var els = Roo.select("#some-el div.some-class", true);
10898 // or select directly from an existing element
10899 var el = Roo.get('some-el');
10900 el.select('div.some-class', true);
10902 els.setWidth(100); // all elements become 100 width
10903 els.hide(true); // all elements fade out and hide
10905 els.setWidth(100).hide(true);
10908 Roo.CompositeElement = function(els){
10909 this.elements = [];
10910 this.addElements(els);
10912 Roo.CompositeElement.prototype = {
10914 addElements : function(els){
10915 if(!els) return this;
10916 if(typeof els == "string"){
10917 els = Roo.Element.selectorFunction(els);
10919 var yels = this.elements;
10920 var index = yels.length-1;
10921 for(var i = 0, len = els.length; i < len; i++) {
10922 yels[++index] = Roo.get(els[i]);
10928 * Clears this composite and adds the elements returned by the passed selector.
10929 * @param {String/Array} els A string CSS selector, an array of elements or an element
10930 * @return {CompositeElement} this
10932 fill : function(els){
10933 this.elements = [];
10939 * Filters this composite to only elements that match the passed selector.
10940 * @param {String} selector A string CSS selector
10941 * @return {CompositeElement} this
10943 filter : function(selector){
10945 this.each(function(el){
10946 if(el.is(selector)){
10947 els[els.length] = el.dom;
10954 invoke : function(fn, args){
10955 var els = this.elements;
10956 for(var i = 0, len = els.length; i < len; i++) {
10957 Roo.Element.prototype[fn].apply(els[i], args);
10962 * Adds elements to this composite.
10963 * @param {String/Array} els A string CSS selector, an array of elements or an element
10964 * @return {CompositeElement} this
10966 add : function(els){
10967 if(typeof els == "string"){
10968 this.addElements(Roo.Element.selectorFunction(els));
10969 }else if(els.length !== undefined){
10970 this.addElements(els);
10972 this.addElements([els]);
10977 * Calls the passed function passing (el, this, index) for each element in this composite.
10978 * @param {Function} fn The function to call
10979 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
10980 * @return {CompositeElement} this
10982 each : function(fn, scope){
10983 var els = this.elements;
10984 for(var i = 0, len = els.length; i < len; i++){
10985 if(fn.call(scope || els[i], els[i], this, i) === false) {
10993 * Returns the Element object at the specified index
10994 * @param {Number} index
10995 * @return {Roo.Element}
10997 item : function(index){
10998 return this.elements[index] || null;
11002 * Returns the first Element
11003 * @return {Roo.Element}
11005 first : function(){
11006 return this.item(0);
11010 * Returns the last Element
11011 * @return {Roo.Element}
11014 return this.item(this.elements.length-1);
11018 * Returns the number of elements in this composite
11021 getCount : function(){
11022 return this.elements.length;
11026 * Returns true if this composite contains the passed element
11029 contains : function(el){
11030 return this.indexOf(el) !== -1;
11034 * Returns true if this composite contains the passed element
11037 indexOf : function(el){
11038 return this.elements.indexOf(Roo.get(el));
11043 * Removes the specified element(s).
11044 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
11045 * or an array of any of those.
11046 * @param {Boolean} removeDom (optional) True to also remove the element from the document
11047 * @return {CompositeElement} this
11049 removeElement : function(el, removeDom){
11050 if(el instanceof Array){
11051 for(var i = 0, len = el.length; i < len; i++){
11052 this.removeElement(el[i]);
11056 var index = typeof el == 'number' ? el : this.indexOf(el);
11059 var d = this.elements[index];
11063 d.parentNode.removeChild(d);
11066 this.elements.splice(index, 1);
11072 * Replaces the specified element with the passed element.
11073 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
11075 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
11076 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
11077 * @return {CompositeElement} this
11079 replaceElement : function(el, replacement, domReplace){
11080 var index = typeof el == 'number' ? el : this.indexOf(el);
11083 this.elements[index].replaceWith(replacement);
11085 this.elements.splice(index, 1, Roo.get(replacement))
11092 * Removes all elements.
11094 clear : function(){
11095 this.elements = [];
11099 Roo.CompositeElement.createCall = function(proto, fnName){
11100 if(!proto[fnName]){
11101 proto[fnName] = function(){
11102 return this.invoke(fnName, arguments);
11106 for(var fnName in Roo.Element.prototype){
11107 if(typeof Roo.Element.prototype[fnName] == "function"){
11108 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11114 * Ext JS Library 1.1.1
11115 * Copyright(c) 2006-2007, Ext JS, LLC.
11117 * Originally Released Under LGPL - original licence link has changed is not relivant.
11120 * <script type="text/javascript">
11124 * @class Roo.CompositeElementLite
11125 * @extends Roo.CompositeElement
11126 * Flyweight composite class. Reuses the same Roo.Element for element operations.
11128 var els = Roo.select("#some-el div.some-class");
11129 // or select directly from an existing element
11130 var el = Roo.get('some-el');
11131 el.select('div.some-class');
11133 els.setWidth(100); // all elements become 100 width
11134 els.hide(true); // all elements fade out and hide
11136 els.setWidth(100).hide(true);
11137 </code></pre><br><br>
11138 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11139 * actions will be performed on all the elements in this collection.</b>
11141 Roo.CompositeElementLite = function(els){
11142 Roo.CompositeElementLite.superclass.constructor.call(this, els);
11143 this.el = new Roo.Element.Flyweight();
11145 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11146 addElements : function(els){
11148 if(els instanceof Array){
11149 this.elements = this.elements.concat(els);
11151 var yels = this.elements;
11152 var index = yels.length-1;
11153 for(var i = 0, len = els.length; i < len; i++) {
11154 yels[++index] = els[i];
11160 invoke : function(fn, args){
11161 var els = this.elements;
11163 for(var i = 0, len = els.length; i < len; i++) {
11165 Roo.Element.prototype[fn].apply(el, args);
11170 * Returns a flyweight Element of the dom element object at the specified index
11171 * @param {Number} index
11172 * @return {Roo.Element}
11174 item : function(index){
11175 if(!this.elements[index]){
11178 this.el.dom = this.elements[index];
11182 // fixes scope with flyweight
11183 addListener : function(eventName, handler, scope, opt){
11184 var els = this.elements;
11185 for(var i = 0, len = els.length; i < len; i++) {
11186 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11192 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11193 * passed is the flyweight (shared) Roo.Element instance, so if you require a
11194 * a reference to the dom node, use el.dom.</b>
11195 * @param {Function} fn The function to call
11196 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11197 * @return {CompositeElement} this
11199 each : function(fn, scope){
11200 var els = this.elements;
11202 for(var i = 0, len = els.length; i < len; i++){
11204 if(fn.call(scope || el, el, this, i) === false){
11211 indexOf : function(el){
11212 return this.elements.indexOf(Roo.getDom(el));
11215 replaceElement : function(el, replacement, domReplace){
11216 var index = typeof el == 'number' ? el : this.indexOf(el);
11218 replacement = Roo.getDom(replacement);
11220 var d = this.elements[index];
11221 d.parentNode.insertBefore(replacement, d);
11222 d.parentNode.removeChild(d);
11224 this.elements.splice(index, 1, replacement);
11229 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11233 * Ext JS Library 1.1.1
11234 * Copyright(c) 2006-2007, Ext JS, LLC.
11236 * Originally Released Under LGPL - original licence link has changed is not relivant.
11239 * <script type="text/javascript">
11245 * @class Roo.data.Connection
11246 * @extends Roo.util.Observable
11247 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11248 * either to a configured URL, or to a URL specified at request time.<br><br>
11250 * Requests made by this class are asynchronous, and will return immediately. No data from
11251 * the server will be available to the statement immediately following the {@link #request} call.
11252 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11254 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11255 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11256 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11257 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11258 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11259 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11260 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11261 * standard DOM methods.
11263 * @param {Object} config a configuration object.
11265 Roo.data.Connection = function(config){
11266 Roo.apply(this, config);
11269 * @event beforerequest
11270 * Fires before a network request is made to retrieve a data object.
11271 * @param {Connection} conn This Connection object.
11272 * @param {Object} options The options config object passed to the {@link #request} method.
11274 "beforerequest" : true,
11276 * @event requestcomplete
11277 * Fires if the request was successfully completed.
11278 * @param {Connection} conn This Connection object.
11279 * @param {Object} response The XHR object containing the response data.
11280 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11281 * @param {Object} options The options config object passed to the {@link #request} method.
11283 "requestcomplete" : true,
11285 * @event requestexception
11286 * Fires if an error HTTP status was returned from the server.
11287 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11288 * @param {Connection} conn This Connection object.
11289 * @param {Object} response The XHR object containing the response data.
11290 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11291 * @param {Object} options The options config object passed to the {@link #request} method.
11293 "requestexception" : true
11295 Roo.data.Connection.superclass.constructor.call(this);
11298 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11300 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11303 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11304 * extra parameters to each request made by this object. (defaults to undefined)
11307 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11308 * to each request made by this object. (defaults to undefined)
11311 * @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)
11314 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11318 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11324 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11327 disableCaching: true,
11330 * Sends an HTTP request to a remote server.
11331 * @param {Object} options An object which may contain the following properties:<ul>
11332 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11333 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11334 * request, a url encoded string or a function to call to get either.</li>
11335 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11336 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11337 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11338 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11339 * <li>options {Object} The parameter to the request call.</li>
11340 * <li>success {Boolean} True if the request succeeded.</li>
11341 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11343 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11344 * The callback is passed the following parameters:<ul>
11345 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11346 * <li>options {Object} The parameter to the request call.</li>
11348 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11349 * The callback is passed the following parameters:<ul>
11350 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11351 * <li>options {Object} The parameter to the request call.</li>
11353 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11354 * for the callback function. Defaults to the browser window.</li>
11355 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11356 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11357 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11358 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11359 * params for the post data. Any params will be appended to the URL.</li>
11360 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11362 * @return {Number} transactionId
11364 request : function(o){
11365 if(this.fireEvent("beforerequest", this, o) !== false){
11368 if(typeof p == "function"){
11369 p = p.call(o.scope||window, o);
11371 if(typeof p == "object"){
11372 p = Roo.urlEncode(o.params);
11374 if(this.extraParams){
11375 var extras = Roo.urlEncode(this.extraParams);
11376 p = p ? (p + '&' + extras) : extras;
11379 var url = o.url || this.url;
11380 if(typeof url == 'function'){
11381 url = url.call(o.scope||window, o);
11385 var form = Roo.getDom(o.form);
11386 url = url || form.action;
11388 var enctype = form.getAttribute("enctype");
11389 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11390 return this.doFormUpload(o, p, url);
11392 var f = Roo.lib.Ajax.serializeForm(form);
11393 p = p ? (p + '&' + f) : f;
11396 var hs = o.headers;
11397 if(this.defaultHeaders){
11398 hs = Roo.apply(hs || {}, this.defaultHeaders);
11405 success: this.handleResponse,
11406 failure: this.handleFailure,
11408 argument: {options: o},
11409 timeout : o.timeout || this.timeout
11412 var method = o.method||this.method||(p ? "POST" : "GET");
11414 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11415 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11418 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11422 }else if(this.autoAbort !== false){
11426 if((method == 'GET' && p) || o.xmlData){
11427 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11430 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11431 return this.transId;
11433 Roo.callback(o.callback, o.scope, [o, null, null]);
11439 * Determine whether this object has a request outstanding.
11440 * @param {Number} transactionId (Optional) defaults to the last transaction
11441 * @return {Boolean} True if there is an outstanding request.
11443 isLoading : function(transId){
11445 return Roo.lib.Ajax.isCallInProgress(transId);
11447 return this.transId ? true : false;
11452 * Aborts any outstanding request.
11453 * @param {Number} transactionId (Optional) defaults to the last transaction
11455 abort : function(transId){
11456 if(transId || this.isLoading()){
11457 Roo.lib.Ajax.abort(transId || this.transId);
11462 handleResponse : function(response){
11463 this.transId = false;
11464 var options = response.argument.options;
11465 response.argument = options ? options.argument : null;
11466 this.fireEvent("requestcomplete", this, response, options);
11467 Roo.callback(options.success, options.scope, [response, options]);
11468 Roo.callback(options.callback, options.scope, [options, true, response]);
11472 handleFailure : function(response, e){
11473 this.transId = false;
11474 var options = response.argument.options;
11475 response.argument = options ? options.argument : null;
11476 this.fireEvent("requestexception", this, response, options, e);
11477 Roo.callback(options.failure, options.scope, [response, options]);
11478 Roo.callback(options.callback, options.scope, [options, false, response]);
11482 doFormUpload : function(o, ps, url){
11484 var frame = document.createElement('iframe');
11487 frame.className = 'x-hidden';
11489 frame.src = Roo.SSL_SECURE_URL;
11491 document.body.appendChild(frame);
11494 document.frames[id].name = id;
11497 var form = Roo.getDom(o.form);
11499 form.method = 'POST';
11500 form.enctype = form.encoding = 'multipart/form-data';
11506 if(ps){ // add dynamic params
11508 ps = Roo.urlDecode(ps, false);
11510 if(ps.hasOwnProperty(k)){
11511 hd = document.createElement('input');
11512 hd.type = 'hidden';
11515 form.appendChild(hd);
11522 var r = { // bogus response object
11527 r.argument = o ? o.argument : null;
11532 doc = frame.contentWindow.document;
11534 doc = (frame.contentDocument || window.frames[id].document);
11536 if(doc && doc.body){
11537 r.responseText = doc.body.innerHTML;
11539 if(doc && doc.XMLDocument){
11540 r.responseXML = doc.XMLDocument;
11542 r.responseXML = doc;
11549 Roo.EventManager.removeListener(frame, 'load', cb, this);
11551 this.fireEvent("requestcomplete", this, r, o);
11552 Roo.callback(o.success, o.scope, [r, o]);
11553 Roo.callback(o.callback, o.scope, [o, true, r]);
11555 setTimeout(function(){document.body.removeChild(frame);}, 100);
11558 Roo.EventManager.on(frame, 'load', cb, this);
11561 if(hiddens){ // remove dynamic params
11562 for(var i = 0, len = hiddens.length; i < len; i++){
11563 form.removeChild(hiddens[i]);
11570 * Ext JS Library 1.1.1
11571 * Copyright(c) 2006-2007, Ext JS, LLC.
11573 * Originally Released Under LGPL - original licence link has changed is not relivant.
11576 * <script type="text/javascript">
11580 * Global Ajax request class.
11583 * @extends Roo.data.Connection
11586 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
11587 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
11588 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
11589 * @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)
11590 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11591 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
11592 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11594 Roo.Ajax = new Roo.data.Connection({
11603 * Serialize the passed form into a url encoded string
11605 * @param {String/HTMLElement} form
11608 serializeForm : function(form){
11609 return Roo.lib.Ajax.serializeForm(form);
11613 * Ext JS Library 1.1.1
11614 * Copyright(c) 2006-2007, Ext JS, LLC.
11616 * Originally Released Under LGPL - original licence link has changed is not relivant.
11619 * <script type="text/javascript">
11624 * @class Roo.UpdateManager
11625 * @extends Roo.util.Observable
11626 * Provides AJAX-style update for Element object.<br><br>
11629 * // Get it from a Roo.Element object
11630 * var el = Roo.get("foo");
11631 * var mgr = el.getUpdateManager();
11632 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11634 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11636 * // or directly (returns the same UpdateManager instance)
11637 * var mgr = new Roo.UpdateManager("myElementId");
11638 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11639 * mgr.on("update", myFcnNeedsToKnow);
11641 // short handed call directly from the element object
11642 Roo.get("foo").load({
11646 text: "Loading Foo..."
11650 * Create new UpdateManager directly.
11651 * @param {String/HTMLElement/Roo.Element} el The element to update
11652 * @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).
11654 Roo.UpdateManager = function(el, forceNew){
11656 if(!forceNew && el.updateManager){
11657 return el.updateManager;
11660 * The Element object
11661 * @type Roo.Element
11665 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11668 this.defaultUrl = null;
11672 * @event beforeupdate
11673 * Fired before an update is made, return false from your handler and the update is cancelled.
11674 * @param {Roo.Element} el
11675 * @param {String/Object/Function} url
11676 * @param {String/Object} params
11678 "beforeupdate": true,
11681 * Fired after successful update is made.
11682 * @param {Roo.Element} el
11683 * @param {Object} oResponseObject The response Object
11688 * Fired on update failure.
11689 * @param {Roo.Element} el
11690 * @param {Object} oResponseObject The response Object
11694 var d = Roo.UpdateManager.defaults;
11696 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11699 this.sslBlankUrl = d.sslBlankUrl;
11701 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11704 this.disableCaching = d.disableCaching;
11706 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11709 this.indicatorText = d.indicatorText;
11711 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11714 this.showLoadIndicator = d.showLoadIndicator;
11716 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11719 this.timeout = d.timeout;
11722 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11725 this.loadScripts = d.loadScripts;
11728 * Transaction object of current executing transaction
11730 this.transaction = null;
11735 this.autoRefreshProcId = null;
11737 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11740 this.refreshDelegate = this.refresh.createDelegate(this);
11742 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11745 this.updateDelegate = this.update.createDelegate(this);
11747 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11750 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11754 this.successDelegate = this.processSuccess.createDelegate(this);
11758 this.failureDelegate = this.processFailure.createDelegate(this);
11760 if(!this.renderer){
11762 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11764 this.renderer = new Roo.UpdateManager.BasicRenderer();
11767 Roo.UpdateManager.superclass.constructor.call(this);
11770 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11772 * Get the Element this UpdateManager is bound to
11773 * @return {Roo.Element} The element
11775 getEl : function(){
11779 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11780 * @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:
11783 url: "your-url.php",<br/>
11784 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11785 callback: yourFunction,<br/>
11786 scope: yourObject, //(optional scope) <br/>
11787 discardUrl: false, <br/>
11788 nocache: false,<br/>
11789 text: "Loading...",<br/>
11791 scripts: false<br/>
11794 * The only required property is url. The optional properties nocache, text and scripts
11795 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11796 * @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}
11797 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11798 * @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.
11800 update : function(url, params, callback, discardUrl){
11801 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11802 var method = this.method,
11804 if(typeof url == "object"){ // must be config object
11807 params = params || cfg.params;
11808 callback = callback || cfg.callback;
11809 discardUrl = discardUrl || cfg.discardUrl;
11810 if(callback && cfg.scope){
11811 callback = callback.createDelegate(cfg.scope);
11813 if(typeof cfg.method != "undefined"){method = cfg.method;};
11814 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11815 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11816 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11817 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11819 this.showLoading();
11821 this.defaultUrl = url;
11823 if(typeof url == "function"){
11824 url = url.call(this);
11827 method = method || (params ? "POST" : "GET");
11828 if(method == "GET"){
11829 url = this.prepareUrl(url);
11832 var o = Roo.apply(cfg ||{}, {
11835 success: this.successDelegate,
11836 failure: this.failureDelegate,
11837 callback: undefined,
11838 timeout: (this.timeout*1000),
11839 argument: {"url": url, "form": null, "callback": callback, "params": params}
11841 Roo.log("updated manager called with timeout of " + o.timeout);
11842 this.transaction = Roo.Ajax.request(o);
11847 * 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.
11848 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11849 * @param {String/HTMLElement} form The form Id or form element
11850 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11851 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11852 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11854 formUpdate : function(form, url, reset, callback){
11855 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11856 if(typeof url == "function"){
11857 url = url.call(this);
11859 form = Roo.getDom(form);
11860 this.transaction = Roo.Ajax.request({
11863 success: this.successDelegate,
11864 failure: this.failureDelegate,
11865 timeout: (this.timeout*1000),
11866 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11868 this.showLoading.defer(1, this);
11873 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11874 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11876 refresh : function(callback){
11877 if(this.defaultUrl == null){
11880 this.update(this.defaultUrl, null, callback, true);
11884 * Set this element to auto refresh.
11885 * @param {Number} interval How often to update (in seconds).
11886 * @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)
11887 * @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}
11888 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11889 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11891 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11893 this.update(url || this.defaultUrl, params, callback, true);
11895 if(this.autoRefreshProcId){
11896 clearInterval(this.autoRefreshProcId);
11898 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11902 * Stop auto refresh on this element.
11904 stopAutoRefresh : function(){
11905 if(this.autoRefreshProcId){
11906 clearInterval(this.autoRefreshProcId);
11907 delete this.autoRefreshProcId;
11911 isAutoRefreshing : function(){
11912 return this.autoRefreshProcId ? true : false;
11915 * Called to update the element to "Loading" state. Override to perform custom action.
11917 showLoading : function(){
11918 if(this.showLoadIndicator){
11919 this.el.update(this.indicatorText);
11924 * Adds unique parameter to query string if disableCaching = true
11927 prepareUrl : function(url){
11928 if(this.disableCaching){
11929 var append = "_dc=" + (new Date().getTime());
11930 if(url.indexOf("?") !== -1){
11931 url += "&" + append;
11933 url += "?" + append;
11942 processSuccess : function(response){
11943 this.transaction = null;
11944 if(response.argument.form && response.argument.reset){
11945 try{ // put in try/catch since some older FF releases had problems with this
11946 response.argument.form.reset();
11949 if(this.loadScripts){
11950 this.renderer.render(this.el, response, this,
11951 this.updateComplete.createDelegate(this, [response]));
11953 this.renderer.render(this.el, response, this);
11954 this.updateComplete(response);
11958 updateComplete : function(response){
11959 this.fireEvent("update", this.el, response);
11960 if(typeof response.argument.callback == "function"){
11961 response.argument.callback(this.el, true, response);
11968 processFailure : function(response){
11969 this.transaction = null;
11970 this.fireEvent("failure", this.el, response);
11971 if(typeof response.argument.callback == "function"){
11972 response.argument.callback(this.el, false, response);
11977 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
11978 * @param {Object} renderer The object implementing the render() method
11980 setRenderer : function(renderer){
11981 this.renderer = renderer;
11984 getRenderer : function(){
11985 return this.renderer;
11989 * Set the defaultUrl used for updates
11990 * @param {String/Function} defaultUrl The url or a function to call to get the url
11992 setDefaultUrl : function(defaultUrl){
11993 this.defaultUrl = defaultUrl;
11997 * Aborts the executing transaction
11999 abort : function(){
12000 if(this.transaction){
12001 Roo.Ajax.abort(this.transaction);
12006 * Returns true if an update is in progress
12007 * @return {Boolean}
12009 isUpdating : function(){
12010 if(this.transaction){
12011 return Roo.Ajax.isLoading(this.transaction);
12018 * @class Roo.UpdateManager.defaults
12019 * @static (not really - but it helps the doc tool)
12020 * The defaults collection enables customizing the default properties of UpdateManager
12022 Roo.UpdateManager.defaults = {
12024 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12030 * True to process scripts by default (Defaults to false).
12033 loadScripts : false,
12036 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12039 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12041 * Whether to append unique parameter on get request to disable caching (Defaults to false).
12044 disableCaching : false,
12046 * Whether to show indicatorText when loading (Defaults to true).
12049 showLoadIndicator : true,
12051 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
12054 indicatorText : '<div class="loading-indicator">Loading...</div>'
12058 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12060 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12061 * @param {String/HTMLElement/Roo.Element} el The element to update
12062 * @param {String} url The url
12063 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12064 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12067 * @member Roo.UpdateManager
12069 Roo.UpdateManager.updateElement = function(el, url, params, options){
12070 var um = Roo.get(el, true).getUpdateManager();
12071 Roo.apply(um, options);
12072 um.update(url, params, options ? options.callback : null);
12074 // alias for backwards compat
12075 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12077 * @class Roo.UpdateManager.BasicRenderer
12078 * Default Content renderer. Updates the elements innerHTML with the responseText.
12080 Roo.UpdateManager.BasicRenderer = function(){};
12082 Roo.UpdateManager.BasicRenderer.prototype = {
12084 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12085 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12086 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12087 * @param {Roo.Element} el The element being rendered
12088 * @param {Object} response The YUI Connect response object
12089 * @param {UpdateManager} updateManager The calling update manager
12090 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12092 render : function(el, response, updateManager, callback){
12093 el.update(response.responseText, updateManager.loadScripts, callback);
12099 * (c)) Alan Knowles
12105 * @class Roo.DomTemplate
12106 * @extends Roo.Template
12107 * An effort at a dom based template engine..
12109 * Similar to XTemplate, except it uses dom parsing to create the template..
12111 * Supported features:
12116 {a_variable} - output encoded.
12117 {a_variable.format:("Y-m-d")} - call a method on the variable
12118 {a_variable:raw} - unencoded output
12119 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
12120 {a_variable:this.method_on_template(...)} - call a method on the template object.
12125 <div roo-for="a_variable or condition.."></div>
12126 <div roo-if="a_variable or condition"></div>
12127 <div roo-exec="some javascript"></div>
12128 <div roo-name="named_template"></div>
12133 Roo.DomTemplate = function()
12135 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
12142 Roo.extend(Roo.DomTemplate, Roo.Template, {
12144 * id counter for sub templates.
12148 * flag to indicate if dom parser is inside a pre,
12149 * it will strip whitespace if not.
12154 * The various sub templates
12162 * basic tag replacing syntax
12165 * // you can fake an object call by doing this
12169 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
12170 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
12172 iterChild : function (node, method) {
12174 var oldPre = this.inPre;
12175 if (node.tagName == 'PRE') {
12178 for( var i = 0; i < node.childNodes.length; i++) {
12179 method.call(this, node.childNodes[i]);
12181 this.inPre = oldPre;
12187 * compile the template
12189 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
12192 compile: function()
12196 // covert the html into DOM...
12200 doc = document.implementation.createHTMLDocument("");
12201 doc.documentElement.innerHTML = this.html ;
12202 div = doc.documentElement;
12204 // old IE... - nasty -- it causes all sorts of issues.. with
12205 // images getting pulled from server..
12206 div = document.createElement('div');
12207 div.innerHTML = this.html;
12209 //doc.documentElement.innerHTML = htmlBody
12215 this.iterChild(div, function(n) {_t.compileNode(n, true); });
12217 var tpls = this.tpls;
12219 // create a top level template from the snippet..
12221 //Roo.log(div.innerHTML);
12228 body : div.innerHTML,
12241 Roo.each(tpls, function(tp){
12242 this.compileTpl(tp);
12243 this.tpls[tp.id] = tp;
12246 this.master = tpls[0];
12252 compileNode : function(node, istop) {
12257 // skip anything not a tag..
12258 if (node.nodeType != 1) {
12259 if (node.nodeType == 3 && !this.inPre) {
12260 // reduce white space..
12261 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
12284 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
12285 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
12286 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
12287 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
12293 // just itterate children..
12294 this.iterChild(node,this.compileNode);
12297 tpl.uid = this.id++;
12298 tpl.value = node.getAttribute('roo-' + tpl.attr);
12299 node.removeAttribute('roo-'+ tpl.attr);
12300 if (tpl.attr != 'name') {
12301 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
12302 node.parentNode.replaceChild(placeholder, node);
12305 var placeholder = document.createElement('span');
12306 placeholder.className = 'roo-tpl-' + tpl.value;
12307 node.parentNode.replaceChild(placeholder, node);
12310 // parent now sees '{domtplXXXX}
12311 this.iterChild(node,this.compileNode);
12313 // we should now have node body...
12314 var div = document.createElement('div');
12315 div.appendChild(node);
12317 // this has the unfortunate side effect of converting tagged attributes
12318 // eg. href="{...}" into %7C...%7D
12319 // this has been fixed by searching for those combo's although it's a bit hacky..
12322 tpl.body = div.innerHTML;
12329 switch (tpl.value) {
12330 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
12331 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
12332 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
12337 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12341 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12345 tpl.id = tpl.value; // replace non characters???
12351 this.tpls.push(tpl);
12361 * Compile a segment of the template into a 'sub-template'
12367 compileTpl : function(tpl)
12369 var fm = Roo.util.Format;
12370 var useF = this.disableFormats !== true;
12372 var sep = Roo.isGecko ? "+\n" : ",\n";
12374 var undef = function(str) {
12375 Roo.debug && Roo.log("Property not found :" + str);
12379 //Roo.log(tpl.body);
12383 var fn = function(m, lbrace, name, format, args)
12386 //Roo.log(arguments);
12387 args = args ? args.replace(/\\'/g,"'") : args;
12388 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
12389 if (typeof(format) == 'undefined') {
12390 format = 'htmlEncode';
12392 if (format == 'raw' ) {
12396 if(name.substr(0, 6) == 'domtpl'){
12397 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
12400 // build an array of options to determine if value is undefined..
12402 // basically get 'xxxx.yyyy' then do
12403 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
12404 // (function () { Roo.log("Property not found"); return ''; })() :
12409 Roo.each(name.split('.'), function(st) {
12410 lookfor += (lookfor.length ? '.': '') + st;
12411 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
12414 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
12417 if(format && useF){
12419 args = args ? ',' + args : "";
12421 if(format.substr(0, 5) != "this."){
12422 format = "fm." + format + '(';
12424 format = 'this.call("'+ format.substr(5) + '", ';
12428 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
12431 if (args && args.length) {
12432 // called with xxyx.yuu:(test,test)
12434 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
12436 // raw.. - :raw modifier..
12437 return "'"+ sep + udef_st + name + ")"+sep+"'";
12441 // branched to use + in gecko and [].join() in others
12443 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
12444 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
12447 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
12448 body.push(tpl.body.replace(/(\r\n|\n)/g,
12449 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
12450 body.push("'].join('');};};");
12451 body = body.join('');
12454 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
12456 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
12463 * same as applyTemplate, except it's done to one of the subTemplates
12464 * when using named templates, you can do:
12466 * var str = pl.applySubTemplate('your-name', values);
12469 * @param {Number} id of the template
12470 * @param {Object} values to apply to template
12471 * @param {Object} parent (normaly the instance of this object)
12473 applySubTemplate : function(id, values, parent)
12477 var t = this.tpls[id];
12481 if(t.ifCall && !t.ifCall.call(this, values, parent)){
12482 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
12486 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
12493 if(t.execCall && t.execCall.call(this, values, parent)){
12497 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12503 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
12504 parent = t.target ? values : parent;
12505 if(t.forCall && vs instanceof Array){
12507 for(var i = 0, len = vs.length; i < len; i++){
12509 buf[buf.length] = t.compiled.call(this, vs[i], parent);
12511 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12513 //Roo.log(t.compiled);
12517 return buf.join('');
12520 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12525 return t.compiled.call(this, vs, parent);
12527 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12529 //Roo.log(t.compiled);
12537 applyTemplate : function(values){
12538 return this.master.compiled.call(this, values, {});
12539 //var s = this.subs;
12542 apply : function(){
12543 return this.applyTemplate.apply(this, arguments);
12548 Roo.DomTemplate.from = function(el){
12549 el = Roo.getDom(el);
12550 return new Roo.Domtemplate(el.value || el.innerHTML);
12553 * Ext JS Library 1.1.1
12554 * Copyright(c) 2006-2007, Ext JS, LLC.
12556 * Originally Released Under LGPL - original licence link has changed is not relivant.
12559 * <script type="text/javascript">
12563 * @class Roo.util.DelayedTask
12564 * Provides a convenient method of performing setTimeout where a new
12565 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12566 * You can use this class to buffer
12567 * the keypress events for a certain number of milliseconds, and perform only if they stop
12568 * for that amount of time.
12569 * @constructor The parameters to this constructor serve as defaults and are not required.
12570 * @param {Function} fn (optional) The default function to timeout
12571 * @param {Object} scope (optional) The default scope of that timeout
12572 * @param {Array} args (optional) The default Array of arguments
12574 Roo.util.DelayedTask = function(fn, scope, args){
12575 var id = null, d, t;
12577 var call = function(){
12578 var now = new Date().getTime();
12582 fn.apply(scope, args || []);
12586 * Cancels any pending timeout and queues a new one
12587 * @param {Number} delay The milliseconds to delay
12588 * @param {Function} newFn (optional) Overrides function passed to constructor
12589 * @param {Object} newScope (optional) Overrides scope passed to constructor
12590 * @param {Array} newArgs (optional) Overrides args passed to constructor
12592 this.delay = function(delay, newFn, newScope, newArgs){
12593 if(id && delay != d){
12597 t = new Date().getTime();
12599 scope = newScope || scope;
12600 args = newArgs || args;
12602 id = setInterval(call, d);
12607 * Cancel the last queued timeout
12609 this.cancel = function(){
12617 * Ext JS Library 1.1.1
12618 * Copyright(c) 2006-2007, Ext JS, LLC.
12620 * Originally Released Under LGPL - original licence link has changed is not relivant.
12623 * <script type="text/javascript">
12627 Roo.util.TaskRunner = function(interval){
12628 interval = interval || 10;
12629 var tasks = [], removeQueue = [];
12631 var running = false;
12633 var stopThread = function(){
12639 var startThread = function(){
12642 id = setInterval(runTasks, interval);
12646 var removeTask = function(task){
12647 removeQueue.push(task);
12653 var runTasks = function(){
12654 if(removeQueue.length > 0){
12655 for(var i = 0, len = removeQueue.length; i < len; i++){
12656 tasks.remove(removeQueue[i]);
12659 if(tasks.length < 1){
12664 var now = new Date().getTime();
12665 for(var i = 0, len = tasks.length; i < len; ++i){
12667 var itime = now - t.taskRunTime;
12668 if(t.interval <= itime){
12669 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12670 t.taskRunTime = now;
12671 if(rt === false || t.taskRunCount === t.repeat){
12676 if(t.duration && t.duration <= (now - t.taskStartTime)){
12683 * Queues a new task.
12684 * @param {Object} task
12686 this.start = function(task){
12688 task.taskStartTime = new Date().getTime();
12689 task.taskRunTime = 0;
12690 task.taskRunCount = 0;
12695 this.stop = function(task){
12700 this.stopAll = function(){
12702 for(var i = 0, len = tasks.length; i < len; i++){
12703 if(tasks[i].onStop){
12712 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12714 * Ext JS Library 1.1.1
12715 * Copyright(c) 2006-2007, Ext JS, LLC.
12717 * Originally Released Under LGPL - original licence link has changed is not relivant.
12720 * <script type="text/javascript">
12725 * @class Roo.util.MixedCollection
12726 * @extends Roo.util.Observable
12727 * A Collection class that maintains both numeric indexes and keys and exposes events.
12729 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12730 * collection (defaults to false)
12731 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12732 * and return the key value for that item. This is used when available to look up the key on items that
12733 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12734 * equivalent to providing an implementation for the {@link #getKey} method.
12736 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12744 * Fires when the collection is cleared.
12749 * Fires when an item is added to the collection.
12750 * @param {Number} index The index at which the item was added.
12751 * @param {Object} o The item added.
12752 * @param {String} key The key associated with the added item.
12757 * Fires when an item is replaced in the collection.
12758 * @param {String} key he key associated with the new added.
12759 * @param {Object} old The item being replaced.
12760 * @param {Object} new The new item.
12765 * Fires when an item is removed from the collection.
12766 * @param {Object} o The item being removed.
12767 * @param {String} key (optional) The key associated with the removed item.
12772 this.allowFunctions = allowFunctions === true;
12774 this.getKey = keyFn;
12776 Roo.util.MixedCollection.superclass.constructor.call(this);
12779 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12780 allowFunctions : false,
12783 * Adds an item to the collection.
12784 * @param {String} key The key to associate with the item
12785 * @param {Object} o The item to add.
12786 * @return {Object} The item added.
12788 add : function(key, o){
12789 if(arguments.length == 1){
12791 key = this.getKey(o);
12793 if(typeof key == "undefined" || key === null){
12795 this.items.push(o);
12796 this.keys.push(null);
12798 var old = this.map[key];
12800 return this.replace(key, o);
12803 this.items.push(o);
12805 this.keys.push(key);
12807 this.fireEvent("add", this.length-1, o, key);
12812 * MixedCollection has a generic way to fetch keys if you implement getKey.
12815 var mc = new Roo.util.MixedCollection();
12816 mc.add(someEl.dom.id, someEl);
12817 mc.add(otherEl.dom.id, otherEl);
12821 var mc = new Roo.util.MixedCollection();
12822 mc.getKey = function(el){
12828 // or via the constructor
12829 var mc = new Roo.util.MixedCollection(false, function(el){
12835 * @param o {Object} The item for which to find the key.
12836 * @return {Object} The key for the passed item.
12838 getKey : function(o){
12843 * Replaces an item in the collection.
12844 * @param {String} key The key associated with the item to replace, or the item to replace.
12845 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12846 * @return {Object} The new item.
12848 replace : function(key, o){
12849 if(arguments.length == 1){
12851 key = this.getKey(o);
12853 var old = this.item(key);
12854 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12855 return this.add(key, o);
12857 var index = this.indexOfKey(key);
12858 this.items[index] = o;
12860 this.fireEvent("replace", key, old, o);
12865 * Adds all elements of an Array or an Object to the collection.
12866 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12867 * an Array of values, each of which are added to the collection.
12869 addAll : function(objs){
12870 if(arguments.length > 1 || objs instanceof Array){
12871 var args = arguments.length > 1 ? arguments : objs;
12872 for(var i = 0, len = args.length; i < len; i++){
12876 for(var key in objs){
12877 if(this.allowFunctions || typeof objs[key] != "function"){
12878 this.add(key, objs[key]);
12885 * Executes the specified function once for every item in the collection, passing each
12886 * item as the first and only parameter. returning false from the function will stop the iteration.
12887 * @param {Function} fn The function to execute for each item.
12888 * @param {Object} scope (optional) The scope in which to execute the function.
12890 each : function(fn, scope){
12891 var items = [].concat(this.items); // each safe for removal
12892 for(var i = 0, len = items.length; i < len; i++){
12893 if(fn.call(scope || items[i], items[i], i, len) === false){
12900 * Executes the specified function once for every key in the collection, passing each
12901 * key, and its associated item as the first two parameters.
12902 * @param {Function} fn The function to execute for each item.
12903 * @param {Object} scope (optional) The scope in which to execute the function.
12905 eachKey : function(fn, scope){
12906 for(var i = 0, len = this.keys.length; i < len; i++){
12907 fn.call(scope || window, this.keys[i], this.items[i], i, len);
12912 * Returns the first item in the collection which elicits a true return value from the
12913 * passed selection function.
12914 * @param {Function} fn The selection function to execute for each item.
12915 * @param {Object} scope (optional) The scope in which to execute the function.
12916 * @return {Object} The first item in the collection which returned true from the selection function.
12918 find : function(fn, scope){
12919 for(var i = 0, len = this.items.length; i < len; i++){
12920 if(fn.call(scope || window, this.items[i], this.keys[i])){
12921 return this.items[i];
12928 * Inserts an item at the specified index in the collection.
12929 * @param {Number} index The index to insert the item at.
12930 * @param {String} key The key to associate with the new item, or the item itself.
12931 * @param {Object} o (optional) If the second parameter was a key, the new item.
12932 * @return {Object} The item inserted.
12934 insert : function(index, key, o){
12935 if(arguments.length == 2){
12937 key = this.getKey(o);
12939 if(index >= this.length){
12940 return this.add(key, o);
12943 this.items.splice(index, 0, o);
12944 if(typeof key != "undefined" && key != null){
12947 this.keys.splice(index, 0, key);
12948 this.fireEvent("add", index, o, key);
12953 * Removed an item from the collection.
12954 * @param {Object} o The item to remove.
12955 * @return {Object} The item removed.
12957 remove : function(o){
12958 return this.removeAt(this.indexOf(o));
12962 * Remove an item from a specified index in the collection.
12963 * @param {Number} index The index within the collection of the item to remove.
12965 removeAt : function(index){
12966 if(index < this.length && index >= 0){
12968 var o = this.items[index];
12969 this.items.splice(index, 1);
12970 var key = this.keys[index];
12971 if(typeof key != "undefined"){
12972 delete this.map[key];
12974 this.keys.splice(index, 1);
12975 this.fireEvent("remove", o, key);
12980 * Removed an item associated with the passed key fom the collection.
12981 * @param {String} key The key of the item to remove.
12983 removeKey : function(key){
12984 return this.removeAt(this.indexOfKey(key));
12988 * Returns the number of items in the collection.
12989 * @return {Number} the number of items in the collection.
12991 getCount : function(){
12992 return this.length;
12996 * Returns index within the collection of the passed Object.
12997 * @param {Object} o The item to find the index of.
12998 * @return {Number} index of the item.
13000 indexOf : function(o){
13001 if(!this.items.indexOf){
13002 for(var i = 0, len = this.items.length; i < len; i++){
13003 if(this.items[i] == o) return i;
13007 return this.items.indexOf(o);
13012 * Returns index within the collection of the passed key.
13013 * @param {String} key The key to find the index of.
13014 * @return {Number} index of the key.
13016 indexOfKey : function(key){
13017 if(!this.keys.indexOf){
13018 for(var i = 0, len = this.keys.length; i < len; i++){
13019 if(this.keys[i] == key) return i;
13023 return this.keys.indexOf(key);
13028 * Returns the item associated with the passed key OR index. Key has priority over index.
13029 * @param {String/Number} key The key or index of the item.
13030 * @return {Object} The item associated with the passed key.
13032 item : function(key){
13033 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
13034 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
13038 * Returns the item at the specified index.
13039 * @param {Number} index The index of the item.
13042 itemAt : function(index){
13043 return this.items[index];
13047 * Returns the item associated with the passed key.
13048 * @param {String/Number} key The key of the item.
13049 * @return {Object} The item associated with the passed key.
13051 key : function(key){
13052 return this.map[key];
13056 * Returns true if the collection contains the passed Object as an item.
13057 * @param {Object} o The Object to look for in the collection.
13058 * @return {Boolean} True if the collection contains the Object as an item.
13060 contains : function(o){
13061 return this.indexOf(o) != -1;
13065 * Returns true if the collection contains the passed Object as a key.
13066 * @param {String} key The key to look for in the collection.
13067 * @return {Boolean} True if the collection contains the Object as a key.
13069 containsKey : function(key){
13070 return typeof this.map[key] != "undefined";
13074 * Removes all items from the collection.
13076 clear : function(){
13081 this.fireEvent("clear");
13085 * Returns the first item in the collection.
13086 * @return {Object} the first item in the collection..
13088 first : function(){
13089 return this.items[0];
13093 * Returns the last item in the collection.
13094 * @return {Object} the last item in the collection..
13097 return this.items[this.length-1];
13100 _sort : function(property, dir, fn){
13101 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
13102 fn = fn || function(a, b){
13105 var c = [], k = this.keys, items = this.items;
13106 for(var i = 0, len = items.length; i < len; i++){
13107 c[c.length] = {key: k[i], value: items[i], index: i};
13109 c.sort(function(a, b){
13110 var v = fn(a[property], b[property]) * dsc;
13112 v = (a.index < b.index ? -1 : 1);
13116 for(var i = 0, len = c.length; i < len; i++){
13117 items[i] = c[i].value;
13120 this.fireEvent("sort", this);
13124 * Sorts this collection with the passed comparison function
13125 * @param {String} direction (optional) "ASC" or "DESC"
13126 * @param {Function} fn (optional) comparison function
13128 sort : function(dir, fn){
13129 this._sort("value", dir, fn);
13133 * Sorts this collection by keys
13134 * @param {String} direction (optional) "ASC" or "DESC"
13135 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
13137 keySort : function(dir, fn){
13138 this._sort("key", dir, fn || function(a, b){
13139 return String(a).toUpperCase()-String(b).toUpperCase();
13144 * Returns a range of items in this collection
13145 * @param {Number} startIndex (optional) defaults to 0
13146 * @param {Number} endIndex (optional) default to the last item
13147 * @return {Array} An array of items
13149 getRange : function(start, end){
13150 var items = this.items;
13151 if(items.length < 1){
13154 start = start || 0;
13155 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
13158 for(var i = start; i <= end; i++) {
13159 r[r.length] = items[i];
13162 for(var i = start; i >= end; i--) {
13163 r[r.length] = items[i];
13170 * Filter the <i>objects</i> in this collection by a specific property.
13171 * Returns a new collection that has been filtered.
13172 * @param {String} property A property on your objects
13173 * @param {String/RegExp} value Either string that the property values
13174 * should start with or a RegExp to test against the property
13175 * @return {MixedCollection} The new filtered collection
13177 filter : function(property, value){
13178 if(!value.exec){ // not a regex
13179 value = String(value);
13180 if(value.length == 0){
13181 return this.clone();
13183 value = new RegExp("^" + Roo.escapeRe(value), "i");
13185 return this.filterBy(function(o){
13186 return o && value.test(o[property]);
13191 * Filter by a function. * Returns a new collection that has been filtered.
13192 * The passed function will be called with each
13193 * object in the collection. If the function returns true, the value is included
13194 * otherwise it is filtered.
13195 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
13196 * @param {Object} scope (optional) The scope of the function (defaults to this)
13197 * @return {MixedCollection} The new filtered collection
13199 filterBy : function(fn, scope){
13200 var r = new Roo.util.MixedCollection();
13201 r.getKey = this.getKey;
13202 var k = this.keys, it = this.items;
13203 for(var i = 0, len = it.length; i < len; i++){
13204 if(fn.call(scope||this, it[i], k[i])){
13205 r.add(k[i], it[i]);
13212 * Creates a duplicate of this collection
13213 * @return {MixedCollection}
13215 clone : function(){
13216 var r = new Roo.util.MixedCollection();
13217 var k = this.keys, it = this.items;
13218 for(var i = 0, len = it.length; i < len; i++){
13219 r.add(k[i], it[i]);
13221 r.getKey = this.getKey;
13226 * Returns the item associated with the passed key or index.
13228 * @param {String/Number} key The key or index of the item.
13229 * @return {Object} The item associated with the passed key.
13231 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
13233 * Ext JS Library 1.1.1
13234 * Copyright(c) 2006-2007, Ext JS, LLC.
13236 * Originally Released Under LGPL - original licence link has changed is not relivant.
13239 * <script type="text/javascript">
13242 * @class Roo.util.JSON
13243 * Modified version of Douglas Crockford"s json.js that doesn"t
13244 * mess with the Object prototype
13245 * http://www.json.org/js.html
13248 Roo.util.JSON = new (function(){
13249 var useHasOwn = {}.hasOwnProperty ? true : false;
13251 // crashes Safari in some instances
13252 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
13254 var pad = function(n) {
13255 return n < 10 ? "0" + n : n;
13268 var encodeString = function(s){
13269 if (/["\\\x00-\x1f]/.test(s)) {
13270 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
13275 c = b.charCodeAt();
13277 Math.floor(c / 16).toString(16) +
13278 (c % 16).toString(16);
13281 return '"' + s + '"';
13284 var encodeArray = function(o){
13285 var a = ["["], b, i, l = o.length, v;
13286 for (i = 0; i < l; i += 1) {
13288 switch (typeof v) {
13297 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
13305 var encodeDate = function(o){
13306 return '"' + o.getFullYear() + "-" +
13307 pad(o.getMonth() + 1) + "-" +
13308 pad(o.getDate()) + "T" +
13309 pad(o.getHours()) + ":" +
13310 pad(o.getMinutes()) + ":" +
13311 pad(o.getSeconds()) + '"';
13315 * Encodes an Object, Array or other value
13316 * @param {Mixed} o The variable to encode
13317 * @return {String} The JSON string
13319 this.encode = function(o)
13321 // should this be extended to fully wrap stringify..
13323 if(typeof o == "undefined" || o === null){
13325 }else if(o instanceof Array){
13326 return encodeArray(o);
13327 }else if(o instanceof Date){
13328 return encodeDate(o);
13329 }else if(typeof o == "string"){
13330 return encodeString(o);
13331 }else if(typeof o == "number"){
13332 return isFinite(o) ? String(o) : "null";
13333 }else if(typeof o == "boolean"){
13336 var a = ["{"], b, i, v;
13338 if(!useHasOwn || o.hasOwnProperty(i)) {
13340 switch (typeof v) {
13349 a.push(this.encode(i), ":",
13350 v === null ? "null" : this.encode(v));
13361 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
13362 * @param {String} json The JSON string
13363 * @return {Object} The resulting object
13365 this.decode = function(json){
13367 return /** eval:var:json */ eval("(" + json + ')');
13371 * Shorthand for {@link Roo.util.JSON#encode}
13372 * @member Roo encode
13374 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
13376 * Shorthand for {@link Roo.util.JSON#decode}
13377 * @member Roo decode
13379 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
13382 * Ext JS Library 1.1.1
13383 * Copyright(c) 2006-2007, Ext JS, LLC.
13385 * Originally Released Under LGPL - original licence link has changed is not relivant.
13388 * <script type="text/javascript">
13392 * @class Roo.util.Format
13393 * Reusable data formatting functions
13396 Roo.util.Format = function(){
13397 var trimRe = /^\s+|\s+$/g;
13400 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
13401 * @param {String} value The string to truncate
13402 * @param {Number} length The maximum length to allow before truncating
13403 * @return {String} The converted text
13405 ellipsis : function(value, len){
13406 if(value && value.length > len){
13407 return value.substr(0, len-3)+"...";
13413 * Checks a reference and converts it to empty string if it is undefined
13414 * @param {Mixed} value Reference to check
13415 * @return {Mixed} Empty string if converted, otherwise the original value
13417 undef : function(value){
13418 return typeof value != "undefined" ? value : "";
13422 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
13423 * @param {String} value The string to encode
13424 * @return {String} The encoded text
13426 htmlEncode : function(value){
13427 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
13431 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13432 * @param {String} value The string to decode
13433 * @return {String} The decoded text
13435 htmlDecode : function(value){
13436 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
13440 * Trims any whitespace from either side of a string
13441 * @param {String} value The text to trim
13442 * @return {String} The trimmed text
13444 trim : function(value){
13445 return String(value).replace(trimRe, "");
13449 * Returns a substring from within an original string
13450 * @param {String} value The original text
13451 * @param {Number} start The start index of the substring
13452 * @param {Number} length The length of the substring
13453 * @return {String} The substring
13455 substr : function(value, start, length){
13456 return String(value).substr(start, length);
13460 * Converts a string to all lower case letters
13461 * @param {String} value The text to convert
13462 * @return {String} The converted text
13464 lowercase : function(value){
13465 return String(value).toLowerCase();
13469 * Converts a string to all upper case letters
13470 * @param {String} value The text to convert
13471 * @return {String} The converted text
13473 uppercase : function(value){
13474 return String(value).toUpperCase();
13478 * Converts the first character only of a string to upper case
13479 * @param {String} value The text to convert
13480 * @return {String} The converted text
13482 capitalize : function(value){
13483 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13487 call : function(value, fn){
13488 if(arguments.length > 2){
13489 var args = Array.prototype.slice.call(arguments, 2);
13490 args.unshift(value);
13492 return /** eval:var:value */ eval(fn).apply(window, args);
13494 /** eval:var:value */
13495 return /** eval:var:value */ eval(fn).call(window, value);
13501 * safer version of Math.toFixed..??/
13502 * @param {Number/String} value The numeric value to format
13503 * @param {Number/String} value Decimal places
13504 * @return {String} The formatted currency string
13506 toFixed : function(v, n)
13508 // why not use to fixed - precision is buggered???
13510 return Math.round(v-0);
13512 var fact = Math.pow(10,n+1);
13513 v = (Math.round((v-0)*fact))/fact;
13514 var z = (''+fact).substring(2);
13515 if (v == Math.floor(v)) {
13516 return Math.floor(v) + '.' + z;
13519 // now just padd decimals..
13520 var ps = String(v).split('.');
13521 var fd = (ps[1] + z);
13522 var r = fd.substring(0,n);
13523 var rm = fd.substring(n);
13525 return ps[0] + '.' + r;
13527 r*=1; // turn it into a number;
13529 if (String(r).length != n) {
13532 r = String(r).substring(1); // chop the end off.
13535 return ps[0] + '.' + r;
13540 * Format a number as US currency
13541 * @param {Number/String} value The numeric value to format
13542 * @return {String} The formatted currency string
13544 usMoney : function(v){
13545 return '$' + Roo.util.Format.number(v);
13550 * eventually this should probably emulate php's number_format
13551 * @param {Number/String} value The numeric value to format
13552 * @param {Number} decimals number of decimal places
13553 * @return {String} The formatted currency string
13555 number : function(v,decimals)
13557 // multiply and round.
13558 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
13559 var mul = Math.pow(10, decimals);
13560 var zero = String(mul).substring(1);
13561 v = (Math.round((v-0)*mul))/mul;
13563 // if it's '0' number.. then
13565 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13567 var ps = v.split('.');
13571 var r = /(\d+)(\d{3})/;
13573 while (r.test(whole)) {
13574 whole = whole.replace(r, '$1' + ',' + '$2');
13580 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
13581 // does not have decimals
13582 (decimals ? ('.' + zero) : '');
13585 return whole + sub ;
13589 * Parse a value into a formatted date using the specified format pattern.
13590 * @param {Mixed} value The value to format
13591 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13592 * @return {String} The formatted date string
13594 date : function(v, format){
13598 if(!(v instanceof Date)){
13599 v = new Date(Date.parse(v));
13601 return v.dateFormat(format || "m/d/Y");
13605 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13606 * @param {String} format Any valid date format string
13607 * @return {Function} The date formatting function
13609 dateRenderer : function(format){
13610 return function(v){
13611 return Roo.util.Format.date(v, format);
13616 stripTagsRE : /<\/?[^>]+>/gi,
13619 * Strips all HTML tags
13620 * @param {Mixed} value The text from which to strip tags
13621 * @return {String} The stripped text
13623 stripTags : function(v){
13624 return !v ? v : String(v).replace(this.stripTagsRE, "");
13629 * Ext JS Library 1.1.1
13630 * Copyright(c) 2006-2007, Ext JS, LLC.
13632 * Originally Released Under LGPL - original licence link has changed is not relivant.
13635 * <script type="text/javascript">
13642 * @class Roo.MasterTemplate
13643 * @extends Roo.Template
13644 * Provides a template that can have child templates. The syntax is:
13646 var t = new Roo.MasterTemplate(
13647 '<select name="{name}">',
13648 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13651 t.add('options', {value: 'foo', text: 'bar'});
13652 // or you can add multiple child elements in one shot
13653 t.addAll('options', [
13654 {value: 'foo', text: 'bar'},
13655 {value: 'foo2', text: 'bar2'},
13656 {value: 'foo3', text: 'bar3'}
13658 // then append, applying the master template values
13659 t.append('my-form', {name: 'my-select'});
13661 * A name attribute for the child template is not required if you have only one child
13662 * template or you want to refer to them by index.
13664 Roo.MasterTemplate = function(){
13665 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13666 this.originalHtml = this.html;
13668 var m, re = this.subTemplateRe;
13671 while(m = re.exec(this.html)){
13672 var name = m[1], content = m[2];
13677 tpl : new Roo.Template(content)
13680 st[name] = st[subIndex];
13682 st[subIndex].tpl.compile();
13683 st[subIndex].tpl.call = this.call.createDelegate(this);
13686 this.subCount = subIndex;
13689 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13691 * The regular expression used to match sub templates
13695 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13698 * Applies the passed values to a child template.
13699 * @param {String/Number} name (optional) The name or index of the child template
13700 * @param {Array/Object} values The values to be applied to the template
13701 * @return {MasterTemplate} this
13703 add : function(name, values){
13704 if(arguments.length == 1){
13705 values = arguments[0];
13708 var s = this.subs[name];
13709 s.buffer[s.buffer.length] = s.tpl.apply(values);
13714 * Applies all the passed values to a child template.
13715 * @param {String/Number} name (optional) The name or index of the child template
13716 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13717 * @param {Boolean} reset (optional) True to reset the template first
13718 * @return {MasterTemplate} this
13720 fill : function(name, values, reset){
13722 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13730 for(var i = 0, len = values.length; i < len; i++){
13731 this.add(name, values[i]);
13737 * Resets the template for reuse
13738 * @return {MasterTemplate} this
13740 reset : function(){
13742 for(var i = 0; i < this.subCount; i++){
13748 applyTemplate : function(values){
13750 var replaceIndex = -1;
13751 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13752 return s[++replaceIndex].buffer.join("");
13754 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13757 apply : function(){
13758 return this.applyTemplate.apply(this, arguments);
13761 compile : function(){return this;}
13765 * Alias for fill().
13768 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13770 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13771 * var tpl = Roo.MasterTemplate.from('element-id');
13772 * @param {String/HTMLElement} el
13773 * @param {Object} config
13776 Roo.MasterTemplate.from = function(el, config){
13777 el = Roo.getDom(el);
13778 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13781 * Ext JS Library 1.1.1
13782 * Copyright(c) 2006-2007, Ext JS, LLC.
13784 * Originally Released Under LGPL - original licence link has changed is not relivant.
13787 * <script type="text/javascript">
13792 * @class Roo.util.CSS
13793 * Utility class for manipulating CSS rules
13796 Roo.util.CSS = function(){
13798 var doc = document;
13800 var camelRe = /(-[a-z])/gi;
13801 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13805 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13806 * tag and appended to the HEAD of the document.
13807 * @param {String|Object} cssText The text containing the css rules
13808 * @param {String} id An id to add to the stylesheet for later removal
13809 * @return {StyleSheet}
13811 createStyleSheet : function(cssText, id){
13813 var head = doc.getElementsByTagName("head")[0];
13814 var nrules = doc.createElement("style");
13815 nrules.setAttribute("type", "text/css");
13817 nrules.setAttribute("id", id);
13819 if (typeof(cssText) != 'string') {
13820 // support object maps..
13821 // not sure if this a good idea..
13822 // perhaps it should be merged with the general css handling
13823 // and handle js style props.
13824 var cssTextNew = [];
13825 for(var n in cssText) {
13827 for(var k in cssText[n]) {
13828 citems.push( k + ' : ' +cssText[n][k] + ';' );
13830 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13833 cssText = cssTextNew.join("\n");
13839 head.appendChild(nrules);
13840 ss = nrules.styleSheet;
13841 ss.cssText = cssText;
13844 nrules.appendChild(doc.createTextNode(cssText));
13846 nrules.cssText = cssText;
13848 head.appendChild(nrules);
13849 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13851 this.cacheStyleSheet(ss);
13856 * Removes a style or link tag by id
13857 * @param {String} id The id of the tag
13859 removeStyleSheet : function(id){
13860 var existing = doc.getElementById(id);
13862 existing.parentNode.removeChild(existing);
13867 * Dynamically swaps an existing stylesheet reference for a new one
13868 * @param {String} id The id of an existing link tag to remove
13869 * @param {String} url The href of the new stylesheet to include
13871 swapStyleSheet : function(id, url){
13872 this.removeStyleSheet(id);
13873 var ss = doc.createElement("link");
13874 ss.setAttribute("rel", "stylesheet");
13875 ss.setAttribute("type", "text/css");
13876 ss.setAttribute("id", id);
13877 ss.setAttribute("href", url);
13878 doc.getElementsByTagName("head")[0].appendChild(ss);
13882 * Refresh the rule cache if you have dynamically added stylesheets
13883 * @return {Object} An object (hash) of rules indexed by selector
13885 refreshCache : function(){
13886 return this.getRules(true);
13890 cacheStyleSheet : function(stylesheet){
13894 try{// try catch for cross domain access issue
13895 var ssRules = stylesheet.cssRules || stylesheet.rules;
13896 for(var j = ssRules.length-1; j >= 0; --j){
13897 rules[ssRules[j].selectorText] = ssRules[j];
13903 * Gets all css rules for the document
13904 * @param {Boolean} refreshCache true to refresh the internal cache
13905 * @return {Object} An object (hash) of rules indexed by selector
13907 getRules : function(refreshCache){
13908 if(rules == null || refreshCache){
13910 var ds = doc.styleSheets;
13911 for(var i =0, len = ds.length; i < len; i++){
13913 this.cacheStyleSheet(ds[i]);
13921 * Gets an an individual CSS rule by selector(s)
13922 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
13923 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
13924 * @return {CSSRule} The CSS rule or null if one is not found
13926 getRule : function(selector, refreshCache){
13927 var rs = this.getRules(refreshCache);
13928 if(!(selector instanceof Array)){
13929 return rs[selector];
13931 for(var i = 0; i < selector.length; i++){
13932 if(rs[selector[i]]){
13933 return rs[selector[i]];
13941 * Updates a rule property
13942 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
13943 * @param {String} property The css property
13944 * @param {String} value The new value for the property
13945 * @return {Boolean} true If a rule was found and updated
13947 updateRule : function(selector, property, value){
13948 if(!(selector instanceof Array)){
13949 var rule = this.getRule(selector);
13951 rule.style[property.replace(camelRe, camelFn)] = value;
13955 for(var i = 0; i < selector.length; i++){
13956 if(this.updateRule(selector[i], property, value)){
13966 * Ext JS Library 1.1.1
13967 * Copyright(c) 2006-2007, Ext JS, LLC.
13969 * Originally Released Under LGPL - original licence link has changed is not relivant.
13972 * <script type="text/javascript">
13978 * @class Roo.util.ClickRepeater
13979 * @extends Roo.util.Observable
13981 * A wrapper class which can be applied to any element. Fires a "click" event while the
13982 * mouse is pressed. The interval between firings may be specified in the config but
13983 * defaults to 10 milliseconds.
13985 * Optionally, a CSS class may be applied to the element during the time it is pressed.
13987 * @cfg {String/HTMLElement/Element} el The element to act as a button.
13988 * @cfg {Number} delay The initial delay before the repeating event begins firing.
13989 * Similar to an autorepeat key delay.
13990 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
13991 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
13992 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
13993 * "interval" and "delay" are ignored. "immediate" is honored.
13994 * @cfg {Boolean} preventDefault True to prevent the default click event
13995 * @cfg {Boolean} stopDefault True to stop the default click event
13998 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
13999 * 2007-02-02 jvs Renamed to ClickRepeater
14000 * 2007-02-03 jvs Modifications for FF Mac and Safari
14003 * @param {String/HTMLElement/Element} el The element to listen on
14004 * @param {Object} config
14006 Roo.util.ClickRepeater = function(el, config)
14008 this.el = Roo.get(el);
14009 this.el.unselectable();
14011 Roo.apply(this, config);
14016 * Fires when the mouse button is depressed.
14017 * @param {Roo.util.ClickRepeater} this
14019 "mousedown" : true,
14022 * Fires on a specified interval during the time the element is pressed.
14023 * @param {Roo.util.ClickRepeater} this
14028 * Fires when the mouse key is released.
14029 * @param {Roo.util.ClickRepeater} this
14034 this.el.on("mousedown", this.handleMouseDown, this);
14035 if(this.preventDefault || this.stopDefault){
14036 this.el.on("click", function(e){
14037 if(this.preventDefault){
14038 e.preventDefault();
14040 if(this.stopDefault){
14046 // allow inline handler
14048 this.on("click", this.handler, this.scope || this);
14051 Roo.util.ClickRepeater.superclass.constructor.call(this);
14054 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
14057 preventDefault : true,
14058 stopDefault : false,
14062 handleMouseDown : function(){
14063 clearTimeout(this.timer);
14065 if(this.pressClass){
14066 this.el.addClass(this.pressClass);
14068 this.mousedownTime = new Date();
14070 Roo.get(document).on("mouseup", this.handleMouseUp, this);
14071 this.el.on("mouseout", this.handleMouseOut, this);
14073 this.fireEvent("mousedown", this);
14074 this.fireEvent("click", this);
14076 this.timer = this.click.defer(this.delay || this.interval, this);
14080 click : function(){
14081 this.fireEvent("click", this);
14082 this.timer = this.click.defer(this.getInterval(), this);
14086 getInterval: function(){
14087 if(!this.accelerate){
14088 return this.interval;
14090 var pressTime = this.mousedownTime.getElapsed();
14091 if(pressTime < 500){
14093 }else if(pressTime < 1700){
14095 }else if(pressTime < 2600){
14097 }else if(pressTime < 3500){
14099 }else if(pressTime < 4400){
14101 }else if(pressTime < 5300){
14103 }else if(pressTime < 6200){
14111 handleMouseOut : function(){
14112 clearTimeout(this.timer);
14113 if(this.pressClass){
14114 this.el.removeClass(this.pressClass);
14116 this.el.on("mouseover", this.handleMouseReturn, this);
14120 handleMouseReturn : function(){
14121 this.el.un("mouseover", this.handleMouseReturn);
14122 if(this.pressClass){
14123 this.el.addClass(this.pressClass);
14129 handleMouseUp : function(){
14130 clearTimeout(this.timer);
14131 this.el.un("mouseover", this.handleMouseReturn);
14132 this.el.un("mouseout", this.handleMouseOut);
14133 Roo.get(document).un("mouseup", this.handleMouseUp);
14134 this.el.removeClass(this.pressClass);
14135 this.fireEvent("mouseup", this);
14139 * Ext JS Library 1.1.1
14140 * Copyright(c) 2006-2007, Ext JS, LLC.
14142 * Originally Released Under LGPL - original licence link has changed is not relivant.
14145 * <script type="text/javascript">
14150 * @class Roo.KeyNav
14151 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
14152 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
14153 * way to implement custom navigation schemes for any UI component.</p>
14154 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
14155 * pageUp, pageDown, del, home, end. Usage:</p>
14157 var nav = new Roo.KeyNav("my-element", {
14158 "left" : function(e){
14159 this.moveLeft(e.ctrlKey);
14161 "right" : function(e){
14162 this.moveRight(e.ctrlKey);
14164 "enter" : function(e){
14171 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14172 * @param {Object} config The config
14174 Roo.KeyNav = function(el, config){
14175 this.el = Roo.get(el);
14176 Roo.apply(this, config);
14177 if(!this.disabled){
14178 this.disabled = true;
14183 Roo.KeyNav.prototype = {
14185 * @cfg {Boolean} disabled
14186 * True to disable this KeyNav instance (defaults to false)
14190 * @cfg {String} defaultEventAction
14191 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
14192 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
14193 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
14195 defaultEventAction: "stopEvent",
14197 * @cfg {Boolean} forceKeyDown
14198 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
14199 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
14200 * handle keydown instead of keypress.
14202 forceKeyDown : false,
14205 prepareEvent : function(e){
14206 var k = e.getKey();
14207 var h = this.keyToHandler[k];
14208 //if(h && this[h]){
14209 // e.stopPropagation();
14211 if(Roo.isSafari && h && k >= 37 && k <= 40){
14217 relay : function(e){
14218 var k = e.getKey();
14219 var h = this.keyToHandler[k];
14221 if(this.doRelay(e, this[h], h) !== true){
14222 e[this.defaultEventAction]();
14228 doRelay : function(e, h, hname){
14229 return h.call(this.scope || this, e);
14232 // possible handlers
14246 // quick lookup hash
14263 * Enable this KeyNav
14265 enable: function(){
14267 // ie won't do special keys on keypress, no one else will repeat keys with keydown
14268 // the EventObject will normalize Safari automatically
14269 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14270 this.el.on("keydown", this.relay, this);
14272 this.el.on("keydown", this.prepareEvent, this);
14273 this.el.on("keypress", this.relay, this);
14275 this.disabled = false;
14280 * Disable this KeyNav
14282 disable: function(){
14283 if(!this.disabled){
14284 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14285 this.el.un("keydown", this.relay);
14287 this.el.un("keydown", this.prepareEvent);
14288 this.el.un("keypress", this.relay);
14290 this.disabled = true;
14295 * Ext JS Library 1.1.1
14296 * Copyright(c) 2006-2007, Ext JS, LLC.
14298 * Originally Released Under LGPL - original licence link has changed is not relivant.
14301 * <script type="text/javascript">
14306 * @class Roo.KeyMap
14307 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
14308 * The constructor accepts the same config object as defined by {@link #addBinding}.
14309 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
14310 * combination it will call the function with this signature (if the match is a multi-key
14311 * combination the callback will still be called only once): (String key, Roo.EventObject e)
14312 * A KeyMap can also handle a string representation of keys.<br />
14315 // map one key by key code
14316 var map = new Roo.KeyMap("my-element", {
14317 key: 13, // or Roo.EventObject.ENTER
14322 // map multiple keys to one action by string
14323 var map = new Roo.KeyMap("my-element", {
14329 // map multiple keys to multiple actions by strings and array of codes
14330 var map = new Roo.KeyMap("my-element", [
14333 fn: function(){ alert("Return was pressed"); }
14336 fn: function(){ alert('a, b or c was pressed'); }
14341 fn: function(){ alert('Control + shift + tab was pressed.'); }
14345 * <b>Note: A KeyMap starts enabled</b>
14347 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14348 * @param {Object} config The config (see {@link #addBinding})
14349 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
14351 Roo.KeyMap = function(el, config, eventName){
14352 this.el = Roo.get(el);
14353 this.eventName = eventName || "keydown";
14354 this.bindings = [];
14356 this.addBinding(config);
14361 Roo.KeyMap.prototype = {
14363 * True to stop the event from bubbling and prevent the default browser action if the
14364 * key was handled by the KeyMap (defaults to false)
14370 * Add a new binding to this KeyMap. The following config object properties are supported:
14372 Property Type Description
14373 ---------- --------------- ----------------------------------------------------------------------
14374 key String/Array A single keycode or an array of keycodes to handle
14375 shift Boolean True to handle key only when shift is pressed (defaults to false)
14376 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
14377 alt Boolean True to handle key only when alt is pressed (defaults to false)
14378 fn Function The function to call when KeyMap finds the expected key combination
14379 scope Object The scope of the callback function
14385 var map = new Roo.KeyMap(document, {
14386 key: Roo.EventObject.ENTER,
14391 //Add a new binding to the existing KeyMap later
14399 * @param {Object/Array} config A single KeyMap config or an array of configs
14401 addBinding : function(config){
14402 if(config instanceof Array){
14403 for(var i = 0, len = config.length; i < len; i++){
14404 this.addBinding(config[i]);
14408 var keyCode = config.key,
14409 shift = config.shift,
14410 ctrl = config.ctrl,
14413 scope = config.scope;
14414 if(typeof keyCode == "string"){
14416 var keyString = keyCode.toUpperCase();
14417 for(var j = 0, len = keyString.length; j < len; j++){
14418 ks.push(keyString.charCodeAt(j));
14422 var keyArray = keyCode instanceof Array;
14423 var handler = function(e){
14424 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14425 var k = e.getKey();
14427 for(var i = 0, len = keyCode.length; i < len; i++){
14428 if(keyCode[i] == k){
14429 if(this.stopEvent){
14432 fn.call(scope || window, k, e);
14438 if(this.stopEvent){
14441 fn.call(scope || window, k, e);
14446 this.bindings.push(handler);
14450 * Shorthand for adding a single key listener
14451 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
14452 * following options:
14453 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14454 * @param {Function} fn The function to call
14455 * @param {Object} scope (optional) The scope of the function
14457 on : function(key, fn, scope){
14458 var keyCode, shift, ctrl, alt;
14459 if(typeof key == "object" && !(key instanceof Array)){
14478 handleKeyDown : function(e){
14479 if(this.enabled){ //just in case
14480 var b = this.bindings;
14481 for(var i = 0, len = b.length; i < len; i++){
14482 b[i].call(this, e);
14488 * Returns true if this KeyMap is enabled
14489 * @return {Boolean}
14491 isEnabled : function(){
14492 return this.enabled;
14496 * Enables this KeyMap
14498 enable: function(){
14500 this.el.on(this.eventName, this.handleKeyDown, this);
14501 this.enabled = true;
14506 * Disable this KeyMap
14508 disable: function(){
14510 this.el.removeListener(this.eventName, this.handleKeyDown, this);
14511 this.enabled = false;
14516 * Ext JS Library 1.1.1
14517 * Copyright(c) 2006-2007, Ext JS, LLC.
14519 * Originally Released Under LGPL - original licence link has changed is not relivant.
14522 * <script type="text/javascript">
14527 * @class Roo.util.TextMetrics
14528 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14529 * wide, in pixels, a given block of text will be.
14532 Roo.util.TextMetrics = function(){
14536 * Measures the size of the specified text
14537 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14538 * that can affect the size of the rendered text
14539 * @param {String} text The text to measure
14540 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14541 * in order to accurately measure the text height
14542 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14544 measure : function(el, text, fixedWidth){
14546 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14549 shared.setFixedWidth(fixedWidth || 'auto');
14550 return shared.getSize(text);
14554 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
14555 * the overhead of multiple calls to initialize the style properties on each measurement.
14556 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14557 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14558 * in order to accurately measure the text height
14559 * @return {Roo.util.TextMetrics.Instance} instance The new instance
14561 createInstance : function(el, fixedWidth){
14562 return Roo.util.TextMetrics.Instance(el, fixedWidth);
14569 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14570 var ml = new Roo.Element(document.createElement('div'));
14571 document.body.appendChild(ml.dom);
14572 ml.position('absolute');
14573 ml.setLeftTop(-1000, -1000);
14577 ml.setWidth(fixedWidth);
14582 * Returns the size of the specified text based on the internal element's style and width properties
14583 * @memberOf Roo.util.TextMetrics.Instance#
14584 * @param {String} text The text to measure
14585 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14587 getSize : function(text){
14589 var s = ml.getSize();
14595 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14596 * that can affect the size of the rendered text
14597 * @memberOf Roo.util.TextMetrics.Instance#
14598 * @param {String/HTMLElement} el The element, dom node or id
14600 bind : function(el){
14602 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14607 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
14608 * to set a fixed width in order to accurately measure the text height.
14609 * @memberOf Roo.util.TextMetrics.Instance#
14610 * @param {Number} width The width to set on the element
14612 setFixedWidth : function(width){
14613 ml.setWidth(width);
14617 * Returns the measured width of the specified text
14618 * @memberOf Roo.util.TextMetrics.Instance#
14619 * @param {String} text The text to measure
14620 * @return {Number} width The width in pixels
14622 getWidth : function(text){
14623 ml.dom.style.width = 'auto';
14624 return this.getSize(text).width;
14628 * Returns the measured height of the specified text. For multiline text, be sure to call
14629 * {@link #setFixedWidth} if necessary.
14630 * @memberOf Roo.util.TextMetrics.Instance#
14631 * @param {String} text The text to measure
14632 * @return {Number} height The height in pixels
14634 getHeight : function(text){
14635 return this.getSize(text).height;
14639 instance.bind(bindTo);
14644 // backwards compat
14645 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14647 * Ext JS Library 1.1.1
14648 * Copyright(c) 2006-2007, Ext JS, LLC.
14650 * Originally Released Under LGPL - original licence link has changed is not relivant.
14653 * <script type="text/javascript">
14657 * @class Roo.state.Provider
14658 * Abstract base class for state provider implementations. This class provides methods
14659 * for encoding and decoding <b>typed</b> variables including dates and defines the
14660 * Provider interface.
14662 Roo.state.Provider = function(){
14664 * @event statechange
14665 * Fires when a state change occurs.
14666 * @param {Provider} this This state provider
14667 * @param {String} key The state key which was changed
14668 * @param {String} value The encoded value for the state
14671 "statechange": true
14674 Roo.state.Provider.superclass.constructor.call(this);
14676 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14678 * Returns the current value for a key
14679 * @param {String} name The key name
14680 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14681 * @return {Mixed} The state data
14683 get : function(name, defaultValue){
14684 return typeof this.state[name] == "undefined" ?
14685 defaultValue : this.state[name];
14689 * Clears a value from the state
14690 * @param {String} name The key name
14692 clear : function(name){
14693 delete this.state[name];
14694 this.fireEvent("statechange", this, name, null);
14698 * Sets the value for a key
14699 * @param {String} name The key name
14700 * @param {Mixed} value The value to set
14702 set : function(name, value){
14703 this.state[name] = value;
14704 this.fireEvent("statechange", this, name, value);
14708 * Decodes a string previously encoded with {@link #encodeValue}.
14709 * @param {String} value The value to decode
14710 * @return {Mixed} The decoded value
14712 decodeValue : function(cookie){
14713 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14714 var matches = re.exec(unescape(cookie));
14715 if(!matches || !matches[1]) return; // non state cookie
14716 var type = matches[1];
14717 var v = matches[2];
14720 return parseFloat(v);
14722 return new Date(Date.parse(v));
14727 var values = v.split("^");
14728 for(var i = 0, len = values.length; i < len; i++){
14729 all.push(this.decodeValue(values[i]));
14734 var values = v.split("^");
14735 for(var i = 0, len = values.length; i < len; i++){
14736 var kv = values[i].split("=");
14737 all[kv[0]] = this.decodeValue(kv[1]);
14746 * Encodes a value including type information. Decode with {@link #decodeValue}.
14747 * @param {Mixed} value The value to encode
14748 * @return {String} The encoded value
14750 encodeValue : function(v){
14752 if(typeof v == "number"){
14754 }else if(typeof v == "boolean"){
14755 enc = "b:" + (v ? "1" : "0");
14756 }else if(v instanceof Date){
14757 enc = "d:" + v.toGMTString();
14758 }else if(v instanceof Array){
14760 for(var i = 0, len = v.length; i < len; i++){
14761 flat += this.encodeValue(v[i]);
14762 if(i != len-1) flat += "^";
14765 }else if(typeof v == "object"){
14768 if(typeof v[key] != "function"){
14769 flat += key + "=" + this.encodeValue(v[key]) + "^";
14772 enc = "o:" + flat.substring(0, flat.length-1);
14776 return escape(enc);
14782 * Ext JS Library 1.1.1
14783 * Copyright(c) 2006-2007, Ext JS, LLC.
14785 * Originally Released Under LGPL - original licence link has changed is not relivant.
14788 * <script type="text/javascript">
14791 * @class Roo.state.Manager
14792 * This is the global state manager. By default all components that are "state aware" check this class
14793 * for state information if you don't pass them a custom state provider. In order for this class
14794 * to be useful, it must be initialized with a provider when your application initializes.
14796 // in your initialization function
14798 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14800 // supposed you have a {@link Roo.BorderLayout}
14801 var layout = new Roo.BorderLayout(...);
14802 layout.restoreState();
14803 // or a {Roo.BasicDialog}
14804 var dialog = new Roo.BasicDialog(...);
14805 dialog.restoreState();
14809 Roo.state.Manager = function(){
14810 var provider = new Roo.state.Provider();
14814 * Configures the default state provider for your application
14815 * @param {Provider} stateProvider The state provider to set
14817 setProvider : function(stateProvider){
14818 provider = stateProvider;
14822 * Returns the current value for a key
14823 * @param {String} name The key name
14824 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14825 * @return {Mixed} The state data
14827 get : function(key, defaultValue){
14828 return provider.get(key, defaultValue);
14832 * Sets the value for a key
14833 * @param {String} name The key name
14834 * @param {Mixed} value The state data
14836 set : function(key, value){
14837 provider.set(key, value);
14841 * Clears a value from the state
14842 * @param {String} name The key name
14844 clear : function(key){
14845 provider.clear(key);
14849 * Gets the currently configured state provider
14850 * @return {Provider} The state provider
14852 getProvider : function(){
14859 * Ext JS Library 1.1.1
14860 * Copyright(c) 2006-2007, Ext JS, LLC.
14862 * Originally Released Under LGPL - original licence link has changed is not relivant.
14865 * <script type="text/javascript">
14868 * @class Roo.state.CookieProvider
14869 * @extends Roo.state.Provider
14870 * The default Provider implementation which saves state via cookies.
14873 var cp = new Roo.state.CookieProvider({
14875 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14876 domain: "roojs.com"
14878 Roo.state.Manager.setProvider(cp);
14880 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14881 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14882 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14883 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14884 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14885 * domain the page is running on including the 'www' like 'www.roojs.com')
14886 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14888 * Create a new CookieProvider
14889 * @param {Object} config The configuration object
14891 Roo.state.CookieProvider = function(config){
14892 Roo.state.CookieProvider.superclass.constructor.call(this);
14894 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14895 this.domain = null;
14896 this.secure = false;
14897 Roo.apply(this, config);
14898 this.state = this.readCookies();
14901 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14903 set : function(name, value){
14904 if(typeof value == "undefined" || value === null){
14908 this.setCookie(name, value);
14909 Roo.state.CookieProvider.superclass.set.call(this, name, value);
14913 clear : function(name){
14914 this.clearCookie(name);
14915 Roo.state.CookieProvider.superclass.clear.call(this, name);
14919 readCookies : function(){
14921 var c = document.cookie + ";";
14922 var re = /\s?(.*?)=(.*?);/g;
14924 while((matches = re.exec(c)) != null){
14925 var name = matches[1];
14926 var value = matches[2];
14927 if(name && name.substring(0,3) == "ys-"){
14928 cookies[name.substr(3)] = this.decodeValue(value);
14935 setCookie : function(name, value){
14936 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
14937 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
14938 ((this.path == null) ? "" : ("; path=" + this.path)) +
14939 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14940 ((this.secure == true) ? "; secure" : "");
14944 clearCookie : function(name){
14945 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
14946 ((this.path == null) ? "" : ("; path=" + this.path)) +
14947 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14948 ((this.secure == true) ? "; secure" : "");
14952 * Ext JS Library 1.1.1
14953 * Copyright(c) 2006-2007, Ext JS, LLC.
14955 * Originally Released Under LGPL - original licence link has changed is not relivant.
14958 * <script type="text/javascript">
14964 * These classes are derivatives of the similarly named classes in the YUI Library.
14965 * The original license:
14966 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
14967 * Code licensed under the BSD License:
14968 * http://developer.yahoo.net/yui/license.txt
14973 var Event=Roo.EventManager;
14974 var Dom=Roo.lib.Dom;
14977 * @class Roo.dd.DragDrop
14978 * @extends Roo.util.Observable
14979 * Defines the interface and base operation of items that that can be
14980 * dragged or can be drop targets. It was designed to be extended, overriding
14981 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
14982 * Up to three html elements can be associated with a DragDrop instance:
14984 * <li>linked element: the element that is passed into the constructor.
14985 * This is the element which defines the boundaries for interaction with
14986 * other DragDrop objects.</li>
14987 * <li>handle element(s): The drag operation only occurs if the element that
14988 * was clicked matches a handle element. By default this is the linked
14989 * element, but there are times that you will want only a portion of the
14990 * linked element to initiate the drag operation, and the setHandleElId()
14991 * method provides a way to define this.</li>
14992 * <li>drag element: this represents the element that would be moved along
14993 * with the cursor during a drag operation. By default, this is the linked
14994 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
14995 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
14998 * This class should not be instantiated until the onload event to ensure that
14999 * the associated elements are available.
15000 * The following would define a DragDrop obj that would interact with any
15001 * other DragDrop obj in the "group1" group:
15003 * dd = new Roo.dd.DragDrop("div1", "group1");
15005 * Since none of the event handlers have been implemented, nothing would
15006 * actually happen if you were to run the code above. Normally you would
15007 * override this class or one of the default implementations, but you can
15008 * also override the methods you want on an instance of the class...
15010 * dd.onDragDrop = function(e, id) {
15011 * alert("dd was dropped on " + id);
15015 * @param {String} id of the element that is linked to this instance
15016 * @param {String} sGroup the group of related DragDrop objects
15017 * @param {object} config an object containing configurable attributes
15018 * Valid properties for DragDrop:
15019 * padding, isTarget, maintainOffset, primaryButtonOnly
15021 Roo.dd.DragDrop = function(id, sGroup, config) {
15023 this.init(id, sGroup, config);
15028 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
15031 * The id of the element associated with this object. This is what we
15032 * refer to as the "linked element" because the size and position of
15033 * this element is used to determine when the drag and drop objects have
15041 * Configuration attributes passed into the constructor
15048 * The id of the element that will be dragged. By default this is same
15049 * as the linked element , but could be changed to another element. Ex:
15051 * @property dragElId
15058 * the id of the element that initiates the drag operation. By default
15059 * this is the linked element, but could be changed to be a child of this
15060 * element. This lets us do things like only starting the drag when the
15061 * header element within the linked html element is clicked.
15062 * @property handleElId
15069 * An associative array of HTML tags that will be ignored if clicked.
15070 * @property invalidHandleTypes
15071 * @type {string: string}
15073 invalidHandleTypes: null,
15076 * An associative array of ids for elements that will be ignored if clicked
15077 * @property invalidHandleIds
15078 * @type {string: string}
15080 invalidHandleIds: null,
15083 * An indexted array of css class names for elements that will be ignored
15085 * @property invalidHandleClasses
15088 invalidHandleClasses: null,
15091 * The linked element's absolute X position at the time the drag was
15093 * @property startPageX
15100 * The linked element's absolute X position at the time the drag was
15102 * @property startPageY
15109 * The group defines a logical collection of DragDrop objects that are
15110 * related. Instances only get events when interacting with other
15111 * DragDrop object in the same group. This lets us define multiple
15112 * groups using a single DragDrop subclass if we want.
15114 * @type {string: string}
15119 * Individual drag/drop instances can be locked. This will prevent
15120 * onmousedown start drag.
15128 * Lock this instance
15131 lock: function() { this.locked = true; },
15134 * Unlock this instace
15137 unlock: function() { this.locked = false; },
15140 * By default, all insances can be a drop target. This can be disabled by
15141 * setting isTarget to false.
15148 * The padding configured for this drag and drop object for calculating
15149 * the drop zone intersection with this object.
15156 * Cached reference to the linked element
15157 * @property _domRef
15163 * Internal typeof flag
15164 * @property __ygDragDrop
15167 __ygDragDrop: true,
15170 * Set to true when horizontal contraints are applied
15171 * @property constrainX
15178 * Set to true when vertical contraints are applied
15179 * @property constrainY
15186 * The left constraint
15194 * The right constraint
15202 * The up constraint
15211 * The down constraint
15219 * Maintain offsets when we resetconstraints. Set to true when you want
15220 * the position of the element relative to its parent to stay the same
15221 * when the page changes
15223 * @property maintainOffset
15226 maintainOffset: false,
15229 * Array of pixel locations the element will snap to if we specified a
15230 * horizontal graduation/interval. This array is generated automatically
15231 * when you define a tick interval.
15238 * Array of pixel locations the element will snap to if we specified a
15239 * vertical graduation/interval. This array is generated automatically
15240 * when you define a tick interval.
15247 * By default the drag and drop instance will only respond to the primary
15248 * button click (left button for a right-handed mouse). Set to true to
15249 * allow drag and drop to start with any mouse click that is propogated
15251 * @property primaryButtonOnly
15254 primaryButtonOnly: true,
15257 * The availabe property is false until the linked dom element is accessible.
15258 * @property available
15264 * By default, drags can only be initiated if the mousedown occurs in the
15265 * region the linked element is. This is done in part to work around a
15266 * bug in some browsers that mis-report the mousedown if the previous
15267 * mouseup happened outside of the window. This property is set to true
15268 * if outer handles are defined.
15270 * @property hasOuterHandles
15274 hasOuterHandles: false,
15277 * Code that executes immediately before the startDrag event
15278 * @method b4StartDrag
15281 b4StartDrag: function(x, y) { },
15284 * Abstract method called after a drag/drop object is clicked
15285 * and the drag or mousedown time thresholds have beeen met.
15286 * @method startDrag
15287 * @param {int} X click location
15288 * @param {int} Y click location
15290 startDrag: function(x, y) { /* override this */ },
15293 * Code that executes immediately before the onDrag event
15297 b4Drag: function(e) { },
15300 * Abstract method called during the onMouseMove event while dragging an
15303 * @param {Event} e the mousemove event
15305 onDrag: function(e) { /* override this */ },
15308 * Abstract method called when this element fist begins hovering over
15309 * another DragDrop obj
15310 * @method onDragEnter
15311 * @param {Event} e the mousemove event
15312 * @param {String|DragDrop[]} id In POINT mode, the element
15313 * id this is hovering over. In INTERSECT mode, an array of one or more
15314 * dragdrop items being hovered over.
15316 onDragEnter: function(e, id) { /* override this */ },
15319 * Code that executes immediately before the onDragOver event
15320 * @method b4DragOver
15323 b4DragOver: function(e) { },
15326 * Abstract method called when this element is hovering over another
15328 * @method onDragOver
15329 * @param {Event} e the mousemove event
15330 * @param {String|DragDrop[]} id In POINT mode, the element
15331 * id this is hovering over. In INTERSECT mode, an array of dd items
15332 * being hovered over.
15334 onDragOver: function(e, id) { /* override this */ },
15337 * Code that executes immediately before the onDragOut event
15338 * @method b4DragOut
15341 b4DragOut: function(e) { },
15344 * Abstract method called when we are no longer hovering over an element
15345 * @method onDragOut
15346 * @param {Event} e the mousemove event
15347 * @param {String|DragDrop[]} id In POINT mode, the element
15348 * id this was hovering over. In INTERSECT mode, an array of dd items
15349 * that the mouse is no longer over.
15351 onDragOut: function(e, id) { /* override this */ },
15354 * Code that executes immediately before the onDragDrop event
15355 * @method b4DragDrop
15358 b4DragDrop: function(e) { },
15361 * Abstract method called when this item is dropped on another DragDrop
15363 * @method onDragDrop
15364 * @param {Event} e the mouseup event
15365 * @param {String|DragDrop[]} id In POINT mode, the element
15366 * id this was dropped on. In INTERSECT mode, an array of dd items this
15369 onDragDrop: function(e, id) { /* override this */ },
15372 * Abstract method called when this item is dropped on an area with no
15374 * @method onInvalidDrop
15375 * @param {Event} e the mouseup event
15377 onInvalidDrop: function(e) { /* override this */ },
15380 * Code that executes immediately before the endDrag event
15381 * @method b4EndDrag
15384 b4EndDrag: function(e) { },
15387 * Fired when we are done dragging the object
15389 * @param {Event} e the mouseup event
15391 endDrag: function(e) { /* override this */ },
15394 * Code executed immediately before the onMouseDown event
15395 * @method b4MouseDown
15396 * @param {Event} e the mousedown event
15399 b4MouseDown: function(e) { },
15402 * Event handler that fires when a drag/drop obj gets a mousedown
15403 * @method onMouseDown
15404 * @param {Event} e the mousedown event
15406 onMouseDown: function(e) { /* override this */ },
15409 * Event handler that fires when a drag/drop obj gets a mouseup
15410 * @method onMouseUp
15411 * @param {Event} e the mouseup event
15413 onMouseUp: function(e) { /* override this */ },
15416 * Override the onAvailable method to do what is needed after the initial
15417 * position was determined.
15418 * @method onAvailable
15420 onAvailable: function () {
15424 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
15427 defaultPadding : {left:0, right:0, top:0, bottom:0},
15430 * Initializes the drag drop object's constraints to restrict movement to a certain element.
15434 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
15435 { dragElId: "existingProxyDiv" });
15436 dd.startDrag = function(){
15437 this.constrainTo("parent-id");
15440 * Or you can initalize it using the {@link Roo.Element} object:
15442 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
15443 startDrag : function(){
15444 this.constrainTo("parent-id");
15448 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
15449 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
15450 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
15451 * an object containing the sides to pad. For example: {right:10, bottom:10}
15452 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
15454 constrainTo : function(constrainTo, pad, inContent){
15455 if(typeof pad == "number"){
15456 pad = {left: pad, right:pad, top:pad, bottom:pad};
15458 pad = pad || this.defaultPadding;
15459 var b = Roo.get(this.getEl()).getBox();
15460 var ce = Roo.get(constrainTo);
15461 var s = ce.getScroll();
15462 var c, cd = ce.dom;
15463 if(cd == document.body){
15464 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
15467 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
15471 var topSpace = b.y - c.y;
15472 var leftSpace = b.x - c.x;
15474 this.resetConstraints();
15475 this.setXConstraint(leftSpace - (pad.left||0), // left
15476 c.width - leftSpace - b.width - (pad.right||0) //right
15478 this.setYConstraint(topSpace - (pad.top||0), //top
15479 c.height - topSpace - b.height - (pad.bottom||0) //bottom
15484 * Returns a reference to the linked element
15486 * @return {HTMLElement} the html element
15488 getEl: function() {
15489 if (!this._domRef) {
15490 this._domRef = Roo.getDom(this.id);
15493 return this._domRef;
15497 * Returns a reference to the actual element to drag. By default this is
15498 * the same as the html element, but it can be assigned to another
15499 * element. An example of this can be found in Roo.dd.DDProxy
15500 * @method getDragEl
15501 * @return {HTMLElement} the html element
15503 getDragEl: function() {
15504 return Roo.getDom(this.dragElId);
15508 * Sets up the DragDrop object. Must be called in the constructor of any
15509 * Roo.dd.DragDrop subclass
15511 * @param id the id of the linked element
15512 * @param {String} sGroup the group of related items
15513 * @param {object} config configuration attributes
15515 init: function(id, sGroup, config) {
15516 this.initTarget(id, sGroup, config);
15517 Event.on(this.id, "mousedown", this.handleMouseDown, this);
15518 // Event.on(this.id, "selectstart", Event.preventDefault);
15522 * Initializes Targeting functionality only... the object does not
15523 * get a mousedown handler.
15524 * @method initTarget
15525 * @param id the id of the linked element
15526 * @param {String} sGroup the group of related items
15527 * @param {object} config configuration attributes
15529 initTarget: function(id, sGroup, config) {
15531 // configuration attributes
15532 this.config = config || {};
15534 // create a local reference to the drag and drop manager
15535 this.DDM = Roo.dd.DDM;
15536 // initialize the groups array
15539 // assume that we have an element reference instead of an id if the
15540 // parameter is not a string
15541 if (typeof id !== "string") {
15548 // add to an interaction group
15549 this.addToGroup((sGroup) ? sGroup : "default");
15551 // We don't want to register this as the handle with the manager
15552 // so we just set the id rather than calling the setter.
15553 this.handleElId = id;
15555 // the linked element is the element that gets dragged by default
15556 this.setDragElId(id);
15558 // by default, clicked anchors will not start drag operations.
15559 this.invalidHandleTypes = { A: "A" };
15560 this.invalidHandleIds = {};
15561 this.invalidHandleClasses = [];
15563 this.applyConfig();
15565 this.handleOnAvailable();
15569 * Applies the configuration parameters that were passed into the constructor.
15570 * This is supposed to happen at each level through the inheritance chain. So
15571 * a DDProxy implentation will execute apply config on DDProxy, DD, and
15572 * DragDrop in order to get all of the parameters that are available in
15574 * @method applyConfig
15576 applyConfig: function() {
15578 // configurable properties:
15579 // padding, isTarget, maintainOffset, primaryButtonOnly
15580 this.padding = this.config.padding || [0, 0, 0, 0];
15581 this.isTarget = (this.config.isTarget !== false);
15582 this.maintainOffset = (this.config.maintainOffset);
15583 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
15588 * Executed when the linked element is available
15589 * @method handleOnAvailable
15592 handleOnAvailable: function() {
15593 this.available = true;
15594 this.resetConstraints();
15595 this.onAvailable();
15599 * Configures the padding for the target zone in px. Effectively expands
15600 * (or reduces) the virtual object size for targeting calculations.
15601 * Supports css-style shorthand; if only one parameter is passed, all sides
15602 * will have that padding, and if only two are passed, the top and bottom
15603 * will have the first param, the left and right the second.
15604 * @method setPadding
15605 * @param {int} iTop Top pad
15606 * @param {int} iRight Right pad
15607 * @param {int} iBot Bot pad
15608 * @param {int} iLeft Left pad
15610 setPadding: function(iTop, iRight, iBot, iLeft) {
15611 // this.padding = [iLeft, iRight, iTop, iBot];
15612 if (!iRight && 0 !== iRight) {
15613 this.padding = [iTop, iTop, iTop, iTop];
15614 } else if (!iBot && 0 !== iBot) {
15615 this.padding = [iTop, iRight, iTop, iRight];
15617 this.padding = [iTop, iRight, iBot, iLeft];
15622 * Stores the initial placement of the linked element.
15623 * @method setInitialPosition
15624 * @param {int} diffX the X offset, default 0
15625 * @param {int} diffY the Y offset, default 0
15627 setInitPosition: function(diffX, diffY) {
15628 var el = this.getEl();
15630 if (!this.DDM.verifyEl(el)) {
15634 var dx = diffX || 0;
15635 var dy = diffY || 0;
15637 var p = Dom.getXY( el );
15639 this.initPageX = p[0] - dx;
15640 this.initPageY = p[1] - dy;
15642 this.lastPageX = p[0];
15643 this.lastPageY = p[1];
15646 this.setStartPosition(p);
15650 * Sets the start position of the element. This is set when the obj
15651 * is initialized, the reset when a drag is started.
15652 * @method setStartPosition
15653 * @param pos current position (from previous lookup)
15656 setStartPosition: function(pos) {
15657 var p = pos || Dom.getXY( this.getEl() );
15658 this.deltaSetXY = null;
15660 this.startPageX = p[0];
15661 this.startPageY = p[1];
15665 * Add this instance to a group of related drag/drop objects. All
15666 * instances belong to at least one group, and can belong to as many
15667 * groups as needed.
15668 * @method addToGroup
15669 * @param sGroup {string} the name of the group
15671 addToGroup: function(sGroup) {
15672 this.groups[sGroup] = true;
15673 this.DDM.regDragDrop(this, sGroup);
15677 * Remove's this instance from the supplied interaction group
15678 * @method removeFromGroup
15679 * @param {string} sGroup The group to drop
15681 removeFromGroup: function(sGroup) {
15682 if (this.groups[sGroup]) {
15683 delete this.groups[sGroup];
15686 this.DDM.removeDDFromGroup(this, sGroup);
15690 * Allows you to specify that an element other than the linked element
15691 * will be moved with the cursor during a drag
15692 * @method setDragElId
15693 * @param id {string} the id of the element that will be used to initiate the drag
15695 setDragElId: function(id) {
15696 this.dragElId = id;
15700 * Allows you to specify a child of the linked element that should be
15701 * used to initiate the drag operation. An example of this would be if
15702 * you have a content div with text and links. Clicking anywhere in the
15703 * content area would normally start the drag operation. Use this method
15704 * to specify that an element inside of the content div is the element
15705 * that starts the drag operation.
15706 * @method setHandleElId
15707 * @param id {string} the id of the element that will be used to
15708 * initiate the drag.
15710 setHandleElId: function(id) {
15711 if (typeof id !== "string") {
15714 this.handleElId = id;
15715 this.DDM.regHandle(this.id, id);
15719 * Allows you to set an element outside of the linked element as a drag
15721 * @method setOuterHandleElId
15722 * @param id the id of the element that will be used to initiate the drag
15724 setOuterHandleElId: function(id) {
15725 if (typeof id !== "string") {
15728 Event.on(id, "mousedown",
15729 this.handleMouseDown, this);
15730 this.setHandleElId(id);
15732 this.hasOuterHandles = true;
15736 * Remove all drag and drop hooks for this element
15739 unreg: function() {
15740 Event.un(this.id, "mousedown",
15741 this.handleMouseDown);
15742 this._domRef = null;
15743 this.DDM._remove(this);
15746 destroy : function(){
15751 * Returns true if this instance is locked, or the drag drop mgr is locked
15752 * (meaning that all drag/drop is disabled on the page.)
15754 * @return {boolean} true if this obj or all drag/drop is locked, else
15757 isLocked: function() {
15758 return (this.DDM.isLocked() || this.locked);
15762 * Fired when this object is clicked
15763 * @method handleMouseDown
15765 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
15768 handleMouseDown: function(e, oDD){
15769 if (this.primaryButtonOnly && e.button != 0) {
15773 if (this.isLocked()) {
15777 this.DDM.refreshCache(this.groups);
15779 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
15780 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
15782 if (this.clickValidator(e)) {
15784 // set the initial element position
15785 this.setStartPosition();
15788 this.b4MouseDown(e);
15789 this.onMouseDown(e);
15791 this.DDM.handleMouseDown(e, this);
15793 this.DDM.stopEvent(e);
15801 clickValidator: function(e) {
15802 var target = e.getTarget();
15803 return ( this.isValidHandleChild(target) &&
15804 (this.id == this.handleElId ||
15805 this.DDM.handleWasClicked(target, this.id)) );
15809 * Allows you to specify a tag name that should not start a drag operation
15810 * when clicked. This is designed to facilitate embedding links within a
15811 * drag handle that do something other than start the drag.
15812 * @method addInvalidHandleType
15813 * @param {string} tagName the type of element to exclude
15815 addInvalidHandleType: function(tagName) {
15816 var type = tagName.toUpperCase();
15817 this.invalidHandleTypes[type] = type;
15821 * Lets you to specify an element id for a child of a drag handle
15822 * that should not initiate a drag
15823 * @method addInvalidHandleId
15824 * @param {string} id the element id of the element you wish to ignore
15826 addInvalidHandleId: function(id) {
15827 if (typeof id !== "string") {
15830 this.invalidHandleIds[id] = id;
15834 * Lets you specify a css class of elements that will not initiate a drag
15835 * @method addInvalidHandleClass
15836 * @param {string} cssClass the class of the elements you wish to ignore
15838 addInvalidHandleClass: function(cssClass) {
15839 this.invalidHandleClasses.push(cssClass);
15843 * Unsets an excluded tag name set by addInvalidHandleType
15844 * @method removeInvalidHandleType
15845 * @param {string} tagName the type of element to unexclude
15847 removeInvalidHandleType: function(tagName) {
15848 var type = tagName.toUpperCase();
15849 // this.invalidHandleTypes[type] = null;
15850 delete this.invalidHandleTypes[type];
15854 * Unsets an invalid handle id
15855 * @method removeInvalidHandleId
15856 * @param {string} id the id of the element to re-enable
15858 removeInvalidHandleId: function(id) {
15859 if (typeof id !== "string") {
15862 delete this.invalidHandleIds[id];
15866 * Unsets an invalid css class
15867 * @method removeInvalidHandleClass
15868 * @param {string} cssClass the class of the element(s) you wish to
15871 removeInvalidHandleClass: function(cssClass) {
15872 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
15873 if (this.invalidHandleClasses[i] == cssClass) {
15874 delete this.invalidHandleClasses[i];
15880 * Checks the tag exclusion list to see if this click should be ignored
15881 * @method isValidHandleChild
15882 * @param {HTMLElement} node the HTMLElement to evaluate
15883 * @return {boolean} true if this is a valid tag type, false if not
15885 isValidHandleChild: function(node) {
15888 // var n = (node.nodeName == "#text") ? node.parentNode : node;
15891 nodeName = node.nodeName.toUpperCase();
15893 nodeName = node.nodeName;
15895 valid = valid && !this.invalidHandleTypes[nodeName];
15896 valid = valid && !this.invalidHandleIds[node.id];
15898 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
15899 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
15908 * Create the array of horizontal tick marks if an interval was specified
15909 * in setXConstraint().
15910 * @method setXTicks
15913 setXTicks: function(iStartX, iTickSize) {
15915 this.xTickSize = iTickSize;
15919 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
15921 this.xTicks[this.xTicks.length] = i;
15926 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
15928 this.xTicks[this.xTicks.length] = i;
15933 this.xTicks.sort(this.DDM.numericSort) ;
15937 * Create the array of vertical tick marks if an interval was specified in
15938 * setYConstraint().
15939 * @method setYTicks
15942 setYTicks: function(iStartY, iTickSize) {
15944 this.yTickSize = iTickSize;
15948 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
15950 this.yTicks[this.yTicks.length] = i;
15955 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
15957 this.yTicks[this.yTicks.length] = i;
15962 this.yTicks.sort(this.DDM.numericSort) ;
15966 * By default, the element can be dragged any place on the screen. Use
15967 * this method to limit the horizontal travel of the element. Pass in
15968 * 0,0 for the parameters if you want to lock the drag to the y axis.
15969 * @method setXConstraint
15970 * @param {int} iLeft the number of pixels the element can move to the left
15971 * @param {int} iRight the number of pixels the element can move to the
15973 * @param {int} iTickSize optional parameter for specifying that the
15975 * should move iTickSize pixels at a time.
15977 setXConstraint: function(iLeft, iRight, iTickSize) {
15978 this.leftConstraint = iLeft;
15979 this.rightConstraint = iRight;
15981 this.minX = this.initPageX - iLeft;
15982 this.maxX = this.initPageX + iRight;
15983 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
15985 this.constrainX = true;
15989 * Clears any constraints applied to this instance. Also clears ticks
15990 * since they can't exist independent of a constraint at this time.
15991 * @method clearConstraints
15993 clearConstraints: function() {
15994 this.constrainX = false;
15995 this.constrainY = false;
16000 * Clears any tick interval defined for this instance
16001 * @method clearTicks
16003 clearTicks: function() {
16004 this.xTicks = null;
16005 this.yTicks = null;
16006 this.xTickSize = 0;
16007 this.yTickSize = 0;
16011 * By default, the element can be dragged any place on the screen. Set
16012 * this to limit the vertical travel of the element. Pass in 0,0 for the
16013 * parameters if you want to lock the drag to the x axis.
16014 * @method setYConstraint
16015 * @param {int} iUp the number of pixels the element can move up
16016 * @param {int} iDown the number of pixels the element can move down
16017 * @param {int} iTickSize optional parameter for specifying that the
16018 * element should move iTickSize pixels at a time.
16020 setYConstraint: function(iUp, iDown, iTickSize) {
16021 this.topConstraint = iUp;
16022 this.bottomConstraint = iDown;
16024 this.minY = this.initPageY - iUp;
16025 this.maxY = this.initPageY + iDown;
16026 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
16028 this.constrainY = true;
16033 * resetConstraints must be called if you manually reposition a dd element.
16034 * @method resetConstraints
16035 * @param {boolean} maintainOffset
16037 resetConstraints: function() {
16040 // Maintain offsets if necessary
16041 if (this.initPageX || this.initPageX === 0) {
16042 // figure out how much this thing has moved
16043 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
16044 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
16046 this.setInitPosition(dx, dy);
16048 // This is the first time we have detected the element's position
16050 this.setInitPosition();
16053 if (this.constrainX) {
16054 this.setXConstraint( this.leftConstraint,
16055 this.rightConstraint,
16059 if (this.constrainY) {
16060 this.setYConstraint( this.topConstraint,
16061 this.bottomConstraint,
16067 * Normally the drag element is moved pixel by pixel, but we can specify
16068 * that it move a number of pixels at a time. This method resolves the
16069 * location when we have it set up like this.
16071 * @param {int} val where we want to place the object
16072 * @param {int[]} tickArray sorted array of valid points
16073 * @return {int} the closest tick
16076 getTick: function(val, tickArray) {
16079 // If tick interval is not defined, it is effectively 1 pixel,
16080 // so we return the value passed to us.
16082 } else if (tickArray[0] >= val) {
16083 // The value is lower than the first tick, so we return the first
16085 return tickArray[0];
16087 for (var i=0, len=tickArray.length; i<len; ++i) {
16089 if (tickArray[next] && tickArray[next] >= val) {
16090 var diff1 = val - tickArray[i];
16091 var diff2 = tickArray[next] - val;
16092 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
16096 // The value is larger than the last tick, so we return the last
16098 return tickArray[tickArray.length - 1];
16105 * @return {string} string representation of the dd obj
16107 toString: function() {
16108 return ("DragDrop " + this.id);
16116 * Ext JS Library 1.1.1
16117 * Copyright(c) 2006-2007, Ext JS, LLC.
16119 * Originally Released Under LGPL - original licence link has changed is not relivant.
16122 * <script type="text/javascript">
16127 * The drag and drop utility provides a framework for building drag and drop
16128 * applications. In addition to enabling drag and drop for specific elements,
16129 * the drag and drop elements are tracked by the manager class, and the
16130 * interactions between the various elements are tracked during the drag and
16131 * the implementing code is notified about these important moments.
16134 // Only load the library once. Rewriting the manager class would orphan
16135 // existing drag and drop instances.
16136 if (!Roo.dd.DragDropMgr) {
16139 * @class Roo.dd.DragDropMgr
16140 * DragDropMgr is a singleton that tracks the element interaction for
16141 * all DragDrop items in the window. Generally, you will not call
16142 * this class directly, but it does have helper methods that could
16143 * be useful in your DragDrop implementations.
16146 Roo.dd.DragDropMgr = function() {
16148 var Event = Roo.EventManager;
16153 * Two dimensional Array of registered DragDrop objects. The first
16154 * dimension is the DragDrop item group, the second the DragDrop
16157 * @type {string: string}
16164 * Array of element ids defined as drag handles. Used to determine
16165 * if the element that generated the mousedown event is actually the
16166 * handle and not the html element itself.
16167 * @property handleIds
16168 * @type {string: string}
16175 * the DragDrop object that is currently being dragged
16176 * @property dragCurrent
16184 * the DragDrop object(s) that are being hovered over
16185 * @property dragOvers
16193 * the X distance between the cursor and the object being dragged
16202 * the Y distance between the cursor and the object being dragged
16211 * Flag to determine if we should prevent the default behavior of the
16212 * events we define. By default this is true, but this can be set to
16213 * false if you need the default behavior (not recommended)
16214 * @property preventDefault
16218 preventDefault: true,
16221 * Flag to determine if we should stop the propagation of the events
16222 * we generate. This is true by default but you may want to set it to
16223 * false if the html element contains other features that require the
16225 * @property stopPropagation
16229 stopPropagation: true,
16232 * Internal flag that is set to true when drag and drop has been
16234 * @property initialized
16241 * All drag and drop can be disabled.
16249 * Called the first time an element is registered.
16255 this.initialized = true;
16259 * In point mode, drag and drop interaction is defined by the
16260 * location of the cursor during the drag/drop
16268 * In intersect mode, drag and drop interactio nis defined by the
16269 * overlap of two or more drag and drop objects.
16270 * @property INTERSECT
16277 * The current drag and drop mode. Default: POINT
16285 * Runs method on all drag and drop objects
16286 * @method _execOnAll
16290 _execOnAll: function(sMethod, args) {
16291 for (var i in this.ids) {
16292 for (var j in this.ids[i]) {
16293 var oDD = this.ids[i][j];
16294 if (! this.isTypeOfDD(oDD)) {
16297 oDD[sMethod].apply(oDD, args);
16303 * Drag and drop initialization. Sets up the global event handlers
16308 _onLoad: function() {
16313 Event.on(document, "mouseup", this.handleMouseUp, this, true);
16314 Event.on(document, "mousemove", this.handleMouseMove, this, true);
16315 Event.on(window, "unload", this._onUnload, this, true);
16316 Event.on(window, "resize", this._onResize, this, true);
16317 // Event.on(window, "mouseout", this._test);
16322 * Reset constraints on all drag and drop objs
16323 * @method _onResize
16327 _onResize: function(e) {
16328 this._execOnAll("resetConstraints", []);
16332 * Lock all drag and drop functionality
16336 lock: function() { this.locked = true; },
16339 * Unlock all drag and drop functionality
16343 unlock: function() { this.locked = false; },
16346 * Is drag and drop locked?
16348 * @return {boolean} True if drag and drop is locked, false otherwise.
16351 isLocked: function() { return this.locked; },
16354 * Location cache that is set for all drag drop objects when a drag is
16355 * initiated, cleared when the drag is finished.
16356 * @property locationCache
16363 * Set useCache to false if you want to force object the lookup of each
16364 * drag and drop linked element constantly during a drag.
16365 * @property useCache
16372 * The number of pixels that the mouse needs to move after the
16373 * mousedown before the drag is initiated. Default=3;
16374 * @property clickPixelThresh
16378 clickPixelThresh: 3,
16381 * The number of milliseconds after the mousedown event to initiate the
16382 * drag if we don't get a mouseup event. Default=1000
16383 * @property clickTimeThresh
16387 clickTimeThresh: 350,
16390 * Flag that indicates that either the drag pixel threshold or the
16391 * mousdown time threshold has been met
16392 * @property dragThreshMet
16397 dragThreshMet: false,
16400 * Timeout used for the click time threshold
16401 * @property clickTimeout
16406 clickTimeout: null,
16409 * The X position of the mousedown event stored for later use when a
16410 * drag threshold is met.
16419 * The Y position of the mousedown event stored for later use when a
16420 * drag threshold is met.
16429 * Each DragDrop instance must be registered with the DragDropMgr.
16430 * This is executed in DragDrop.init()
16431 * @method regDragDrop
16432 * @param {DragDrop} oDD the DragDrop object to register
16433 * @param {String} sGroup the name of the group this element belongs to
16436 regDragDrop: function(oDD, sGroup) {
16437 if (!this.initialized) { this.init(); }
16439 if (!this.ids[sGroup]) {
16440 this.ids[sGroup] = {};
16442 this.ids[sGroup][oDD.id] = oDD;
16446 * Removes the supplied dd instance from the supplied group. Executed
16447 * by DragDrop.removeFromGroup, so don't call this function directly.
16448 * @method removeDDFromGroup
16452 removeDDFromGroup: function(oDD, sGroup) {
16453 if (!this.ids[sGroup]) {
16454 this.ids[sGroup] = {};
16457 var obj = this.ids[sGroup];
16458 if (obj && obj[oDD.id]) {
16459 delete obj[oDD.id];
16464 * Unregisters a drag and drop item. This is executed in
16465 * DragDrop.unreg, use that method instead of calling this directly.
16470 _remove: function(oDD) {
16471 for (var g in oDD.groups) {
16472 if (g && this.ids[g][oDD.id]) {
16473 delete this.ids[g][oDD.id];
16476 delete this.handleIds[oDD.id];
16480 * Each DragDrop handle element must be registered. This is done
16481 * automatically when executing DragDrop.setHandleElId()
16482 * @method regHandle
16483 * @param {String} sDDId the DragDrop id this element is a handle for
16484 * @param {String} sHandleId the id of the element that is the drag
16488 regHandle: function(sDDId, sHandleId) {
16489 if (!this.handleIds[sDDId]) {
16490 this.handleIds[sDDId] = {};
16492 this.handleIds[sDDId][sHandleId] = sHandleId;
16496 * Utility function to determine if a given element has been
16497 * registered as a drag drop item.
16498 * @method isDragDrop
16499 * @param {String} id the element id to check
16500 * @return {boolean} true if this element is a DragDrop item,
16504 isDragDrop: function(id) {
16505 return ( this.getDDById(id) ) ? true : false;
16509 * Returns the drag and drop instances that are in all groups the
16510 * passed in instance belongs to.
16511 * @method getRelated
16512 * @param {DragDrop} p_oDD the obj to get related data for
16513 * @param {boolean} bTargetsOnly if true, only return targetable objs
16514 * @return {DragDrop[]} the related instances
16517 getRelated: function(p_oDD, bTargetsOnly) {
16519 for (var i in p_oDD.groups) {
16520 for (j in this.ids[i]) {
16521 var dd = this.ids[i][j];
16522 if (! this.isTypeOfDD(dd)) {
16525 if (!bTargetsOnly || dd.isTarget) {
16526 oDDs[oDDs.length] = dd;
16535 * Returns true if the specified dd target is a legal target for
16536 * the specifice drag obj
16537 * @method isLegalTarget
16538 * @param {DragDrop} the drag obj
16539 * @param {DragDrop} the target
16540 * @return {boolean} true if the target is a legal target for the
16544 isLegalTarget: function (oDD, oTargetDD) {
16545 var targets = this.getRelated(oDD, true);
16546 for (var i=0, len=targets.length;i<len;++i) {
16547 if (targets[i].id == oTargetDD.id) {
16556 * My goal is to be able to transparently determine if an object is
16557 * typeof DragDrop, and the exact subclass of DragDrop. typeof
16558 * returns "object", oDD.constructor.toString() always returns
16559 * "DragDrop" and not the name of the subclass. So for now it just
16560 * evaluates a well-known variable in DragDrop.
16561 * @method isTypeOfDD
16562 * @param {Object} the object to evaluate
16563 * @return {boolean} true if typeof oDD = DragDrop
16566 isTypeOfDD: function (oDD) {
16567 return (oDD && oDD.__ygDragDrop);
16571 * Utility function to determine if a given element has been
16572 * registered as a drag drop handle for the given Drag Drop object.
16574 * @param {String} id the element id to check
16575 * @return {boolean} true if this element is a DragDrop handle, false
16579 isHandle: function(sDDId, sHandleId) {
16580 return ( this.handleIds[sDDId] &&
16581 this.handleIds[sDDId][sHandleId] );
16585 * Returns the DragDrop instance for a given id
16586 * @method getDDById
16587 * @param {String} id the id of the DragDrop object
16588 * @return {DragDrop} the drag drop object, null if it is not found
16591 getDDById: function(id) {
16592 for (var i in this.ids) {
16593 if (this.ids[i][id]) {
16594 return this.ids[i][id];
16601 * Fired after a registered DragDrop object gets the mousedown event.
16602 * Sets up the events required to track the object being dragged
16603 * @method handleMouseDown
16604 * @param {Event} e the event
16605 * @param oDD the DragDrop object being dragged
16609 handleMouseDown: function(e, oDD) {
16611 Roo.QuickTips.disable();
16613 this.currentTarget = e.getTarget();
16615 this.dragCurrent = oDD;
16617 var el = oDD.getEl();
16619 // track start position
16620 this.startX = e.getPageX();
16621 this.startY = e.getPageY();
16623 this.deltaX = this.startX - el.offsetLeft;
16624 this.deltaY = this.startY - el.offsetTop;
16626 this.dragThreshMet = false;
16628 this.clickTimeout = setTimeout(
16630 var DDM = Roo.dd.DDM;
16631 DDM.startDrag(DDM.startX, DDM.startY);
16633 this.clickTimeThresh );
16637 * Fired when either the drag pixel threshol or the mousedown hold
16638 * time threshold has been met.
16639 * @method startDrag
16640 * @param x {int} the X position of the original mousedown
16641 * @param y {int} the Y position of the original mousedown
16644 startDrag: function(x, y) {
16645 clearTimeout(this.clickTimeout);
16646 if (this.dragCurrent) {
16647 this.dragCurrent.b4StartDrag(x, y);
16648 this.dragCurrent.startDrag(x, y);
16650 this.dragThreshMet = true;
16654 * Internal function to handle the mouseup event. Will be invoked
16655 * from the context of the document.
16656 * @method handleMouseUp
16657 * @param {Event} e the event
16661 handleMouseUp: function(e) {
16664 Roo.QuickTips.enable();
16666 if (! this.dragCurrent) {
16670 clearTimeout(this.clickTimeout);
16672 if (this.dragThreshMet) {
16673 this.fireEvents(e, true);
16683 * Utility to stop event propagation and event default, if these
16684 * features are turned on.
16685 * @method stopEvent
16686 * @param {Event} e the event as returned by this.getEvent()
16689 stopEvent: function(e){
16690 if(this.stopPropagation) {
16691 e.stopPropagation();
16694 if (this.preventDefault) {
16695 e.preventDefault();
16700 * Internal function to clean up event handlers after the drag
16701 * operation is complete
16703 * @param {Event} e the event
16707 stopDrag: function(e) {
16708 // Fire the drag end event for the item that was dragged
16709 if (this.dragCurrent) {
16710 if (this.dragThreshMet) {
16711 this.dragCurrent.b4EndDrag(e);
16712 this.dragCurrent.endDrag(e);
16715 this.dragCurrent.onMouseUp(e);
16718 this.dragCurrent = null;
16719 this.dragOvers = {};
16723 * Internal function to handle the mousemove event. Will be invoked
16724 * from the context of the html element.
16726 * @TODO figure out what we can do about mouse events lost when the
16727 * user drags objects beyond the window boundary. Currently we can
16728 * detect this in internet explorer by verifying that the mouse is
16729 * down during the mousemove event. Firefox doesn't give us the
16730 * button state on the mousemove event.
16731 * @method handleMouseMove
16732 * @param {Event} e the event
16736 handleMouseMove: function(e) {
16737 if (! this.dragCurrent) {
16741 // var button = e.which || e.button;
16743 // check for IE mouseup outside of page boundary
16744 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
16746 return this.handleMouseUp(e);
16749 if (!this.dragThreshMet) {
16750 var diffX = Math.abs(this.startX - e.getPageX());
16751 var diffY = Math.abs(this.startY - e.getPageY());
16752 if (diffX > this.clickPixelThresh ||
16753 diffY > this.clickPixelThresh) {
16754 this.startDrag(this.startX, this.startY);
16758 if (this.dragThreshMet) {
16759 this.dragCurrent.b4Drag(e);
16760 this.dragCurrent.onDrag(e);
16761 if(!this.dragCurrent.moveOnly){
16762 this.fireEvents(e, false);
16772 * Iterates over all of the DragDrop elements to find ones we are
16773 * hovering over or dropping on
16774 * @method fireEvents
16775 * @param {Event} e the event
16776 * @param {boolean} isDrop is this a drop op or a mouseover op?
16780 fireEvents: function(e, isDrop) {
16781 var dc = this.dragCurrent;
16783 // If the user did the mouse up outside of the window, we could
16784 // get here even though we have ended the drag.
16785 if (!dc || dc.isLocked()) {
16789 var pt = e.getPoint();
16791 // cache the previous dragOver array
16797 var enterEvts = [];
16799 // Check to see if the object(s) we were hovering over is no longer
16800 // being hovered over so we can fire the onDragOut event
16801 for (var i in this.dragOvers) {
16803 var ddo = this.dragOvers[i];
16805 if (! this.isTypeOfDD(ddo)) {
16809 if (! this.isOverTarget(pt, ddo, this.mode)) {
16810 outEvts.push( ddo );
16813 oldOvers[i] = true;
16814 delete this.dragOvers[i];
16817 for (var sGroup in dc.groups) {
16819 if ("string" != typeof sGroup) {
16823 for (i in this.ids[sGroup]) {
16824 var oDD = this.ids[sGroup][i];
16825 if (! this.isTypeOfDD(oDD)) {
16829 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
16830 if (this.isOverTarget(pt, oDD, this.mode)) {
16831 // look for drop interactions
16833 dropEvts.push( oDD );
16834 // look for drag enter and drag over interactions
16837 // initial drag over: dragEnter fires
16838 if (!oldOvers[oDD.id]) {
16839 enterEvts.push( oDD );
16840 // subsequent drag overs: dragOver fires
16842 overEvts.push( oDD );
16845 this.dragOvers[oDD.id] = oDD;
16853 if (outEvts.length) {
16854 dc.b4DragOut(e, outEvts);
16855 dc.onDragOut(e, outEvts);
16858 if (enterEvts.length) {
16859 dc.onDragEnter(e, enterEvts);
16862 if (overEvts.length) {
16863 dc.b4DragOver(e, overEvts);
16864 dc.onDragOver(e, overEvts);
16867 if (dropEvts.length) {
16868 dc.b4DragDrop(e, dropEvts);
16869 dc.onDragDrop(e, dropEvts);
16873 // fire dragout events
16875 for (i=0, len=outEvts.length; i<len; ++i) {
16876 dc.b4DragOut(e, outEvts[i].id);
16877 dc.onDragOut(e, outEvts[i].id);
16880 // fire enter events
16881 for (i=0,len=enterEvts.length; i<len; ++i) {
16882 // dc.b4DragEnter(e, oDD.id);
16883 dc.onDragEnter(e, enterEvts[i].id);
16886 // fire over events
16887 for (i=0,len=overEvts.length; i<len; ++i) {
16888 dc.b4DragOver(e, overEvts[i].id);
16889 dc.onDragOver(e, overEvts[i].id);
16892 // fire drop events
16893 for (i=0, len=dropEvts.length; i<len; ++i) {
16894 dc.b4DragDrop(e, dropEvts[i].id);
16895 dc.onDragDrop(e, dropEvts[i].id);
16900 // notify about a drop that did not find a target
16901 if (isDrop && !dropEvts.length) {
16902 dc.onInvalidDrop(e);
16908 * Helper function for getting the best match from the list of drag
16909 * and drop objects returned by the drag and drop events when we are
16910 * in INTERSECT mode. It returns either the first object that the
16911 * cursor is over, or the object that has the greatest overlap with
16912 * the dragged element.
16913 * @method getBestMatch
16914 * @param {DragDrop[]} dds The array of drag and drop objects
16916 * @return {DragDrop} The best single match
16919 getBestMatch: function(dds) {
16921 // Return null if the input is not what we expect
16922 //if (!dds || !dds.length || dds.length == 0) {
16924 // If there is only one item, it wins
16925 //} else if (dds.length == 1) {
16927 var len = dds.length;
16932 // Loop through the targeted items
16933 for (var i=0; i<len; ++i) {
16935 // If the cursor is over the object, it wins. If the
16936 // cursor is over multiple matches, the first one we come
16938 if (dd.cursorIsOver) {
16941 // Otherwise the object with the most overlap wins
16944 winner.overlap.getArea() < dd.overlap.getArea()) {
16955 * Refreshes the cache of the top-left and bottom-right points of the
16956 * drag and drop objects in the specified group(s). This is in the
16957 * format that is stored in the drag and drop instance, so typical
16960 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
16964 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
16966 * @TODO this really should be an indexed array. Alternatively this
16967 * method could accept both.
16968 * @method refreshCache
16969 * @param {Object} groups an associative array of groups to refresh
16972 refreshCache: function(groups) {
16973 for (var sGroup in groups) {
16974 if ("string" != typeof sGroup) {
16977 for (var i in this.ids[sGroup]) {
16978 var oDD = this.ids[sGroup][i];
16980 if (this.isTypeOfDD(oDD)) {
16981 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
16982 var loc = this.getLocation(oDD);
16984 this.locationCache[oDD.id] = loc;
16986 delete this.locationCache[oDD.id];
16987 // this will unregister the drag and drop object if
16988 // the element is not in a usable state
16997 * This checks to make sure an element exists and is in the DOM. The
16998 * main purpose is to handle cases where innerHTML is used to remove
16999 * drag and drop objects from the DOM. IE provides an 'unspecified
17000 * error' when trying to access the offsetParent of such an element
17002 * @param {HTMLElement} el the element to check
17003 * @return {boolean} true if the element looks usable
17006 verifyEl: function(el) {
17011 parent = el.offsetParent;
17014 parent = el.offsetParent;
17025 * Returns a Region object containing the drag and drop element's position
17026 * and size, including the padding configured for it
17027 * @method getLocation
17028 * @param {DragDrop} oDD the drag and drop object to get the
17030 * @return {Roo.lib.Region} a Region object representing the total area
17031 * the element occupies, including any padding
17032 * the instance is configured for.
17035 getLocation: function(oDD) {
17036 if (! this.isTypeOfDD(oDD)) {
17040 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
17043 pos= Roo.lib.Dom.getXY(el);
17051 x2 = x1 + el.offsetWidth;
17053 y2 = y1 + el.offsetHeight;
17055 t = y1 - oDD.padding[0];
17056 r = x2 + oDD.padding[1];
17057 b = y2 + oDD.padding[2];
17058 l = x1 - oDD.padding[3];
17060 return new Roo.lib.Region( t, r, b, l );
17064 * Checks the cursor location to see if it over the target
17065 * @method isOverTarget
17066 * @param {Roo.lib.Point} pt The point to evaluate
17067 * @param {DragDrop} oTarget the DragDrop object we are inspecting
17068 * @return {boolean} true if the mouse is over the target
17072 isOverTarget: function(pt, oTarget, intersect) {
17073 // use cache if available
17074 var loc = this.locationCache[oTarget.id];
17075 if (!loc || !this.useCache) {
17076 loc = this.getLocation(oTarget);
17077 this.locationCache[oTarget.id] = loc;
17085 oTarget.cursorIsOver = loc.contains( pt );
17087 // DragDrop is using this as a sanity check for the initial mousedown
17088 // in this case we are done. In POINT mode, if the drag obj has no
17089 // contraints, we are also done. Otherwise we need to evaluate the
17090 // location of the target as related to the actual location of the
17091 // dragged element.
17092 var dc = this.dragCurrent;
17093 if (!dc || !dc.getTargetCoord ||
17094 (!intersect && !dc.constrainX && !dc.constrainY)) {
17095 return oTarget.cursorIsOver;
17098 oTarget.overlap = null;
17100 // Get the current location of the drag element, this is the
17101 // location of the mouse event less the delta that represents
17102 // where the original mousedown happened on the element. We
17103 // need to consider constraints and ticks as well.
17104 var pos = dc.getTargetCoord(pt.x, pt.y);
17106 var el = dc.getDragEl();
17107 var curRegion = new Roo.lib.Region( pos.y,
17108 pos.x + el.offsetWidth,
17109 pos.y + el.offsetHeight,
17112 var overlap = curRegion.intersect(loc);
17115 oTarget.overlap = overlap;
17116 return (intersect) ? true : oTarget.cursorIsOver;
17123 * unload event handler
17124 * @method _onUnload
17128 _onUnload: function(e, me) {
17129 Roo.dd.DragDropMgr.unregAll();
17133 * Cleans up the drag and drop events and objects.
17138 unregAll: function() {
17140 if (this.dragCurrent) {
17142 this.dragCurrent = null;
17145 this._execOnAll("unreg", []);
17147 for (i in this.elementCache) {
17148 delete this.elementCache[i];
17151 this.elementCache = {};
17156 * A cache of DOM elements
17157 * @property elementCache
17164 * Get the wrapper for the DOM element specified
17165 * @method getElWrapper
17166 * @param {String} id the id of the element to get
17167 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
17169 * @deprecated This wrapper isn't that useful
17172 getElWrapper: function(id) {
17173 var oWrapper = this.elementCache[id];
17174 if (!oWrapper || !oWrapper.el) {
17175 oWrapper = this.elementCache[id] =
17176 new this.ElementWrapper(Roo.getDom(id));
17182 * Returns the actual DOM element
17183 * @method getElement
17184 * @param {String} id the id of the elment to get
17185 * @return {Object} The element
17186 * @deprecated use Roo.getDom instead
17189 getElement: function(id) {
17190 return Roo.getDom(id);
17194 * Returns the style property for the DOM element (i.e.,
17195 * document.getElById(id).style)
17197 * @param {String} id the id of the elment to get
17198 * @return {Object} The style property of the element
17199 * @deprecated use Roo.getDom instead
17202 getCss: function(id) {
17203 var el = Roo.getDom(id);
17204 return (el) ? el.style : null;
17208 * Inner class for cached elements
17209 * @class DragDropMgr.ElementWrapper
17214 ElementWrapper: function(el) {
17219 this.el = el || null;
17224 this.id = this.el && el.id;
17226 * A reference to the style property
17229 this.css = this.el && el.style;
17233 * Returns the X position of an html element
17235 * @param el the element for which to get the position
17236 * @return {int} the X coordinate
17238 * @deprecated use Roo.lib.Dom.getX instead
17241 getPosX: function(el) {
17242 return Roo.lib.Dom.getX(el);
17246 * Returns the Y position of an html element
17248 * @param el the element for which to get the position
17249 * @return {int} the Y coordinate
17250 * @deprecated use Roo.lib.Dom.getY instead
17253 getPosY: function(el) {
17254 return Roo.lib.Dom.getY(el);
17258 * Swap two nodes. In IE, we use the native method, for others we
17259 * emulate the IE behavior
17261 * @param n1 the first node to swap
17262 * @param n2 the other node to swap
17265 swapNode: function(n1, n2) {
17269 var p = n2.parentNode;
17270 var s = n2.nextSibling;
17273 p.insertBefore(n1, n2);
17274 } else if (n2 == n1.nextSibling) {
17275 p.insertBefore(n2, n1);
17277 n1.parentNode.replaceChild(n2, n1);
17278 p.insertBefore(n1, s);
17284 * Returns the current scroll position
17285 * @method getScroll
17289 getScroll: function () {
17290 var t, l, dde=document.documentElement, db=document.body;
17291 if (dde && (dde.scrollTop || dde.scrollLeft)) {
17293 l = dde.scrollLeft;
17300 return { top: t, left: l };
17304 * Returns the specified element style property
17306 * @param {HTMLElement} el the element
17307 * @param {string} styleProp the style property
17308 * @return {string} The value of the style property
17309 * @deprecated use Roo.lib.Dom.getStyle
17312 getStyle: function(el, styleProp) {
17313 return Roo.fly(el).getStyle(styleProp);
17317 * Gets the scrollTop
17318 * @method getScrollTop
17319 * @return {int} the document's scrollTop
17322 getScrollTop: function () { return this.getScroll().top; },
17325 * Gets the scrollLeft
17326 * @method getScrollLeft
17327 * @return {int} the document's scrollTop
17330 getScrollLeft: function () { return this.getScroll().left; },
17333 * Sets the x/y position of an element to the location of the
17336 * @param {HTMLElement} moveEl The element to move
17337 * @param {HTMLElement} targetEl The position reference element
17340 moveToEl: function (moveEl, targetEl) {
17341 var aCoord = Roo.lib.Dom.getXY(targetEl);
17342 Roo.lib.Dom.setXY(moveEl, aCoord);
17346 * Numeric array sort function
17347 * @method numericSort
17350 numericSort: function(a, b) { return (a - b); },
17354 * @property _timeoutCount
17361 * Trying to make the load order less important. Without this we get
17362 * an error if this file is loaded before the Event Utility.
17363 * @method _addListeners
17367 _addListeners: function() {
17368 var DDM = Roo.dd.DDM;
17369 if ( Roo.lib.Event && document ) {
17372 if (DDM._timeoutCount > 2000) {
17374 setTimeout(DDM._addListeners, 10);
17375 if (document && document.body) {
17376 DDM._timeoutCount += 1;
17383 * Recursively searches the immediate parent and all child nodes for
17384 * the handle element in order to determine wheter or not it was
17386 * @method handleWasClicked
17387 * @param node the html element to inspect
17390 handleWasClicked: function(node, id) {
17391 if (this.isHandle(id, node.id)) {
17394 // check to see if this is a text node child of the one we want
17395 var p = node.parentNode;
17398 if (this.isHandle(id, p.id)) {
17413 // shorter alias, save a few bytes
17414 Roo.dd.DDM = Roo.dd.DragDropMgr;
17415 Roo.dd.DDM._addListeners();
17419 * Ext JS Library 1.1.1
17420 * Copyright(c) 2006-2007, Ext JS, LLC.
17422 * Originally Released Under LGPL - original licence link has changed is not relivant.
17425 * <script type="text/javascript">
17430 * A DragDrop implementation where the linked element follows the
17431 * mouse cursor during a drag.
17432 * @extends Roo.dd.DragDrop
17434 * @param {String} id the id of the linked element
17435 * @param {String} sGroup the group of related DragDrop items
17436 * @param {object} config an object containing configurable attributes
17437 * Valid properties for DD:
17440 Roo.dd.DD = function(id, sGroup, config) {
17442 this.init(id, sGroup, config);
17446 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
17449 * When set to true, the utility automatically tries to scroll the browser
17450 * window wehn a drag and drop element is dragged near the viewport boundary.
17451 * Defaults to true.
17458 * Sets the pointer offset to the distance between the linked element's top
17459 * left corner and the location the element was clicked
17460 * @method autoOffset
17461 * @param {int} iPageX the X coordinate of the click
17462 * @param {int} iPageY the Y coordinate of the click
17464 autoOffset: function(iPageX, iPageY) {
17465 var x = iPageX - this.startPageX;
17466 var y = iPageY - this.startPageY;
17467 this.setDelta(x, y);
17471 * Sets the pointer offset. You can call this directly to force the
17472 * offset to be in a particular location (e.g., pass in 0,0 to set it
17473 * to the center of the object)
17475 * @param {int} iDeltaX the distance from the left
17476 * @param {int} iDeltaY the distance from the top
17478 setDelta: function(iDeltaX, iDeltaY) {
17479 this.deltaX = iDeltaX;
17480 this.deltaY = iDeltaY;
17484 * Sets the drag element to the location of the mousedown or click event,
17485 * maintaining the cursor location relative to the location on the element
17486 * that was clicked. Override this if you want to place the element in a
17487 * location other than where the cursor is.
17488 * @method setDragElPos
17489 * @param {int} iPageX the X coordinate of the mousedown or drag event
17490 * @param {int} iPageY the Y coordinate of the mousedown or drag event
17492 setDragElPos: function(iPageX, iPageY) {
17493 // the first time we do this, we are going to check to make sure
17494 // the element has css positioning
17496 var el = this.getDragEl();
17497 this.alignElWithMouse(el, iPageX, iPageY);
17501 * Sets the element to the location of the mousedown or click event,
17502 * maintaining the cursor location relative to the location on the element
17503 * that was clicked. Override this if you want to place the element in a
17504 * location other than where the cursor is.
17505 * @method alignElWithMouse
17506 * @param {HTMLElement} el the element to move
17507 * @param {int} iPageX the X coordinate of the mousedown or drag event
17508 * @param {int} iPageY the Y coordinate of the mousedown or drag event
17510 alignElWithMouse: function(el, iPageX, iPageY) {
17511 var oCoord = this.getTargetCoord(iPageX, iPageY);
17512 var fly = el.dom ? el : Roo.fly(el);
17513 if (!this.deltaSetXY) {
17514 var aCoord = [oCoord.x, oCoord.y];
17516 var newLeft = fly.getLeft(true);
17517 var newTop = fly.getTop(true);
17518 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
17520 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
17523 this.cachePosition(oCoord.x, oCoord.y);
17524 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
17529 * Saves the most recent position so that we can reset the constraints and
17530 * tick marks on-demand. We need to know this so that we can calculate the
17531 * number of pixels the element is offset from its original position.
17532 * @method cachePosition
17533 * @param iPageX the current x position (optional, this just makes it so we
17534 * don't have to look it up again)
17535 * @param iPageY the current y position (optional, this just makes it so we
17536 * don't have to look it up again)
17538 cachePosition: function(iPageX, iPageY) {
17540 this.lastPageX = iPageX;
17541 this.lastPageY = iPageY;
17543 var aCoord = Roo.lib.Dom.getXY(this.getEl());
17544 this.lastPageX = aCoord[0];
17545 this.lastPageY = aCoord[1];
17550 * Auto-scroll the window if the dragged object has been moved beyond the
17551 * visible window boundary.
17552 * @method autoScroll
17553 * @param {int} x the drag element's x position
17554 * @param {int} y the drag element's y position
17555 * @param {int} h the height of the drag element
17556 * @param {int} w the width of the drag element
17559 autoScroll: function(x, y, h, w) {
17562 // The client height
17563 var clientH = Roo.lib.Dom.getViewWidth();
17565 // The client width
17566 var clientW = Roo.lib.Dom.getViewHeight();
17568 // The amt scrolled down
17569 var st = this.DDM.getScrollTop();
17571 // The amt scrolled right
17572 var sl = this.DDM.getScrollLeft();
17574 // Location of the bottom of the element
17577 // Location of the right of the element
17580 // The distance from the cursor to the bottom of the visible area,
17581 // adjusted so that we don't scroll if the cursor is beyond the
17582 // element drag constraints
17583 var toBot = (clientH + st - y - this.deltaY);
17585 // The distance from the cursor to the right of the visible area
17586 var toRight = (clientW + sl - x - this.deltaX);
17589 // How close to the edge the cursor must be before we scroll
17590 // var thresh = (document.all) ? 100 : 40;
17593 // How many pixels to scroll per autoscroll op. This helps to reduce
17594 // clunky scrolling. IE is more sensitive about this ... it needs this
17595 // value to be higher.
17596 var scrAmt = (document.all) ? 80 : 30;
17598 // Scroll down if we are near the bottom of the visible page and the
17599 // obj extends below the crease
17600 if ( bot > clientH && toBot < thresh ) {
17601 window.scrollTo(sl, st + scrAmt);
17604 // Scroll up if the window is scrolled down and the top of the object
17605 // goes above the top border
17606 if ( y < st && st > 0 && y - st < thresh ) {
17607 window.scrollTo(sl, st - scrAmt);
17610 // Scroll right if the obj is beyond the right border and the cursor is
17611 // near the border.
17612 if ( right > clientW && toRight < thresh ) {
17613 window.scrollTo(sl + scrAmt, st);
17616 // Scroll left if the window has been scrolled to the right and the obj
17617 // extends past the left border
17618 if ( x < sl && sl > 0 && x - sl < thresh ) {
17619 window.scrollTo(sl - scrAmt, st);
17625 * Finds the location the element should be placed if we want to move
17626 * it to where the mouse location less the click offset would place us.
17627 * @method getTargetCoord
17628 * @param {int} iPageX the X coordinate of the click
17629 * @param {int} iPageY the Y coordinate of the click
17630 * @return an object that contains the coordinates (Object.x and Object.y)
17633 getTargetCoord: function(iPageX, iPageY) {
17636 var x = iPageX - this.deltaX;
17637 var y = iPageY - this.deltaY;
17639 if (this.constrainX) {
17640 if (x < this.minX) { x = this.minX; }
17641 if (x > this.maxX) { x = this.maxX; }
17644 if (this.constrainY) {
17645 if (y < this.minY) { y = this.minY; }
17646 if (y > this.maxY) { y = this.maxY; }
17649 x = this.getTick(x, this.xTicks);
17650 y = this.getTick(y, this.yTicks);
17657 * Sets up config options specific to this class. Overrides
17658 * Roo.dd.DragDrop, but all versions of this method through the
17659 * inheritance chain are called
17661 applyConfig: function() {
17662 Roo.dd.DD.superclass.applyConfig.call(this);
17663 this.scroll = (this.config.scroll !== false);
17667 * Event that fires prior to the onMouseDown event. Overrides
17670 b4MouseDown: function(e) {
17671 // this.resetConstraints();
17672 this.autoOffset(e.getPageX(),
17677 * Event that fires prior to the onDrag event. Overrides
17680 b4Drag: function(e) {
17681 this.setDragElPos(e.getPageX(),
17685 toString: function() {
17686 return ("DD " + this.id);
17689 //////////////////////////////////////////////////////////////////////////
17690 // Debugging ygDragDrop events that can be overridden
17691 //////////////////////////////////////////////////////////////////////////
17693 startDrag: function(x, y) {
17696 onDrag: function(e) {
17699 onDragEnter: function(e, id) {
17702 onDragOver: function(e, id) {
17705 onDragOut: function(e, id) {
17708 onDragDrop: function(e, id) {
17711 endDrag: function(e) {
17718 * Ext JS Library 1.1.1
17719 * Copyright(c) 2006-2007, Ext JS, LLC.
17721 * Originally Released Under LGPL - original licence link has changed is not relivant.
17724 * <script type="text/javascript">
17728 * @class Roo.dd.DDProxy
17729 * A DragDrop implementation that inserts an empty, bordered div into
17730 * the document that follows the cursor during drag operations. At the time of
17731 * the click, the frame div is resized to the dimensions of the linked html
17732 * element, and moved to the exact location of the linked element.
17734 * References to the "frame" element refer to the single proxy element that
17735 * was created to be dragged in place of all DDProxy elements on the
17738 * @extends Roo.dd.DD
17740 * @param {String} id the id of the linked html element
17741 * @param {String} sGroup the group of related DragDrop objects
17742 * @param {object} config an object containing configurable attributes
17743 * Valid properties for DDProxy in addition to those in DragDrop:
17744 * resizeFrame, centerFrame, dragElId
17746 Roo.dd.DDProxy = function(id, sGroup, config) {
17748 this.init(id, sGroup, config);
17754 * The default drag frame div id
17755 * @property Roo.dd.DDProxy.dragElId
17759 Roo.dd.DDProxy.dragElId = "ygddfdiv";
17761 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
17764 * By default we resize the drag frame to be the same size as the element
17765 * we want to drag (this is to get the frame effect). We can turn it off
17766 * if we want a different behavior.
17767 * @property resizeFrame
17773 * By default the frame is positioned exactly where the drag element is, so
17774 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
17775 * you do not have constraints on the obj is to have the drag frame centered
17776 * around the cursor. Set centerFrame to true for this effect.
17777 * @property centerFrame
17780 centerFrame: false,
17783 * Creates the proxy element if it does not yet exist
17784 * @method createFrame
17786 createFrame: function() {
17788 var body = document.body;
17790 if (!body || !body.firstChild) {
17791 setTimeout( function() { self.createFrame(); }, 50 );
17795 var div = this.getDragEl();
17798 div = document.createElement("div");
17799 div.id = this.dragElId;
17802 s.position = "absolute";
17803 s.visibility = "hidden";
17805 s.border = "2px solid #aaa";
17808 // appendChild can blow up IE if invoked prior to the window load event
17809 // while rendering a table. It is possible there are other scenarios
17810 // that would cause this to happen as well.
17811 body.insertBefore(div, body.firstChild);
17816 * Initialization for the drag frame element. Must be called in the
17817 * constructor of all subclasses
17818 * @method initFrame
17820 initFrame: function() {
17821 this.createFrame();
17824 applyConfig: function() {
17825 Roo.dd.DDProxy.superclass.applyConfig.call(this);
17827 this.resizeFrame = (this.config.resizeFrame !== false);
17828 this.centerFrame = (this.config.centerFrame);
17829 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
17833 * Resizes the drag frame to the dimensions of the clicked object, positions
17834 * it over the object, and finally displays it
17835 * @method showFrame
17836 * @param {int} iPageX X click position
17837 * @param {int} iPageY Y click position
17840 showFrame: function(iPageX, iPageY) {
17841 var el = this.getEl();
17842 var dragEl = this.getDragEl();
17843 var s = dragEl.style;
17845 this._resizeProxy();
17847 if (this.centerFrame) {
17848 this.setDelta( Math.round(parseInt(s.width, 10)/2),
17849 Math.round(parseInt(s.height, 10)/2) );
17852 this.setDragElPos(iPageX, iPageY);
17854 Roo.fly(dragEl).show();
17858 * The proxy is automatically resized to the dimensions of the linked
17859 * element when a drag is initiated, unless resizeFrame is set to false
17860 * @method _resizeProxy
17863 _resizeProxy: function() {
17864 if (this.resizeFrame) {
17865 var el = this.getEl();
17866 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
17870 // overrides Roo.dd.DragDrop
17871 b4MouseDown: function(e) {
17872 var x = e.getPageX();
17873 var y = e.getPageY();
17874 this.autoOffset(x, y);
17875 this.setDragElPos(x, y);
17878 // overrides Roo.dd.DragDrop
17879 b4StartDrag: function(x, y) {
17880 // show the drag frame
17881 this.showFrame(x, y);
17884 // overrides Roo.dd.DragDrop
17885 b4EndDrag: function(e) {
17886 Roo.fly(this.getDragEl()).hide();
17889 // overrides Roo.dd.DragDrop
17890 // By default we try to move the element to the last location of the frame.
17891 // This is so that the default behavior mirrors that of Roo.dd.DD.
17892 endDrag: function(e) {
17894 var lel = this.getEl();
17895 var del = this.getDragEl();
17897 // Show the drag frame briefly so we can get its position
17898 del.style.visibility = "";
17901 // Hide the linked element before the move to get around a Safari
17903 lel.style.visibility = "hidden";
17904 Roo.dd.DDM.moveToEl(lel, del);
17905 del.style.visibility = "hidden";
17906 lel.style.visibility = "";
17911 beforeMove : function(){
17915 afterDrag : function(){
17919 toString: function() {
17920 return ("DDProxy " + this.id);
17926 * Ext JS Library 1.1.1
17927 * Copyright(c) 2006-2007, Ext JS, LLC.
17929 * Originally Released Under LGPL - original licence link has changed is not relivant.
17932 * <script type="text/javascript">
17936 * @class Roo.dd.DDTarget
17937 * A DragDrop implementation that does not move, but can be a drop
17938 * target. You would get the same result by simply omitting implementation
17939 * for the event callbacks, but this way we reduce the processing cost of the
17940 * event listener and the callbacks.
17941 * @extends Roo.dd.DragDrop
17943 * @param {String} id the id of the element that is a drop target
17944 * @param {String} sGroup the group of related DragDrop objects
17945 * @param {object} config an object containing configurable attributes
17946 * Valid properties for DDTarget in addition to those in
17950 Roo.dd.DDTarget = function(id, sGroup, config) {
17952 this.initTarget(id, sGroup, config);
17954 if (config.listeners || config.events) {
17955 Roo.dd.DragDrop.superclass.constructor.call(this, {
17956 listeners : config.listeners || {},
17957 events : config.events || {}
17962 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
17963 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
17964 toString: function() {
17965 return ("DDTarget " + this.id);
17970 * Ext JS Library 1.1.1
17971 * Copyright(c) 2006-2007, Ext JS, LLC.
17973 * Originally Released Under LGPL - original licence link has changed is not relivant.
17976 * <script type="text/javascript">
17981 * @class Roo.dd.ScrollManager
17982 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
17983 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
17986 Roo.dd.ScrollManager = function(){
17987 var ddm = Roo.dd.DragDropMgr;
17994 var onStop = function(e){
17999 var triggerRefresh = function(){
18000 if(ddm.dragCurrent){
18001 ddm.refreshCache(ddm.dragCurrent.groups);
18005 var doScroll = function(){
18006 if(ddm.dragCurrent){
18007 var dds = Roo.dd.ScrollManager;
18009 if(proc.el.scroll(proc.dir, dds.increment)){
18013 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
18018 var clearProc = function(){
18020 clearInterval(proc.id);
18027 var startProc = function(el, dir){
18028 Roo.log('scroll startproc');
18032 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
18035 var onFire = function(e, isDrop){
18037 if(isDrop || !ddm.dragCurrent){ return; }
18038 var dds = Roo.dd.ScrollManager;
18039 if(!dragEl || dragEl != ddm.dragCurrent){
18040 dragEl = ddm.dragCurrent;
18041 // refresh regions on drag start
18042 dds.refreshCache();
18045 var xy = Roo.lib.Event.getXY(e);
18046 var pt = new Roo.lib.Point(xy[0], xy[1]);
18047 for(var id in els){
18048 var el = els[id], r = el._region;
18049 if(r && r.contains(pt) && el.isScrollable()){
18050 if(r.bottom - pt.y <= dds.thresh){
18052 startProc(el, "down");
18055 }else if(r.right - pt.x <= dds.thresh){
18057 startProc(el, "left");
18060 }else if(pt.y - r.top <= dds.thresh){
18062 startProc(el, "up");
18065 }else if(pt.x - r.left <= dds.thresh){
18067 startProc(el, "right");
18076 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
18077 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
18081 * Registers new overflow element(s) to auto scroll
18082 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
18084 register : function(el){
18085 if(el instanceof Array){
18086 for(var i = 0, len = el.length; i < len; i++) {
18087 this.register(el[i]);
18093 Roo.dd.ScrollManager.els = els;
18097 * Unregisters overflow element(s) so they are no longer scrolled
18098 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
18100 unregister : function(el){
18101 if(el instanceof Array){
18102 for(var i = 0, len = el.length; i < len; i++) {
18103 this.unregister(el[i]);
18112 * The number of pixels from the edge of a container the pointer needs to be to
18113 * trigger scrolling (defaults to 25)
18119 * The number of pixels to scroll in each scroll increment (defaults to 50)
18125 * The frequency of scrolls in milliseconds (defaults to 500)
18131 * True to animate the scroll (defaults to true)
18137 * The animation duration in seconds -
18138 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
18144 * Manually trigger a cache refresh.
18146 refreshCache : function(){
18147 for(var id in els){
18148 if(typeof els[id] == 'object'){ // for people extending the object prototype
18149 els[id]._region = els[id].getRegion();
18156 * Ext JS Library 1.1.1
18157 * Copyright(c) 2006-2007, Ext JS, LLC.
18159 * Originally Released Under LGPL - original licence link has changed is not relivant.
18162 * <script type="text/javascript">
18167 * @class Roo.dd.Registry
18168 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
18169 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
18172 Roo.dd.Registry = function(){
18175 var autoIdSeed = 0;
18177 var getId = function(el, autogen){
18178 if(typeof el == "string"){
18182 if(!id && autogen !== false){
18183 id = "roodd-" + (++autoIdSeed);
18191 * Register a drag drop element
18192 * @param {String|HTMLElement} element The id or DOM node to register
18193 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
18194 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
18195 * knows how to interpret, plus there are some specific properties known to the Registry that should be
18196 * populated in the data object (if applicable):
18198 Value Description<br />
18199 --------- ------------------------------------------<br />
18200 handles Array of DOM nodes that trigger dragging<br />
18201 for the element being registered<br />
18202 isHandle True if the element passed in triggers<br />
18203 dragging itself, else false
18206 register : function(el, data){
18208 if(typeof el == "string"){
18209 el = document.getElementById(el);
18212 elements[getId(el)] = data;
18213 if(data.isHandle !== false){
18214 handles[data.ddel.id] = data;
18217 var hs = data.handles;
18218 for(var i = 0, len = hs.length; i < len; i++){
18219 handles[getId(hs[i])] = data;
18225 * Unregister a drag drop element
18226 * @param {String|HTMLElement} element The id or DOM node to unregister
18228 unregister : function(el){
18229 var id = getId(el, false);
18230 var data = elements[id];
18232 delete elements[id];
18234 var hs = data.handles;
18235 for(var i = 0, len = hs.length; i < len; i++){
18236 delete handles[getId(hs[i], false)];
18243 * Returns the handle registered for a DOM Node by id
18244 * @param {String|HTMLElement} id The DOM node or id to look up
18245 * @return {Object} handle The custom handle data
18247 getHandle : function(id){
18248 if(typeof id != "string"){ // must be element?
18251 return handles[id];
18255 * Returns the handle that is registered for the DOM node that is the target of the event
18256 * @param {Event} e The event
18257 * @return {Object} handle The custom handle data
18259 getHandleFromEvent : function(e){
18260 var t = Roo.lib.Event.getTarget(e);
18261 return t ? handles[t.id] : null;
18265 * Returns a custom data object that is registered for a DOM node by id
18266 * @param {String|HTMLElement} id The DOM node or id to look up
18267 * @return {Object} data The custom data
18269 getTarget : function(id){
18270 if(typeof id != "string"){ // must be element?
18273 return elements[id];
18277 * Returns a custom data object that is registered for the DOM node that is the target of the event
18278 * @param {Event} e The event
18279 * @return {Object} data The custom data
18281 getTargetFromEvent : function(e){
18282 var t = Roo.lib.Event.getTarget(e);
18283 return t ? elements[t.id] || handles[t.id] : null;
18288 * Ext JS Library 1.1.1
18289 * Copyright(c) 2006-2007, Ext JS, LLC.
18291 * Originally Released Under LGPL - original licence link has changed is not relivant.
18294 * <script type="text/javascript">
18299 * @class Roo.dd.StatusProxy
18300 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
18301 * default drag proxy used by all Roo.dd components.
18303 * @param {Object} config
18305 Roo.dd.StatusProxy = function(config){
18306 Roo.apply(this, config);
18307 this.id = this.id || Roo.id();
18308 this.el = new Roo.Layer({
18310 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
18311 {tag: "div", cls: "x-dd-drop-icon"},
18312 {tag: "div", cls: "x-dd-drag-ghost"}
18315 shadow: !config || config.shadow !== false
18317 this.ghost = Roo.get(this.el.dom.childNodes[1]);
18318 this.dropStatus = this.dropNotAllowed;
18321 Roo.dd.StatusProxy.prototype = {
18323 * @cfg {String} dropAllowed
18324 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
18326 dropAllowed : "x-dd-drop-ok",
18328 * @cfg {String} dropNotAllowed
18329 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
18331 dropNotAllowed : "x-dd-drop-nodrop",
18334 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
18335 * over the current target element.
18336 * @param {String} cssClass The css class for the new drop status indicator image
18338 setStatus : function(cssClass){
18339 cssClass = cssClass || this.dropNotAllowed;
18340 if(this.dropStatus != cssClass){
18341 this.el.replaceClass(this.dropStatus, cssClass);
18342 this.dropStatus = cssClass;
18347 * Resets the status indicator to the default dropNotAllowed value
18348 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
18350 reset : function(clearGhost){
18351 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
18352 this.dropStatus = this.dropNotAllowed;
18354 this.ghost.update("");
18359 * Updates the contents of the ghost element
18360 * @param {String} html The html that will replace the current innerHTML of the ghost element
18362 update : function(html){
18363 if(typeof html == "string"){
18364 this.ghost.update(html);
18366 this.ghost.update("");
18367 html.style.margin = "0";
18368 this.ghost.dom.appendChild(html);
18370 // ensure float = none set?? cant remember why though.
18371 var el = this.ghost.dom.firstChild;
18373 Roo.fly(el).setStyle('float', 'none');
18378 * Returns the underlying proxy {@link Roo.Layer}
18379 * @return {Roo.Layer} el
18381 getEl : function(){
18386 * Returns the ghost element
18387 * @return {Roo.Element} el
18389 getGhost : function(){
18395 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
18397 hide : function(clear){
18405 * Stops the repair animation if it's currently running
18408 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
18414 * Displays this proxy
18421 * Force the Layer to sync its shadow and shim positions to the element
18428 * Causes the proxy to return to its position of origin via an animation. Should be called after an
18429 * invalid drop operation by the item being dragged.
18430 * @param {Array} xy The XY position of the element ([x, y])
18431 * @param {Function} callback The function to call after the repair is complete
18432 * @param {Object} scope The scope in which to execute the callback
18434 repair : function(xy, callback, scope){
18435 this.callback = callback;
18436 this.scope = scope;
18437 if(xy && this.animRepair !== false){
18438 this.el.addClass("x-dd-drag-repair");
18439 this.el.hideUnders(true);
18440 this.anim = this.el.shift({
18441 duration: this.repairDuration || .5,
18445 callback: this.afterRepair,
18449 this.afterRepair();
18454 afterRepair : function(){
18456 if(typeof this.callback == "function"){
18457 this.callback.call(this.scope || this);
18459 this.callback = null;
18464 * Ext JS Library 1.1.1
18465 * Copyright(c) 2006-2007, Ext JS, LLC.
18467 * Originally Released Under LGPL - original licence link has changed is not relivant.
18470 * <script type="text/javascript">
18474 * @class Roo.dd.DragSource
18475 * @extends Roo.dd.DDProxy
18476 * A simple class that provides the basic implementation needed to make any element draggable.
18478 * @param {String/HTMLElement/Element} el The container element
18479 * @param {Object} config
18481 Roo.dd.DragSource = function(el, config){
18482 this.el = Roo.get(el);
18483 this.dragData = {};
18485 Roo.apply(this, config);
18488 this.proxy = new Roo.dd.StatusProxy();
18491 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
18492 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
18494 this.dragging = false;
18497 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
18499 * @cfg {String} dropAllowed
18500 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
18502 dropAllowed : "x-dd-drop-ok",
18504 * @cfg {String} dropNotAllowed
18505 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
18507 dropNotAllowed : "x-dd-drop-nodrop",
18510 * Returns the data object associated with this drag source
18511 * @return {Object} data An object containing arbitrary data
18513 getDragData : function(e){
18514 return this.dragData;
18518 onDragEnter : function(e, id){
18519 var target = Roo.dd.DragDropMgr.getDDById(id);
18520 this.cachedTarget = target;
18521 if(this.beforeDragEnter(target, e, id) !== false){
18522 if(target.isNotifyTarget){
18523 var status = target.notifyEnter(this, e, this.dragData);
18524 this.proxy.setStatus(status);
18526 this.proxy.setStatus(this.dropAllowed);
18529 if(this.afterDragEnter){
18531 * An empty function by default, but provided so that you can perform a custom action
18532 * when the dragged item enters the drop target by providing an implementation.
18533 * @param {Roo.dd.DragDrop} target The drop target
18534 * @param {Event} e The event object
18535 * @param {String} id The id of the dragged element
18536 * @method afterDragEnter
18538 this.afterDragEnter(target, e, id);
18544 * An empty function by default, but provided so that you can perform a custom action
18545 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
18546 * @param {Roo.dd.DragDrop} target The drop target
18547 * @param {Event} e The event object
18548 * @param {String} id The id of the dragged element
18549 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
18551 beforeDragEnter : function(target, e, id){
18556 alignElWithMouse: function() {
18557 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
18562 onDragOver : function(e, id){
18563 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
18564 if(this.beforeDragOver(target, e, id) !== false){
18565 if(target.isNotifyTarget){
18566 var status = target.notifyOver(this, e, this.dragData);
18567 this.proxy.setStatus(status);
18570 if(this.afterDragOver){
18572 * An empty function by default, but provided so that you can perform a custom action
18573 * while the dragged item is over the drop target by providing an implementation.
18574 * @param {Roo.dd.DragDrop} target The drop target
18575 * @param {Event} e The event object
18576 * @param {String} id The id of the dragged element
18577 * @method afterDragOver
18579 this.afterDragOver(target, e, id);
18585 * An empty function by default, but provided so that you can perform a custom action
18586 * while the dragged item is over the drop target and optionally cancel the onDragOver.
18587 * @param {Roo.dd.DragDrop} target The drop target
18588 * @param {Event} e The event object
18589 * @param {String} id The id of the dragged element
18590 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
18592 beforeDragOver : function(target, e, id){
18597 onDragOut : function(e, id){
18598 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
18599 if(this.beforeDragOut(target, e, id) !== false){
18600 if(target.isNotifyTarget){
18601 target.notifyOut(this, e, this.dragData);
18603 this.proxy.reset();
18604 if(this.afterDragOut){
18606 * An empty function by default, but provided so that you can perform a custom action
18607 * after the dragged item is dragged out of the target without dropping.
18608 * @param {Roo.dd.DragDrop} target The drop target
18609 * @param {Event} e The event object
18610 * @param {String} id The id of the dragged element
18611 * @method afterDragOut
18613 this.afterDragOut(target, e, id);
18616 this.cachedTarget = null;
18620 * An empty function by default, but provided so that you can perform a custom action before the dragged
18621 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
18622 * @param {Roo.dd.DragDrop} target The drop target
18623 * @param {Event} e The event object
18624 * @param {String} id The id of the dragged element
18625 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
18627 beforeDragOut : function(target, e, id){
18632 onDragDrop : function(e, id){
18633 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
18634 if(this.beforeDragDrop(target, e, id) !== false){
18635 if(target.isNotifyTarget){
18636 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
18637 this.onValidDrop(target, e, id);
18639 this.onInvalidDrop(target, e, id);
18642 this.onValidDrop(target, e, id);
18645 if(this.afterDragDrop){
18647 * An empty function by default, but provided so that you can perform a custom action
18648 * after a valid drag drop has occurred by providing an implementation.
18649 * @param {Roo.dd.DragDrop} target The drop target
18650 * @param {Event} e The event object
18651 * @param {String} id The id of the dropped element
18652 * @method afterDragDrop
18654 this.afterDragDrop(target, e, id);
18657 delete this.cachedTarget;
18661 * An empty function by default, but provided so that you can perform a custom action before the dragged
18662 * item is dropped onto the target and optionally cancel the onDragDrop.
18663 * @param {Roo.dd.DragDrop} target The drop target
18664 * @param {Event} e The event object
18665 * @param {String} id The id of the dragged element
18666 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
18668 beforeDragDrop : function(target, e, id){
18673 onValidDrop : function(target, e, id){
18675 if(this.afterValidDrop){
18677 * An empty function by default, but provided so that you can perform a custom action
18678 * after a valid drop has occurred by providing an implementation.
18679 * @param {Object} target The target DD
18680 * @param {Event} e The event object
18681 * @param {String} id The id of the dropped element
18682 * @method afterInvalidDrop
18684 this.afterValidDrop(target, e, id);
18689 getRepairXY : function(e, data){
18690 return this.el.getXY();
18694 onInvalidDrop : function(target, e, id){
18695 this.beforeInvalidDrop(target, e, id);
18696 if(this.cachedTarget){
18697 if(this.cachedTarget.isNotifyTarget){
18698 this.cachedTarget.notifyOut(this, e, this.dragData);
18700 this.cacheTarget = null;
18702 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
18704 if(this.afterInvalidDrop){
18706 * An empty function by default, but provided so that you can perform a custom action
18707 * after an invalid drop has occurred by providing an implementation.
18708 * @param {Event} e The event object
18709 * @param {String} id The id of the dropped element
18710 * @method afterInvalidDrop
18712 this.afterInvalidDrop(e, id);
18717 afterRepair : function(){
18719 this.el.highlight(this.hlColor || "c3daf9");
18721 this.dragging = false;
18725 * An empty function by default, but provided so that you can perform a custom action after an invalid
18726 * drop has occurred.
18727 * @param {Roo.dd.DragDrop} target The drop target
18728 * @param {Event} e The event object
18729 * @param {String} id The id of the dragged element
18730 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
18732 beforeInvalidDrop : function(target, e, id){
18737 handleMouseDown : function(e){
18738 if(this.dragging) {
18741 var data = this.getDragData(e);
18742 if(data && this.onBeforeDrag(data, e) !== false){
18743 this.dragData = data;
18745 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
18750 * An empty function by default, but provided so that you can perform a custom action before the initial
18751 * drag event begins and optionally cancel it.
18752 * @param {Object} data An object containing arbitrary data to be shared with drop targets
18753 * @param {Event} e The event object
18754 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
18756 onBeforeDrag : function(data, e){
18761 * An empty function by default, but provided so that you can perform a custom action once the initial
18762 * drag event has begun. The drag cannot be canceled from this function.
18763 * @param {Number} x The x position of the click on the dragged object
18764 * @param {Number} y The y position of the click on the dragged object
18766 onStartDrag : Roo.emptyFn,
18768 // private - YUI override
18769 startDrag : function(x, y){
18770 this.proxy.reset();
18771 this.dragging = true;
18772 this.proxy.update("");
18773 this.onInitDrag(x, y);
18778 onInitDrag : function(x, y){
18779 var clone = this.el.dom.cloneNode(true);
18780 clone.id = Roo.id(); // prevent duplicate ids
18781 this.proxy.update(clone);
18782 this.onStartDrag(x, y);
18787 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
18788 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
18790 getProxy : function(){
18795 * Hides the drag source's {@link Roo.dd.StatusProxy}
18797 hideProxy : function(){
18799 this.proxy.reset(true);
18800 this.dragging = false;
18804 triggerCacheRefresh : function(){
18805 Roo.dd.DDM.refreshCache(this.groups);
18808 // private - override to prevent hiding
18809 b4EndDrag: function(e) {
18812 // private - override to prevent moving
18813 endDrag : function(e){
18814 this.onEndDrag(this.dragData, e);
18818 onEndDrag : function(data, e){
18821 // private - pin to cursor
18822 autoOffset : function(x, y) {
18823 this.setDelta(-12, -20);
18827 * Ext JS Library 1.1.1
18828 * Copyright(c) 2006-2007, Ext JS, LLC.
18830 * Originally Released Under LGPL - original licence link has changed is not relivant.
18833 * <script type="text/javascript">
18838 * @class Roo.dd.DropTarget
18839 * @extends Roo.dd.DDTarget
18840 * A simple class that provides the basic implementation needed to make any element a drop target that can have
18841 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
18843 * @param {String/HTMLElement/Element} el The container element
18844 * @param {Object} config
18846 Roo.dd.DropTarget = function(el, config){
18847 this.el = Roo.get(el);
18849 var listeners = false; ;
18850 if (config && config.listeners) {
18851 listeners= config.listeners;
18852 delete config.listeners;
18854 Roo.apply(this, config);
18856 if(this.containerScroll){
18857 Roo.dd.ScrollManager.register(this.el);
18861 * @scope Roo.dd.DropTarget
18866 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
18867 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
18868 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
18870 * IMPORTANT : it should set this.overClass and this.dropAllowed
18872 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18873 * @param {Event} e The event
18874 * @param {Object} data An object containing arbitrary data supplied by the drag source
18880 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
18881 * This method will be called on every mouse movement while the drag source is over the drop target.
18882 * This default implementation simply returns the dropAllowed config value.
18884 * IMPORTANT : it should set this.dropAllowed
18886 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18887 * @param {Event} e The event
18888 * @param {Object} data An object containing arbitrary data supplied by the drag source
18894 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
18895 * out of the target without dropping. This default implementation simply removes the CSS class specified by
18896 * overClass (if any) from the drop element.
18898 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18899 * @param {Event} e The event
18900 * @param {Object} data An object containing arbitrary data supplied by the drag source
18906 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
18907 * been dropped on it. This method has no default implementation and returns false, so you must provide an
18908 * implementation that does something to process the drop event and returns true so that the drag source's
18909 * repair action does not run.
18911 * IMPORTANT : it should set this.success
18913 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
18914 * @param {Event} e The event
18915 * @param {Object} data An object containing arbitrary data supplied by the drag source
18921 Roo.dd.DropTarget.superclass.constructor.call( this,
18923 this.ddGroup || this.group,
18926 listeners : listeners || {}
18934 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
18936 * @cfg {String} overClass
18937 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
18940 * @cfg {String} ddGroup
18941 * The drag drop group to handle drop events for
18945 * @cfg {String} dropAllowed
18946 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
18948 dropAllowed : "x-dd-drop-ok",
18950 * @cfg {String} dropNotAllowed
18951 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
18953 dropNotAllowed : "x-dd-drop-nodrop",
18955 * @cfg {boolean} success
18956 * set this after drop listener..
18960 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
18961 * if the drop point is valid for over/enter..
18968 isNotifyTarget : true,
18973 notifyEnter : function(dd, e, data)
18976 this.fireEvent('enter', dd, e, data);
18977 if(this.overClass){
18978 this.el.addClass(this.overClass);
18980 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
18981 this.valid ? this.dropAllowed : this.dropNotAllowed
18988 notifyOver : function(dd, e, data)
18991 this.fireEvent('over', dd, e, data);
18992 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
18993 this.valid ? this.dropAllowed : this.dropNotAllowed
19000 notifyOut : function(dd, e, data)
19002 this.fireEvent('out', dd, e, data);
19003 if(this.overClass){
19004 this.el.removeClass(this.overClass);
19011 notifyDrop : function(dd, e, data)
19013 this.success = false;
19014 this.fireEvent('drop', dd, e, data);
19015 return this.success;
19019 * Ext JS Library 1.1.1
19020 * Copyright(c) 2006-2007, Ext JS, LLC.
19022 * Originally Released Under LGPL - original licence link has changed is not relivant.
19025 * <script type="text/javascript">
19030 * @class Roo.dd.DragZone
19031 * @extends Roo.dd.DragSource
19032 * This class provides a container DD instance that proxies for multiple child node sources.<br />
19033 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
19035 * @param {String/HTMLElement/Element} el The container element
19036 * @param {Object} config
19038 Roo.dd.DragZone = function(el, config){
19039 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
19040 if(this.containerScroll){
19041 Roo.dd.ScrollManager.register(this.el);
19045 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
19047 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
19048 * for auto scrolling during drag operations.
19051 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
19052 * method after a failed drop (defaults to "c3daf9" - light blue)
19056 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
19057 * for a valid target to drag based on the mouse down. Override this method
19058 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
19059 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
19060 * @param {EventObject} e The mouse down event
19061 * @return {Object} The dragData
19063 getDragData : function(e){
19064 return Roo.dd.Registry.getHandleFromEvent(e);
19068 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
19069 * this.dragData.ddel
19070 * @param {Number} x The x position of the click on the dragged object
19071 * @param {Number} y The y position of the click on the dragged object
19072 * @return {Boolean} true to continue the drag, false to cancel
19074 onInitDrag : function(x, y){
19075 this.proxy.update(this.dragData.ddel.cloneNode(true));
19076 this.onStartDrag(x, y);
19081 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
19083 afterRepair : function(){
19085 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
19087 this.dragging = false;
19091 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
19092 * the XY of this.dragData.ddel
19093 * @param {EventObject} e The mouse up event
19094 * @return {Array} The xy location (e.g. [100, 200])
19096 getRepairXY : function(e){
19097 return Roo.Element.fly(this.dragData.ddel).getXY();
19101 * Ext JS Library 1.1.1
19102 * Copyright(c) 2006-2007, Ext JS, LLC.
19104 * Originally Released Under LGPL - original licence link has changed is not relivant.
19107 * <script type="text/javascript">
19110 * @class Roo.dd.DropZone
19111 * @extends Roo.dd.DropTarget
19112 * This class provides a container DD instance that proxies for multiple child node targets.<br />
19113 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
19115 * @param {String/HTMLElement/Element} el The container element
19116 * @param {Object} config
19118 Roo.dd.DropZone = function(el, config){
19119 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
19122 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
19124 * Returns a custom data object associated with the DOM node that is the target of the event. By default
19125 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
19126 * provide your own custom lookup.
19127 * @param {Event} e The event
19128 * @return {Object} data The custom data
19130 getTargetFromEvent : function(e){
19131 return Roo.dd.Registry.getTargetFromEvent(e);
19135 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
19136 * that it has registered. This method has no default implementation and should be overridden to provide
19137 * node-specific processing if necessary.
19138 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
19139 * {@link #getTargetFromEvent} for this node)
19140 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19141 * @param {Event} e The event
19142 * @param {Object} data An object containing arbitrary data supplied by the drag source
19144 onNodeEnter : function(n, dd, e, data){
19149 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
19150 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
19151 * overridden to provide the proper feedback.
19152 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
19153 * {@link #getTargetFromEvent} for this node)
19154 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19155 * @param {Event} e The event
19156 * @param {Object} data An object containing arbitrary data supplied by the drag source
19157 * @return {String} status The CSS class that communicates the drop status back to the source so that the
19158 * underlying {@link Roo.dd.StatusProxy} can be updated
19160 onNodeOver : function(n, dd, e, data){
19161 return this.dropAllowed;
19165 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
19166 * the drop node without dropping. This method has no default implementation and should be overridden to provide
19167 * node-specific processing if necessary.
19168 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
19169 * {@link #getTargetFromEvent} for this node)
19170 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19171 * @param {Event} e The event
19172 * @param {Object} data An object containing arbitrary data supplied by the drag source
19174 onNodeOut : function(n, dd, e, data){
19179 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
19180 * the drop node. The default implementation returns false, so it should be overridden to provide the
19181 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
19182 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
19183 * {@link #getTargetFromEvent} for this node)
19184 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19185 * @param {Event} e The event
19186 * @param {Object} data An object containing arbitrary data supplied by the drag source
19187 * @return {Boolean} True if the drop was valid, else false
19189 onNodeDrop : function(n, dd, e, data){
19194 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
19195 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
19196 * it should be overridden to provide the proper feedback if necessary.
19197 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19198 * @param {Event} e The event
19199 * @param {Object} data An object containing arbitrary data supplied by the drag source
19200 * @return {String} status The CSS class that communicates the drop status back to the source so that the
19201 * underlying {@link Roo.dd.StatusProxy} can be updated
19203 onContainerOver : function(dd, e, data){
19204 return this.dropNotAllowed;
19208 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
19209 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
19210 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
19211 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
19212 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19213 * @param {Event} e The event
19214 * @param {Object} data An object containing arbitrary data supplied by the drag source
19215 * @return {Boolean} True if the drop was valid, else false
19217 onContainerDrop : function(dd, e, data){
19222 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
19223 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
19224 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
19225 * you should override this method and provide a custom implementation.
19226 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19227 * @param {Event} e The event
19228 * @param {Object} data An object containing arbitrary data supplied by the drag source
19229 * @return {String} status The CSS class that communicates the drop status back to the source so that the
19230 * underlying {@link Roo.dd.StatusProxy} can be updated
19232 notifyEnter : function(dd, e, data){
19233 return this.dropNotAllowed;
19237 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
19238 * This method will be called on every mouse movement while the drag source is over the drop zone.
19239 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
19240 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
19241 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
19242 * registered node, it will call {@link #onContainerOver}.
19243 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19244 * @param {Event} e The event
19245 * @param {Object} data An object containing arbitrary data supplied by the drag source
19246 * @return {String} status The CSS class that communicates the drop status back to the source so that the
19247 * underlying {@link Roo.dd.StatusProxy} can be updated
19249 notifyOver : function(dd, e, data){
19250 var n = this.getTargetFromEvent(e);
19251 if(!n){ // not over valid drop target
19252 if(this.lastOverNode){
19253 this.onNodeOut(this.lastOverNode, dd, e, data);
19254 this.lastOverNode = null;
19256 return this.onContainerOver(dd, e, data);
19258 if(this.lastOverNode != n){
19259 if(this.lastOverNode){
19260 this.onNodeOut(this.lastOverNode, dd, e, data);
19262 this.onNodeEnter(n, dd, e, data);
19263 this.lastOverNode = n;
19265 return this.onNodeOver(n, dd, e, data);
19269 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
19270 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
19271 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
19272 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
19273 * @param {Event} e The event
19274 * @param {Object} data An object containing arbitrary data supplied by the drag zone
19276 notifyOut : function(dd, e, data){
19277 if(this.lastOverNode){
19278 this.onNodeOut(this.lastOverNode, dd, e, data);
19279 this.lastOverNode = null;
19284 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
19285 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
19286 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
19287 * otherwise it will call {@link #onContainerDrop}.
19288 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
19289 * @param {Event} e The event
19290 * @param {Object} data An object containing arbitrary data supplied by the drag source
19291 * @return {Boolean} True if the drop was valid, else false
19293 notifyDrop : function(dd, e, data){
19294 if(this.lastOverNode){
19295 this.onNodeOut(this.lastOverNode, dd, e, data);
19296 this.lastOverNode = null;
19298 var n = this.getTargetFromEvent(e);
19300 this.onNodeDrop(n, dd, e, data) :
19301 this.onContainerDrop(dd, e, data);
19305 triggerCacheRefresh : function(){
19306 Roo.dd.DDM.refreshCache(this.groups);
19310 * Ext JS Library 1.1.1
19311 * Copyright(c) 2006-2007, Ext JS, LLC.
19313 * Originally Released Under LGPL - original licence link has changed is not relivant.
19316 * <script type="text/javascript">
19321 * @class Roo.data.SortTypes
19323 * Defines the default sorting (casting?) comparison functions used when sorting data.
19325 Roo.data.SortTypes = {
19327 * Default sort that does nothing
19328 * @param {Mixed} s The value being converted
19329 * @return {Mixed} The comparison value
19331 none : function(s){
19336 * The regular expression used to strip tags
19340 stripTagsRE : /<\/?[^>]+>/gi,
19343 * Strips all HTML tags to sort on text only
19344 * @param {Mixed} s The value being converted
19345 * @return {String} The comparison value
19347 asText : function(s){
19348 return String(s).replace(this.stripTagsRE, "");
19352 * Strips all HTML tags to sort on text only - Case insensitive
19353 * @param {Mixed} s The value being converted
19354 * @return {String} The comparison value
19356 asUCText : function(s){
19357 return String(s).toUpperCase().replace(this.stripTagsRE, "");
19361 * Case insensitive string
19362 * @param {Mixed} s The value being converted
19363 * @return {String} The comparison value
19365 asUCString : function(s) {
19366 return String(s).toUpperCase();
19371 * @param {Mixed} s The value being converted
19372 * @return {Number} The comparison value
19374 asDate : function(s) {
19378 if(s instanceof Date){
19379 return s.getTime();
19381 return Date.parse(String(s));
19386 * @param {Mixed} s The value being converted
19387 * @return {Float} The comparison value
19389 asFloat : function(s) {
19390 var val = parseFloat(String(s).replace(/,/g, ""));
19391 if(isNaN(val)) val = 0;
19397 * @param {Mixed} s The value being converted
19398 * @return {Number} The comparison value
19400 asInt : function(s) {
19401 var val = parseInt(String(s).replace(/,/g, ""));
19402 if(isNaN(val)) val = 0;
19407 * Ext JS Library 1.1.1
19408 * Copyright(c) 2006-2007, Ext JS, LLC.
19410 * Originally Released Under LGPL - original licence link has changed is not relivant.
19413 * <script type="text/javascript">
19417 * @class Roo.data.Record
19418 * Instances of this class encapsulate both record <em>definition</em> information, and record
19419 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
19420 * to access Records cached in an {@link Roo.data.Store} object.<br>
19422 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
19423 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
19426 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
19428 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
19429 * {@link #create}. The parameters are the same.
19430 * @param {Array} data An associative Array of data values keyed by the field name.
19431 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
19432 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
19433 * not specified an integer id is generated.
19435 Roo.data.Record = function(data, id){
19436 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
19441 * Generate a constructor for a specific record layout.
19442 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
19443 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
19444 * Each field definition object may contain the following properties: <ul>
19445 * <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,
19446 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
19447 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
19448 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
19449 * is being used, then this is a string containing the javascript expression to reference the data relative to
19450 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
19451 * to the data item relative to the record element. If the mapping expression is the same as the field name,
19452 * this may be omitted.</p></li>
19453 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
19454 * <ul><li>auto (Default, implies no conversion)</li>
19459 * <li>date</li></ul></p></li>
19460 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
19461 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
19462 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
19463 * by the Reader into an object that will be stored in the Record. It is passed the
19464 * following parameters:<ul>
19465 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
19467 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
19469 * <br>usage:<br><pre><code>
19470 var TopicRecord = Roo.data.Record.create(
19471 {name: 'title', mapping: 'topic_title'},
19472 {name: 'author', mapping: 'username'},
19473 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
19474 {name: 'lastPost', mapping: 'post_time', type: 'date'},
19475 {name: 'lastPoster', mapping: 'user2'},
19476 {name: 'excerpt', mapping: 'post_text'}
19479 var myNewRecord = new TopicRecord({
19480 title: 'Do my job please',
19483 lastPost: new Date(),
19484 lastPoster: 'Animal',
19485 excerpt: 'No way dude!'
19487 myStore.add(myNewRecord);
19492 Roo.data.Record.create = function(o){
19493 var f = function(){
19494 f.superclass.constructor.apply(this, arguments);
19496 Roo.extend(f, Roo.data.Record);
19497 var p = f.prototype;
19498 p.fields = new Roo.util.MixedCollection(false, function(field){
19501 for(var i = 0, len = o.length; i < len; i++){
19502 p.fields.add(new Roo.data.Field(o[i]));
19504 f.getField = function(name){
19505 return p.fields.get(name);
19510 Roo.data.Record.AUTO_ID = 1000;
19511 Roo.data.Record.EDIT = 'edit';
19512 Roo.data.Record.REJECT = 'reject';
19513 Roo.data.Record.COMMIT = 'commit';
19515 Roo.data.Record.prototype = {
19517 * Readonly flag - true if this record has been modified.
19526 join : function(store){
19527 this.store = store;
19531 * Set the named field to the specified value.
19532 * @param {String} name The name of the field to set.
19533 * @param {Object} value The value to set the field to.
19535 set : function(name, value){
19536 if(this.data[name] == value){
19540 if(!this.modified){
19541 this.modified = {};
19543 if(typeof this.modified[name] == 'undefined'){
19544 this.modified[name] = this.data[name];
19546 this.data[name] = value;
19547 if(!this.editing && this.store){
19548 this.store.afterEdit(this);
19553 * Get the value of the named field.
19554 * @param {String} name The name of the field to get the value of.
19555 * @return {Object} The value of the field.
19557 get : function(name){
19558 return this.data[name];
19562 beginEdit : function(){
19563 this.editing = true;
19564 this.modified = {};
19568 cancelEdit : function(){
19569 this.editing = false;
19570 delete this.modified;
19574 endEdit : function(){
19575 this.editing = false;
19576 if(this.dirty && this.store){
19577 this.store.afterEdit(this);
19582 * Usually called by the {@link Roo.data.Store} which owns the Record.
19583 * Rejects all changes made to the Record since either creation, or the last commit operation.
19584 * Modified fields are reverted to their original values.
19586 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
19587 * of reject operations.
19589 reject : function(){
19590 var m = this.modified;
19592 if(typeof m[n] != "function"){
19593 this.data[n] = m[n];
19596 this.dirty = false;
19597 delete this.modified;
19598 this.editing = false;
19600 this.store.afterReject(this);
19605 * Usually called by the {@link Roo.data.Store} which owns the Record.
19606 * Commits all changes made to the Record since either creation, or the last commit operation.
19608 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
19609 * of commit operations.
19611 commit : function(){
19612 this.dirty = false;
19613 delete this.modified;
19614 this.editing = false;
19616 this.store.afterCommit(this);
19621 hasError : function(){
19622 return this.error != null;
19626 clearError : function(){
19631 * Creates a copy of this record.
19632 * @param {String} id (optional) A new record id if you don't want to use this record's id
19635 copy : function(newId) {
19636 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
19640 * Ext JS Library 1.1.1
19641 * Copyright(c) 2006-2007, Ext JS, LLC.
19643 * Originally Released Under LGPL - original licence link has changed is not relivant.
19646 * <script type="text/javascript">
19652 * @class Roo.data.Store
19653 * @extends Roo.util.Observable
19654 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
19655 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
19657 * 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
19658 * has no knowledge of the format of the data returned by the Proxy.<br>
19660 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
19661 * instances from the data object. These records are cached and made available through accessor functions.
19663 * Creates a new Store.
19664 * @param {Object} config A config object containing the objects needed for the Store to access data,
19665 * and read the data into Records.
19667 Roo.data.Store = function(config){
19668 this.data = new Roo.util.MixedCollection(false);
19669 this.data.getKey = function(o){
19672 this.baseParams = {};
19674 this.paramNames = {
19679 "multisort" : "_multisort"
19682 if(config && config.data){
19683 this.inlineData = config.data;
19684 delete config.data;
19687 Roo.apply(this, config);
19689 if(this.reader){ // reader passed
19690 this.reader = Roo.factory(this.reader, Roo.data);
19691 this.reader.xmodule = this.xmodule || false;
19692 if(!this.recordType){
19693 this.recordType = this.reader.recordType;
19695 if(this.reader.onMetaChange){
19696 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
19700 if(this.recordType){
19701 this.fields = this.recordType.prototype.fields;
19703 this.modified = [];
19707 * @event datachanged
19708 * Fires when the data cache has changed, and a widget which is using this Store
19709 * as a Record cache should refresh its view.
19710 * @param {Store} this
19712 datachanged : true,
19714 * @event metachange
19715 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
19716 * @param {Store} this
19717 * @param {Object} meta The JSON metadata
19722 * Fires when Records have been added to the Store
19723 * @param {Store} this
19724 * @param {Roo.data.Record[]} records The array of Records added
19725 * @param {Number} index The index at which the record(s) were added
19730 * Fires when a Record has been removed from the Store
19731 * @param {Store} this
19732 * @param {Roo.data.Record} record The Record that was removed
19733 * @param {Number} index The index at which the record was removed
19738 * Fires when a Record has been updated
19739 * @param {Store} this
19740 * @param {Roo.data.Record} record The Record that was updated
19741 * @param {String} operation The update operation being performed. Value may be one of:
19743 Roo.data.Record.EDIT
19744 Roo.data.Record.REJECT
19745 Roo.data.Record.COMMIT
19751 * Fires when the data cache has been cleared.
19752 * @param {Store} this
19756 * @event beforeload
19757 * Fires before a request is made for a new data object. If the beforeload handler returns false
19758 * the load action will be canceled.
19759 * @param {Store} this
19760 * @param {Object} options The loading options that were specified (see {@link #load} for details)
19764 * @event beforeloadadd
19765 * Fires after a new set of Records has been loaded.
19766 * @param {Store} this
19767 * @param {Roo.data.Record[]} records The Records that were loaded
19768 * @param {Object} options The loading options that were specified (see {@link #load} for details)
19770 beforeloadadd : true,
19773 * Fires after a new set of Records has been loaded, before they are added to the store.
19774 * @param {Store} this
19775 * @param {Roo.data.Record[]} records The Records that were loaded
19776 * @param {Object} options The loading options that were specified (see {@link #load} for details)
19777 * @params {Object} return from reader
19781 * @event loadexception
19782 * Fires if an exception occurs in the Proxy during loading.
19783 * Called with the signature of the Proxy's "loadexception" event.
19784 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
19787 * @param {Object} return from JsonData.reader() - success, totalRecords, records
19788 * @param {Object} load options
19789 * @param {Object} jsonData from your request (normally this contains the Exception)
19791 loadexception : true
19795 this.proxy = Roo.factory(this.proxy, Roo.data);
19796 this.proxy.xmodule = this.xmodule || false;
19797 this.relayEvents(this.proxy, ["loadexception"]);
19799 this.sortToggle = {};
19800 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
19802 Roo.data.Store.superclass.constructor.call(this);
19804 if(this.inlineData){
19805 this.loadData(this.inlineData);
19806 delete this.inlineData;
19810 Roo.extend(Roo.data.Store, Roo.util.Observable, {
19812 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
19813 * without a remote query - used by combo/forms at present.
19817 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
19820 * @cfg {Array} data Inline data to be loaded when the store is initialized.
19823 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
19824 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
19827 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
19828 * on any HTTP request
19831 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
19834 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
19838 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
19839 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
19841 remoteSort : false,
19844 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
19845 * loaded or when a record is removed. (defaults to false).
19847 pruneModifiedRecords : false,
19850 lastOptions : null,
19853 * Add Records to the Store and fires the add event.
19854 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
19856 add : function(records){
19857 records = [].concat(records);
19858 for(var i = 0, len = records.length; i < len; i++){
19859 records[i].join(this);
19861 var index = this.data.length;
19862 this.data.addAll(records);
19863 this.fireEvent("add", this, records, index);
19867 * Remove a Record from the Store and fires the remove event.
19868 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
19870 remove : function(record){
19871 var index = this.data.indexOf(record);
19872 this.data.removeAt(index);
19873 if(this.pruneModifiedRecords){
19874 this.modified.remove(record);
19876 this.fireEvent("remove", this, record, index);
19880 * Remove all Records from the Store and fires the clear event.
19882 removeAll : function(){
19884 if(this.pruneModifiedRecords){
19885 this.modified = [];
19887 this.fireEvent("clear", this);
19891 * Inserts Records to the Store at the given index and fires the add event.
19892 * @param {Number} index The start index at which to insert the passed Records.
19893 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
19895 insert : function(index, records){
19896 records = [].concat(records);
19897 for(var i = 0, len = records.length; i < len; i++){
19898 this.data.insert(index, records[i]);
19899 records[i].join(this);
19901 this.fireEvent("add", this, records, index);
19905 * Get the index within the cache of the passed Record.
19906 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
19907 * @return {Number} The index of the passed Record. Returns -1 if not found.
19909 indexOf : function(record){
19910 return this.data.indexOf(record);
19914 * Get the index within the cache of the Record with the passed id.
19915 * @param {String} id The id of the Record to find.
19916 * @return {Number} The index of the Record. Returns -1 if not found.
19918 indexOfId : function(id){
19919 return this.data.indexOfKey(id);
19923 * Get the Record with the specified id.
19924 * @param {String} id The id of the Record to find.
19925 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
19927 getById : function(id){
19928 return this.data.key(id);
19932 * Get the Record at the specified index.
19933 * @param {Number} index The index of the Record to find.
19934 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
19936 getAt : function(index){
19937 return this.data.itemAt(index);
19941 * Returns a range of Records between specified indices.
19942 * @param {Number} startIndex (optional) The starting index (defaults to 0)
19943 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
19944 * @return {Roo.data.Record[]} An array of Records
19946 getRange : function(start, end){
19947 return this.data.getRange(start, end);
19951 storeOptions : function(o){
19952 o = Roo.apply({}, o);
19955 this.lastOptions = o;
19959 * Loads the Record cache from the configured Proxy using the configured Reader.
19961 * If using remote paging, then the first load call must specify the <em>start</em>
19962 * and <em>limit</em> properties in the options.params property to establish the initial
19963 * position within the dataset, and the number of Records to cache on each read from the Proxy.
19965 * <strong>It is important to note that for remote data sources, loading is asynchronous,
19966 * and this call will return before the new data has been loaded. Perform any post-processing
19967 * in a callback function, or in a "load" event handler.</strong>
19969 * @param {Object} options An object containing properties which control loading options:<ul>
19970 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
19971 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
19972 * passed the following arguments:<ul>
19973 * <li>r : Roo.data.Record[]</li>
19974 * <li>options: Options object from the load call</li>
19975 * <li>success: Boolean success indicator</li></ul></li>
19976 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
19977 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
19980 load : function(options){
19981 options = options || {};
19982 if(this.fireEvent("beforeload", this, options) !== false){
19983 this.storeOptions(options);
19984 var p = Roo.apply(options.params || {}, this.baseParams);
19985 // if meta was not loaded from remote source.. try requesting it.
19986 if (!this.reader.metaFromRemote) {
19987 p._requestMeta = 1;
19989 if(this.sortInfo && this.remoteSort){
19990 var pn = this.paramNames;
19991 p[pn["sort"]] = this.sortInfo.field;
19992 p[pn["dir"]] = this.sortInfo.direction;
19994 if (this.multiSort) {
19995 var pn = this.paramNames;
19996 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
19999 this.proxy.load(p, this.reader, this.loadRecords, this, options);
20004 * Reloads the Record cache from the configured Proxy using the configured Reader and
20005 * the options from the last load operation performed.
20006 * @param {Object} options (optional) An object containing properties which may override the options
20007 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
20008 * the most recently used options are reused).
20010 reload : function(options){
20011 this.load(Roo.applyIf(options||{}, this.lastOptions));
20015 // Called as a callback by the Reader during a load operation.
20016 loadRecords : function(o, options, success){
20017 if(!o || success === false){
20018 if(success !== false){
20019 this.fireEvent("load", this, [], options, o);
20021 if(options.callback){
20022 options.callback.call(options.scope || this, [], options, false);
20026 // if data returned failure - throw an exception.
20027 if (o.success === false) {
20028 // show a message if no listener is registered.
20029 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
20030 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
20032 // loadmask wil be hooked into this..
20033 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
20036 var r = o.records, t = o.totalRecords || r.length;
20038 this.fireEvent("beforeloadadd", this, r, options, o);
20040 if(!options || options.add !== true){
20041 if(this.pruneModifiedRecords){
20042 this.modified = [];
20044 for(var i = 0, len = r.length; i < len; i++){
20048 this.data = this.snapshot;
20049 delete this.snapshot;
20052 this.data.addAll(r);
20053 this.totalLength = t;
20055 this.fireEvent("datachanged", this);
20057 this.totalLength = Math.max(t, this.data.length+r.length);
20060 this.fireEvent("load", this, r, options, o);
20061 if(options.callback){
20062 options.callback.call(options.scope || this, r, options, true);
20068 * Loads data from a passed data block. A Reader which understands the format of the data
20069 * must have been configured in the constructor.
20070 * @param {Object} data The data block from which to read the Records. The format of the data expected
20071 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
20072 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
20074 loadData : function(o, append){
20075 var r = this.reader.readRecords(o);
20076 this.loadRecords(r, {add: append}, true);
20080 * Gets the number of cached records.
20082 * <em>If using paging, this may not be the total size of the dataset. If the data object
20083 * used by the Reader contains the dataset size, then the getTotalCount() function returns
20084 * the data set size</em>
20086 getCount : function(){
20087 return this.data.length || 0;
20091 * Gets the total number of records in the dataset as returned by the server.
20093 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
20094 * the dataset size</em>
20096 getTotalCount : function(){
20097 return this.totalLength || 0;
20101 * Returns the sort state of the Store as an object with two properties:
20103 field {String} The name of the field by which the Records are sorted
20104 direction {String} The sort order, "ASC" or "DESC"
20107 getSortState : function(){
20108 return this.sortInfo;
20112 applySort : function(){
20113 if(this.sortInfo && !this.remoteSort){
20114 var s = this.sortInfo, f = s.field;
20115 var st = this.fields.get(f).sortType;
20116 var fn = function(r1, r2){
20117 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
20118 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
20120 this.data.sort(s.direction, fn);
20121 if(this.snapshot && this.snapshot != this.data){
20122 this.snapshot.sort(s.direction, fn);
20128 * Sets the default sort column and order to be used by the next load operation.
20129 * @param {String} fieldName The name of the field to sort by.
20130 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
20132 setDefaultSort : function(field, dir){
20133 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
20137 * Sort the Records.
20138 * If remote sorting is used, the sort is performed on the server, and the cache is
20139 * reloaded. If local sorting is used, the cache is sorted internally.
20140 * @param {String} fieldName The name of the field to sort by.
20141 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
20143 sort : function(fieldName, dir){
20144 var f = this.fields.get(fieldName);
20146 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
20148 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
20149 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
20154 this.sortToggle[f.name] = dir;
20155 this.sortInfo = {field: f.name, direction: dir};
20156 if(!this.remoteSort){
20158 this.fireEvent("datachanged", this);
20160 this.load(this.lastOptions);
20165 * Calls the specified function for each of the Records in the cache.
20166 * @param {Function} fn The function to call. The Record is passed as the first parameter.
20167 * Returning <em>false</em> aborts and exits the iteration.
20168 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
20170 each : function(fn, scope){
20171 this.data.each(fn, scope);
20175 * Gets all records modified since the last commit. Modified records are persisted across load operations
20176 * (e.g., during paging).
20177 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
20179 getModifiedRecords : function(){
20180 return this.modified;
20184 createFilterFn : function(property, value, anyMatch){
20185 if(!value.exec){ // not a regex
20186 value = String(value);
20187 if(value.length == 0){
20190 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
20192 return function(r){
20193 return value.test(r.data[property]);
20198 * Sums the value of <i>property</i> for each record between start and end and returns the result.
20199 * @param {String} property A field on your records
20200 * @param {Number} start The record index to start at (defaults to 0)
20201 * @param {Number} end The last record index to include (defaults to length - 1)
20202 * @return {Number} The sum
20204 sum : function(property, start, end){
20205 var rs = this.data.items, v = 0;
20206 start = start || 0;
20207 end = (end || end === 0) ? end : rs.length-1;
20209 for(var i = start; i <= end; i++){
20210 v += (rs[i].data[property] || 0);
20216 * Filter the records by a specified property.
20217 * @param {String} field A field on your records
20218 * @param {String/RegExp} value Either a string that the field
20219 * should start with or a RegExp to test against the field
20220 * @param {Boolean} anyMatch True to match any part not just the beginning
20222 filter : function(property, value, anyMatch){
20223 var fn = this.createFilterFn(property, value, anyMatch);
20224 return fn ? this.filterBy(fn) : this.clearFilter();
20228 * Filter by a function. The specified function will be called with each
20229 * record in this data source. If the function returns true the record is included,
20230 * otherwise it is filtered.
20231 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
20232 * @param {Object} scope (optional) The scope of the function (defaults to this)
20234 filterBy : function(fn, scope){
20235 this.snapshot = this.snapshot || this.data;
20236 this.data = this.queryBy(fn, scope||this);
20237 this.fireEvent("datachanged", this);
20241 * Query the records by a specified property.
20242 * @param {String} field A field on your records
20243 * @param {String/RegExp} value Either a string that the field
20244 * should start with or a RegExp to test against the field
20245 * @param {Boolean} anyMatch True to match any part not just the beginning
20246 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
20248 query : function(property, value, anyMatch){
20249 var fn = this.createFilterFn(property, value, anyMatch);
20250 return fn ? this.queryBy(fn) : this.data.clone();
20254 * Query by a function. The specified function will be called with each
20255 * record in this data source. If the function returns true the record is included
20257 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
20258 * @param {Object} scope (optional) The scope of the function (defaults to this)
20259 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
20261 queryBy : function(fn, scope){
20262 var data = this.snapshot || this.data;
20263 return data.filterBy(fn, scope||this);
20267 * Collects unique values for a particular dataIndex from this store.
20268 * @param {String} dataIndex The property to collect
20269 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
20270 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
20271 * @return {Array} An array of the unique values
20273 collect : function(dataIndex, allowNull, bypassFilter){
20274 var d = (bypassFilter === true && this.snapshot) ?
20275 this.snapshot.items : this.data.items;
20276 var v, sv, r = [], l = {};
20277 for(var i = 0, len = d.length; i < len; i++){
20278 v = d[i].data[dataIndex];
20280 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
20289 * Revert to a view of the Record cache with no filtering applied.
20290 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
20292 clearFilter : function(suppressEvent){
20293 if(this.snapshot && this.snapshot != this.data){
20294 this.data = this.snapshot;
20295 delete this.snapshot;
20296 if(suppressEvent !== true){
20297 this.fireEvent("datachanged", this);
20303 afterEdit : function(record){
20304 if(this.modified.indexOf(record) == -1){
20305 this.modified.push(record);
20307 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
20311 afterReject : function(record){
20312 this.modified.remove(record);
20313 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
20317 afterCommit : function(record){
20318 this.modified.remove(record);
20319 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
20323 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
20324 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
20326 commitChanges : function(){
20327 var m = this.modified.slice(0);
20328 this.modified = [];
20329 for(var i = 0, len = m.length; i < len; i++){
20335 * Cancel outstanding changes on all changed records.
20337 rejectChanges : function(){
20338 var m = this.modified.slice(0);
20339 this.modified = [];
20340 for(var i = 0, len = m.length; i < len; i++){
20345 onMetaChange : function(meta, rtype, o){
20346 this.recordType = rtype;
20347 this.fields = rtype.prototype.fields;
20348 delete this.snapshot;
20349 this.sortInfo = meta.sortInfo || this.sortInfo;
20350 this.modified = [];
20351 this.fireEvent('metachange', this, this.reader.meta);
20355 * Ext JS Library 1.1.1
20356 * Copyright(c) 2006-2007, Ext JS, LLC.
20358 * Originally Released Under LGPL - original licence link has changed is not relivant.
20361 * <script type="text/javascript">
20365 * @class Roo.data.SimpleStore
20366 * @extends Roo.data.Store
20367 * Small helper class to make creating Stores from Array data easier.
20368 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
20369 * @cfg {Array} fields An array of field definition objects, or field name strings.
20370 * @cfg {Array} data The multi-dimensional array of data
20372 * @param {Object} config
20374 Roo.data.SimpleStore = function(config){
20375 Roo.data.SimpleStore.superclass.constructor.call(this, {
20377 reader: new Roo.data.ArrayReader({
20380 Roo.data.Record.create(config.fields)
20382 proxy : new Roo.data.MemoryProxy(config.data)
20386 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
20388 * Ext JS Library 1.1.1
20389 * Copyright(c) 2006-2007, Ext JS, LLC.
20391 * Originally Released Under LGPL - original licence link has changed is not relivant.
20394 * <script type="text/javascript">
20399 * @extends Roo.data.Store
20400 * @class Roo.data.JsonStore
20401 * Small helper class to make creating Stores for JSON data easier. <br/>
20403 var store = new Roo.data.JsonStore({
20404 url: 'get-images.php',
20406 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
20409 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
20410 * JsonReader and HttpProxy (unless inline data is provided).</b>
20411 * @cfg {Array} fields An array of field definition objects, or field name strings.
20413 * @param {Object} config
20415 Roo.data.JsonStore = function(c){
20416 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
20417 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
20418 reader: new Roo.data.JsonReader(c, c.fields)
20421 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
20423 * Ext JS Library 1.1.1
20424 * Copyright(c) 2006-2007, Ext JS, LLC.
20426 * Originally Released Under LGPL - original licence link has changed is not relivant.
20429 * <script type="text/javascript">
20433 Roo.data.Field = function(config){
20434 if(typeof config == "string"){
20435 config = {name: config};
20437 Roo.apply(this, config);
20440 this.type = "auto";
20443 var st = Roo.data.SortTypes;
20444 // named sortTypes are supported, here we look them up
20445 if(typeof this.sortType == "string"){
20446 this.sortType = st[this.sortType];
20449 // set default sortType for strings and dates
20450 if(!this.sortType){
20453 this.sortType = st.asUCString;
20456 this.sortType = st.asDate;
20459 this.sortType = st.none;
20464 var stripRe = /[\$,%]/g;
20466 // prebuilt conversion function for this field, instead of
20467 // switching every time we're reading a value
20469 var cv, dateFormat = this.dateFormat;
20474 cv = function(v){ return v; };
20477 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
20481 return v !== undefined && v !== null && v !== '' ?
20482 parseInt(String(v).replace(stripRe, ""), 10) : '';
20487 return v !== undefined && v !== null && v !== '' ?
20488 parseFloat(String(v).replace(stripRe, ""), 10) : '';
20493 cv = function(v){ return v === true || v === "true" || v == 1; };
20500 if(v instanceof Date){
20504 if(dateFormat == "timestamp"){
20505 return new Date(v*1000);
20507 return Date.parseDate(v, dateFormat);
20509 var parsed = Date.parse(v);
20510 return parsed ? new Date(parsed) : null;
20519 Roo.data.Field.prototype = {
20527 * Ext JS Library 1.1.1
20528 * Copyright(c) 2006-2007, Ext JS, LLC.
20530 * Originally Released Under LGPL - original licence link has changed is not relivant.
20533 * <script type="text/javascript">
20536 // Base class for reading structured data from a data source. This class is intended to be
20537 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
20540 * @class Roo.data.DataReader
20541 * Base class for reading structured data from a data source. This class is intended to be
20542 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
20545 Roo.data.DataReader = function(meta, recordType){
20549 this.recordType = recordType instanceof Array ?
20550 Roo.data.Record.create(recordType) : recordType;
20553 Roo.data.DataReader.prototype = {
20555 * Create an empty record
20556 * @param {Object} data (optional) - overlay some values
20557 * @return {Roo.data.Record} record created.
20559 newRow : function(d) {
20561 this.recordType.prototype.fields.each(function(c) {
20563 case 'int' : da[c.name] = 0; break;
20564 case 'date' : da[c.name] = new Date(); break;
20565 case 'float' : da[c.name] = 0.0; break;
20566 case 'boolean' : da[c.name] = false; break;
20567 default : da[c.name] = ""; break;
20571 return new this.recordType(Roo.apply(da, d));
20576 * Ext JS Library 1.1.1
20577 * Copyright(c) 2006-2007, Ext JS, LLC.
20579 * Originally Released Under LGPL - original licence link has changed is not relivant.
20582 * <script type="text/javascript">
20586 * @class Roo.data.DataProxy
20587 * @extends Roo.data.Observable
20588 * This class is an abstract base class for implementations which provide retrieval of
20589 * unformatted data objects.<br>
20591 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
20592 * (of the appropriate type which knows how to parse the data object) to provide a block of
20593 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
20595 * Custom implementations must implement the load method as described in
20596 * {@link Roo.data.HttpProxy#load}.
20598 Roo.data.DataProxy = function(){
20601 * @event beforeload
20602 * Fires before a network request is made to retrieve a data object.
20603 * @param {Object} This DataProxy object.
20604 * @param {Object} params The params parameter to the load function.
20609 * Fires before the load method's callback is called.
20610 * @param {Object} This DataProxy object.
20611 * @param {Object} o The data object.
20612 * @param {Object} arg The callback argument object passed to the load function.
20616 * @event loadexception
20617 * Fires if an Exception occurs during data retrieval.
20618 * @param {Object} This DataProxy object.
20619 * @param {Object} o The data object.
20620 * @param {Object} arg The callback argument object passed to the load function.
20621 * @param {Object} e The Exception.
20623 loadexception : true
20625 Roo.data.DataProxy.superclass.constructor.call(this);
20628 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
20631 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
20635 * Ext JS Library 1.1.1
20636 * Copyright(c) 2006-2007, Ext JS, LLC.
20638 * Originally Released Under LGPL - original licence link has changed is not relivant.
20641 * <script type="text/javascript">
20644 * @class Roo.data.MemoryProxy
20645 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
20646 * to the Reader when its load method is called.
20648 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
20650 Roo.data.MemoryProxy = function(data){
20654 Roo.data.MemoryProxy.superclass.constructor.call(this);
20658 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
20660 * Load data from the requested source (in this case an in-memory
20661 * data object passed to the constructor), read the data object into
20662 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
20663 * process that block using the passed callback.
20664 * @param {Object} params This parameter is not used by the MemoryProxy class.
20665 * @param {Roo.data.DataReader} reader The Reader object which converts the data
20666 * object into a block of Roo.data.Records.
20667 * @param {Function} callback The function into which to pass the block of Roo.data.records.
20668 * The function must be passed <ul>
20669 * <li>The Record block object</li>
20670 * <li>The "arg" argument from the load function</li>
20671 * <li>A boolean success indicator</li>
20673 * @param {Object} scope The scope in which to call the callback
20674 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
20676 load : function(params, reader, callback, scope, arg){
20677 params = params || {};
20680 result = reader.readRecords(this.data);
20682 this.fireEvent("loadexception", this, arg, null, e);
20683 callback.call(scope, null, arg, false);
20686 callback.call(scope, result, arg, true);
20690 update : function(params, records){
20695 * Ext JS Library 1.1.1
20696 * Copyright(c) 2006-2007, Ext JS, LLC.
20698 * Originally Released Under LGPL - original licence link has changed is not relivant.
20701 * <script type="text/javascript">
20704 * @class Roo.data.HttpProxy
20705 * @extends Roo.data.DataProxy
20706 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
20707 * configured to reference a certain URL.<br><br>
20709 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
20710 * from which the running page was served.<br><br>
20712 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
20714 * Be aware that to enable the browser to parse an XML document, the server must set
20715 * the Content-Type header in the HTTP response to "text/xml".
20717 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
20718 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
20719 * will be used to make the request.
20721 Roo.data.HttpProxy = function(conn){
20722 Roo.data.HttpProxy.superclass.constructor.call(this);
20723 // is conn a conn config or a real conn?
20725 this.useAjax = !conn || !conn.events;
20729 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
20730 // thse are take from connection...
20733 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
20736 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
20737 * extra parameters to each request made by this object. (defaults to undefined)
20740 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
20741 * to each request made by this object. (defaults to undefined)
20744 * @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)
20747 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
20750 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
20756 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
20760 * Return the {@link Roo.data.Connection} object being used by this Proxy.
20761 * @return {Connection} The Connection object. This object may be used to subscribe to events on
20762 * a finer-grained basis than the DataProxy events.
20764 getConnection : function(){
20765 return this.useAjax ? Roo.Ajax : this.conn;
20769 * Load data from the configured {@link Roo.data.Connection}, read the data object into
20770 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
20771 * process that block using the passed callback.
20772 * @param {Object} params An object containing properties which are to be used as HTTP parameters
20773 * for the request to the remote server.
20774 * @param {Roo.data.DataReader} reader The Reader object which converts the data
20775 * object into a block of Roo.data.Records.
20776 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
20777 * The function must be passed <ul>
20778 * <li>The Record block object</li>
20779 * <li>The "arg" argument from the load function</li>
20780 * <li>A boolean success indicator</li>
20782 * @param {Object} scope The scope in which to call the callback
20783 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
20785 load : function(params, reader, callback, scope, arg){
20786 if(this.fireEvent("beforeload", this, params) !== false){
20788 params : params || {},
20790 callback : callback,
20795 callback : this.loadResponse,
20799 Roo.applyIf(o, this.conn);
20800 if(this.activeRequest){
20801 Roo.Ajax.abort(this.activeRequest);
20803 this.activeRequest = Roo.Ajax.request(o);
20805 this.conn.request(o);
20808 callback.call(scope||this, null, arg, false);
20813 loadResponse : function(o, success, response){
20814 delete this.activeRequest;
20816 this.fireEvent("loadexception", this, o, response);
20817 o.request.callback.call(o.request.scope, null, o.request.arg, false);
20822 result = o.reader.read(response);
20824 this.fireEvent("loadexception", this, o, response, e);
20825 o.request.callback.call(o.request.scope, null, o.request.arg, false);
20829 this.fireEvent("load", this, o, o.request.arg);
20830 o.request.callback.call(o.request.scope, result, o.request.arg, true);
20834 update : function(dataSet){
20839 updateResponse : function(dataSet){
20844 * Ext JS Library 1.1.1
20845 * Copyright(c) 2006-2007, Ext JS, LLC.
20847 * Originally Released Under LGPL - original licence link has changed is not relivant.
20850 * <script type="text/javascript">
20854 * @class Roo.data.ScriptTagProxy
20855 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
20856 * other than the originating domain of the running page.<br><br>
20858 * <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
20859 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
20861 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
20862 * source code that is used as the source inside a <script> tag.<br><br>
20864 * In order for the browser to process the returned data, the server must wrap the data object
20865 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
20866 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
20867 * depending on whether the callback name was passed:
20870 boolean scriptTag = false;
20871 String cb = request.getParameter("callback");
20874 response.setContentType("text/javascript");
20876 response.setContentType("application/x-json");
20878 Writer out = response.getWriter();
20880 out.write(cb + "(");
20882 out.print(dataBlock.toJsonString());
20889 * @param {Object} config A configuration object.
20891 Roo.data.ScriptTagProxy = function(config){
20892 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
20893 Roo.apply(this, config);
20894 this.head = document.getElementsByTagName("head")[0];
20897 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
20899 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
20901 * @cfg {String} url The URL from which to request the data object.
20904 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
20908 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
20909 * the server the name of the callback function set up by the load call to process the returned data object.
20910 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
20911 * javascript output which calls this named function passing the data object as its only parameter.
20913 callbackParam : "callback",
20915 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
20916 * name to the request.
20921 * Load data from the configured URL, read the data object into
20922 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
20923 * process that block using the passed callback.
20924 * @param {Object} params An object containing properties which are to be used as HTTP parameters
20925 * for the request to the remote server.
20926 * @param {Roo.data.DataReader} reader The Reader object which converts the data
20927 * object into a block of Roo.data.Records.
20928 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
20929 * The function must be passed <ul>
20930 * <li>The Record block object</li>
20931 * <li>The "arg" argument from the load function</li>
20932 * <li>A boolean success indicator</li>
20934 * @param {Object} scope The scope in which to call the callback
20935 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
20937 load : function(params, reader, callback, scope, arg){
20938 if(this.fireEvent("beforeload", this, params) !== false){
20940 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
20942 var url = this.url;
20943 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
20945 url += "&_dc=" + (new Date().getTime());
20947 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
20950 cb : "stcCallback"+transId,
20951 scriptId : "stcScript"+transId,
20955 callback : callback,
20961 window[trans.cb] = function(o){
20962 conn.handleResponse(o, trans);
20965 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
20967 if(this.autoAbort !== false){
20971 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
20973 var script = document.createElement("script");
20974 script.setAttribute("src", url);
20975 script.setAttribute("type", "text/javascript");
20976 script.setAttribute("id", trans.scriptId);
20977 this.head.appendChild(script);
20979 this.trans = trans;
20981 callback.call(scope||this, null, arg, false);
20986 isLoading : function(){
20987 return this.trans ? true : false;
20991 * Abort the current server request.
20993 abort : function(){
20994 if(this.isLoading()){
20995 this.destroyTrans(this.trans);
21000 destroyTrans : function(trans, isLoaded){
21001 this.head.removeChild(document.getElementById(trans.scriptId));
21002 clearTimeout(trans.timeoutId);
21004 window[trans.cb] = undefined;
21006 delete window[trans.cb];
21009 // if hasn't been loaded, wait for load to remove it to prevent script error
21010 window[trans.cb] = function(){
21011 window[trans.cb] = undefined;
21013 delete window[trans.cb];
21020 handleResponse : function(o, trans){
21021 this.trans = false;
21022 this.destroyTrans(trans, true);
21025 result = trans.reader.readRecords(o);
21027 this.fireEvent("loadexception", this, o, trans.arg, e);
21028 trans.callback.call(trans.scope||window, null, trans.arg, false);
21031 this.fireEvent("load", this, o, trans.arg);
21032 trans.callback.call(trans.scope||window, result, trans.arg, true);
21036 handleFailure : function(trans){
21037 this.trans = false;
21038 this.destroyTrans(trans, false);
21039 this.fireEvent("loadexception", this, null, trans.arg);
21040 trans.callback.call(trans.scope||window, null, trans.arg, false);
21044 * Ext JS Library 1.1.1
21045 * Copyright(c) 2006-2007, Ext JS, LLC.
21047 * Originally Released Under LGPL - original licence link has changed is not relivant.
21050 * <script type="text/javascript">
21054 * @class Roo.data.JsonReader
21055 * @extends Roo.data.DataReader
21056 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
21057 * based on mappings in a provided Roo.data.Record constructor.
21059 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
21060 * in the reply previously.
21065 var RecordDef = Roo.data.Record.create([
21066 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
21067 {name: 'occupation'} // This field will use "occupation" as the mapping.
21069 var myReader = new Roo.data.JsonReader({
21070 totalProperty: "results", // The property which contains the total dataset size (optional)
21071 root: "rows", // The property which contains an Array of row objects
21072 id: "id" // The property within each row object that provides an ID for the record (optional)
21076 * This would consume a JSON file like this:
21078 { 'results': 2, 'rows': [
21079 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
21080 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
21083 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
21084 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
21085 * paged from the remote server.
21086 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
21087 * @cfg {String} root name of the property which contains the Array of row objects.
21088 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
21090 * Create a new JsonReader
21091 * @param {Object} meta Metadata configuration options
21092 * @param {Object} recordType Either an Array of field definition objects,
21093 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
21095 Roo.data.JsonReader = function(meta, recordType){
21098 // set some defaults:
21099 Roo.applyIf(meta, {
21100 totalProperty: 'total',
21101 successProperty : 'success',
21106 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
21108 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
21111 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
21112 * Used by Store query builder to append _requestMeta to params.
21115 metaFromRemote : false,
21117 * This method is only used by a DataProxy which has retrieved data from a remote server.
21118 * @param {Object} response The XHR object which contains the JSON data in its responseText.
21119 * @return {Object} data A data block which is used by an Roo.data.Store object as
21120 * a cache of Roo.data.Records.
21122 read : function(response){
21123 var json = response.responseText;
21125 var o = /* eval:var:o */ eval("("+json+")");
21127 throw {message: "JsonReader.read: Json object not found"};
21133 this.metaFromRemote = true;
21134 this.meta = o.metaData;
21135 this.recordType = Roo.data.Record.create(o.metaData.fields);
21136 this.onMetaChange(this.meta, this.recordType, o);
21138 return this.readRecords(o);
21141 // private function a store will implement
21142 onMetaChange : function(meta, recordType, o){
21149 simpleAccess: function(obj, subsc) {
21156 getJsonAccessor: function(){
21158 return function(expr) {
21160 return(re.test(expr))
21161 ? new Function("obj", "return obj." + expr)
21166 return Roo.emptyFn;
21171 * Create a data block containing Roo.data.Records from an XML document.
21172 * @param {Object} o An object which contains an Array of row objects in the property specified
21173 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
21174 * which contains the total size of the dataset.
21175 * @return {Object} data A data block which is used by an Roo.data.Store object as
21176 * a cache of Roo.data.Records.
21178 readRecords : function(o){
21180 * After any data loads, the raw JSON data is available for further custom processing.
21184 var s = this.meta, Record = this.recordType,
21185 f = Record.prototype.fields, fi = f.items, fl = f.length;
21187 // Generate extraction functions for the totalProperty, the root, the id, and for each field
21189 if(s.totalProperty) {
21190 this.getTotal = this.getJsonAccessor(s.totalProperty);
21192 if(s.successProperty) {
21193 this.getSuccess = this.getJsonAccessor(s.successProperty);
21195 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
21197 var g = this.getJsonAccessor(s.id);
21198 this.getId = function(rec) {
21200 return (r === undefined || r === "") ? null : r;
21203 this.getId = function(){return null;};
21206 for(var jj = 0; jj < fl; jj++){
21208 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
21209 this.ef[jj] = this.getJsonAccessor(map);
21213 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
21214 if(s.totalProperty){
21215 var vt = parseInt(this.getTotal(o), 10);
21220 if(s.successProperty){
21221 var vs = this.getSuccess(o);
21222 if(vs === false || vs === 'false'){
21227 for(var i = 0; i < c; i++){
21230 var id = this.getId(n);
21231 for(var j = 0; j < fl; j++){
21233 var v = this.ef[j](n);
21235 Roo.log('missing convert for ' + f.name);
21239 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
21241 var record = new Record(values, id);
21243 records[i] = record;
21249 totalRecords : totalRecords
21254 * Ext JS Library 1.1.1
21255 * Copyright(c) 2006-2007, Ext JS, LLC.
21257 * Originally Released Under LGPL - original licence link has changed is not relivant.
21260 * <script type="text/javascript">
21264 * @class Roo.data.XmlReader
21265 * @extends Roo.data.DataReader
21266 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
21267 * based on mappings in a provided Roo.data.Record constructor.<br><br>
21269 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
21270 * header in the HTTP response must be set to "text/xml".</em>
21274 var RecordDef = Roo.data.Record.create([
21275 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
21276 {name: 'occupation'} // This field will use "occupation" as the mapping.
21278 var myReader = new Roo.data.XmlReader({
21279 totalRecords: "results", // The element which contains the total dataset size (optional)
21280 record: "row", // The repeated element which contains row information
21281 id: "id" // The element within the row that provides an ID for the record (optional)
21285 * This would consume an XML file like this:
21289 <results>2</results>
21292 <name>Bill</name>
21293 <occupation>Gardener</occupation>
21297 <name>Ben</name>
21298 <occupation>Horticulturalist</occupation>
21302 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
21303 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
21304 * paged from the remote server.
21305 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
21306 * @cfg {String} success The DomQuery path to the success attribute used by forms.
21307 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
21308 * a record identifier value.
21310 * Create a new XmlReader
21311 * @param {Object} meta Metadata configuration options
21312 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
21313 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
21314 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
21316 Roo.data.XmlReader = function(meta, recordType){
21318 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
21320 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
21322 * This method is only used by a DataProxy which has retrieved data from a remote server.
21323 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
21324 * to contain a method called 'responseXML' that returns an XML document object.
21325 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
21326 * a cache of Roo.data.Records.
21328 read : function(response){
21329 var doc = response.responseXML;
21331 throw {message: "XmlReader.read: XML Document not available"};
21333 return this.readRecords(doc);
21337 * Create a data block containing Roo.data.Records from an XML document.
21338 * @param {Object} doc A parsed XML document.
21339 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
21340 * a cache of Roo.data.Records.
21342 readRecords : function(doc){
21344 * After any data loads/reads, the raw XML Document is available for further custom processing.
21345 * @type XMLDocument
21347 this.xmlData = doc;
21348 var root = doc.documentElement || doc;
21349 var q = Roo.DomQuery;
21350 var recordType = this.recordType, fields = recordType.prototype.fields;
21351 var sid = this.meta.id;
21352 var totalRecords = 0, success = true;
21353 if(this.meta.totalRecords){
21354 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
21357 if(this.meta.success){
21358 var sv = q.selectValue(this.meta.success, root, true);
21359 success = sv !== false && sv !== 'false';
21362 var ns = q.select(this.meta.record, root);
21363 for(var i = 0, len = ns.length; i < len; i++) {
21366 var id = sid ? q.selectValue(sid, n) : undefined;
21367 for(var j = 0, jlen = fields.length; j < jlen; j++){
21368 var f = fields.items[j];
21369 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
21371 values[f.name] = v;
21373 var record = new recordType(values, id);
21375 records[records.length] = record;
21381 totalRecords : totalRecords || records.length
21386 * Ext JS Library 1.1.1
21387 * Copyright(c) 2006-2007, Ext JS, LLC.
21389 * Originally Released Under LGPL - original licence link has changed is not relivant.
21392 * <script type="text/javascript">
21396 * @class Roo.data.ArrayReader
21397 * @extends Roo.data.DataReader
21398 * Data reader class to create an Array of Roo.data.Record objects from an Array.
21399 * Each element of that Array represents a row of data fields. The
21400 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
21401 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
21405 var RecordDef = Roo.data.Record.create([
21406 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
21407 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
21409 var myReader = new Roo.data.ArrayReader({
21410 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
21414 * This would consume an Array like this:
21416 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
21418 * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
21420 * Create a new JsonReader
21421 * @param {Object} meta Metadata configuration options.
21422 * @param {Object} recordType Either an Array of field definition objects
21423 * as specified to {@link Roo.data.Record#create},
21424 * or an {@link Roo.data.Record} object
21425 * created using {@link Roo.data.Record#create}.
21427 Roo.data.ArrayReader = function(meta, recordType){
21428 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
21431 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
21433 * Create a data block containing Roo.data.Records from an XML document.
21434 * @param {Object} o An Array of row objects which represents the dataset.
21435 * @return {Object} data A data block which is used by an Roo.data.Store object as
21436 * a cache of Roo.data.Records.
21438 readRecords : function(o){
21439 var sid = this.meta ? this.meta.id : null;
21440 var recordType = this.recordType, fields = recordType.prototype.fields;
21443 for(var i = 0; i < root.length; i++){
21446 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
21447 for(var j = 0, jlen = fields.length; j < jlen; j++){
21448 var f = fields.items[j];
21449 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
21450 var v = n[k] !== undefined ? n[k] : f.defaultValue;
21452 values[f.name] = v;
21454 var record = new recordType(values, id);
21456 records[records.length] = record;
21460 totalRecords : records.length
21465 * Ext JS Library 1.1.1
21466 * Copyright(c) 2006-2007, Ext JS, LLC.
21468 * Originally Released Under LGPL - original licence link has changed is not relivant.
21471 * <script type="text/javascript">
21476 * @class Roo.data.Tree
21477 * @extends Roo.util.Observable
21478 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
21479 * in the tree have most standard DOM functionality.
21481 * @param {Node} root (optional) The root node
21483 Roo.data.Tree = function(root){
21484 this.nodeHash = {};
21486 * The root node for this tree
21491 this.setRootNode(root);
21496 * Fires when a new child node is appended to a node in this tree.
21497 * @param {Tree} tree The owner tree
21498 * @param {Node} parent The parent node
21499 * @param {Node} node The newly appended node
21500 * @param {Number} index The index of the newly appended node
21505 * Fires when a child node is removed from a node in this tree.
21506 * @param {Tree} tree The owner tree
21507 * @param {Node} parent The parent node
21508 * @param {Node} node The child node removed
21513 * Fires when a node is moved to a new location in the tree
21514 * @param {Tree} tree The owner tree
21515 * @param {Node} node The node moved
21516 * @param {Node} oldParent The old parent of this node
21517 * @param {Node} newParent The new parent of this node
21518 * @param {Number} index The index it was moved to
21523 * Fires when a new child node is inserted in a node in this tree.
21524 * @param {Tree} tree The owner tree
21525 * @param {Node} parent The parent node
21526 * @param {Node} node The child node inserted
21527 * @param {Node} refNode The child node the node was inserted before
21531 * @event beforeappend
21532 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
21533 * @param {Tree} tree The owner tree
21534 * @param {Node} parent The parent node
21535 * @param {Node} node The child node to be appended
21537 "beforeappend" : true,
21539 * @event beforeremove
21540 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
21541 * @param {Tree} tree The owner tree
21542 * @param {Node} parent The parent node
21543 * @param {Node} node The child node to be removed
21545 "beforeremove" : true,
21547 * @event beforemove
21548 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
21549 * @param {Tree} tree The owner tree
21550 * @param {Node} node The node being moved
21551 * @param {Node} oldParent The parent of the node
21552 * @param {Node} newParent The new parent the node is moving to
21553 * @param {Number} index The index it is being moved to
21555 "beforemove" : true,
21557 * @event beforeinsert
21558 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
21559 * @param {Tree} tree The owner tree
21560 * @param {Node} parent The parent node
21561 * @param {Node} node The child node to be inserted
21562 * @param {Node} refNode The child node the node is being inserted before
21564 "beforeinsert" : true
21567 Roo.data.Tree.superclass.constructor.call(this);
21570 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
21571 pathSeparator: "/",
21573 proxyNodeEvent : function(){
21574 return this.fireEvent.apply(this, arguments);
21578 * Returns the root node for this tree.
21581 getRootNode : function(){
21586 * Sets the root node for this tree.
21587 * @param {Node} node
21590 setRootNode : function(node){
21592 node.ownerTree = this;
21593 node.isRoot = true;
21594 this.registerNode(node);
21599 * Gets a node in this tree by its id.
21600 * @param {String} id
21603 getNodeById : function(id){
21604 return this.nodeHash[id];
21607 registerNode : function(node){
21608 this.nodeHash[node.id] = node;
21611 unregisterNode : function(node){
21612 delete this.nodeHash[node.id];
21615 toString : function(){
21616 return "[Tree"+(this.id?" "+this.id:"")+"]";
21621 * @class Roo.data.Node
21622 * @extends Roo.util.Observable
21623 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
21624 * @cfg {String} id The id for this node. If one is not specified, one is generated.
21626 * @param {Object} attributes The attributes/config for the node
21628 Roo.data.Node = function(attributes){
21630 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
21633 this.attributes = attributes || {};
21634 this.leaf = this.attributes.leaf;
21636 * The node id. @type String
21638 this.id = this.attributes.id;
21640 this.id = Roo.id(null, "ynode-");
21641 this.attributes.id = this.id;
21646 * All child nodes of this node. @type Array
21648 this.childNodes = [];
21649 if(!this.childNodes.indexOf){ // indexOf is a must
21650 this.childNodes.indexOf = function(o){
21651 for(var i = 0, len = this.length; i < len; i++){
21660 * The parent node for this node. @type Node
21662 this.parentNode = null;
21664 * The first direct child node of this node, or null if this node has no child nodes. @type Node
21666 this.firstChild = null;
21668 * The last direct child node of this node, or null if this node has no child nodes. @type Node
21670 this.lastChild = null;
21672 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
21674 this.previousSibling = null;
21676 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
21678 this.nextSibling = null;
21683 * Fires when a new child node is appended
21684 * @param {Tree} tree The owner tree
21685 * @param {Node} this This node
21686 * @param {Node} node The newly appended node
21687 * @param {Number} index The index of the newly appended node
21692 * Fires when a child node is removed
21693 * @param {Tree} tree The owner tree
21694 * @param {Node} this This node
21695 * @param {Node} node The removed node
21700 * Fires when this node is moved to a new location in the tree
21701 * @param {Tree} tree The owner tree
21702 * @param {Node} this This node
21703 * @param {Node} oldParent The old parent of this node
21704 * @param {Node} newParent The new parent of this node
21705 * @param {Number} index The index it was moved to
21710 * Fires when a new child node is inserted.
21711 * @param {Tree} tree The owner tree
21712 * @param {Node} this This node
21713 * @param {Node} node The child node inserted
21714 * @param {Node} refNode The child node the node was inserted before
21718 * @event beforeappend
21719 * Fires before a new child is appended, return false to cancel the append.
21720 * @param {Tree} tree The owner tree
21721 * @param {Node} this This node
21722 * @param {Node} node The child node to be appended
21724 "beforeappend" : true,
21726 * @event beforeremove
21727 * Fires before a child is removed, return false to cancel the remove.
21728 * @param {Tree} tree The owner tree
21729 * @param {Node} this This node
21730 * @param {Node} node The child node to be removed
21732 "beforeremove" : true,
21734 * @event beforemove
21735 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
21736 * @param {Tree} tree The owner tree
21737 * @param {Node} this This node
21738 * @param {Node} oldParent The parent of this node
21739 * @param {Node} newParent The new parent this node is moving to
21740 * @param {Number} index The index it is being moved to
21742 "beforemove" : true,
21744 * @event beforeinsert
21745 * Fires before a new child is inserted, return false to cancel the insert.
21746 * @param {Tree} tree The owner tree
21747 * @param {Node} this This node
21748 * @param {Node} node The child node to be inserted
21749 * @param {Node} refNode The child node the node is being inserted before
21751 "beforeinsert" : true
21753 this.listeners = this.attributes.listeners;
21754 Roo.data.Node.superclass.constructor.call(this);
21757 Roo.extend(Roo.data.Node, Roo.util.Observable, {
21758 fireEvent : function(evtName){
21759 // first do standard event for this node
21760 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
21763 // then bubble it up to the tree if the event wasn't cancelled
21764 var ot = this.getOwnerTree();
21766 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
21774 * Returns true if this node is a leaf
21775 * @return {Boolean}
21777 isLeaf : function(){
21778 return this.leaf === true;
21782 setFirstChild : function(node){
21783 this.firstChild = node;
21787 setLastChild : function(node){
21788 this.lastChild = node;
21793 * Returns true if this node is the last child of its parent
21794 * @return {Boolean}
21796 isLast : function(){
21797 return (!this.parentNode ? true : this.parentNode.lastChild == this);
21801 * Returns true if this node is the first child of its parent
21802 * @return {Boolean}
21804 isFirst : function(){
21805 return (!this.parentNode ? true : this.parentNode.firstChild == this);
21808 hasChildNodes : function(){
21809 return !this.isLeaf() && this.childNodes.length > 0;
21813 * Insert node(s) as the last child node of this node.
21814 * @param {Node/Array} node The node or Array of nodes to append
21815 * @return {Node} The appended node if single append, or null if an array was passed
21817 appendChild : function(node){
21819 if(node instanceof Array){
21821 }else if(arguments.length > 1){
21824 // if passed an array or multiple args do them one by one
21826 for(var i = 0, len = multi.length; i < len; i++) {
21827 this.appendChild(multi[i]);
21830 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
21833 var index = this.childNodes.length;
21834 var oldParent = node.parentNode;
21835 // it's a move, make sure we move it cleanly
21837 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
21840 oldParent.removeChild(node);
21842 index = this.childNodes.length;
21844 this.setFirstChild(node);
21846 this.childNodes.push(node);
21847 node.parentNode = this;
21848 var ps = this.childNodes[index-1];
21850 node.previousSibling = ps;
21851 ps.nextSibling = node;
21853 node.previousSibling = null;
21855 node.nextSibling = null;
21856 this.setLastChild(node);
21857 node.setOwnerTree(this.getOwnerTree());
21858 this.fireEvent("append", this.ownerTree, this, node, index);
21860 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
21867 * Removes a child node from this node.
21868 * @param {Node} node The node to remove
21869 * @return {Node} The removed node
21871 removeChild : function(node){
21872 var index = this.childNodes.indexOf(node);
21876 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
21880 // remove it from childNodes collection
21881 this.childNodes.splice(index, 1);
21884 if(node.previousSibling){
21885 node.previousSibling.nextSibling = node.nextSibling;
21887 if(node.nextSibling){
21888 node.nextSibling.previousSibling = node.previousSibling;
21891 // update child refs
21892 if(this.firstChild == node){
21893 this.setFirstChild(node.nextSibling);
21895 if(this.lastChild == node){
21896 this.setLastChild(node.previousSibling);
21899 node.setOwnerTree(null);
21900 // clear any references from the node
21901 node.parentNode = null;
21902 node.previousSibling = null;
21903 node.nextSibling = null;
21904 this.fireEvent("remove", this.ownerTree, this, node);
21909 * Inserts the first node before the second node in this nodes childNodes collection.
21910 * @param {Node} node The node to insert
21911 * @param {Node} refNode The node to insert before (if null the node is appended)
21912 * @return {Node} The inserted node
21914 insertBefore : function(node, refNode){
21915 if(!refNode){ // like standard Dom, refNode can be null for append
21916 return this.appendChild(node);
21919 if(node == refNode){
21923 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
21926 var index = this.childNodes.indexOf(refNode);
21927 var oldParent = node.parentNode;
21928 var refIndex = index;
21930 // when moving internally, indexes will change after remove
21931 if(oldParent == this && this.childNodes.indexOf(node) < index){
21935 // it's a move, make sure we move it cleanly
21937 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
21940 oldParent.removeChild(node);
21943 this.setFirstChild(node);
21945 this.childNodes.splice(refIndex, 0, node);
21946 node.parentNode = this;
21947 var ps = this.childNodes[refIndex-1];
21949 node.previousSibling = ps;
21950 ps.nextSibling = node;
21952 node.previousSibling = null;
21954 node.nextSibling = refNode;
21955 refNode.previousSibling = node;
21956 node.setOwnerTree(this.getOwnerTree());
21957 this.fireEvent("insert", this.ownerTree, this, node, refNode);
21959 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
21965 * Returns the child node at the specified index.
21966 * @param {Number} index
21969 item : function(index){
21970 return this.childNodes[index];
21974 * Replaces one child node in this node with another.
21975 * @param {Node} newChild The replacement node
21976 * @param {Node} oldChild The node to replace
21977 * @return {Node} The replaced node
21979 replaceChild : function(newChild, oldChild){
21980 this.insertBefore(newChild, oldChild);
21981 this.removeChild(oldChild);
21986 * Returns the index of a child node
21987 * @param {Node} node
21988 * @return {Number} The index of the node or -1 if it was not found
21990 indexOf : function(child){
21991 return this.childNodes.indexOf(child);
21995 * Returns the tree this node is in.
21998 getOwnerTree : function(){
21999 // if it doesn't have one, look for one
22000 if(!this.ownerTree){
22004 this.ownerTree = p.ownerTree;
22010 return this.ownerTree;
22014 * Returns depth of this node (the root node has a depth of 0)
22017 getDepth : function(){
22020 while(p.parentNode){
22028 setOwnerTree : function(tree){
22029 // if it's move, we need to update everyone
22030 if(tree != this.ownerTree){
22031 if(this.ownerTree){
22032 this.ownerTree.unregisterNode(this);
22034 this.ownerTree = tree;
22035 var cs = this.childNodes;
22036 for(var i = 0, len = cs.length; i < len; i++) {
22037 cs[i].setOwnerTree(tree);
22040 tree.registerNode(this);
22046 * Returns the path for this node. The path can be used to expand or select this node programmatically.
22047 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
22048 * @return {String} The path
22050 getPath : function(attr){
22051 attr = attr || "id";
22052 var p = this.parentNode;
22053 var b = [this.attributes[attr]];
22055 b.unshift(p.attributes[attr]);
22058 var sep = this.getOwnerTree().pathSeparator;
22059 return sep + b.join(sep);
22063 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
22064 * function call will be the scope provided or the current node. The arguments to the function
22065 * will be the args provided or the current node. If the function returns false at any point,
22066 * the bubble is stopped.
22067 * @param {Function} fn The function to call
22068 * @param {Object} scope (optional) The scope of the function (defaults to current node)
22069 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
22071 bubble : function(fn, scope, args){
22074 if(fn.call(scope || p, args || p) === false){
22082 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
22083 * function call will be the scope provided or the current node. The arguments to the function
22084 * will be the args provided or the current node. If the function returns false at any point,
22085 * the cascade is stopped on that branch.
22086 * @param {Function} fn The function to call
22087 * @param {Object} scope (optional) The scope of the function (defaults to current node)
22088 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
22090 cascade : function(fn, scope, args){
22091 if(fn.call(scope || this, args || this) !== false){
22092 var cs = this.childNodes;
22093 for(var i = 0, len = cs.length; i < len; i++) {
22094 cs[i].cascade(fn, scope, args);
22100 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
22101 * function call will be the scope provided or the current node. The arguments to the function
22102 * will be the args provided or the current node. If the function returns false at any point,
22103 * the iteration stops.
22104 * @param {Function} fn The function to call
22105 * @param {Object} scope (optional) The scope of the function (defaults to current node)
22106 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
22108 eachChild : function(fn, scope, args){
22109 var cs = this.childNodes;
22110 for(var i = 0, len = cs.length; i < len; i++) {
22111 if(fn.call(scope || this, args || cs[i]) === false){
22118 * Finds the first child that has the attribute with the specified value.
22119 * @param {String} attribute The attribute name
22120 * @param {Mixed} value The value to search for
22121 * @return {Node} The found child or null if none was found
22123 findChild : function(attribute, value){
22124 var cs = this.childNodes;
22125 for(var i = 0, len = cs.length; i < len; i++) {
22126 if(cs[i].attributes[attribute] == value){
22134 * Finds the first child by a custom function. The child matches if the function passed
22136 * @param {Function} fn
22137 * @param {Object} scope (optional)
22138 * @return {Node} The found child or null if none was found
22140 findChildBy : function(fn, scope){
22141 var cs = this.childNodes;
22142 for(var i = 0, len = cs.length; i < len; i++) {
22143 if(fn.call(scope||cs[i], cs[i]) === true){
22151 * Sorts this nodes children using the supplied sort function
22152 * @param {Function} fn
22153 * @param {Object} scope (optional)
22155 sort : function(fn, scope){
22156 var cs = this.childNodes;
22157 var len = cs.length;
22159 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
22161 for(var i = 0; i < len; i++){
22163 n.previousSibling = cs[i-1];
22164 n.nextSibling = cs[i+1];
22166 this.setFirstChild(n);
22169 this.setLastChild(n);
22176 * Returns true if this node is an ancestor (at any point) of the passed node.
22177 * @param {Node} node
22178 * @return {Boolean}
22180 contains : function(node){
22181 return node.isAncestor(this);
22185 * Returns true if the passed node is an ancestor (at any point) of this node.
22186 * @param {Node} node
22187 * @return {Boolean}
22189 isAncestor : function(node){
22190 var p = this.parentNode;
22200 toString : function(){
22201 return "[Node"+(this.id?" "+this.id:"")+"]";
22205 * Ext JS Library 1.1.1
22206 * Copyright(c) 2006-2007, Ext JS, LLC.
22208 * Originally Released Under LGPL - original licence link has changed is not relivant.
22211 * <script type="text/javascript">
22216 * @class Roo.ComponentMgr
22217 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
22220 Roo.ComponentMgr = function(){
22221 var all = new Roo.util.MixedCollection();
22225 * Registers a component.
22226 * @param {Roo.Component} c The component
22228 register : function(c){
22233 * Unregisters a component.
22234 * @param {Roo.Component} c The component
22236 unregister : function(c){
22241 * Returns a component by id
22242 * @param {String} id The component id
22244 get : function(id){
22245 return all.get(id);
22249 * Registers a function that will be called when a specified component is added to ComponentMgr
22250 * @param {String} id The component id
22251 * @param {Funtction} fn The callback function
22252 * @param {Object} scope The scope of the callback
22254 onAvailable : function(id, fn, scope){
22255 all.on("add", function(index, o){
22257 fn.call(scope || o, o);
22258 all.un("add", fn, scope);
22265 * Ext JS Library 1.1.1
22266 * Copyright(c) 2006-2007, Ext JS, LLC.
22268 * Originally Released Under LGPL - original licence link has changed is not relivant.
22271 * <script type="text/javascript">
22275 * @class Roo.Component
22276 * @extends Roo.util.Observable
22277 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
22278 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
22279 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
22280 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
22281 * All visual components (widgets) that require rendering into a layout should subclass Component.
22283 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
22284 * 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
22285 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
22287 Roo.Component = function(config){
22288 config = config || {};
22289 if(config.tagName || config.dom || typeof config == "string"){ // element object
22290 config = {el: config, id: config.id || config};
22292 this.initialConfig = config;
22294 Roo.apply(this, config);
22298 * Fires after the component is disabled.
22299 * @param {Roo.Component} this
22304 * Fires after the component is enabled.
22305 * @param {Roo.Component} this
22309 * @event beforeshow
22310 * Fires before the component is shown. Return false to stop the show.
22311 * @param {Roo.Component} this
22316 * Fires after the component is shown.
22317 * @param {Roo.Component} this
22321 * @event beforehide
22322 * Fires before the component is hidden. Return false to stop the hide.
22323 * @param {Roo.Component} this
22328 * Fires after the component is hidden.
22329 * @param {Roo.Component} this
22333 * @event beforerender
22334 * Fires before the component is rendered. Return false to stop the render.
22335 * @param {Roo.Component} this
22337 beforerender : true,
22340 * Fires after the component is rendered.
22341 * @param {Roo.Component} this
22345 * @event beforedestroy
22346 * Fires before the component is destroyed. Return false to stop the destroy.
22347 * @param {Roo.Component} this
22349 beforedestroy : true,
22352 * Fires after the component is destroyed.
22353 * @param {Roo.Component} this
22358 this.id = "ext-comp-" + (++Roo.Component.AUTO_ID);
22360 Roo.ComponentMgr.register(this);
22361 Roo.Component.superclass.constructor.call(this);
22362 this.initComponent();
22363 if(this.renderTo){ // not supported by all components yet. use at your own risk!
22364 this.render(this.renderTo);
22365 delete this.renderTo;
22370 Roo.Component.AUTO_ID = 1000;
22372 Roo.extend(Roo.Component, Roo.util.Observable, {
22374 * @scope Roo.Component.prototype
22376 * true if this component is hidden. Read-only.
22381 * true if this component is disabled. Read-only.
22386 * true if this component has been rendered. Read-only.
22390 /** @cfg {String} disableClass
22391 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
22393 disabledClass : "x-item-disabled",
22394 /** @cfg {Boolean} allowDomMove
22395 * Whether the component can move the Dom node when rendering (defaults to true).
22397 allowDomMove : true,
22398 /** @cfg {String} hideMode
22399 * How this component should hidden. Supported values are
22400 * "visibility" (css visibility), "offsets" (negative offset position) and
22401 * "display" (css display) - defaults to "display".
22403 hideMode: 'display',
22406 ctype : "Roo.Component",
22409 * @cfg {String} actionMode
22410 * which property holds the element that used for hide() / show() / disable() / enable()
22416 getActionEl : function(){
22417 return this[this.actionMode];
22420 initComponent : Roo.emptyFn,
22422 * If this is a lazy rendering component, render it to its container element.
22423 * @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.
22425 render : function(container, position){
22426 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
22427 if(!container && this.el){
22428 this.el = Roo.get(this.el);
22429 container = this.el.dom.parentNode;
22430 this.allowDomMove = false;
22432 this.container = Roo.get(container);
22433 this.rendered = true;
22434 if(position !== undefined){
22435 if(typeof position == 'number'){
22436 position = this.container.dom.childNodes[position];
22438 position = Roo.getDom(position);
22441 this.onRender(this.container, position || null);
22443 this.el.addClass(this.cls);
22447 this.el.applyStyles(this.style);
22450 this.fireEvent("render", this);
22451 this.afterRender(this.container);
22463 // default function is not really useful
22464 onRender : function(ct, position){
22466 this.el = Roo.get(this.el);
22467 if(this.allowDomMove !== false){
22468 ct.dom.insertBefore(this.el.dom, position);
22474 getAutoCreate : function(){
22475 var cfg = typeof this.autoCreate == "object" ?
22476 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
22477 if(this.id && !cfg.id){
22484 afterRender : Roo.emptyFn,
22487 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
22488 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
22490 destroy : function(){
22491 if(this.fireEvent("beforedestroy", this) !== false){
22492 this.purgeListeners();
22493 this.beforeDestroy();
22495 this.el.removeAllListeners();
22497 if(this.actionMode == "container"){
22498 this.container.remove();
22502 Roo.ComponentMgr.unregister(this);
22503 this.fireEvent("destroy", this);
22508 beforeDestroy : function(){
22513 onDestroy : function(){
22518 * Returns the underlying {@link Roo.Element}.
22519 * @return {Roo.Element} The element
22521 getEl : function(){
22526 * Returns the id of this component.
22529 getId : function(){
22534 * Try to focus this component.
22535 * @param {Boolean} selectText True to also select the text in this component (if applicable)
22536 * @return {Roo.Component} this
22538 focus : function(selectText){
22541 if(selectText === true){
22542 this.el.dom.select();
22557 * Disable this component.
22558 * @return {Roo.Component} this
22560 disable : function(){
22564 this.disabled = true;
22565 this.fireEvent("disable", this);
22570 onDisable : function(){
22571 this.getActionEl().addClass(this.disabledClass);
22572 this.el.dom.disabled = true;
22576 * Enable this component.
22577 * @return {Roo.Component} this
22579 enable : function(){
22583 this.disabled = false;
22584 this.fireEvent("enable", this);
22589 onEnable : function(){
22590 this.getActionEl().removeClass(this.disabledClass);
22591 this.el.dom.disabled = false;
22595 * Convenience function for setting disabled/enabled by boolean.
22596 * @param {Boolean} disabled
22598 setDisabled : function(disabled){
22599 this[disabled ? "disable" : "enable"]();
22603 * Show this component.
22604 * @return {Roo.Component} this
22607 if(this.fireEvent("beforeshow", this) !== false){
22608 this.hidden = false;
22612 this.fireEvent("show", this);
22618 onShow : function(){
22619 var ae = this.getActionEl();
22620 if(this.hideMode == 'visibility'){
22621 ae.dom.style.visibility = "visible";
22622 }else if(this.hideMode == 'offsets'){
22623 ae.removeClass('x-hidden');
22625 ae.dom.style.display = "";
22630 * Hide this component.
22631 * @return {Roo.Component} this
22634 if(this.fireEvent("beforehide", this) !== false){
22635 this.hidden = true;
22639 this.fireEvent("hide", this);
22645 onHide : function(){
22646 var ae = this.getActionEl();
22647 if(this.hideMode == 'visibility'){
22648 ae.dom.style.visibility = "hidden";
22649 }else if(this.hideMode == 'offsets'){
22650 ae.addClass('x-hidden');
22652 ae.dom.style.display = "none";
22657 * Convenience function to hide or show this component by boolean.
22658 * @param {Boolean} visible True to show, false to hide
22659 * @return {Roo.Component} this
22661 setVisible: function(visible){
22671 * Returns true if this component is visible.
22673 isVisible : function(){
22674 return this.getActionEl().isVisible();
22677 cloneConfig : function(overrides){
22678 overrides = overrides || {};
22679 var id = overrides.id || Roo.id();
22680 var cfg = Roo.applyIf(overrides, this.initialConfig);
22681 cfg.id = id; // prevent dup id
22682 return new this.constructor(cfg);
22686 * Ext JS Library 1.1.1
22687 * Copyright(c) 2006-2007, Ext JS, LLC.
22689 * Originally Released Under LGPL - original licence link has changed is not relivant.
22692 * <script type="text/javascript">
22697 * @extends Roo.Element
22698 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
22699 * automatic maintaining of shadow/shim positions.
22700 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
22701 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
22702 * you can pass a string with a CSS class name. False turns off the shadow.
22703 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
22704 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
22705 * @cfg {String} cls CSS class to add to the element
22706 * @cfg {Number} zindex Starting z-index (defaults to 11000)
22707 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
22709 * @param {Object} config An object with config options.
22710 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
22713 Roo.Layer = function(config, existingEl){
22714 config = config || {};
22715 var dh = Roo.DomHelper;
22716 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
22718 this.dom = Roo.getDom(existingEl);
22721 var o = config.dh || {tag: "div", cls: "x-layer"};
22722 this.dom = dh.append(pel, o);
22725 this.addClass(config.cls);
22727 this.constrain = config.constrain !== false;
22728 this.visibilityMode = Roo.Element.VISIBILITY;
22730 this.id = this.dom.id = config.id;
22732 this.id = Roo.id(this.dom);
22734 this.zindex = config.zindex || this.getZIndex();
22735 this.position("absolute", this.zindex);
22737 this.shadowOffset = config.shadowOffset || 4;
22738 this.shadow = new Roo.Shadow({
22739 offset : this.shadowOffset,
22740 mode : config.shadow
22743 this.shadowOffset = 0;
22745 this.useShim = config.shim !== false && Roo.useShims;
22746 this.useDisplay = config.useDisplay;
22750 var supr = Roo.Element.prototype;
22752 // shims are shared among layer to keep from having 100 iframes
22755 Roo.extend(Roo.Layer, Roo.Element, {
22757 getZIndex : function(){
22758 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
22761 getShim : function(){
22768 var shim = shims.shift();
22770 shim = this.createShim();
22771 shim.enableDisplayMode('block');
22772 shim.dom.style.display = 'none';
22773 shim.dom.style.visibility = 'visible';
22775 var pn = this.dom.parentNode;
22776 if(shim.dom.parentNode != pn){
22777 pn.insertBefore(shim.dom, this.dom);
22779 shim.setStyle('z-index', this.getZIndex()-2);
22784 hideShim : function(){
22786 this.shim.setDisplayed(false);
22787 shims.push(this.shim);
22792 disableShadow : function(){
22794 this.shadowDisabled = true;
22795 this.shadow.hide();
22796 this.lastShadowOffset = this.shadowOffset;
22797 this.shadowOffset = 0;
22801 enableShadow : function(show){
22803 this.shadowDisabled = false;
22804 this.shadowOffset = this.lastShadowOffset;
22805 delete this.lastShadowOffset;
22813 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
22814 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
22815 sync : function(doShow){
22816 var sw = this.shadow;
22817 if(!this.updating && this.isVisible() && (sw || this.useShim)){
22818 var sh = this.getShim();
22820 var w = this.getWidth(),
22821 h = this.getHeight();
22823 var l = this.getLeft(true),
22824 t = this.getTop(true);
22826 if(sw && !this.shadowDisabled){
22827 if(doShow && !sw.isVisible()){
22830 sw.realign(l, t, w, h);
22836 // fit the shim behind the shadow, so it is shimmed too
22837 var a = sw.adjusts, s = sh.dom.style;
22838 s.left = (Math.min(l, l+a.l))+"px";
22839 s.top = (Math.min(t, t+a.t))+"px";
22840 s.width = (w+a.w)+"px";
22841 s.height = (h+a.h)+"px";
22848 sh.setLeftTop(l, t);
22855 destroy : function(){
22858 this.shadow.hide();
22860 this.removeAllListeners();
22861 var pn = this.dom.parentNode;
22863 pn.removeChild(this.dom);
22865 Roo.Element.uncache(this.id);
22868 remove : function(){
22873 beginUpdate : function(){
22874 this.updating = true;
22878 endUpdate : function(){
22879 this.updating = false;
22884 hideUnders : function(negOffset){
22886 this.shadow.hide();
22892 constrainXY : function(){
22893 if(this.constrain){
22894 var vw = Roo.lib.Dom.getViewWidth(),
22895 vh = Roo.lib.Dom.getViewHeight();
22896 var s = Roo.get(document).getScroll();
22898 var xy = this.getXY();
22899 var x = xy[0], y = xy[1];
22900 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
22901 // only move it if it needs it
22903 // first validate right/bottom
22904 if((x + w) > vw+s.left){
22905 x = vw - w - this.shadowOffset;
22908 if((y + h) > vh+s.top){
22909 y = vh - h - this.shadowOffset;
22912 // then make sure top/left isn't negative
22923 var ay = this.avoidY;
22924 if(y <= ay && (y+h) >= ay){
22930 supr.setXY.call(this, xy);
22936 isVisible : function(){
22937 return this.visible;
22941 showAction : function(){
22942 this.visible = true; // track visibility to prevent getStyle calls
22943 if(this.useDisplay === true){
22944 this.setDisplayed("");
22945 }else if(this.lastXY){
22946 supr.setXY.call(this, this.lastXY);
22947 }else if(this.lastLT){
22948 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
22953 hideAction : function(){
22954 this.visible = false;
22955 if(this.useDisplay === true){
22956 this.setDisplayed(false);
22958 this.setLeftTop(-10000,-10000);
22962 // overridden Element method
22963 setVisible : function(v, a, d, c, e){
22968 var cb = function(){
22973 }.createDelegate(this);
22974 supr.setVisible.call(this, true, true, d, cb, e);
22977 this.hideUnders(true);
22986 }.createDelegate(this);
22988 supr.setVisible.call(this, v, a, d, cb, e);
22997 storeXY : function(xy){
22998 delete this.lastLT;
23002 storeLeftTop : function(left, top){
23003 delete this.lastXY;
23004 this.lastLT = [left, top];
23008 beforeFx : function(){
23009 this.beforeAction();
23010 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
23014 afterFx : function(){
23015 Roo.Layer.superclass.afterFx.apply(this, arguments);
23016 this.sync(this.isVisible());
23020 beforeAction : function(){
23021 if(!this.updating && this.shadow){
23022 this.shadow.hide();
23026 // overridden Element method
23027 setLeft : function(left){
23028 this.storeLeftTop(left, this.getTop(true));
23029 supr.setLeft.apply(this, arguments);
23033 setTop : function(top){
23034 this.storeLeftTop(this.getLeft(true), top);
23035 supr.setTop.apply(this, arguments);
23039 setLeftTop : function(left, top){
23040 this.storeLeftTop(left, top);
23041 supr.setLeftTop.apply(this, arguments);
23045 setXY : function(xy, a, d, c, e){
23047 this.beforeAction();
23049 var cb = this.createCB(c);
23050 supr.setXY.call(this, xy, a, d, cb, e);
23057 createCB : function(c){
23068 // overridden Element method
23069 setX : function(x, a, d, c, e){
23070 this.setXY([x, this.getY()], a, d, c, e);
23073 // overridden Element method
23074 setY : function(y, a, d, c, e){
23075 this.setXY([this.getX(), y], a, d, c, e);
23078 // overridden Element method
23079 setSize : function(w, h, a, d, c, e){
23080 this.beforeAction();
23081 var cb = this.createCB(c);
23082 supr.setSize.call(this, w, h, a, d, cb, e);
23088 // overridden Element method
23089 setWidth : function(w, a, d, c, e){
23090 this.beforeAction();
23091 var cb = this.createCB(c);
23092 supr.setWidth.call(this, w, a, d, cb, e);
23098 // overridden Element method
23099 setHeight : function(h, a, d, c, e){
23100 this.beforeAction();
23101 var cb = this.createCB(c);
23102 supr.setHeight.call(this, h, a, d, cb, e);
23108 // overridden Element method
23109 setBounds : function(x, y, w, h, a, d, c, e){
23110 this.beforeAction();
23111 var cb = this.createCB(c);
23113 this.storeXY([x, y]);
23114 supr.setXY.call(this, [x, y]);
23115 supr.setSize.call(this, w, h, a, d, cb, e);
23118 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
23124 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
23125 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
23126 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
23127 * @param {Number} zindex The new z-index to set
23128 * @return {this} The Layer
23130 setZIndex : function(zindex){
23131 this.zindex = zindex;
23132 this.setStyle("z-index", zindex + 2);
23134 this.shadow.setZIndex(zindex + 1);
23137 this.shim.setStyle("z-index", zindex);
23143 * Ext JS Library 1.1.1
23144 * Copyright(c) 2006-2007, Ext JS, LLC.
23146 * Originally Released Under LGPL - original licence link has changed is not relivant.
23149 * <script type="text/javascript">
23154 * @class Roo.Shadow
23155 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
23156 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
23157 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
23159 * Create a new Shadow
23160 * @param {Object} config The config object
23162 Roo.Shadow = function(config){
23163 Roo.apply(this, config);
23164 if(typeof this.mode != "string"){
23165 this.mode = this.defaultMode;
23167 var o = this.offset, a = {h: 0};
23168 var rad = Math.floor(this.offset/2);
23169 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
23175 a.l -= this.offset + rad;
23176 a.t -= this.offset + rad;
23187 a.l -= (this.offset - rad);
23188 a.t -= this.offset + rad;
23190 a.w -= (this.offset - rad)*2;
23201 a.l -= (this.offset - rad);
23202 a.t -= (this.offset - rad);
23204 a.w -= (this.offset + rad + 1);
23205 a.h -= (this.offset + rad);
23214 Roo.Shadow.prototype = {
23216 * @cfg {String} mode
23217 * The shadow display mode. Supports the following options:<br />
23218 * sides: Shadow displays on both sides and bottom only<br />
23219 * frame: Shadow displays equally on all four sides<br />
23220 * drop: Traditional bottom-right drop shadow (default)
23223 * @cfg {String} offset
23224 * The number of pixels to offset the shadow from the element (defaults to 4)
23229 defaultMode: "drop",
23232 * Displays the shadow under the target element
23233 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
23235 show : function(target){
23236 target = Roo.get(target);
23238 this.el = Roo.Shadow.Pool.pull();
23239 if(this.el.dom.nextSibling != target.dom){
23240 this.el.insertBefore(target);
23243 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
23245 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
23248 target.getLeft(true),
23249 target.getTop(true),
23253 this.el.dom.style.display = "block";
23257 * Returns true if the shadow is visible, else false
23259 isVisible : function(){
23260 return this.el ? true : false;
23264 * Direct alignment when values are already available. Show must be called at least once before
23265 * calling this method to ensure it is initialized.
23266 * @param {Number} left The target element left position
23267 * @param {Number} top The target element top position
23268 * @param {Number} width The target element width
23269 * @param {Number} height The target element height
23271 realign : function(l, t, w, h){
23275 var a = this.adjusts, d = this.el.dom, s = d.style;
23277 s.left = (l+a.l)+"px";
23278 s.top = (t+a.t)+"px";
23279 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
23281 if(s.width != sws || s.height != shs){
23285 var cn = d.childNodes;
23286 var sww = Math.max(0, (sw-12))+"px";
23287 cn[0].childNodes[1].style.width = sww;
23288 cn[1].childNodes[1].style.width = sww;
23289 cn[2].childNodes[1].style.width = sww;
23290 cn[1].style.height = Math.max(0, (sh-12))+"px";
23296 * Hides this shadow
23300 this.el.dom.style.display = "none";
23301 Roo.Shadow.Pool.push(this.el);
23307 * Adjust the z-index of this shadow
23308 * @param {Number} zindex The new z-index
23310 setZIndex : function(z){
23313 this.el.setStyle("z-index", z);
23318 // Private utility class that manages the internal Shadow cache
23319 Roo.Shadow.Pool = function(){
23321 var markup = Roo.isIE ?
23322 '<div class="x-ie-shadow"></div>' :
23323 '<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>';
23326 var sh = p.shift();
23328 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
23329 sh.autoBoxAdjust = false;
23334 push : function(sh){
23340 * Ext JS Library 1.1.1
23341 * Copyright(c) 2006-2007, Ext JS, LLC.
23343 * Originally Released Under LGPL - original licence link has changed is not relivant.
23346 * <script type="text/javascript">
23350 * @class Roo.BoxComponent
23351 * @extends Roo.Component
23352 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
23353 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
23354 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
23355 * layout containers.
23357 * @param {Roo.Element/String/Object} config The configuration options.
23359 Roo.BoxComponent = function(config){
23360 Roo.Component.call(this, config);
23364 * Fires after the component is resized.
23365 * @param {Roo.Component} this
23366 * @param {Number} adjWidth The box-adjusted width that was set
23367 * @param {Number} adjHeight The box-adjusted height that was set
23368 * @param {Number} rawWidth The width that was originally specified
23369 * @param {Number} rawHeight The height that was originally specified
23374 * Fires after the component is moved.
23375 * @param {Roo.Component} this
23376 * @param {Number} x The new x position
23377 * @param {Number} y The new y position
23383 Roo.extend(Roo.BoxComponent, Roo.Component, {
23384 // private, set in afterRender to signify that the component has been rendered
23386 // private, used to defer height settings to subclasses
23387 deferHeight: false,
23388 /** @cfg {Number} width
23389 * width (optional) size of component
23391 /** @cfg {Number} height
23392 * height (optional) size of component
23396 * Sets the width and height of the component. This method fires the resize event. This method can accept
23397 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
23398 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
23399 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
23400 * @return {Roo.BoxComponent} this
23402 setSize : function(w, h){
23403 // support for standard size objects
23404 if(typeof w == 'object'){
23409 if(!this.boxReady){
23415 // prevent recalcs when not needed
23416 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
23419 this.lastSize = {width: w, height: h};
23421 var adj = this.adjustSize(w, h);
23422 var aw = adj.width, ah = adj.height;
23423 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
23424 var rz = this.getResizeEl();
23425 if(!this.deferHeight && aw !== undefined && ah !== undefined){
23426 rz.setSize(aw, ah);
23427 }else if(!this.deferHeight && ah !== undefined){
23429 }else if(aw !== undefined){
23432 this.onResize(aw, ah, w, h);
23433 this.fireEvent('resize', this, aw, ah, w, h);
23439 * Gets the current size of the component's underlying element.
23440 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
23442 getSize : function(){
23443 return this.el.getSize();
23447 * Gets the current XY position of the component's underlying element.
23448 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
23449 * @return {Array} The XY position of the element (e.g., [100, 200])
23451 getPosition : function(local){
23452 if(local === true){
23453 return [this.el.getLeft(true), this.el.getTop(true)];
23455 return this.xy || this.el.getXY();
23459 * Gets the current box measurements of the component's underlying element.
23460 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
23461 * @returns {Object} box An object in the format {x, y, width, height}
23463 getBox : function(local){
23464 var s = this.el.getSize();
23466 s.x = this.el.getLeft(true);
23467 s.y = this.el.getTop(true);
23469 var xy = this.xy || this.el.getXY();
23477 * Sets the current box measurements of the component's underlying element.
23478 * @param {Object} box An object in the format {x, y, width, height}
23479 * @returns {Roo.BoxComponent} this
23481 updateBox : function(box){
23482 this.setSize(box.width, box.height);
23483 this.setPagePosition(box.x, box.y);
23488 getResizeEl : function(){
23489 return this.resizeEl || this.el;
23493 getPositionEl : function(){
23494 return this.positionEl || this.el;
23498 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
23499 * This method fires the move event.
23500 * @param {Number} left The new left
23501 * @param {Number} top The new top
23502 * @returns {Roo.BoxComponent} this
23504 setPosition : function(x, y){
23507 if(!this.boxReady){
23510 var adj = this.adjustPosition(x, y);
23511 var ax = adj.x, ay = adj.y;
23513 var el = this.getPositionEl();
23514 if(ax !== undefined || ay !== undefined){
23515 if(ax !== undefined && ay !== undefined){
23516 el.setLeftTop(ax, ay);
23517 }else if(ax !== undefined){
23519 }else if(ay !== undefined){
23522 this.onPosition(ax, ay);
23523 this.fireEvent('move', this, ax, ay);
23529 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
23530 * This method fires the move event.
23531 * @param {Number} x The new x position
23532 * @param {Number} y The new y position
23533 * @returns {Roo.BoxComponent} this
23535 setPagePosition : function(x, y){
23538 if(!this.boxReady){
23541 if(x === undefined || y === undefined){ // cannot translate undefined points
23544 var p = this.el.translatePoints(x, y);
23545 this.setPosition(p.left, p.top);
23550 onRender : function(ct, position){
23551 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
23553 this.resizeEl = Roo.get(this.resizeEl);
23555 if(this.positionEl){
23556 this.positionEl = Roo.get(this.positionEl);
23561 afterRender : function(){
23562 Roo.BoxComponent.superclass.afterRender.call(this);
23563 this.boxReady = true;
23564 this.setSize(this.width, this.height);
23565 if(this.x || this.y){
23566 this.setPosition(this.x, this.y);
23568 if(this.pageX || this.pageY){
23569 this.setPagePosition(this.pageX, this.pageY);
23574 * Force the component's size to recalculate based on the underlying element's current height and width.
23575 * @returns {Roo.BoxComponent} this
23577 syncSize : function(){
23578 delete this.lastSize;
23579 this.setSize(this.el.getWidth(), this.el.getHeight());
23584 * Called after the component is resized, this method is empty by default but can be implemented by any
23585 * subclass that needs to perform custom logic after a resize occurs.
23586 * @param {Number} adjWidth The box-adjusted width that was set
23587 * @param {Number} adjHeight The box-adjusted height that was set
23588 * @param {Number} rawWidth The width that was originally specified
23589 * @param {Number} rawHeight The height that was originally specified
23591 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
23596 * Called after the component is moved, this method is empty by default but can be implemented by any
23597 * subclass that needs to perform custom logic after a move occurs.
23598 * @param {Number} x The new x position
23599 * @param {Number} y The new y position
23601 onPosition : function(x, y){
23606 adjustSize : function(w, h){
23607 if(this.autoWidth){
23610 if(this.autoHeight){
23613 return {width : w, height: h};
23617 adjustPosition : function(x, y){
23618 return {x : x, y: y};
23622 * Ext JS Library 1.1.1
23623 * Copyright(c) 2006-2007, Ext JS, LLC.
23625 * Originally Released Under LGPL - original licence link has changed is not relivant.
23628 * <script type="text/javascript">
23633 * @class Roo.SplitBar
23634 * @extends Roo.util.Observable
23635 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
23639 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
23640 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
23641 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
23642 split.minSize = 100;
23643 split.maxSize = 600;
23644 split.animate = true;
23645 split.on('moved', splitterMoved);
23648 * Create a new SplitBar
23649 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
23650 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
23651 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
23652 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
23653 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
23654 position of the SplitBar).
23656 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
23659 this.el = Roo.get(dragElement, true);
23660 this.el.dom.unselectable = "on";
23662 this.resizingEl = Roo.get(resizingElement, true);
23666 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
23667 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
23670 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
23673 * The minimum size of the resizing element. (Defaults to 0)
23679 * The maximum size of the resizing element. (Defaults to 2000)
23682 this.maxSize = 2000;
23685 * Whether to animate the transition to the new size
23688 this.animate = false;
23691 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
23694 this.useShim = false;
23699 if(!existingProxy){
23701 this.proxy = Roo.SplitBar.createProxy(this.orientation);
23703 this.proxy = Roo.get(existingProxy).dom;
23706 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
23709 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
23712 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
23715 this.dragSpecs = {};
23718 * @private The adapter to use to positon and resize elements
23720 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
23721 this.adapter.init(this);
23723 if(this.orientation == Roo.SplitBar.HORIZONTAL){
23725 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
23726 this.el.addClass("x-splitbar-h");
23729 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
23730 this.el.addClass("x-splitbar-v");
23736 * Fires when the splitter is moved (alias for {@link #event-moved})
23737 * @param {Roo.SplitBar} this
23738 * @param {Number} newSize the new width or height
23743 * Fires when the splitter is moved
23744 * @param {Roo.SplitBar} this
23745 * @param {Number} newSize the new width or height
23749 * @event beforeresize
23750 * Fires before the splitter is dragged
23751 * @param {Roo.SplitBar} this
23753 "beforeresize" : true,
23755 "beforeapply" : true
23758 Roo.util.Observable.call(this);
23761 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
23762 onStartProxyDrag : function(x, y){
23763 this.fireEvent("beforeresize", this);
23765 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
23767 o.enableDisplayMode("block");
23768 // all splitbars share the same overlay
23769 Roo.SplitBar.prototype.overlay = o;
23771 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
23772 this.overlay.show();
23773 Roo.get(this.proxy).setDisplayed("block");
23774 var size = this.adapter.getElementSize(this);
23775 this.activeMinSize = this.getMinimumSize();;
23776 this.activeMaxSize = this.getMaximumSize();;
23777 var c1 = size - this.activeMinSize;
23778 var c2 = Math.max(this.activeMaxSize - size, 0);
23779 if(this.orientation == Roo.SplitBar.HORIZONTAL){
23780 this.dd.resetConstraints();
23781 this.dd.setXConstraint(
23782 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
23783 this.placement == Roo.SplitBar.LEFT ? c2 : c1
23785 this.dd.setYConstraint(0, 0);
23787 this.dd.resetConstraints();
23788 this.dd.setXConstraint(0, 0);
23789 this.dd.setYConstraint(
23790 this.placement == Roo.SplitBar.TOP ? c1 : c2,
23791 this.placement == Roo.SplitBar.TOP ? c2 : c1
23794 this.dragSpecs.startSize = size;
23795 this.dragSpecs.startPoint = [x, y];
23796 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
23800 * @private Called after the drag operation by the DDProxy
23802 onEndProxyDrag : function(e){
23803 Roo.get(this.proxy).setDisplayed(false);
23804 var endPoint = Roo.lib.Event.getXY(e);
23806 this.overlay.hide();
23809 if(this.orientation == Roo.SplitBar.HORIZONTAL){
23810 newSize = this.dragSpecs.startSize +
23811 (this.placement == Roo.SplitBar.LEFT ?
23812 endPoint[0] - this.dragSpecs.startPoint[0] :
23813 this.dragSpecs.startPoint[0] - endPoint[0]
23816 newSize = this.dragSpecs.startSize +
23817 (this.placement == Roo.SplitBar.TOP ?
23818 endPoint[1] - this.dragSpecs.startPoint[1] :
23819 this.dragSpecs.startPoint[1] - endPoint[1]
23822 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
23823 if(newSize != this.dragSpecs.startSize){
23824 if(this.fireEvent('beforeapply', this, newSize) !== false){
23825 this.adapter.setElementSize(this, newSize);
23826 this.fireEvent("moved", this, newSize);
23827 this.fireEvent("resize", this, newSize);
23833 * Get the adapter this SplitBar uses
23834 * @return The adapter object
23836 getAdapter : function(){
23837 return this.adapter;
23841 * Set the adapter this SplitBar uses
23842 * @param {Object} adapter A SplitBar adapter object
23844 setAdapter : function(adapter){
23845 this.adapter = adapter;
23846 this.adapter.init(this);
23850 * Gets the minimum size for the resizing element
23851 * @return {Number} The minimum size
23853 getMinimumSize : function(){
23854 return this.minSize;
23858 * Sets the minimum size for the resizing element
23859 * @param {Number} minSize The minimum size
23861 setMinimumSize : function(minSize){
23862 this.minSize = minSize;
23866 * Gets the maximum size for the resizing element
23867 * @return {Number} The maximum size
23869 getMaximumSize : function(){
23870 return this.maxSize;
23874 * Sets the maximum size for the resizing element
23875 * @param {Number} maxSize The maximum size
23877 setMaximumSize : function(maxSize){
23878 this.maxSize = maxSize;
23882 * Sets the initialize size for the resizing element
23883 * @param {Number} size The initial size
23885 setCurrentSize : function(size){
23886 var oldAnimate = this.animate;
23887 this.animate = false;
23888 this.adapter.setElementSize(this, size);
23889 this.animate = oldAnimate;
23893 * Destroy this splitbar.
23894 * @param {Boolean} removeEl True to remove the element
23896 destroy : function(removeEl){
23898 this.shim.remove();
23901 this.proxy.parentNode.removeChild(this.proxy);
23909 * @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.
23911 Roo.SplitBar.createProxy = function(dir){
23912 var proxy = new Roo.Element(document.createElement("div"));
23913 proxy.unselectable();
23914 var cls = 'x-splitbar-proxy';
23915 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
23916 document.body.appendChild(proxy.dom);
23921 * @class Roo.SplitBar.BasicLayoutAdapter
23922 * Default Adapter. It assumes the splitter and resizing element are not positioned
23923 * elements and only gets/sets the width of the element. Generally used for table based layouts.
23925 Roo.SplitBar.BasicLayoutAdapter = function(){
23928 Roo.SplitBar.BasicLayoutAdapter.prototype = {
23929 // do nothing for now
23930 init : function(s){
23934 * Called before drag operations to get the current size of the resizing element.
23935 * @param {Roo.SplitBar} s The SplitBar using this adapter
23937 getElementSize : function(s){
23938 if(s.orientation == Roo.SplitBar.HORIZONTAL){
23939 return s.resizingEl.getWidth();
23941 return s.resizingEl.getHeight();
23946 * Called after drag operations to set the size of the resizing element.
23947 * @param {Roo.SplitBar} s The SplitBar using this adapter
23948 * @param {Number} newSize The new size to set
23949 * @param {Function} onComplete A function to be invoked when resizing is complete
23951 setElementSize : function(s, newSize, onComplete){
23952 if(s.orientation == Roo.SplitBar.HORIZONTAL){
23954 s.resizingEl.setWidth(newSize);
23956 onComplete(s, newSize);
23959 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
23964 s.resizingEl.setHeight(newSize);
23966 onComplete(s, newSize);
23969 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
23976 *@class Roo.SplitBar.AbsoluteLayoutAdapter
23977 * @extends Roo.SplitBar.BasicLayoutAdapter
23978 * Adapter that moves the splitter element to align with the resized sizing element.
23979 * Used with an absolute positioned SplitBar.
23980 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
23981 * document.body, make sure you assign an id to the body element.
23983 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
23984 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
23985 this.container = Roo.get(container);
23988 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
23989 init : function(s){
23990 this.basic.init(s);
23993 getElementSize : function(s){
23994 return this.basic.getElementSize(s);
23997 setElementSize : function(s, newSize, onComplete){
23998 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
24001 moveSplitter : function(s){
24002 var yes = Roo.SplitBar;
24003 switch(s.placement){
24005 s.el.setX(s.resizingEl.getRight());
24008 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
24011 s.el.setY(s.resizingEl.getBottom());
24014 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
24021 * Orientation constant - Create a vertical SplitBar
24025 Roo.SplitBar.VERTICAL = 1;
24028 * Orientation constant - Create a horizontal SplitBar
24032 Roo.SplitBar.HORIZONTAL = 2;
24035 * Placement constant - The resizing element is to the left of the splitter element
24039 Roo.SplitBar.LEFT = 1;
24042 * Placement constant - The resizing element is to the right of the splitter element
24046 Roo.SplitBar.RIGHT = 2;
24049 * Placement constant - The resizing element is positioned above the splitter element
24053 Roo.SplitBar.TOP = 3;
24056 * Placement constant - The resizing element is positioned under splitter element
24060 Roo.SplitBar.BOTTOM = 4;
24063 * Ext JS Library 1.1.1
24064 * Copyright(c) 2006-2007, Ext JS, LLC.
24066 * Originally Released Under LGPL - original licence link has changed is not relivant.
24069 * <script type="text/javascript">
24074 * @extends Roo.util.Observable
24075 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
24076 * This class also supports single and multi selection modes. <br>
24077 * Create a data model bound view:
24079 var store = new Roo.data.Store(...);
24081 var view = new Roo.View({
24083 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
24085 singleSelect: true,
24086 selectedClass: "ydataview-selected",
24090 // listen for node click?
24091 view.on("click", function(vw, index, node, e){
24092 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
24096 dataModel.load("foobar.xml");
24098 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
24100 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
24101 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
24103 * Note: old style constructor is still suported (container, template, config)
24106 * Create a new View
24107 * @param {Object} config The config object
24110 Roo.View = function(config, depreciated_tpl, depreciated_config){
24112 if (typeof(depreciated_tpl) == 'undefined') {
24113 // new way.. - universal constructor.
24114 Roo.apply(this, config);
24115 this.el = Roo.get(this.el);
24118 this.el = Roo.get(config);
24119 this.tpl = depreciated_tpl;
24120 Roo.apply(this, depreciated_config);
24122 this.wrapEl = this.el.wrap().wrap();
24123 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
24126 if(typeof(this.tpl) == "string"){
24127 this.tpl = new Roo.Template(this.tpl);
24129 // support xtype ctors..
24130 this.tpl = new Roo.factory(this.tpl, Roo);
24134 this.tpl.compile();
24142 * @event beforeclick
24143 * Fires before a click is processed. Returns false to cancel the default action.
24144 * @param {Roo.View} this
24145 * @param {Number} index The index of the target node
24146 * @param {HTMLElement} node The target node
24147 * @param {Roo.EventObject} e The raw event object
24149 "beforeclick" : true,
24152 * Fires when a template node is clicked.
24153 * @param {Roo.View} this
24154 * @param {Number} index The index of the target node
24155 * @param {HTMLElement} node The target node
24156 * @param {Roo.EventObject} e The raw event object
24161 * Fires when a template node is double clicked.
24162 * @param {Roo.View} this
24163 * @param {Number} index The index of the target node
24164 * @param {HTMLElement} node The target node
24165 * @param {Roo.EventObject} e The raw event object
24169 * @event contextmenu
24170 * Fires when a template node is right clicked.
24171 * @param {Roo.View} this
24172 * @param {Number} index The index of the target node
24173 * @param {HTMLElement} node The target node
24174 * @param {Roo.EventObject} e The raw event object
24176 "contextmenu" : true,
24178 * @event selectionchange
24179 * Fires when the selected nodes change.
24180 * @param {Roo.View} this
24181 * @param {Array} selections Array of the selected nodes
24183 "selectionchange" : true,
24186 * @event beforeselect
24187 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
24188 * @param {Roo.View} this
24189 * @param {HTMLElement} node The node to be selected
24190 * @param {Array} selections Array of currently selected nodes
24192 "beforeselect" : true,
24194 * @event preparedata
24195 * Fires on every row to render, to allow you to change the data.
24196 * @param {Roo.View} this
24197 * @param {Object} data to be rendered (change this)
24199 "preparedata" : true
24207 "click": this.onClick,
24208 "dblclick": this.onDblClick,
24209 "contextmenu": this.onContextMenu,
24213 this.selections = [];
24215 this.cmp = new Roo.CompositeElementLite([]);
24217 this.store = Roo.factory(this.store, Roo.data);
24218 this.setStore(this.store, true);
24221 if ( this.footer && this.footer.xtype) {
24223 var fctr = this.wrapEl.appendChild(document.createElement("div"));
24225 this.footer.dataSource = this.store
24226 this.footer.container = fctr;
24227 this.footer = Roo.factory(this.footer, Roo);
24228 fctr.insertFirst(this.el);
24230 // this is a bit insane - as the paging toolbar seems to detach the el..
24231 // dom.parentNode.parentNode.parentNode
24232 // they get detached?
24236 Roo.View.superclass.constructor.call(this);
24241 Roo.extend(Roo.View, Roo.util.Observable, {
24244 * @cfg {Roo.data.Store} store Data store to load data from.
24249 * @cfg {String|Roo.Element} el The container element.
24254 * @cfg {String|Roo.Template} tpl The template used by this View
24258 * @cfg {String} dataName the named area of the template to use as the data area
24259 * Works with domtemplates roo-name="name"
24263 * @cfg {String} selectedClass The css class to add to selected nodes
24265 selectedClass : "x-view-selected",
24267 * @cfg {String} emptyText The empty text to show when nothing is loaded.
24272 * @cfg {String} text to display on mask (default Loading)
24276 * @cfg {Boolean} multiSelect Allow multiple selection
24278 multiSelect : false,
24280 * @cfg {Boolean} singleSelect Allow single selection
24282 singleSelect: false,
24285 * @cfg {Boolean} toggleSelect - selecting
24287 toggleSelect : false,
24290 * Returns the element this view is bound to.
24291 * @return {Roo.Element}
24293 getEl : function(){
24294 return this.wrapEl;
24300 * Refreshes the view. - called by datachanged on the store. - do not call directly.
24302 refresh : function(){
24305 // if we are using something like 'domtemplate', then
24306 // the what gets used is:
24307 // t.applySubtemplate(NAME, data, wrapping data..)
24308 // the outer template then get' applied with
24309 // the store 'extra data'
24310 // and the body get's added to the
24311 // roo-name="data" node?
24312 // <span class='roo-tpl-{name}'></span> ?????
24316 this.clearSelections();
24317 this.el.update("");
24319 var records = this.store.getRange();
24320 if(records.length < 1) {
24322 // is this valid?? = should it render a template??
24324 this.el.update(this.emptyText);
24328 if (this.dataName) {
24329 this.el.update(t.apply(this.store.meta)); //????
24330 el = this.el.child('.roo-tpl-' + this.dataName);
24333 for(var i = 0, len = records.length; i < len; i++){
24334 var data = this.prepareData(records[i].data, i, records[i]);
24335 this.fireEvent("preparedata", this, data, i, records[i]);
24336 html[html.length] = Roo.util.Format.trim(
24338 t.applySubtemplate(this.dataName, data, this.store.meta) :
24345 el.update(html.join(""));
24346 this.nodes = el.dom.childNodes;
24347 this.updateIndexes(0);
24351 * Function to override to reformat the data that is sent to
24352 * the template for each node.
24353 * DEPRICATED - use the preparedata event handler.
24354 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
24355 * a JSON object for an UpdateManager bound view).
24357 prepareData : function(data, index, record)
24359 this.fireEvent("preparedata", this, data, index, record);
24363 onUpdate : function(ds, record){
24364 this.clearSelections();
24365 var index = this.store.indexOf(record);
24366 var n = this.nodes[index];
24367 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
24368 n.parentNode.removeChild(n);
24369 this.updateIndexes(index, index);
24375 onAdd : function(ds, records, index)
24377 this.clearSelections();
24378 if(this.nodes.length == 0){
24382 var n = this.nodes[index];
24383 for(var i = 0, len = records.length; i < len; i++){
24384 var d = this.prepareData(records[i].data, i, records[i]);
24386 this.tpl.insertBefore(n, d);
24389 this.tpl.append(this.el, d);
24392 this.updateIndexes(index);
24395 onRemove : function(ds, record, index){
24396 this.clearSelections();
24397 var el = this.dataName ?
24398 this.el.child('.roo-tpl-' + this.dataName) :
24400 el.dom.removeChild(this.nodes[index]);
24401 this.updateIndexes(index);
24405 * Refresh an individual node.
24406 * @param {Number} index
24408 refreshNode : function(index){
24409 this.onUpdate(this.store, this.store.getAt(index));
24412 updateIndexes : function(startIndex, endIndex){
24413 var ns = this.nodes;
24414 startIndex = startIndex || 0;
24415 endIndex = endIndex || ns.length - 1;
24416 for(var i = startIndex; i <= endIndex; i++){
24417 ns[i].nodeIndex = i;
24422 * Changes the data store this view uses and refresh the view.
24423 * @param {Store} store
24425 setStore : function(store, initial){
24426 if(!initial && this.store){
24427 this.store.un("datachanged", this.refresh);
24428 this.store.un("add", this.onAdd);
24429 this.store.un("remove", this.onRemove);
24430 this.store.un("update", this.onUpdate);
24431 this.store.un("clear", this.refresh);
24432 this.store.un("beforeload", this.onBeforeLoad);
24433 this.store.un("load", this.onLoad);
24434 this.store.un("loadexception", this.onLoad);
24438 store.on("datachanged", this.refresh, this);
24439 store.on("add", this.onAdd, this);
24440 store.on("remove", this.onRemove, this);
24441 store.on("update", this.onUpdate, this);
24442 store.on("clear", this.refresh, this);
24443 store.on("beforeload", this.onBeforeLoad, this);
24444 store.on("load", this.onLoad, this);
24445 store.on("loadexception", this.onLoad, this);
24453 * onbeforeLoad - masks the loading area.
24456 onBeforeLoad : function()
24458 this.el.update("");
24459 this.el.mask(this.mask ? this.mask : "Loading" );
24461 onLoad : function ()
24468 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
24469 * @param {HTMLElement} node
24470 * @return {HTMLElement} The template node
24472 findItemFromChild : function(node){
24473 var el = this.dataName ?
24474 this.el.child('.roo-tpl-' + this.dataName,true) :
24477 if(!node || node.parentNode == el){
24480 var p = node.parentNode;
24481 while(p && p != el){
24482 if(p.parentNode == el){
24491 onClick : function(e){
24492 var item = this.findItemFromChild(e.getTarget());
24494 var index = this.indexOf(item);
24495 if(this.onItemClick(item, index, e) !== false){
24496 this.fireEvent("click", this, index, item, e);
24499 this.clearSelections();
24504 onContextMenu : function(e){
24505 var item = this.findItemFromChild(e.getTarget());
24507 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
24512 onDblClick : function(e){
24513 var item = this.findItemFromChild(e.getTarget());
24515 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
24519 onItemClick : function(item, index, e)
24521 if(this.fireEvent("beforeclick", this, index, item, e) === false){
24524 if (this.toggleSelect) {
24525 var m = this.isSelected(item) ? 'unselect' : 'select';
24528 _t[m](item, true, false);
24531 if(this.multiSelect || this.singleSelect){
24532 if(this.multiSelect && e.shiftKey && this.lastSelection){
24533 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
24535 this.select(item, this.multiSelect && e.ctrlKey);
24536 this.lastSelection = item;
24538 e.preventDefault();
24544 * Get the number of selected nodes.
24547 getSelectionCount : function(){
24548 return this.selections.length;
24552 * Get the currently selected nodes.
24553 * @return {Array} An array of HTMLElements
24555 getSelectedNodes : function(){
24556 return this.selections;
24560 * Get the indexes of the selected nodes.
24563 getSelectedIndexes : function(){
24564 var indexes = [], s = this.selections;
24565 for(var i = 0, len = s.length; i < len; i++){
24566 indexes.push(s[i].nodeIndex);
24572 * Clear all selections
24573 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
24575 clearSelections : function(suppressEvent){
24576 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
24577 this.cmp.elements = this.selections;
24578 this.cmp.removeClass(this.selectedClass);
24579 this.selections = [];
24580 if(!suppressEvent){
24581 this.fireEvent("selectionchange", this, this.selections);
24587 * Returns true if the passed node is selected
24588 * @param {HTMLElement/Number} node The node or node index
24589 * @return {Boolean}
24591 isSelected : function(node){
24592 var s = this.selections;
24596 node = this.getNode(node);
24597 return s.indexOf(node) !== -1;
24602 * @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
24603 * @param {Boolean} keepExisting (optional) true to keep existing selections
24604 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
24606 select : function(nodeInfo, keepExisting, suppressEvent){
24607 if(nodeInfo instanceof Array){
24609 this.clearSelections(true);
24611 for(var i = 0, len = nodeInfo.length; i < len; i++){
24612 this.select(nodeInfo[i], true, true);
24616 var node = this.getNode(nodeInfo);
24617 if(!node || this.isSelected(node)){
24618 return; // already selected.
24621 this.clearSelections(true);
24623 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
24624 Roo.fly(node).addClass(this.selectedClass);
24625 this.selections.push(node);
24626 if(!suppressEvent){
24627 this.fireEvent("selectionchange", this, this.selections);
24635 * @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
24636 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
24637 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
24639 unselect : function(nodeInfo, keepExisting, suppressEvent)
24641 if(nodeInfo instanceof Array){
24642 Roo.each(this.selections, function(s) {
24643 this.unselect(s, nodeInfo);
24647 var node = this.getNode(nodeInfo);
24648 if(!node || !this.isSelected(node)){
24649 Roo.log("not selected");
24650 return; // not selected.
24654 Roo.each(this.selections, function(s) {
24656 Roo.fly(node).removeClass(this.selectedClass);
24663 this.selections= ns;
24664 this.fireEvent("selectionchange", this, this.selections);
24668 * Gets a template node.
24669 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
24670 * @return {HTMLElement} The node or null if it wasn't found
24672 getNode : function(nodeInfo){
24673 if(typeof nodeInfo == "string"){
24674 return document.getElementById(nodeInfo);
24675 }else if(typeof nodeInfo == "number"){
24676 return this.nodes[nodeInfo];
24682 * Gets a range template nodes.
24683 * @param {Number} startIndex
24684 * @param {Number} endIndex
24685 * @return {Array} An array of nodes
24687 getNodes : function(start, end){
24688 var ns = this.nodes;
24689 start = start || 0;
24690 end = typeof end == "undefined" ? ns.length - 1 : end;
24693 for(var i = start; i <= end; i++){
24697 for(var i = start; i >= end; i--){
24705 * Finds the index of the passed node
24706 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
24707 * @return {Number} The index of the node or -1
24709 indexOf : function(node){
24710 node = this.getNode(node);
24711 if(typeof node.nodeIndex == "number"){
24712 return node.nodeIndex;
24714 var ns = this.nodes;
24715 for(var i = 0, len = ns.length; i < len; i++){
24725 * Ext JS Library 1.1.1
24726 * Copyright(c) 2006-2007, Ext JS, LLC.
24728 * Originally Released Under LGPL - original licence link has changed is not relivant.
24731 * <script type="text/javascript">
24735 * @class Roo.JsonView
24736 * @extends Roo.View
24737 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
24739 var view = new Roo.JsonView({
24740 container: "my-element",
24741 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
24746 // listen for node click?
24747 view.on("click", function(vw, index, node, e){
24748 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
24751 // direct load of JSON data
24752 view.load("foobar.php");
24754 // Example from my blog list
24755 var tpl = new Roo.Template(
24756 '<div class="entry">' +
24757 '<a class="entry-title" href="{link}">{title}</a>' +
24758 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
24759 "</div><hr />"
24762 var moreView = new Roo.JsonView({
24763 container : "entry-list",
24767 moreView.on("beforerender", this.sortEntries, this);
24769 url: "/blog/get-posts.php",
24770 params: "allposts=true",
24771 text: "Loading Blog Entries..."
24775 * Note: old code is supported with arguments : (container, template, config)
24779 * Create a new JsonView
24781 * @param {Object} config The config object
24784 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
24787 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
24789 var um = this.el.getUpdateManager();
24790 um.setRenderer(this);
24791 um.on("update", this.onLoad, this);
24792 um.on("failure", this.onLoadException, this);
24795 * @event beforerender
24796 * Fires before rendering of the downloaded JSON data.
24797 * @param {Roo.JsonView} this
24798 * @param {Object} data The JSON data loaded
24802 * Fires when data is loaded.
24803 * @param {Roo.JsonView} this
24804 * @param {Object} data The JSON data loaded
24805 * @param {Object} response The raw Connect response object
24808 * @event loadexception
24809 * Fires when loading fails.
24810 * @param {Roo.JsonView} this
24811 * @param {Object} response The raw Connect response object
24814 'beforerender' : true,
24816 'loadexception' : true
24819 Roo.extend(Roo.JsonView, Roo.View, {
24821 * @type {String} The root property in the loaded JSON object that contains the data
24826 * Refreshes the view.
24828 refresh : function(){
24829 this.clearSelections();
24830 this.el.update("");
24832 var o = this.jsonData;
24833 if(o && o.length > 0){
24834 for(var i = 0, len = o.length; i < len; i++){
24835 var data = this.prepareData(o[i], i, o);
24836 html[html.length] = this.tpl.apply(data);
24839 html.push(this.emptyText);
24841 this.el.update(html.join(""));
24842 this.nodes = this.el.dom.childNodes;
24843 this.updateIndexes(0);
24847 * 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.
24848 * @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:
24851 url: "your-url.php",
24852 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
24853 callback: yourFunction,
24854 scope: yourObject, //(optional scope)
24857 text: "Loading...",
24862 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
24863 * 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.
24864 * @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}
24865 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
24866 * @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.
24869 var um = this.el.getUpdateManager();
24870 um.update.apply(um, arguments);
24873 render : function(el, response){
24874 this.clearSelections();
24875 this.el.update("");
24878 o = Roo.util.JSON.decode(response.responseText);
24881 o = o[this.jsonRoot];
24886 * The current JSON data or null
24889 this.beforeRender();
24894 * Get the number of records in the current JSON dataset
24897 getCount : function(){
24898 return this.jsonData ? this.jsonData.length : 0;
24902 * Returns the JSON object for the specified node(s)
24903 * @param {HTMLElement/Array} node The node or an array of nodes
24904 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
24905 * you get the JSON object for the node
24907 getNodeData : function(node){
24908 if(node instanceof Array){
24910 for(var i = 0, len = node.length; i < len; i++){
24911 data.push(this.getNodeData(node[i]));
24915 return this.jsonData[this.indexOf(node)] || null;
24918 beforeRender : function(){
24919 this.snapshot = this.jsonData;
24921 this.sort.apply(this, this.sortInfo);
24923 this.fireEvent("beforerender", this, this.jsonData);
24926 onLoad : function(el, o){
24927 this.fireEvent("load", this, this.jsonData, o);
24930 onLoadException : function(el, o){
24931 this.fireEvent("loadexception", this, o);
24935 * Filter the data by a specific property.
24936 * @param {String} property A property on your JSON objects
24937 * @param {String/RegExp} value Either string that the property values
24938 * should start with, or a RegExp to test against the property
24940 filter : function(property, value){
24943 var ss = this.snapshot;
24944 if(typeof value == "string"){
24945 var vlen = value.length;
24947 this.clearFilter();
24950 value = value.toLowerCase();
24951 for(var i = 0, len = ss.length; i < len; i++){
24953 if(o[property].substr(0, vlen).toLowerCase() == value){
24957 } else if(value.exec){ // regex?
24958 for(var i = 0, len = ss.length; i < len; i++){
24960 if(value.test(o[property])){
24967 this.jsonData = data;
24973 * Filter by a function. The passed function will be called with each
24974 * object in the current dataset. If the function returns true the value is kept,
24975 * otherwise it is filtered.
24976 * @param {Function} fn
24977 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
24979 filterBy : function(fn, scope){
24982 var ss = this.snapshot;
24983 for(var i = 0, len = ss.length; i < len; i++){
24985 if(fn.call(scope || this, o)){
24989 this.jsonData = data;
24995 * Clears the current filter.
24997 clearFilter : function(){
24998 if(this.snapshot && this.jsonData != this.snapshot){
24999 this.jsonData = this.snapshot;
25006 * Sorts the data for this view and refreshes it.
25007 * @param {String} property A property on your JSON objects to sort on
25008 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
25009 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
25011 sort : function(property, dir, sortType){
25012 this.sortInfo = Array.prototype.slice.call(arguments, 0);
25015 var dsc = dir && dir.toLowerCase() == "desc";
25016 var f = function(o1, o2){
25017 var v1 = sortType ? sortType(o1[p]) : o1[p];
25018 var v2 = sortType ? sortType(o2[p]) : o2[p];
25021 return dsc ? +1 : -1;
25022 } else if(v1 > v2){
25023 return dsc ? -1 : +1;
25028 this.jsonData.sort(f);
25030 if(this.jsonData != this.snapshot){
25031 this.snapshot.sort(f);
25037 * Ext JS Library 1.1.1
25038 * Copyright(c) 2006-2007, Ext JS, LLC.
25040 * Originally Released Under LGPL - original licence link has changed is not relivant.
25043 * <script type="text/javascript">
25048 * @class Roo.ColorPalette
25049 * @extends Roo.Component
25050 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
25051 * Here's an example of typical usage:
25053 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
25054 cp.render('my-div');
25056 cp.on('select', function(palette, selColor){
25057 // do something with selColor
25061 * Create a new ColorPalette
25062 * @param {Object} config The config object
25064 Roo.ColorPalette = function(config){
25065 Roo.ColorPalette.superclass.constructor.call(this, config);
25069 * Fires when a color is selected
25070 * @param {ColorPalette} this
25071 * @param {String} color The 6-digit color hex code (without the # symbol)
25077 this.on("select", this.handler, this.scope, true);
25080 Roo.extend(Roo.ColorPalette, Roo.Component, {
25082 * @cfg {String} itemCls
25083 * The CSS class to apply to the containing element (defaults to "x-color-palette")
25085 itemCls : "x-color-palette",
25087 * @cfg {String} value
25088 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
25089 * the hex codes are case-sensitive.
25092 clickEvent:'click',
25094 ctype: "Roo.ColorPalette",
25097 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
25099 allowReselect : false,
25102 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
25103 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
25104 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
25105 * of colors with the width setting until the box is symmetrical.</p>
25106 * <p>You can override individual colors if needed:</p>
25108 var cp = new Roo.ColorPalette();
25109 cp.colors[0] = "FF0000"; // change the first box to red
25112 Or you can provide a custom array of your own for complete control:
25114 var cp = new Roo.ColorPalette();
25115 cp.colors = ["000000", "993300", "333300"];
25120 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
25121 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
25122 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
25123 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
25124 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
25128 onRender : function(container, position){
25129 var t = new Roo.MasterTemplate(
25130 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
25132 var c = this.colors;
25133 for(var i = 0, len = c.length; i < len; i++){
25136 var el = document.createElement("div");
25137 el.className = this.itemCls;
25139 container.dom.insertBefore(el, position);
25140 this.el = Roo.get(el);
25141 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
25142 if(this.clickEvent != 'click'){
25143 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
25148 afterRender : function(){
25149 Roo.ColorPalette.superclass.afterRender.call(this);
25151 var s = this.value;
25158 handleClick : function(e, t){
25159 e.preventDefault();
25160 if(!this.disabled){
25161 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
25162 this.select(c.toUpperCase());
25167 * Selects the specified color in the palette (fires the select event)
25168 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
25170 select : function(color){
25171 color = color.replace("#", "");
25172 if(color != this.value || this.allowReselect){
25175 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
25177 el.child("a.color-"+color).addClass("x-color-palette-sel");
25178 this.value = color;
25179 this.fireEvent("select", this, color);
25184 * Ext JS Library 1.1.1
25185 * Copyright(c) 2006-2007, Ext JS, LLC.
25187 * Originally Released Under LGPL - original licence link has changed is not relivant.
25190 * <script type="text/javascript">
25194 * @class Roo.DatePicker
25195 * @extends Roo.Component
25196 * Simple date picker class.
25198 * Create a new DatePicker
25199 * @param {Object} config The config object
25201 Roo.DatePicker = function(config){
25202 Roo.DatePicker.superclass.constructor.call(this, config);
25204 this.value = config && config.value ?
25205 config.value.clearTime() : new Date().clearTime();
25210 * Fires when a date is selected
25211 * @param {DatePicker} this
25212 * @param {Date} date The selected date
25216 * @event monthchange
25217 * Fires when the displayed month changes
25218 * @param {DatePicker} this
25219 * @param {Date} date The selected month
25221 'monthchange': true
25225 this.on("select", this.handler, this.scope || this);
25227 // build the disabledDatesRE
25228 if(!this.disabledDatesRE && this.disabledDates){
25229 var dd = this.disabledDates;
25231 for(var i = 0; i < dd.length; i++){
25233 if(i != dd.length-1) re += "|";
25235 this.disabledDatesRE = new RegExp(re + ")");
25239 Roo.extend(Roo.DatePicker, Roo.Component, {
25241 * @cfg {String} todayText
25242 * The text to display on the button that selects the current date (defaults to "Today")
25244 todayText : "Today",
25246 * @cfg {String} okText
25247 * The text to display on the ok button
25249 okText : " OK ", //   to give the user extra clicking room
25251 * @cfg {String} cancelText
25252 * The text to display on the cancel button
25254 cancelText : "Cancel",
25256 * @cfg {String} todayTip
25257 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
25259 todayTip : "{0} (Spacebar)",
25261 * @cfg {Date} minDate
25262 * Minimum allowable date (JavaScript date object, defaults to null)
25266 * @cfg {Date} maxDate
25267 * Maximum allowable date (JavaScript date object, defaults to null)
25271 * @cfg {String} minText
25272 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
25274 minText : "This date is before the minimum date",
25276 * @cfg {String} maxText
25277 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
25279 maxText : "This date is after the maximum date",
25281 * @cfg {String} format
25282 * The default date format string which can be overriden for localization support. The format must be
25283 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
25287 * @cfg {Array} disabledDays
25288 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
25290 disabledDays : null,
25292 * @cfg {String} disabledDaysText
25293 * The tooltip to display when the date falls on a disabled day (defaults to "")
25295 disabledDaysText : "",
25297 * @cfg {RegExp} disabledDatesRE
25298 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
25300 disabledDatesRE : null,
25302 * @cfg {String} disabledDatesText
25303 * The tooltip text to display when the date falls on a disabled date (defaults to "")
25305 disabledDatesText : "",
25307 * @cfg {Boolean} constrainToViewport
25308 * True to constrain the date picker to the viewport (defaults to true)
25310 constrainToViewport : true,
25312 * @cfg {Array} monthNames
25313 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
25315 monthNames : Date.monthNames,
25317 * @cfg {Array} dayNames
25318 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
25320 dayNames : Date.dayNames,
25322 * @cfg {String} nextText
25323 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
25325 nextText: 'Next Month (Control+Right)',
25327 * @cfg {String} prevText
25328 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
25330 prevText: 'Previous Month (Control+Left)',
25332 * @cfg {String} monthYearText
25333 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
25335 monthYearText: 'Choose a month (Control+Up/Down to move years)',
25337 * @cfg {Number} startDay
25338 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
25342 * @cfg {Bool} showClear
25343 * Show a clear button (usefull for date form elements that can be blank.)
25349 * Sets the value of the date field
25350 * @param {Date} value The date to set
25352 setValue : function(value){
25353 var old = this.value;
25355 if (typeof(value) == 'string') {
25357 value = Date.parseDate(value, this.format);
25360 value = new Date();
25363 this.value = value.clearTime(true);
25365 this.update(this.value);
25370 * Gets the current selected value of the date field
25371 * @return {Date} The selected date
25373 getValue : function(){
25378 focus : function(){
25380 this.update(this.activeDate);
25385 onRender : function(container, position){
25388 '<table cellspacing="0">',
25389 '<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>',
25390 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
25391 var dn = this.dayNames;
25392 for(var i = 0; i < 7; i++){
25393 var d = this.startDay+i;
25397 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
25399 m[m.length] = "</tr></thead><tbody><tr>";
25400 for(var i = 0; i < 42; i++) {
25401 if(i % 7 == 0 && i != 0){
25402 m[m.length] = "</tr><tr>";
25404 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
25406 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
25407 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
25409 var el = document.createElement("div");
25410 el.className = "x-date-picker";
25411 el.innerHTML = m.join("");
25413 container.dom.insertBefore(el, position);
25415 this.el = Roo.get(el);
25416 this.eventEl = Roo.get(el.firstChild);
25418 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
25419 handler: this.showPrevMonth,
25421 preventDefault:true,
25425 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
25426 handler: this.showNextMonth,
25428 preventDefault:true,
25432 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
25434 this.monthPicker = this.el.down('div.x-date-mp');
25435 this.monthPicker.enableDisplayMode('block');
25437 var kn = new Roo.KeyNav(this.eventEl, {
25438 "left" : function(e){
25440 this.showPrevMonth() :
25441 this.update(this.activeDate.add("d", -1));
25444 "right" : function(e){
25446 this.showNextMonth() :
25447 this.update(this.activeDate.add("d", 1));
25450 "up" : function(e){
25452 this.showNextYear() :
25453 this.update(this.activeDate.add("d", -7));
25456 "down" : function(e){
25458 this.showPrevYear() :
25459 this.update(this.activeDate.add("d", 7));
25462 "pageUp" : function(e){
25463 this.showNextMonth();
25466 "pageDown" : function(e){
25467 this.showPrevMonth();
25470 "enter" : function(e){
25471 e.stopPropagation();
25478 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
25480 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
25482 this.el.unselectable();
25484 this.cells = this.el.select("table.x-date-inner tbody td");
25485 this.textNodes = this.el.query("table.x-date-inner tbody span");
25487 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
25489 tooltip: this.monthYearText
25492 this.mbtn.on('click', this.showMonthPicker, this);
25493 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
25496 var today = (new Date()).dateFormat(this.format);
25498 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
25499 if (this.showClear) {
25500 baseTb.add( new Roo.Toolbar.Fill());
25503 text: String.format(this.todayText, today),
25504 tooltip: String.format(this.todayTip, today),
25505 handler: this.selectToday,
25509 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
25512 if (this.showClear) {
25514 baseTb.add( new Roo.Toolbar.Fill());
25517 cls: 'x-btn-icon x-btn-clear',
25518 handler: function() {
25520 this.fireEvent("select", this, '');
25530 this.update(this.value);
25533 createMonthPicker : function(){
25534 if(!this.monthPicker.dom.firstChild){
25535 var buf = ['<table border="0" cellspacing="0">'];
25536 for(var i = 0; i < 6; i++){
25538 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
25539 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
25541 '<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>' :
25542 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
25546 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
25548 '</button><button type="button" class="x-date-mp-cancel">',
25550 '</button></td></tr>',
25553 this.monthPicker.update(buf.join(''));
25554 this.monthPicker.on('click', this.onMonthClick, this);
25555 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
25557 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
25558 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
25560 this.mpMonths.each(function(m, a, i){
25563 m.dom.xmonth = 5 + Math.round(i * .5);
25565 m.dom.xmonth = Math.round((i-1) * .5);
25571 showMonthPicker : function(){
25572 this.createMonthPicker();
25573 var size = this.el.getSize();
25574 this.monthPicker.setSize(size);
25575 this.monthPicker.child('table').setSize(size);
25577 this.mpSelMonth = (this.activeDate || this.value).getMonth();
25578 this.updateMPMonth(this.mpSelMonth);
25579 this.mpSelYear = (this.activeDate || this.value).getFullYear();
25580 this.updateMPYear(this.mpSelYear);
25582 this.monthPicker.slideIn('t', {duration:.2});
25585 updateMPYear : function(y){
25587 var ys = this.mpYears.elements;
25588 for(var i = 1; i <= 10; i++){
25589 var td = ys[i-1], y2;
25591 y2 = y + Math.round(i * .5);
25592 td.firstChild.innerHTML = y2;
25595 y2 = y - (5-Math.round(i * .5));
25596 td.firstChild.innerHTML = y2;
25599 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
25603 updateMPMonth : function(sm){
25604 this.mpMonths.each(function(m, a, i){
25605 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
25609 selectMPMonth: function(m){
25613 onMonthClick : function(e, t){
25615 var el = new Roo.Element(t), pn;
25616 if(el.is('button.x-date-mp-cancel')){
25617 this.hideMonthPicker();
25619 else if(el.is('button.x-date-mp-ok')){
25620 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
25621 this.hideMonthPicker();
25623 else if(pn = el.up('td.x-date-mp-month', 2)){
25624 this.mpMonths.removeClass('x-date-mp-sel');
25625 pn.addClass('x-date-mp-sel');
25626 this.mpSelMonth = pn.dom.xmonth;
25628 else if(pn = el.up('td.x-date-mp-year', 2)){
25629 this.mpYears.removeClass('x-date-mp-sel');
25630 pn.addClass('x-date-mp-sel');
25631 this.mpSelYear = pn.dom.xyear;
25633 else if(el.is('a.x-date-mp-prev')){
25634 this.updateMPYear(this.mpyear-10);
25636 else if(el.is('a.x-date-mp-next')){
25637 this.updateMPYear(this.mpyear+10);
25641 onMonthDblClick : function(e, t){
25643 var el = new Roo.Element(t), pn;
25644 if(pn = el.up('td.x-date-mp-month', 2)){
25645 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
25646 this.hideMonthPicker();
25648 else if(pn = el.up('td.x-date-mp-year', 2)){
25649 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
25650 this.hideMonthPicker();
25654 hideMonthPicker : function(disableAnim){
25655 if(this.monthPicker){
25656 if(disableAnim === true){
25657 this.monthPicker.hide();
25659 this.monthPicker.slideOut('t', {duration:.2});
25665 showPrevMonth : function(e){
25666 this.update(this.activeDate.add("mo", -1));
25670 showNextMonth : function(e){
25671 this.update(this.activeDate.add("mo", 1));
25675 showPrevYear : function(){
25676 this.update(this.activeDate.add("y", -1));
25680 showNextYear : function(){
25681 this.update(this.activeDate.add("y", 1));
25685 handleMouseWheel : function(e){
25686 var delta = e.getWheelDelta();
25688 this.showPrevMonth();
25690 } else if(delta < 0){
25691 this.showNextMonth();
25697 handleDateClick : function(e, t){
25699 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
25700 this.setValue(new Date(t.dateValue));
25701 this.fireEvent("select", this, this.value);
25706 selectToday : function(){
25707 this.setValue(new Date().clearTime());
25708 this.fireEvent("select", this, this.value);
25712 update : function(date)
25714 var vd = this.activeDate;
25715 this.activeDate = date;
25717 var t = date.getTime();
25718 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
25719 this.cells.removeClass("x-date-selected");
25720 this.cells.each(function(c){
25721 if(c.dom.firstChild.dateValue == t){
25722 c.addClass("x-date-selected");
25723 setTimeout(function(){
25724 try{c.dom.firstChild.focus();}catch(e){}
25733 var days = date.getDaysInMonth();
25734 var firstOfMonth = date.getFirstDateOfMonth();
25735 var startingPos = firstOfMonth.getDay()-this.startDay;
25737 if(startingPos <= this.startDay){
25741 var pm = date.add("mo", -1);
25742 var prevStart = pm.getDaysInMonth()-startingPos;
25744 var cells = this.cells.elements;
25745 var textEls = this.textNodes;
25746 days += startingPos;
25748 // convert everything to numbers so it's fast
25749 var day = 86400000;
25750 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
25751 var today = new Date().clearTime().getTime();
25752 var sel = date.clearTime().getTime();
25753 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
25754 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
25755 var ddMatch = this.disabledDatesRE;
25756 var ddText = this.disabledDatesText;
25757 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
25758 var ddaysText = this.disabledDaysText;
25759 var format = this.format;
25761 var setCellClass = function(cal, cell){
25763 var t = d.getTime();
25764 cell.firstChild.dateValue = t;
25766 cell.className += " x-date-today";
25767 cell.title = cal.todayText;
25770 cell.className += " x-date-selected";
25771 setTimeout(function(){
25772 try{cell.firstChild.focus();}catch(e){}
25777 cell.className = " x-date-disabled";
25778 cell.title = cal.minText;
25782 cell.className = " x-date-disabled";
25783 cell.title = cal.maxText;
25787 if(ddays.indexOf(d.getDay()) != -1){
25788 cell.title = ddaysText;
25789 cell.className = " x-date-disabled";
25792 if(ddMatch && format){
25793 var fvalue = d.dateFormat(format);
25794 if(ddMatch.test(fvalue)){
25795 cell.title = ddText.replace("%0", fvalue);
25796 cell.className = " x-date-disabled";
25802 for(; i < startingPos; i++) {
25803 textEls[i].innerHTML = (++prevStart);
25804 d.setDate(d.getDate()+1);
25805 cells[i].className = "x-date-prevday";
25806 setCellClass(this, cells[i]);
25808 for(; i < days; i++){
25809 intDay = i - startingPos + 1;
25810 textEls[i].innerHTML = (intDay);
25811 d.setDate(d.getDate()+1);
25812 cells[i].className = "x-date-active";
25813 setCellClass(this, cells[i]);
25816 for(; i < 42; i++) {
25817 textEls[i].innerHTML = (++extraDays);
25818 d.setDate(d.getDate()+1);
25819 cells[i].className = "x-date-nextday";
25820 setCellClass(this, cells[i]);
25823 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
25824 this.fireEvent('monthchange', this, date);
25826 if(!this.internalRender){
25827 var main = this.el.dom.firstChild;
25828 var w = main.offsetWidth;
25829 this.el.setWidth(w + this.el.getBorderWidth("lr"));
25830 Roo.fly(main).setWidth(w);
25831 this.internalRender = true;
25832 // opera does not respect the auto grow header center column
25833 // then, after it gets a width opera refuses to recalculate
25834 // without a second pass
25835 if(Roo.isOpera && !this.secondPass){
25836 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
25837 this.secondPass = true;
25838 this.update.defer(10, this, [date]);
25846 * Ext JS Library 1.1.1
25847 * Copyright(c) 2006-2007, Ext JS, LLC.
25849 * Originally Released Under LGPL - original licence link has changed is not relivant.
25852 * <script type="text/javascript">
25855 * @class Roo.TabPanel
25856 * @extends Roo.util.Observable
25857 * A lightweight tab container.
25861 // basic tabs 1, built from existing content
25862 var tabs = new Roo.TabPanel("tabs1");
25863 tabs.addTab("script", "View Script");
25864 tabs.addTab("markup", "View Markup");
25865 tabs.activate("script");
25867 // more advanced tabs, built from javascript
25868 var jtabs = new Roo.TabPanel("jtabs");
25869 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
25871 // set up the UpdateManager
25872 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
25873 var updater = tab2.getUpdateManager();
25874 updater.setDefaultUrl("ajax1.htm");
25875 tab2.on('activate', updater.refresh, updater, true);
25877 // Use setUrl for Ajax loading
25878 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
25879 tab3.setUrl("ajax2.htm", null, true);
25882 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
25885 jtabs.activate("jtabs-1");
25888 * Create a new TabPanel.
25889 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
25890 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
25892 Roo.TabPanel = function(container, config){
25894 * The container element for this TabPanel.
25895 * @type Roo.Element
25897 this.el = Roo.get(container, true);
25899 if(typeof config == "boolean"){
25900 this.tabPosition = config ? "bottom" : "top";
25902 Roo.apply(this, config);
25905 if(this.tabPosition == "bottom"){
25906 this.bodyEl = Roo.get(this.createBody(this.el.dom));
25907 this.el.addClass("x-tabs-bottom");
25909 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
25910 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
25911 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
25913 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
25915 if(this.tabPosition != "bottom"){
25916 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
25917 * @type Roo.Element
25919 this.bodyEl = Roo.get(this.createBody(this.el.dom));
25920 this.el.addClass("x-tabs-top");
25924 this.bodyEl.setStyle("position", "relative");
25926 this.active = null;
25927 this.activateDelegate = this.activate.createDelegate(this);
25932 * Fires when the active tab changes
25933 * @param {Roo.TabPanel} this
25934 * @param {Roo.TabPanelItem} activePanel The new active tab
25938 * @event beforetabchange
25939 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
25940 * @param {Roo.TabPanel} this
25941 * @param {Object} e Set cancel to true on this object to cancel the tab change
25942 * @param {Roo.TabPanelItem} tab The tab being changed to
25944 "beforetabchange" : true
25947 Roo.EventManager.onWindowResize(this.onResize, this);
25948 this.cpad = this.el.getPadding("lr");
25949 this.hiddenCount = 0;
25952 // toolbar on the tabbar support...
25953 if (this.toolbar) {
25954 var tcfg = this.toolbar;
25955 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
25956 this.toolbar = new Roo.Toolbar(tcfg);
25957 if (Roo.isSafari) {
25958 var tbl = tcfg.container.child('table', true);
25959 tbl.setAttribute('width', '100%');
25966 Roo.TabPanel.superclass.constructor.call(this);
25969 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
25971 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
25973 tabPosition : "top",
25975 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
25977 currentTabWidth : 0,
25979 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
25983 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
25987 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
25989 preferredTabWidth : 175,
25991 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
25993 resizeTabs : false,
25995 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
25997 monitorResize : true,
25999 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
26004 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
26005 * @param {String} id The id of the div to use <b>or create</b>
26006 * @param {String} text The text for the tab
26007 * @param {String} content (optional) Content to put in the TabPanelItem body
26008 * @param {Boolean} closable (optional) True to create a close icon on the tab
26009 * @return {Roo.TabPanelItem} The created TabPanelItem
26011 addTab : function(id, text, content, closable){
26012 var item = new Roo.TabPanelItem(this, id, text, closable);
26013 this.addTabItem(item);
26015 item.setContent(content);
26021 * Returns the {@link Roo.TabPanelItem} with the specified id/index
26022 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
26023 * @return {Roo.TabPanelItem}
26025 getTab : function(id){
26026 return this.items[id];
26030 * Hides the {@link Roo.TabPanelItem} with the specified id/index
26031 * @param {String/Number} id The id or index of the TabPanelItem to hide.
26033 hideTab : function(id){
26034 var t = this.items[id];
26037 this.hiddenCount++;
26038 this.autoSizeTabs();
26043 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
26044 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
26046 unhideTab : function(id){
26047 var t = this.items[id];
26049 t.setHidden(false);
26050 this.hiddenCount--;
26051 this.autoSizeTabs();
26056 * Adds an existing {@link Roo.TabPanelItem}.
26057 * @param {Roo.TabPanelItem} item The TabPanelItem to add
26059 addTabItem : function(item){
26060 this.items[item.id] = item;
26061 this.items.push(item);
26062 if(this.resizeTabs){
26063 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
26064 this.autoSizeTabs();
26071 * Removes a {@link Roo.TabPanelItem}.
26072 * @param {String/Number} id The id or index of the TabPanelItem to remove.
26074 removeTab : function(id){
26075 var items = this.items;
26076 var tab = items[id];
26077 if(!tab) { return; }
26078 var index = items.indexOf(tab);
26079 if(this.active == tab && items.length > 1){
26080 var newTab = this.getNextAvailable(index);
26085 this.stripEl.dom.removeChild(tab.pnode.dom);
26086 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
26087 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
26089 items.splice(index, 1);
26090 delete this.items[tab.id];
26091 tab.fireEvent("close", tab);
26092 tab.purgeListeners();
26093 this.autoSizeTabs();
26096 getNextAvailable : function(start){
26097 var items = this.items;
26099 // look for a next tab that will slide over to
26100 // replace the one being removed
26101 while(index < items.length){
26102 var item = items[++index];
26103 if(item && !item.isHidden()){
26107 // if one isn't found select the previous tab (on the left)
26110 var item = items[--index];
26111 if(item && !item.isHidden()){
26119 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
26120 * @param {String/Number} id The id or index of the TabPanelItem to disable.
26122 disableTab : function(id){
26123 var tab = this.items[id];
26124 if(tab && this.active != tab){
26130 * Enables a {@link Roo.TabPanelItem} that is disabled.
26131 * @param {String/Number} id The id or index of the TabPanelItem to enable.
26133 enableTab : function(id){
26134 var tab = this.items[id];
26139 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
26140 * @param {String/Number} id The id or index of the TabPanelItem to activate.
26141 * @return {Roo.TabPanelItem} The TabPanelItem.
26143 activate : function(id){
26144 var tab = this.items[id];
26148 if(tab == this.active || tab.disabled){
26152 this.fireEvent("beforetabchange", this, e, tab);
26153 if(e.cancel !== true && !tab.disabled){
26155 this.active.hide();
26157 this.active = this.items[id];
26158 this.active.show();
26159 this.fireEvent("tabchange", this, this.active);
26165 * Gets the active {@link Roo.TabPanelItem}.
26166 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
26168 getActiveTab : function(){
26169 return this.active;
26173 * Updates the tab body element to fit the height of the container element
26174 * for overflow scrolling
26175 * @param {Number} targetHeight (optional) Override the starting height from the elements height
26177 syncHeight : function(targetHeight){
26178 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
26179 var bm = this.bodyEl.getMargins();
26180 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
26181 this.bodyEl.setHeight(newHeight);
26185 onResize : function(){
26186 if(this.monitorResize){
26187 this.autoSizeTabs();
26192 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
26194 beginUpdate : function(){
26195 this.updating = true;
26199 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
26201 endUpdate : function(){
26202 this.updating = false;
26203 this.autoSizeTabs();
26207 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
26209 autoSizeTabs : function(){
26210 var count = this.items.length;
26211 var vcount = count - this.hiddenCount;
26212 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
26213 var w = Math.max(this.el.getWidth() - this.cpad, 10);
26214 var availWidth = Math.floor(w / vcount);
26215 var b = this.stripBody;
26216 if(b.getWidth() > w){
26217 var tabs = this.items;
26218 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
26219 if(availWidth < this.minTabWidth){
26220 /*if(!this.sleft){ // incomplete scrolling code
26221 this.createScrollButtons();
26224 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
26227 if(this.currentTabWidth < this.preferredTabWidth){
26228 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
26234 * Returns the number of tabs in this TabPanel.
26237 getCount : function(){
26238 return this.items.length;
26242 * Resizes all the tabs to the passed width
26243 * @param {Number} The new width
26245 setTabWidth : function(width){
26246 this.currentTabWidth = width;
26247 for(var i = 0, len = this.items.length; i < len; i++) {
26248 if(!this.items[i].isHidden())this.items[i].setWidth(width);
26253 * Destroys this TabPanel
26254 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
26256 destroy : function(removeEl){
26257 Roo.EventManager.removeResizeListener(this.onResize, this);
26258 for(var i = 0, len = this.items.length; i < len; i++){
26259 this.items[i].purgeListeners();
26261 if(removeEl === true){
26262 this.el.update("");
26269 * @class Roo.TabPanelItem
26270 * @extends Roo.util.Observable
26271 * Represents an individual item (tab plus body) in a TabPanel.
26272 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
26273 * @param {String} id The id of this TabPanelItem
26274 * @param {String} text The text for the tab of this TabPanelItem
26275 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
26277 Roo.TabPanelItem = function(tabPanel, id, text, closable){
26279 * The {@link Roo.TabPanel} this TabPanelItem belongs to
26280 * @type Roo.TabPanel
26282 this.tabPanel = tabPanel;
26284 * The id for this TabPanelItem
26289 this.disabled = false;
26293 this.loaded = false;
26294 this.closable = closable;
26297 * The body element for this TabPanelItem.
26298 * @type Roo.Element
26300 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
26301 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
26302 this.bodyEl.setStyle("display", "block");
26303 this.bodyEl.setStyle("zoom", "1");
26306 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
26308 this.el = Roo.get(els.el, true);
26309 this.inner = Roo.get(els.inner, true);
26310 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
26311 this.pnode = Roo.get(els.el.parentNode, true);
26312 this.el.on("mousedown", this.onTabMouseDown, this);
26313 this.el.on("click", this.onTabClick, this);
26316 var c = Roo.get(els.close, true);
26317 c.dom.title = this.closeText;
26318 c.addClassOnOver("close-over");
26319 c.on("click", this.closeClick, this);
26325 * Fires when this tab becomes the active tab.
26326 * @param {Roo.TabPanel} tabPanel The parent TabPanel
26327 * @param {Roo.TabPanelItem} this
26331 * @event beforeclose
26332 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
26333 * @param {Roo.TabPanelItem} this
26334 * @param {Object} e Set cancel to true on this object to cancel the close.
26336 "beforeclose": true,
26339 * Fires when this tab is closed.
26340 * @param {Roo.TabPanelItem} this
26344 * @event deactivate
26345 * Fires when this tab is no longer the active tab.
26346 * @param {Roo.TabPanel} tabPanel The parent TabPanel
26347 * @param {Roo.TabPanelItem} this
26349 "deactivate" : true
26351 this.hidden = false;
26353 Roo.TabPanelItem.superclass.constructor.call(this);
26356 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
26357 purgeListeners : function(){
26358 Roo.util.Observable.prototype.purgeListeners.call(this);
26359 this.el.removeAllListeners();
26362 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
26365 this.pnode.addClass("on");
26368 this.tabPanel.stripWrap.repaint();
26370 this.fireEvent("activate", this.tabPanel, this);
26374 * Returns true if this tab is the active tab.
26375 * @return {Boolean}
26377 isActive : function(){
26378 return this.tabPanel.getActiveTab() == this;
26382 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
26385 this.pnode.removeClass("on");
26387 this.fireEvent("deactivate", this.tabPanel, this);
26390 hideAction : function(){
26391 this.bodyEl.hide();
26392 this.bodyEl.setStyle("position", "absolute");
26393 this.bodyEl.setLeft("-20000px");
26394 this.bodyEl.setTop("-20000px");
26397 showAction : function(){
26398 this.bodyEl.setStyle("position", "relative");
26399 this.bodyEl.setTop("");
26400 this.bodyEl.setLeft("");
26401 this.bodyEl.show();
26405 * Set the tooltip for the tab.
26406 * @param {String} tooltip The tab's tooltip
26408 setTooltip : function(text){
26409 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
26410 this.textEl.dom.qtip = text;
26411 this.textEl.dom.removeAttribute('title');
26413 this.textEl.dom.title = text;
26417 onTabClick : function(e){
26418 e.preventDefault();
26419 this.tabPanel.activate(this.id);
26422 onTabMouseDown : function(e){
26423 e.preventDefault();
26424 this.tabPanel.activate(this.id);
26427 getWidth : function(){
26428 return this.inner.getWidth();
26431 setWidth : function(width){
26432 var iwidth = width - this.pnode.getPadding("lr");
26433 this.inner.setWidth(iwidth);
26434 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
26435 this.pnode.setWidth(width);
26439 * Show or hide the tab
26440 * @param {Boolean} hidden True to hide or false to show.
26442 setHidden : function(hidden){
26443 this.hidden = hidden;
26444 this.pnode.setStyle("display", hidden ? "none" : "");
26448 * Returns true if this tab is "hidden"
26449 * @return {Boolean}
26451 isHidden : function(){
26452 return this.hidden;
26456 * Returns the text for this tab
26459 getText : function(){
26463 autoSize : function(){
26464 //this.el.beginMeasure();
26465 this.textEl.setWidth(1);
26466 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
26467 //this.el.endMeasure();
26471 * Sets the text for the tab (Note: this also sets the tooltip text)
26472 * @param {String} text The tab's text and tooltip
26474 setText : function(text){
26476 this.textEl.update(text);
26477 this.setTooltip(text);
26478 if(!this.tabPanel.resizeTabs){
26483 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
26485 activate : function(){
26486 this.tabPanel.activate(this.id);
26490 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
26492 disable : function(){
26493 if(this.tabPanel.active != this){
26494 this.disabled = true;
26495 this.pnode.addClass("disabled");
26500 * Enables this TabPanelItem if it was previously disabled.
26502 enable : function(){
26503 this.disabled = false;
26504 this.pnode.removeClass("disabled");
26508 * Sets the content for this TabPanelItem.
26509 * @param {String} content The content
26510 * @param {Boolean} loadScripts true to look for and load scripts
26512 setContent : function(content, loadScripts){
26513 this.bodyEl.update(content, loadScripts);
26517 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
26518 * @return {Roo.UpdateManager} The UpdateManager
26520 getUpdateManager : function(){
26521 return this.bodyEl.getUpdateManager();
26525 * Set a URL to be used to load the content for this TabPanelItem.
26526 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
26527 * @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)
26528 * @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)
26529 * @return {Roo.UpdateManager} The UpdateManager
26531 setUrl : function(url, params, loadOnce){
26532 if(this.refreshDelegate){
26533 this.un('activate', this.refreshDelegate);
26535 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
26536 this.on("activate", this.refreshDelegate);
26537 return this.bodyEl.getUpdateManager();
26541 _handleRefresh : function(url, params, loadOnce){
26542 if(!loadOnce || !this.loaded){
26543 var updater = this.bodyEl.getUpdateManager();
26544 updater.update(url, params, this._setLoaded.createDelegate(this));
26549 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
26550 * Will fail silently if the setUrl method has not been called.
26551 * This does not activate the panel, just updates its content.
26553 refresh : function(){
26554 if(this.refreshDelegate){
26555 this.loaded = false;
26556 this.refreshDelegate();
26561 _setLoaded : function(){
26562 this.loaded = true;
26566 closeClick : function(e){
26569 this.fireEvent("beforeclose", this, o);
26570 if(o.cancel !== true){
26571 this.tabPanel.removeTab(this.id);
26575 * The text displayed in the tooltip for the close icon.
26578 closeText : "Close this tab"
26582 Roo.TabPanel.prototype.createStrip = function(container){
26583 var strip = document.createElement("div");
26584 strip.className = "x-tabs-wrap";
26585 container.appendChild(strip);
26589 Roo.TabPanel.prototype.createStripList = function(strip){
26590 // div wrapper for retard IE
26591 // returns the "tr" element.
26592 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
26593 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
26594 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
26595 return strip.firstChild.firstChild.firstChild.firstChild;
26598 Roo.TabPanel.prototype.createBody = function(container){
26599 var body = document.createElement("div");
26600 Roo.id(body, "tab-body");
26601 Roo.fly(body).addClass("x-tabs-body");
26602 container.appendChild(body);
26606 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
26607 var body = Roo.getDom(id);
26609 body = document.createElement("div");
26612 Roo.fly(body).addClass("x-tabs-item-body");
26613 bodyEl.insertBefore(body, bodyEl.firstChild);
26617 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
26618 var td = document.createElement("td");
26619 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
26620 //stripEl.appendChild(td);
26622 td.className = "x-tabs-closable";
26623 if(!this.closeTpl){
26624 this.closeTpl = new Roo.Template(
26625 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
26626 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
26627 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
26630 var el = this.closeTpl.overwrite(td, {"text": text});
26631 var close = el.getElementsByTagName("div")[0];
26632 var inner = el.getElementsByTagName("em")[0];
26633 return {"el": el, "close": close, "inner": inner};
26636 this.tabTpl = new Roo.Template(
26637 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
26638 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
26641 var el = this.tabTpl.overwrite(td, {"text": text});
26642 var inner = el.getElementsByTagName("em")[0];
26643 return {"el": el, "inner": inner};
26647 * Ext JS Library 1.1.1
26648 * Copyright(c) 2006-2007, Ext JS, LLC.
26650 * Originally Released Under LGPL - original licence link has changed is not relivant.
26653 * <script type="text/javascript">
26657 * @class Roo.Button
26658 * @extends Roo.util.Observable
26659 * Simple Button class
26660 * @cfg {String} text The button text
26661 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
26662 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
26663 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
26664 * @cfg {Object} scope The scope of the handler
26665 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
26666 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
26667 * @cfg {Boolean} hidden True to start hidden (defaults to false)
26668 * @cfg {Boolean} disabled True to start disabled (defaults to false)
26669 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
26670 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
26671 applies if enableToggle = true)
26672 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
26673 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
26674 an {@link Roo.util.ClickRepeater} config object (defaults to false).
26676 * Create a new button
26677 * @param {Object} config The config object
26679 Roo.Button = function(renderTo, config)
26683 renderTo = config.renderTo || false;
26686 Roo.apply(this, config);
26690 * Fires when this button is clicked
26691 * @param {Button} this
26692 * @param {EventObject} e The click event
26697 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
26698 * @param {Button} this
26699 * @param {Boolean} pressed
26704 * Fires when the mouse hovers over the button
26705 * @param {Button} this
26706 * @param {Event} e The event object
26708 'mouseover' : true,
26711 * Fires when the mouse exits the button
26712 * @param {Button} this
26713 * @param {Event} e The event object
26718 * Fires when the button is rendered
26719 * @param {Button} this
26724 this.menu = Roo.menu.MenuMgr.get(this.menu);
26726 // register listeners first!! - so render can be captured..
26727 Roo.util.Observable.call(this);
26729 this.render(renderTo);
26735 Roo.extend(Roo.Button, Roo.util.Observable, {
26741 * Read-only. True if this button is hidden
26746 * Read-only. True if this button is disabled
26751 * Read-only. True if this button is pressed (only if enableToggle = true)
26757 * @cfg {Number} tabIndex
26758 * The DOM tabIndex for this button (defaults to undefined)
26760 tabIndex : undefined,
26763 * @cfg {Boolean} enableToggle
26764 * True to enable pressed/not pressed toggling (defaults to false)
26766 enableToggle: false,
26768 * @cfg {Mixed} menu
26769 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
26773 * @cfg {String} menuAlign
26774 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
26776 menuAlign : "tl-bl?",
26779 * @cfg {String} iconCls
26780 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
26782 iconCls : undefined,
26784 * @cfg {String} type
26785 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
26790 menuClassTarget: 'tr',
26793 * @cfg {String} clickEvent
26794 * The type of event to map to the button's event handler (defaults to 'click')
26796 clickEvent : 'click',
26799 * @cfg {Boolean} handleMouseEvents
26800 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
26802 handleMouseEvents : true,
26805 * @cfg {String} tooltipType
26806 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
26808 tooltipType : 'qtip',
26811 * @cfg {String} cls
26812 * A CSS class to apply to the button's main element.
26816 * @cfg {Roo.Template} template (Optional)
26817 * An {@link Roo.Template} with which to create the Button's main element. This Template must
26818 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
26819 * require code modifications if required elements (e.g. a button) aren't present.
26823 render : function(renderTo){
26825 if(this.hideParent){
26826 this.parentEl = Roo.get(renderTo);
26828 if(!this.dhconfig){
26829 if(!this.template){
26830 if(!Roo.Button.buttonTemplate){
26831 // hideous table template
26832 Roo.Button.buttonTemplate = new Roo.Template(
26833 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
26834 '<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>',
26835 "</tr></tbody></table>");
26837 this.template = Roo.Button.buttonTemplate;
26839 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
26840 var btnEl = btn.child("button:first");
26841 btnEl.on('focus', this.onFocus, this);
26842 btnEl.on('blur', this.onBlur, this);
26844 btn.addClass(this.cls);
26847 btnEl.setStyle('background-image', 'url(' +this.icon +')');
26850 btnEl.addClass(this.iconCls);
26852 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
26855 if(this.tabIndex !== undefined){
26856 btnEl.dom.tabIndex = this.tabIndex;
26859 if(typeof this.tooltip == 'object'){
26860 Roo.QuickTips.tips(Roo.apply({
26864 btnEl.dom[this.tooltipType] = this.tooltip;
26868 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
26872 this.el.dom.id = this.el.id = this.id;
26875 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
26876 this.menu.on("show", this.onMenuShow, this);
26877 this.menu.on("hide", this.onMenuHide, this);
26879 btn.addClass("x-btn");
26880 if(Roo.isIE && !Roo.isIE7){
26881 this.autoWidth.defer(1, this);
26885 if(this.handleMouseEvents){
26886 btn.on("mouseover", this.onMouseOver, this);
26887 btn.on("mouseout", this.onMouseOut, this);
26888 btn.on("mousedown", this.onMouseDown, this);
26890 btn.on(this.clickEvent, this.onClick, this);
26891 //btn.on("mouseup", this.onMouseUp, this);
26898 Roo.ButtonToggleMgr.register(this);
26900 this.el.addClass("x-btn-pressed");
26903 var repeater = new Roo.util.ClickRepeater(btn,
26904 typeof this.repeat == "object" ? this.repeat : {}
26906 repeater.on("click", this.onClick, this);
26909 this.fireEvent('render', this);
26913 * Returns the button's underlying element
26914 * @return {Roo.Element} The element
26916 getEl : function(){
26921 * Destroys this Button and removes any listeners.
26923 destroy : function(){
26924 Roo.ButtonToggleMgr.unregister(this);
26925 this.el.removeAllListeners();
26926 this.purgeListeners();
26931 autoWidth : function(){
26933 this.el.setWidth("auto");
26934 if(Roo.isIE7 && Roo.isStrict){
26935 var ib = this.el.child('button');
26936 if(ib && ib.getWidth() > 20){
26938 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
26943 this.el.beginMeasure();
26945 if(this.el.getWidth() < this.minWidth){
26946 this.el.setWidth(this.minWidth);
26949 this.el.endMeasure();
26956 * Assigns this button's click handler
26957 * @param {Function} handler The function to call when the button is clicked
26958 * @param {Object} scope (optional) Scope for the function passed in
26960 setHandler : function(handler, scope){
26961 this.handler = handler;
26962 this.scope = scope;
26966 * Sets this button's text
26967 * @param {String} text The button text
26969 setText : function(text){
26972 this.el.child("td.x-btn-center button.x-btn-text").update(text);
26978 * Gets the text for this button
26979 * @return {String} The button text
26981 getText : function(){
26989 this.hidden = false;
26991 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
26999 this.hidden = true;
27001 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
27006 * Convenience function for boolean show/hide
27007 * @param {Boolean} visible True to show, false to hide
27009 setVisible: function(visible){
27018 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
27019 * @param {Boolean} state (optional) Force a particular state
27021 toggle : function(state){
27022 state = state === undefined ? !this.pressed : state;
27023 if(state != this.pressed){
27025 this.el.addClass("x-btn-pressed");
27026 this.pressed = true;
27027 this.fireEvent("toggle", this, true);
27029 this.el.removeClass("x-btn-pressed");
27030 this.pressed = false;
27031 this.fireEvent("toggle", this, false);
27033 if(this.toggleHandler){
27034 this.toggleHandler.call(this.scope || this, this, state);
27042 focus : function(){
27043 this.el.child('button:first').focus();
27047 * Disable this button
27049 disable : function(){
27051 this.el.addClass("x-btn-disabled");
27053 this.disabled = true;
27057 * Enable this button
27059 enable : function(){
27061 this.el.removeClass("x-btn-disabled");
27063 this.disabled = false;
27067 * Convenience function for boolean enable/disable
27068 * @param {Boolean} enabled True to enable, false to disable
27070 setDisabled : function(v){
27071 this[v !== true ? "enable" : "disable"]();
27075 onClick : function(e){
27077 e.preventDefault();
27082 if(!this.disabled){
27083 if(this.enableToggle){
27086 if(this.menu && !this.menu.isVisible()){
27087 this.menu.show(this.el, this.menuAlign);
27089 this.fireEvent("click", this, e);
27091 this.el.removeClass("x-btn-over");
27092 this.handler.call(this.scope || this, this, e);
27097 onMouseOver : function(e){
27098 if(!this.disabled){
27099 this.el.addClass("x-btn-over");
27100 this.fireEvent('mouseover', this, e);
27104 onMouseOut : function(e){
27105 if(!e.within(this.el, true)){
27106 this.el.removeClass("x-btn-over");
27107 this.fireEvent('mouseout', this, e);
27111 onFocus : function(e){
27112 if(!this.disabled){
27113 this.el.addClass("x-btn-focus");
27117 onBlur : function(e){
27118 this.el.removeClass("x-btn-focus");
27121 onMouseDown : function(e){
27122 if(!this.disabled && e.button == 0){
27123 this.el.addClass("x-btn-click");
27124 Roo.get(document).on('mouseup', this.onMouseUp, this);
27128 onMouseUp : function(e){
27130 this.el.removeClass("x-btn-click");
27131 Roo.get(document).un('mouseup', this.onMouseUp, this);
27135 onMenuShow : function(e){
27136 this.el.addClass("x-btn-menu-active");
27139 onMenuHide : function(e){
27140 this.el.removeClass("x-btn-menu-active");
27144 // Private utility class used by Button
27145 Roo.ButtonToggleMgr = function(){
27148 function toggleGroup(btn, state){
27150 var g = groups[btn.toggleGroup];
27151 for(var i = 0, l = g.length; i < l; i++){
27153 g[i].toggle(false);
27160 register : function(btn){
27161 if(!btn.toggleGroup){
27164 var g = groups[btn.toggleGroup];
27166 g = groups[btn.toggleGroup] = [];
27169 btn.on("toggle", toggleGroup);
27172 unregister : function(btn){
27173 if(!btn.toggleGroup){
27176 var g = groups[btn.toggleGroup];
27179 btn.un("toggle", toggleGroup);
27185 * Ext JS Library 1.1.1
27186 * Copyright(c) 2006-2007, Ext JS, LLC.
27188 * Originally Released Under LGPL - original licence link has changed is not relivant.
27191 * <script type="text/javascript">
27195 * @class Roo.SplitButton
27196 * @extends Roo.Button
27197 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
27198 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
27199 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
27200 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
27201 * @cfg {String} arrowTooltip The title attribute of the arrow
27203 * Create a new menu button
27204 * @param {String/HTMLElement/Element} renderTo The element to append the button to
27205 * @param {Object} config The config object
27207 Roo.SplitButton = function(renderTo, config){
27208 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
27210 * @event arrowclick
27211 * Fires when this button's arrow is clicked
27212 * @param {SplitButton} this
27213 * @param {EventObject} e The click event
27215 this.addEvents({"arrowclick":true});
27218 Roo.extend(Roo.SplitButton, Roo.Button, {
27219 render : function(renderTo){
27220 // this is one sweet looking template!
27221 var tpl = new Roo.Template(
27222 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
27223 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
27224 '<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>',
27225 "</tbody></table></td><td>",
27226 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
27227 '<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>',
27228 "</tbody></table></td></tr></table>"
27230 var btn = tpl.append(renderTo, [this.text, this.type], true);
27231 var btnEl = btn.child("button");
27233 btn.addClass(this.cls);
27236 btnEl.setStyle('background-image', 'url(' +this.icon +')');
27239 btnEl.addClass(this.iconCls);
27241 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
27245 if(this.handleMouseEvents){
27246 btn.on("mouseover", this.onMouseOver, this);
27247 btn.on("mouseout", this.onMouseOut, this);
27248 btn.on("mousedown", this.onMouseDown, this);
27249 btn.on("mouseup", this.onMouseUp, this);
27251 btn.on(this.clickEvent, this.onClick, this);
27253 if(typeof this.tooltip == 'object'){
27254 Roo.QuickTips.tips(Roo.apply({
27258 btnEl.dom[this.tooltipType] = this.tooltip;
27261 if(this.arrowTooltip){
27262 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
27271 this.el.addClass("x-btn-pressed");
27273 if(Roo.isIE && !Roo.isIE7){
27274 this.autoWidth.defer(1, this);
27279 this.menu.on("show", this.onMenuShow, this);
27280 this.menu.on("hide", this.onMenuHide, this);
27282 this.fireEvent('render', this);
27286 autoWidth : function(){
27288 var tbl = this.el.child("table:first");
27289 var tbl2 = this.el.child("table:last");
27290 this.el.setWidth("auto");
27291 tbl.setWidth("auto");
27292 if(Roo.isIE7 && Roo.isStrict){
27293 var ib = this.el.child('button:first');
27294 if(ib && ib.getWidth() > 20){
27296 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
27301 this.el.beginMeasure();
27303 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
27304 tbl.setWidth(this.minWidth-tbl2.getWidth());
27307 this.el.endMeasure();
27310 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
27314 * Sets this button's click handler
27315 * @param {Function} handler The function to call when the button is clicked
27316 * @param {Object} scope (optional) Scope for the function passed above
27318 setHandler : function(handler, scope){
27319 this.handler = handler;
27320 this.scope = scope;
27324 * Sets this button's arrow click handler
27325 * @param {Function} handler The function to call when the arrow is clicked
27326 * @param {Object} scope (optional) Scope for the function passed above
27328 setArrowHandler : function(handler, scope){
27329 this.arrowHandler = handler;
27330 this.scope = scope;
27336 focus : function(){
27338 this.el.child("button:first").focus();
27343 onClick : function(e){
27344 e.preventDefault();
27345 if(!this.disabled){
27346 if(e.getTarget(".x-btn-menu-arrow-wrap")){
27347 if(this.menu && !this.menu.isVisible()){
27348 this.menu.show(this.el, this.menuAlign);
27350 this.fireEvent("arrowclick", this, e);
27351 if(this.arrowHandler){
27352 this.arrowHandler.call(this.scope || this, this, e);
27355 this.fireEvent("click", this, e);
27357 this.handler.call(this.scope || this, this, e);
27363 onMouseDown : function(e){
27364 if(!this.disabled){
27365 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
27369 onMouseUp : function(e){
27370 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
27375 // backwards compat
27376 Roo.MenuButton = Roo.SplitButton;/*
27378 * Ext JS Library 1.1.1
27379 * Copyright(c) 2006-2007, Ext JS, LLC.
27381 * Originally Released Under LGPL - original licence link has changed is not relivant.
27384 * <script type="text/javascript">
27388 * @class Roo.Toolbar
27389 * Basic Toolbar class.
27391 * Creates a new Toolbar
27392 * @param {Object} container The config object
27394 Roo.Toolbar = function(container, buttons, config)
27396 /// old consturctor format still supported..
27397 if(container instanceof Array){ // omit the container for later rendering
27398 buttons = container;
27402 if (typeof(container) == 'object' && container.xtype) {
27403 config = container;
27404 container = config.container;
27405 buttons = config.buttons || []; // not really - use items!!
27408 if (config && config.items) {
27409 xitems = config.items;
27410 delete config.items;
27412 Roo.apply(this, config);
27413 this.buttons = buttons;
27416 this.render(container);
27418 this.xitems = xitems;
27419 Roo.each(xitems, function(b) {
27425 Roo.Toolbar.prototype = {
27427 * @cfg {Array} items
27428 * array of button configs or elements to add (will be converted to a MixedCollection)
27432 * @cfg {String/HTMLElement/Element} container
27433 * The id or element that will contain the toolbar
27436 render : function(ct){
27437 this.el = Roo.get(ct);
27439 this.el.addClass(this.cls);
27441 // using a table allows for vertical alignment
27442 // 100% width is needed by Safari...
27443 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
27444 this.tr = this.el.child("tr", true);
27446 this.items = new Roo.util.MixedCollection(false, function(o){
27447 return o.id || ("item" + (++autoId));
27450 this.add.apply(this, this.buttons);
27451 delete this.buttons;
27456 * Adds element(s) to the toolbar -- this function takes a variable number of
27457 * arguments of mixed type and adds them to the toolbar.
27458 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
27460 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
27461 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
27462 * <li>Field: Any form field (equivalent to {@link #addField})</li>
27463 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
27464 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
27465 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
27466 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
27467 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
27468 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
27470 * @param {Mixed} arg2
27471 * @param {Mixed} etc.
27474 var a = arguments, l = a.length;
27475 for(var i = 0; i < l; i++){
27480 _add : function(el) {
27483 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
27486 if (el.applyTo){ // some kind of form field
27487 return this.addField(el);
27489 if (el.render){ // some kind of Toolbar.Item
27490 return this.addItem(el);
27492 if (typeof el == "string"){ // string
27493 if(el == "separator" || el == "-"){
27494 return this.addSeparator();
27497 return this.addSpacer();
27500 return this.addFill();
27502 return this.addText(el);
27505 if(el.tagName){ // element
27506 return this.addElement(el);
27508 if(typeof el == "object"){ // must be button config?
27509 return this.addButton(el);
27511 // and now what?!?!
27517 * Add an Xtype element
27518 * @param {Object} xtype Xtype Object
27519 * @return {Object} created Object
27521 addxtype : function(e){
27522 return this.add(e);
27526 * Returns the Element for this toolbar.
27527 * @return {Roo.Element}
27529 getEl : function(){
27535 * @return {Roo.Toolbar.Item} The separator item
27537 addSeparator : function(){
27538 return this.addItem(new Roo.Toolbar.Separator());
27542 * Adds a spacer element
27543 * @return {Roo.Toolbar.Spacer} The spacer item
27545 addSpacer : function(){
27546 return this.addItem(new Roo.Toolbar.Spacer());
27550 * Adds a fill element that forces subsequent additions to the right side of the toolbar
27551 * @return {Roo.Toolbar.Fill} The fill item
27553 addFill : function(){
27554 return this.addItem(new Roo.Toolbar.Fill());
27558 * Adds any standard HTML element to the toolbar
27559 * @param {String/HTMLElement/Element} el The element or id of the element to add
27560 * @return {Roo.Toolbar.Item} The element's item
27562 addElement : function(el){
27563 return this.addItem(new Roo.Toolbar.Item(el));
27566 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
27567 * @type Roo.util.MixedCollection
27572 * Adds any Toolbar.Item or subclass
27573 * @param {Roo.Toolbar.Item} item
27574 * @return {Roo.Toolbar.Item} The item
27576 addItem : function(item){
27577 var td = this.nextBlock();
27579 this.items.add(item);
27584 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
27585 * @param {Object/Array} config A button config or array of configs
27586 * @return {Roo.Toolbar.Button/Array}
27588 addButton : function(config){
27589 if(config instanceof Array){
27591 for(var i = 0, len = config.length; i < len; i++) {
27592 buttons.push(this.addButton(config[i]));
27597 if(!(config instanceof Roo.Toolbar.Button)){
27599 new Roo.Toolbar.SplitButton(config) :
27600 new Roo.Toolbar.Button(config);
27602 var td = this.nextBlock();
27609 * Adds text to the toolbar
27610 * @param {String} text The text to add
27611 * @return {Roo.Toolbar.Item} The element's item
27613 addText : function(text){
27614 return this.addItem(new Roo.Toolbar.TextItem(text));
27618 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
27619 * @param {Number} index The index where the item is to be inserted
27620 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
27621 * @return {Roo.Toolbar.Button/Item}
27623 insertButton : function(index, item){
27624 if(item instanceof Array){
27626 for(var i = 0, len = item.length; i < len; i++) {
27627 buttons.push(this.insertButton(index + i, item[i]));
27631 if (!(item instanceof Roo.Toolbar.Button)){
27632 item = new Roo.Toolbar.Button(item);
27634 var td = document.createElement("td");
27635 this.tr.insertBefore(td, this.tr.childNodes[index]);
27637 this.items.insert(index, item);
27642 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
27643 * @param {Object} config
27644 * @return {Roo.Toolbar.Item} The element's item
27646 addDom : function(config, returnEl){
27647 var td = this.nextBlock();
27648 Roo.DomHelper.overwrite(td, config);
27649 var ti = new Roo.Toolbar.Item(td.firstChild);
27651 this.items.add(ti);
27656 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
27657 * @type Roo.util.MixedCollection
27662 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
27663 * Note: the field should not have been rendered yet. For a field that has already been
27664 * rendered, use {@link #addElement}.
27665 * @param {Roo.form.Field} field
27666 * @return {Roo.ToolbarItem}
27670 addField : function(field) {
27671 if (!this.fields) {
27673 this.fields = new Roo.util.MixedCollection(false, function(o){
27674 return o.id || ("item" + (++autoId));
27679 var td = this.nextBlock();
27681 var ti = new Roo.Toolbar.Item(td.firstChild);
27683 this.items.add(ti);
27684 this.fields.add(field);
27695 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
27696 this.el.child('div').hide();
27704 this.el.child('div').show();
27708 nextBlock : function(){
27709 var td = document.createElement("td");
27710 this.tr.appendChild(td);
27715 destroy : function(){
27716 if(this.items){ // rendered?
27717 Roo.destroy.apply(Roo, this.items.items);
27719 if(this.fields){ // rendered?
27720 Roo.destroy.apply(Roo, this.fields.items);
27722 Roo.Element.uncache(this.el, this.tr);
27727 * @class Roo.Toolbar.Item
27728 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
27730 * Creates a new Item
27731 * @param {HTMLElement} el
27733 Roo.Toolbar.Item = function(el){
27734 this.el = Roo.getDom(el);
27735 this.id = Roo.id(this.el);
27736 this.hidden = false;
27739 Roo.Toolbar.Item.prototype = {
27742 * Get this item's HTML Element
27743 * @return {HTMLElement}
27745 getEl : function(){
27750 render : function(td){
27752 td.appendChild(this.el);
27756 * Removes and destroys this item.
27758 destroy : function(){
27759 this.td.parentNode.removeChild(this.td);
27766 this.hidden = false;
27767 this.td.style.display = "";
27774 this.hidden = true;
27775 this.td.style.display = "none";
27779 * Convenience function for boolean show/hide.
27780 * @param {Boolean} visible true to show/false to hide
27782 setVisible: function(visible){
27791 * Try to focus this item.
27793 focus : function(){
27794 Roo.fly(this.el).focus();
27798 * Disables this item.
27800 disable : function(){
27801 Roo.fly(this.td).addClass("x-item-disabled");
27802 this.disabled = true;
27803 this.el.disabled = true;
27807 * Enables this item.
27809 enable : function(){
27810 Roo.fly(this.td).removeClass("x-item-disabled");
27811 this.disabled = false;
27812 this.el.disabled = false;
27818 * @class Roo.Toolbar.Separator
27819 * @extends Roo.Toolbar.Item
27820 * A simple toolbar separator class
27822 * Creates a new Separator
27824 Roo.Toolbar.Separator = function(){
27825 var s = document.createElement("span");
27826 s.className = "ytb-sep";
27827 Roo.Toolbar.Separator.superclass.constructor.call(this, s);
27829 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
27830 enable:Roo.emptyFn,
27831 disable:Roo.emptyFn,
27836 * @class Roo.Toolbar.Spacer
27837 * @extends Roo.Toolbar.Item
27838 * A simple element that adds extra horizontal space to a toolbar.
27840 * Creates a new Spacer
27842 Roo.Toolbar.Spacer = function(){
27843 var s = document.createElement("div");
27844 s.className = "ytb-spacer";
27845 Roo.Toolbar.Spacer.superclass.constructor.call(this, s);
27847 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
27848 enable:Roo.emptyFn,
27849 disable:Roo.emptyFn,
27854 * @class Roo.Toolbar.Fill
27855 * @extends Roo.Toolbar.Spacer
27856 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
27858 * Creates a new Spacer
27860 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
27862 render : function(td){
27863 td.style.width = '100%';
27864 Roo.Toolbar.Fill.superclass.render.call(this, td);
27869 * @class Roo.Toolbar.TextItem
27870 * @extends Roo.Toolbar.Item
27871 * A simple class that renders text directly into a toolbar.
27873 * Creates a new TextItem
27874 * @param {String} text
27876 Roo.Toolbar.TextItem = function(text){
27877 if (typeof(text) == 'object') {
27880 var s = document.createElement("span");
27881 s.className = "ytb-text";
27882 s.innerHTML = text;
27883 Roo.Toolbar.TextItem.superclass.constructor.call(this, s);
27885 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
27886 enable:Roo.emptyFn,
27887 disable:Roo.emptyFn,
27892 * @class Roo.Toolbar.Button
27893 * @extends Roo.Button
27894 * A button that renders into a toolbar.
27896 * Creates a new Button
27897 * @param {Object} config A standard {@link Roo.Button} config object
27899 Roo.Toolbar.Button = function(config){
27900 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
27902 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
27903 render : function(td){
27905 Roo.Toolbar.Button.superclass.render.call(this, td);
27909 * Removes and destroys this button
27911 destroy : function(){
27912 Roo.Toolbar.Button.superclass.destroy.call(this);
27913 this.td.parentNode.removeChild(this.td);
27917 * Shows this button
27920 this.hidden = false;
27921 this.td.style.display = "";
27925 * Hides this button
27928 this.hidden = true;
27929 this.td.style.display = "none";
27933 * Disables this item
27935 disable : function(){
27936 Roo.fly(this.td).addClass("x-item-disabled");
27937 this.disabled = true;
27941 * Enables this item
27943 enable : function(){
27944 Roo.fly(this.td).removeClass("x-item-disabled");
27945 this.disabled = false;
27948 // backwards compat
27949 Roo.ToolbarButton = Roo.Toolbar.Button;
27952 * @class Roo.Toolbar.SplitButton
27953 * @extends Roo.SplitButton
27954 * A menu button that renders into a toolbar.
27956 * Creates a new SplitButton
27957 * @param {Object} config A standard {@link Roo.SplitButton} config object
27959 Roo.Toolbar.SplitButton = function(config){
27960 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
27962 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
27963 render : function(td){
27965 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
27969 * Removes and destroys this button
27971 destroy : function(){
27972 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
27973 this.td.parentNode.removeChild(this.td);
27977 * Shows this button
27980 this.hidden = false;
27981 this.td.style.display = "";
27985 * Hides this button
27988 this.hidden = true;
27989 this.td.style.display = "none";
27993 // backwards compat
27994 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
27996 * Ext JS Library 1.1.1
27997 * Copyright(c) 2006-2007, Ext JS, LLC.
27999 * Originally Released Under LGPL - original licence link has changed is not relivant.
28002 * <script type="text/javascript">
28006 * @class Roo.PagingToolbar
28007 * @extends Roo.Toolbar
28008 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
28010 * Create a new PagingToolbar
28011 * @param {Object} config The config object
28013 Roo.PagingToolbar = function(el, ds, config)
28015 // old args format still supported... - xtype is prefered..
28016 if (typeof(el) == 'object' && el.xtype) {
28017 // created from xtype...
28019 ds = el.dataSource;
28020 el = config.container;
28023 if (config.items) {
28024 items = config.items;
28028 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
28031 this.renderButtons(this.el);
28034 // supprot items array.
28036 Roo.each(items, function(e) {
28037 this.add(Roo.factory(e));
28042 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
28044 * @cfg {Roo.data.Store} dataSource
28045 * The underlying data store providing the paged data
28048 * @cfg {String/HTMLElement/Element} container
28049 * container The id or element that will contain the toolbar
28052 * @cfg {Boolean} displayInfo
28053 * True to display the displayMsg (defaults to false)
28056 * @cfg {Number} pageSize
28057 * The number of records to display per page (defaults to 20)
28061 * @cfg {String} displayMsg
28062 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
28064 displayMsg : 'Displaying {0} - {1} of {2}',
28066 * @cfg {String} emptyMsg
28067 * The message to display when no records are found (defaults to "No data to display")
28069 emptyMsg : 'No data to display',
28071 * Customizable piece of the default paging text (defaults to "Page")
28074 beforePageText : "Page",
28076 * Customizable piece of the default paging text (defaults to "of %0")
28079 afterPageText : "of {0}",
28081 * Customizable piece of the default paging text (defaults to "First Page")
28084 firstText : "First Page",
28086 * Customizable piece of the default paging text (defaults to "Previous Page")
28089 prevText : "Previous Page",
28091 * Customizable piece of the default paging text (defaults to "Next Page")
28094 nextText : "Next Page",
28096 * Customizable piece of the default paging text (defaults to "Last Page")
28099 lastText : "Last Page",
28101 * Customizable piece of the default paging text (defaults to "Refresh")
28104 refreshText : "Refresh",
28107 renderButtons : function(el){
28108 Roo.PagingToolbar.superclass.render.call(this, el);
28109 this.first = this.addButton({
28110 tooltip: this.firstText,
28111 cls: "x-btn-icon x-grid-page-first",
28113 handler: this.onClick.createDelegate(this, ["first"])
28115 this.prev = this.addButton({
28116 tooltip: this.prevText,
28117 cls: "x-btn-icon x-grid-page-prev",
28119 handler: this.onClick.createDelegate(this, ["prev"])
28121 //this.addSeparator();
28122 this.add(this.beforePageText);
28123 this.field = Roo.get(this.addDom({
28128 cls: "x-grid-page-number"
28130 this.field.on("keydown", this.onPagingKeydown, this);
28131 this.field.on("focus", function(){this.dom.select();});
28132 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
28133 this.field.setHeight(18);
28134 //this.addSeparator();
28135 this.next = this.addButton({
28136 tooltip: this.nextText,
28137 cls: "x-btn-icon x-grid-page-next",
28139 handler: this.onClick.createDelegate(this, ["next"])
28141 this.last = this.addButton({
28142 tooltip: this.lastText,
28143 cls: "x-btn-icon x-grid-page-last",
28145 handler: this.onClick.createDelegate(this, ["last"])
28147 //this.addSeparator();
28148 this.loading = this.addButton({
28149 tooltip: this.refreshText,
28150 cls: "x-btn-icon x-grid-loading",
28151 handler: this.onClick.createDelegate(this, ["refresh"])
28154 if(this.displayInfo){
28155 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
28160 updateInfo : function(){
28161 if(this.displayEl){
28162 var count = this.ds.getCount();
28163 var msg = count == 0 ?
28167 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
28169 this.displayEl.update(msg);
28174 onLoad : function(ds, r, o){
28175 this.cursor = o.params ? o.params.start : 0;
28176 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
28178 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
28179 this.field.dom.value = ap;
28180 this.first.setDisabled(ap == 1);
28181 this.prev.setDisabled(ap == 1);
28182 this.next.setDisabled(ap == ps);
28183 this.last.setDisabled(ap == ps);
28184 this.loading.enable();
28189 getPageData : function(){
28190 var total = this.ds.getTotalCount();
28193 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
28194 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
28199 onLoadError : function(){
28200 this.loading.enable();
28204 onPagingKeydown : function(e){
28205 var k = e.getKey();
28206 var d = this.getPageData();
28208 var v = this.field.dom.value, pageNum;
28209 if(!v || isNaN(pageNum = parseInt(v, 10))){
28210 this.field.dom.value = d.activePage;
28213 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
28214 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
28217 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))
28219 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
28220 this.field.dom.value = pageNum;
28221 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
28224 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
28226 var v = this.field.dom.value, pageNum;
28227 var increment = (e.shiftKey) ? 10 : 1;
28228 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
28230 if(!v || isNaN(pageNum = parseInt(v, 10))) {
28231 this.field.dom.value = d.activePage;
28234 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
28236 this.field.dom.value = parseInt(v, 10) + increment;
28237 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
28238 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
28245 beforeLoad : function(){
28247 this.loading.disable();
28252 onClick : function(which){
28256 ds.load({params:{start: 0, limit: this.pageSize}});
28259 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
28262 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
28265 var total = ds.getTotalCount();
28266 var extra = total % this.pageSize;
28267 var lastStart = extra ? (total - extra) : total-this.pageSize;
28268 ds.load({params:{start: lastStart, limit: this.pageSize}});
28271 ds.load({params:{start: this.cursor, limit: this.pageSize}});
28277 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
28278 * @param {Roo.data.Store} store The data store to unbind
28280 unbind : function(ds){
28281 ds.un("beforeload", this.beforeLoad, this);
28282 ds.un("load", this.onLoad, this);
28283 ds.un("loadexception", this.onLoadError, this);
28284 ds.un("remove", this.updateInfo, this);
28285 ds.un("add", this.updateInfo, this);
28286 this.ds = undefined;
28290 * Binds the paging toolbar to the specified {@link Roo.data.Store}
28291 * @param {Roo.data.Store} store The data store to bind
28293 bind : function(ds){
28294 ds.on("beforeload", this.beforeLoad, this);
28295 ds.on("load", this.onLoad, this);
28296 ds.on("loadexception", this.onLoadError, this);
28297 ds.on("remove", this.updateInfo, this);
28298 ds.on("add", this.updateInfo, this);
28303 * Ext JS Library 1.1.1
28304 * Copyright(c) 2006-2007, Ext JS, LLC.
28306 * Originally Released Under LGPL - original licence link has changed is not relivant.
28309 * <script type="text/javascript">
28313 * @class Roo.Resizable
28314 * @extends Roo.util.Observable
28315 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
28316 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
28317 * 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
28318 * the element will be wrapped for you automatically.</p>
28319 * <p>Here is the list of valid resize handles:</p>
28322 ------ -------------------
28331 'hd' horizontal drag
28334 * <p>Here's an example showing the creation of a typical Resizable:</p>
28336 var resizer = new Roo.Resizable("element-id", {
28344 resizer.on("resize", myHandler);
28346 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
28347 * resizer.east.setDisplayed(false);</p>
28348 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
28349 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
28350 * resize operation's new size (defaults to [0, 0])
28351 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
28352 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
28353 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
28354 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
28355 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
28356 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
28357 * @cfg {Number} width The width of the element in pixels (defaults to null)
28358 * @cfg {Number} height The height of the element in pixels (defaults to null)
28359 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
28360 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
28361 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
28362 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
28363 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
28364 * in favor of the handles config option (defaults to false)
28365 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
28366 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
28367 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
28368 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
28369 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
28370 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
28371 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
28372 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
28373 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
28374 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
28375 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
28377 * Create a new resizable component
28378 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
28379 * @param {Object} config configuration options
28381 Roo.Resizable = function(el, config)
28383 this.el = Roo.get(el);
28385 if(config && config.wrap){
28386 config.resizeChild = this.el;
28387 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
28388 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
28389 this.el.setStyle("overflow", "hidden");
28390 this.el.setPositioning(config.resizeChild.getPositioning());
28391 config.resizeChild.clearPositioning();
28392 if(!config.width || !config.height){
28393 var csize = config.resizeChild.getSize();
28394 this.el.setSize(csize.width, csize.height);
28396 if(config.pinned && !config.adjustments){
28397 config.adjustments = "auto";
28401 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
28402 this.proxy.unselectable();
28403 this.proxy.enableDisplayMode('block');
28405 Roo.apply(this, config);
28408 this.disableTrackOver = true;
28409 this.el.addClass("x-resizable-pinned");
28411 // if the element isn't positioned, make it relative
28412 var position = this.el.getStyle("position");
28413 if(position != "absolute" && position != "fixed"){
28414 this.el.setStyle("position", "relative");
28416 if(!this.handles){ // no handles passed, must be legacy style
28417 this.handles = 's,e,se';
28418 if(this.multiDirectional){
28419 this.handles += ',n,w';
28422 if(this.handles == "all"){
28423 this.handles = "n s e w ne nw se sw";
28425 var hs = this.handles.split(/\s*?[,;]\s*?| /);
28426 var ps = Roo.Resizable.positions;
28427 for(var i = 0, len = hs.length; i < len; i++){
28428 if(hs[i] && ps[hs[i]]){
28429 var pos = ps[hs[i]];
28430 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
28434 this.corner = this.southeast;
28436 // updateBox = the box can move..
28437 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
28438 this.updateBox = true;
28441 this.activeHandle = null;
28443 if(this.resizeChild){
28444 if(typeof this.resizeChild == "boolean"){
28445 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
28447 this.resizeChild = Roo.get(this.resizeChild, true);
28451 if(this.adjustments == "auto"){
28452 var rc = this.resizeChild;
28453 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
28454 if(rc && (hw || hn)){
28455 rc.position("relative");
28456 rc.setLeft(hw ? hw.el.getWidth() : 0);
28457 rc.setTop(hn ? hn.el.getHeight() : 0);
28459 this.adjustments = [
28460 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
28461 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
28465 if(this.draggable){
28466 this.dd = this.dynamic ?
28467 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
28468 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
28474 * @event beforeresize
28475 * Fired before resize is allowed. Set enabled to false to cancel resize.
28476 * @param {Roo.Resizable} this
28477 * @param {Roo.EventObject} e The mousedown event
28479 "beforeresize" : true,
28482 * Fired a resizing.
28483 * @param {Roo.Resizable} this
28484 * @param {Number} x The new x position
28485 * @param {Number} y The new y position
28486 * @param {Number} w The new w width
28487 * @param {Number} h The new h hight
28488 * @param {Roo.EventObject} e The mouseup event
28493 * Fired after a resize.
28494 * @param {Roo.Resizable} this
28495 * @param {Number} width The new width
28496 * @param {Number} height The new height
28497 * @param {Roo.EventObject} e The mouseup event
28502 if(this.width !== null && this.height !== null){
28503 this.resizeTo(this.width, this.height);
28505 this.updateChildSize();
28508 this.el.dom.style.zoom = 1;
28510 Roo.Resizable.superclass.constructor.call(this);
28513 Roo.extend(Roo.Resizable, Roo.util.Observable, {
28514 resizeChild : false,
28515 adjustments : [0, 0],
28525 multiDirectional : false,
28526 disableTrackOver : false,
28527 easing : 'easeOutStrong',
28528 widthIncrement : 0,
28529 heightIncrement : 0,
28533 preserveRatio : false,
28534 transparent: false,
28540 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
28542 constrainTo: undefined,
28544 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
28546 resizeRegion: undefined,
28550 * Perform a manual resize
28551 * @param {Number} width
28552 * @param {Number} height
28554 resizeTo : function(width, height){
28555 this.el.setSize(width, height);
28556 this.updateChildSize();
28557 this.fireEvent("resize", this, width, height, null);
28561 startSizing : function(e, handle){
28562 this.fireEvent("beforeresize", this, e);
28563 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
28566 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
28567 this.overlay.unselectable();
28568 this.overlay.enableDisplayMode("block");
28569 this.overlay.on("mousemove", this.onMouseMove, this);
28570 this.overlay.on("mouseup", this.onMouseUp, this);
28572 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
28574 this.resizing = true;
28575 this.startBox = this.el.getBox();
28576 this.startPoint = e.getXY();
28577 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
28578 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
28580 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
28581 this.overlay.show();
28583 if(this.constrainTo) {
28584 var ct = Roo.get(this.constrainTo);
28585 this.resizeRegion = ct.getRegion().adjust(
28586 ct.getFrameWidth('t'),
28587 ct.getFrameWidth('l'),
28588 -ct.getFrameWidth('b'),
28589 -ct.getFrameWidth('r')
28593 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
28595 this.proxy.setBox(this.startBox);
28597 this.proxy.setStyle('visibility', 'visible');
28603 onMouseDown : function(handle, e){
28606 this.activeHandle = handle;
28607 this.startSizing(e, handle);
28612 onMouseUp : function(e){
28613 var size = this.resizeElement();
28614 this.resizing = false;
28616 this.overlay.hide();
28618 this.fireEvent("resize", this, size.width, size.height, e);
28622 updateChildSize : function(){
28624 if(this.resizeChild){
28626 var child = this.resizeChild;
28627 var adj = this.adjustments;
28628 if(el.dom.offsetWidth){
28629 var b = el.getSize(true);
28630 child.setSize(b.width+adj[0], b.height+adj[1]);
28632 // Second call here for IE
28633 // The first call enables instant resizing and
28634 // the second call corrects scroll bars if they
28637 setTimeout(function(){
28638 if(el.dom.offsetWidth){
28639 var b = el.getSize(true);
28640 child.setSize(b.width+adj[0], b.height+adj[1]);
28648 snap : function(value, inc, min){
28649 if(!inc || !value) return value;
28650 var newValue = value;
28651 var m = value % inc;
28654 newValue = value + (inc-m);
28656 newValue = value - m;
28659 return Math.max(min, newValue);
28663 resizeElement : function(){
28664 var box = this.proxy.getBox();
28665 if(this.updateBox){
28666 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
28668 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
28670 this.updateChildSize();
28678 constrain : function(v, diff, m, mx){
28681 }else if(v - diff > mx){
28688 onMouseMove : function(e){
28691 try{// try catch so if something goes wrong the user doesn't get hung
28693 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
28697 //var curXY = this.startPoint;
28698 var curSize = this.curSize || this.startBox;
28699 var x = this.startBox.x, y = this.startBox.y;
28700 var ox = x, oy = y;
28701 var w = curSize.width, h = curSize.height;
28702 var ow = w, oh = h;
28703 var mw = this.minWidth, mh = this.minHeight;
28704 var mxw = this.maxWidth, mxh = this.maxHeight;
28705 var wi = this.widthIncrement;
28706 var hi = this.heightIncrement;
28708 var eventXY = e.getXY();
28709 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
28710 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
28712 var pos = this.activeHandle.position;
28717 w = Math.min(Math.max(mw, w), mxw);
28722 h = Math.min(Math.max(mh, h), mxh);
28727 w = Math.min(Math.max(mw, w), mxw);
28728 h = Math.min(Math.max(mh, h), mxh);
28731 diffY = this.constrain(h, diffY, mh, mxh);
28738 var adiffX = Math.abs(diffX);
28739 var sub = (adiffX % wi); // how much
28740 if (sub > (wi/2)) { // far enough to snap
28741 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
28743 // remove difference..
28744 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
28748 x = Math.max(this.minX, x);
28751 diffX = this.constrain(w, diffX, mw, mxw);
28757 w = Math.min(Math.max(mw, w), mxw);
28758 diffY = this.constrain(h, diffY, mh, mxh);
28763 diffX = this.constrain(w, diffX, mw, mxw);
28764 diffY = this.constrain(h, diffY, mh, mxh);
28771 diffX = this.constrain(w, diffX, mw, mxw);
28773 h = Math.min(Math.max(mh, h), mxh);
28779 var sw = this.snap(w, wi, mw);
28780 var sh = this.snap(h, hi, mh);
28781 if(sw != w || sh != h){
28804 if(this.preserveRatio){
28809 h = Math.min(Math.max(mh, h), mxh);
28814 w = Math.min(Math.max(mw, w), mxw);
28819 w = Math.min(Math.max(mw, w), mxw);
28825 w = Math.min(Math.max(mw, w), mxw);
28831 h = Math.min(Math.max(mh, h), mxh);
28839 h = Math.min(Math.max(mh, h), mxh);
28849 h = Math.min(Math.max(mh, h), mxh);
28857 if (pos == 'hdrag') {
28860 this.proxy.setBounds(x, y, w, h);
28862 this.resizeElement();
28866 this.fireEvent("resizing", this, x, y, w, h, e);
28870 handleOver : function(){
28872 this.el.addClass("x-resizable-over");
28877 handleOut : function(){
28878 if(!this.resizing){
28879 this.el.removeClass("x-resizable-over");
28884 * Returns the element this component is bound to.
28885 * @return {Roo.Element}
28887 getEl : function(){
28892 * Returns the resizeChild element (or null).
28893 * @return {Roo.Element}
28895 getResizeChild : function(){
28896 return this.resizeChild;
28898 groupHandler : function()
28903 * Destroys this resizable. If the element was wrapped and
28904 * removeEl is not true then the element remains.
28905 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
28907 destroy : function(removeEl){
28908 this.proxy.remove();
28910 this.overlay.removeAllListeners();
28911 this.overlay.remove();
28913 var ps = Roo.Resizable.positions;
28915 if(typeof ps[k] != "function" && this[ps[k]]){
28916 var h = this[ps[k]];
28917 h.el.removeAllListeners();
28922 this.el.update("");
28929 // hash to map config positions to true positions
28930 Roo.Resizable.positions = {
28931 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
28936 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
28938 // only initialize the template if resizable is used
28939 var tpl = Roo.DomHelper.createTemplate(
28940 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
28943 Roo.Resizable.Handle.prototype.tpl = tpl;
28945 this.position = pos;
28947 // show north drag fro topdra
28948 var handlepos = pos == 'hdrag' ? 'north' : pos;
28950 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
28951 if (pos == 'hdrag') {
28952 this.el.setStyle('cursor', 'pointer');
28954 this.el.unselectable();
28956 this.el.setOpacity(0);
28958 this.el.on("mousedown", this.onMouseDown, this);
28959 if(!disableTrackOver){
28960 this.el.on("mouseover", this.onMouseOver, this);
28961 this.el.on("mouseout", this.onMouseOut, this);
28966 Roo.Resizable.Handle.prototype = {
28967 afterResize : function(rz){
28971 onMouseDown : function(e){
28972 this.rz.onMouseDown(this, e);
28975 onMouseOver : function(e){
28976 this.rz.handleOver(this, e);
28979 onMouseOut : function(e){
28980 this.rz.handleOut(this, e);
28984 * Ext JS Library 1.1.1
28985 * Copyright(c) 2006-2007, Ext JS, LLC.
28987 * Originally Released Under LGPL - original licence link has changed is not relivant.
28990 * <script type="text/javascript">
28994 * @class Roo.Editor
28995 * @extends Roo.Component
28996 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
28998 * Create a new Editor
28999 * @param {Roo.form.Field} field The Field object (or descendant)
29000 * @param {Object} config The config object
29002 Roo.Editor = function(field, config){
29003 Roo.Editor.superclass.constructor.call(this, config);
29004 this.field = field;
29007 * @event beforestartedit
29008 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
29009 * false from the handler of this event.
29010 * @param {Editor} this
29011 * @param {Roo.Element} boundEl The underlying element bound to this editor
29012 * @param {Mixed} value The field value being set
29014 "beforestartedit" : true,
29017 * Fires when this editor is displayed
29018 * @param {Roo.Element} boundEl The underlying element bound to this editor
29019 * @param {Mixed} value The starting field value
29021 "startedit" : true,
29023 * @event beforecomplete
29024 * Fires after a change has been made to the field, but before the change is reflected in the underlying
29025 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
29026 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
29027 * event will not fire since no edit actually occurred.
29028 * @param {Editor} this
29029 * @param {Mixed} value The current field value
29030 * @param {Mixed} startValue The original field value
29032 "beforecomplete" : true,
29035 * Fires after editing is complete and any changed value has been written to the underlying field.
29036 * @param {Editor} this
29037 * @param {Mixed} value The current field value
29038 * @param {Mixed} startValue The original field value
29042 * @event specialkey
29043 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
29044 * {@link Roo.EventObject#getKey} to determine which key was pressed.
29045 * @param {Roo.form.Field} this
29046 * @param {Roo.EventObject} e The event object
29048 "specialkey" : true
29052 Roo.extend(Roo.Editor, Roo.Component, {
29054 * @cfg {Boolean/String} autosize
29055 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
29056 * or "height" to adopt the height only (defaults to false)
29059 * @cfg {Boolean} revertInvalid
29060 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
29061 * validation fails (defaults to true)
29064 * @cfg {Boolean} ignoreNoChange
29065 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
29066 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
29067 * will never be ignored.
29070 * @cfg {Boolean} hideEl
29071 * False to keep the bound element visible while the editor is displayed (defaults to true)
29074 * @cfg {Mixed} value
29075 * The data value of the underlying field (defaults to "")
29079 * @cfg {String} alignment
29080 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
29084 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
29085 * for bottom-right shadow (defaults to "frame")
29089 * @cfg {Boolean} constrain True to constrain the editor to the viewport
29093 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
29095 completeOnEnter : false,
29097 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
29099 cancelOnEsc : false,
29101 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
29106 onRender : function(ct, position){
29107 this.el = new Roo.Layer({
29108 shadow: this.shadow,
29114 constrain: this.constrain
29116 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
29117 if(this.field.msgTarget != 'title'){
29118 this.field.msgTarget = 'qtip';
29120 this.field.render(this.el);
29122 this.field.el.dom.setAttribute('autocomplete', 'off');
29124 this.field.on("specialkey", this.onSpecialKey, this);
29125 if(this.swallowKeys){
29126 this.field.el.swallowEvent(['keydown','keypress']);
29129 this.field.on("blur", this.onBlur, this);
29130 if(this.field.grow){
29131 this.field.on("autosize", this.el.sync, this.el, {delay:1});
29135 onSpecialKey : function(field, e)
29137 //Roo.log('editor onSpecialKey');
29138 if(this.completeOnEnter && e.getKey() == e.ENTER){
29140 this.completeEdit();
29143 // do not fire special key otherwise it might hide close the editor...
29144 if(e.getKey() == e.ENTER){
29147 if(this.cancelOnEsc && e.getKey() == e.ESC){
29151 this.fireEvent('specialkey', field, e);
29156 * Starts the editing process and shows the editor.
29157 * @param {String/HTMLElement/Element} el The element to edit
29158 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
29159 * to the innerHTML of el.
29161 startEdit : function(el, value){
29163 this.completeEdit();
29165 this.boundEl = Roo.get(el);
29166 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
29167 if(!this.rendered){
29168 this.render(this.parentEl || document.body);
29170 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
29173 this.startValue = v;
29174 this.field.setValue(v);
29176 var sz = this.boundEl.getSize();
29177 switch(this.autoSize){
29179 this.setSize(sz.width, "");
29182 this.setSize("", sz.height);
29185 this.setSize(sz.width, sz.height);
29188 this.el.alignTo(this.boundEl, this.alignment);
29189 this.editing = true;
29191 Roo.QuickTips.disable();
29197 * Sets the height and width of this editor.
29198 * @param {Number} width The new width
29199 * @param {Number} height The new height
29201 setSize : function(w, h){
29202 this.field.setSize(w, h);
29209 * Realigns the editor to the bound field based on the current alignment config value.
29211 realign : function(){
29212 this.el.alignTo(this.boundEl, this.alignment);
29216 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
29217 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
29219 completeEdit : function(remainVisible){
29223 var v = this.getValue();
29224 if(this.revertInvalid !== false && !this.field.isValid()){
29225 v = this.startValue;
29226 this.cancelEdit(true);
29228 if(String(v) === String(this.startValue) && this.ignoreNoChange){
29229 this.editing = false;
29233 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
29234 this.editing = false;
29235 if(this.updateEl && this.boundEl){
29236 this.boundEl.update(v);
29238 if(remainVisible !== true){
29241 this.fireEvent("complete", this, v, this.startValue);
29246 onShow : function(){
29248 if(this.hideEl !== false){
29249 this.boundEl.hide();
29252 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
29253 this.fixIEFocus = true;
29254 this.deferredFocus.defer(50, this);
29256 this.field.focus();
29258 this.fireEvent("startedit", this.boundEl, this.startValue);
29261 deferredFocus : function(){
29263 this.field.focus();
29268 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
29269 * reverted to the original starting value.
29270 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
29271 * cancel (defaults to false)
29273 cancelEdit : function(remainVisible){
29275 this.setValue(this.startValue);
29276 if(remainVisible !== true){
29283 onBlur : function(){
29284 if(this.allowBlur !== true && this.editing){
29285 this.completeEdit();
29290 onHide : function(){
29292 this.completeEdit();
29296 if(this.field.collapse){
29297 this.field.collapse();
29300 if(this.hideEl !== false){
29301 this.boundEl.show();
29304 Roo.QuickTips.enable();
29309 * Sets the data value of the editor
29310 * @param {Mixed} value Any valid value supported by the underlying field
29312 setValue : function(v){
29313 this.field.setValue(v);
29317 * Gets the data value of the editor
29318 * @return {Mixed} The data value
29320 getValue : function(){
29321 return this.field.getValue();
29325 * Ext JS Library 1.1.1
29326 * Copyright(c) 2006-2007, Ext JS, LLC.
29328 * Originally Released Under LGPL - original licence link has changed is not relivant.
29331 * <script type="text/javascript">
29335 * @class Roo.BasicDialog
29336 * @extends Roo.util.Observable
29337 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
29339 var dlg = new Roo.BasicDialog("my-dlg", {
29348 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
29349 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
29350 dlg.addButton('Cancel', dlg.hide, dlg);
29353 <b>A Dialog should always be a direct child of the body element.</b>
29354 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
29355 * @cfg {String} title Default text to display in the title bar (defaults to null)
29356 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
29357 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
29358 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
29359 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
29360 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
29361 * (defaults to null with no animation)
29362 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
29363 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
29364 * property for valid values (defaults to 'all')
29365 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
29366 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
29367 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
29368 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
29369 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
29370 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
29371 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
29372 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
29373 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
29374 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
29375 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
29376 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
29377 * draggable = true (defaults to false)
29378 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
29379 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
29380 * shadow (defaults to false)
29381 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
29382 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
29383 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
29384 * @cfg {Array} buttons Array of buttons
29385 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
29387 * Create a new BasicDialog.
29388 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
29389 * @param {Object} config Configuration options
29391 Roo.BasicDialog = function(el, config){
29392 this.el = Roo.get(el);
29393 var dh = Roo.DomHelper;
29394 if(!this.el && config && config.autoCreate){
29395 if(typeof config.autoCreate == "object"){
29396 if(!config.autoCreate.id){
29397 config.autoCreate.id = el;
29399 this.el = dh.append(document.body,
29400 config.autoCreate, true);
29402 this.el = dh.append(document.body,
29403 {tag: "div", id: el, style:'visibility:hidden;'}, true);
29407 el.setDisplayed(true);
29408 el.hide = this.hideAction;
29410 el.addClass("x-dlg");
29412 Roo.apply(this, config);
29414 this.proxy = el.createProxy("x-dlg-proxy");
29415 this.proxy.hide = this.hideAction;
29416 this.proxy.setOpacity(.5);
29420 el.setWidth(config.width);
29423 el.setHeight(config.height);
29425 this.size = el.getSize();
29426 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
29427 this.xy = [config.x,config.y];
29429 this.xy = el.getCenterXY(true);
29431 /** The header element @type Roo.Element */
29432 this.header = el.child("> .x-dlg-hd");
29433 /** The body element @type Roo.Element */
29434 this.body = el.child("> .x-dlg-bd");
29435 /** The footer element @type Roo.Element */
29436 this.footer = el.child("> .x-dlg-ft");
29439 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
29442 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
29445 this.header.unselectable();
29447 this.header.update(this.title);
29449 // this element allows the dialog to be focused for keyboard event
29450 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
29451 this.focusEl.swallowEvent("click", true);
29453 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
29455 // wrap the body and footer for special rendering
29456 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
29458 this.bwrap.dom.appendChild(this.footer.dom);
29461 this.bg = this.el.createChild({
29462 tag: "div", cls:"x-dlg-bg",
29463 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
29465 this.centerBg = this.bg.child("div.x-dlg-bg-center");
29468 if(this.autoScroll !== false && !this.autoTabs){
29469 this.body.setStyle("overflow", "auto");
29472 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
29474 if(this.closable !== false){
29475 this.el.addClass("x-dlg-closable");
29476 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
29477 this.close.on("click", this.closeClick, this);
29478 this.close.addClassOnOver("x-dlg-close-over");
29480 if(this.collapsible !== false){
29481 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
29482 this.collapseBtn.on("click", this.collapseClick, this);
29483 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
29484 this.header.on("dblclick", this.collapseClick, this);
29486 if(this.resizable !== false){
29487 this.el.addClass("x-dlg-resizable");
29488 this.resizer = new Roo.Resizable(el, {
29489 minWidth: this.minWidth || 80,
29490 minHeight:this.minHeight || 80,
29491 handles: this.resizeHandles || "all",
29494 this.resizer.on("beforeresize", this.beforeResize, this);
29495 this.resizer.on("resize", this.onResize, this);
29497 if(this.draggable !== false){
29498 el.addClass("x-dlg-draggable");
29499 if (!this.proxyDrag) {
29500 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
29503 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
29505 dd.setHandleElId(this.header.id);
29506 dd.endDrag = this.endMove.createDelegate(this);
29507 dd.startDrag = this.startMove.createDelegate(this);
29508 dd.onDrag = this.onDrag.createDelegate(this);
29513 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
29514 this.mask.enableDisplayMode("block");
29516 this.el.addClass("x-dlg-modal");
29519 this.shadow = new Roo.Shadow({
29520 mode : typeof this.shadow == "string" ? this.shadow : "sides",
29521 offset : this.shadowOffset
29524 this.shadowOffset = 0;
29526 if(Roo.useShims && this.shim !== false){
29527 this.shim = this.el.createShim();
29528 this.shim.hide = this.hideAction;
29536 if (this.buttons) {
29537 var bts= this.buttons;
29539 Roo.each(bts, function(b) {
29548 * Fires when a key is pressed
29549 * @param {Roo.BasicDialog} this
29550 * @param {Roo.EventObject} e
29555 * Fires when this dialog is moved by the user.
29556 * @param {Roo.BasicDialog} this
29557 * @param {Number} x The new page X
29558 * @param {Number} y The new page Y
29563 * Fires when this dialog is resized by the user.
29564 * @param {Roo.BasicDialog} this
29565 * @param {Number} width The new width
29566 * @param {Number} height The new height
29570 * @event beforehide
29571 * Fires before this dialog is hidden.
29572 * @param {Roo.BasicDialog} this
29574 "beforehide" : true,
29577 * Fires when this dialog is hidden.
29578 * @param {Roo.BasicDialog} this
29582 * @event beforeshow
29583 * Fires before this dialog is shown.
29584 * @param {Roo.BasicDialog} this
29586 "beforeshow" : true,
29589 * Fires when this dialog is shown.
29590 * @param {Roo.BasicDialog} this
29594 el.on("keydown", this.onKeyDown, this);
29595 el.on("mousedown", this.toFront, this);
29596 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
29598 Roo.DialogManager.register(this);
29599 Roo.BasicDialog.superclass.constructor.call(this);
29602 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
29603 shadowOffset: Roo.isIE ? 6 : 5,
29606 minButtonWidth: 75,
29607 defaultButton: null,
29608 buttonAlign: "right",
29613 * Sets the dialog title text
29614 * @param {String} text The title text to display
29615 * @return {Roo.BasicDialog} this
29617 setTitle : function(text){
29618 this.header.update(text);
29623 closeClick : function(){
29628 collapseClick : function(){
29629 this[this.collapsed ? "expand" : "collapse"]();
29633 * Collapses the dialog to its minimized state (only the title bar is visible).
29634 * Equivalent to the user clicking the collapse dialog button.
29636 collapse : function(){
29637 if(!this.collapsed){
29638 this.collapsed = true;
29639 this.el.addClass("x-dlg-collapsed");
29640 this.restoreHeight = this.el.getHeight();
29641 this.resizeTo(this.el.getWidth(), this.header.getHeight());
29646 * Expands a collapsed dialog back to its normal state. Equivalent to the user
29647 * clicking the expand dialog button.
29649 expand : function(){
29650 if(this.collapsed){
29651 this.collapsed = false;
29652 this.el.removeClass("x-dlg-collapsed");
29653 this.resizeTo(this.el.getWidth(), this.restoreHeight);
29658 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
29659 * @return {Roo.TabPanel} The tabs component
29661 initTabs : function(){
29662 var tabs = this.getTabs();
29663 while(tabs.getTab(0)){
29666 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
29668 tabs.addTab(Roo.id(dom), dom.title);
29676 beforeResize : function(){
29677 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
29681 onResize : function(){
29682 this.refreshSize();
29683 this.syncBodyHeight();
29684 this.adjustAssets();
29686 this.fireEvent("resize", this, this.size.width, this.size.height);
29690 onKeyDown : function(e){
29691 if(this.isVisible()){
29692 this.fireEvent("keydown", this, e);
29697 * Resizes the dialog.
29698 * @param {Number} width
29699 * @param {Number} height
29700 * @return {Roo.BasicDialog} this
29702 resizeTo : function(width, height){
29703 this.el.setSize(width, height);
29704 this.size = {width: width, height: height};
29705 this.syncBodyHeight();
29706 if(this.fixedcenter){
29709 if(this.isVisible()){
29710 this.constrainXY();
29711 this.adjustAssets();
29713 this.fireEvent("resize", this, width, height);
29719 * Resizes the dialog to fit the specified content size.
29720 * @param {Number} width
29721 * @param {Number} height
29722 * @return {Roo.BasicDialog} this
29724 setContentSize : function(w, h){
29725 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
29726 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
29727 //if(!this.el.isBorderBox()){
29728 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
29729 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
29732 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
29733 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
29735 this.resizeTo(w, h);
29740 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
29741 * executed in response to a particular key being pressed while the dialog is active.
29742 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
29743 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
29744 * @param {Function} fn The function to call
29745 * @param {Object} scope (optional) The scope of the function
29746 * @return {Roo.BasicDialog} this
29748 addKeyListener : function(key, fn, scope){
29749 var keyCode, shift, ctrl, alt;
29750 if(typeof key == "object" && !(key instanceof Array)){
29751 keyCode = key["key"];
29752 shift = key["shift"];
29753 ctrl = key["ctrl"];
29758 var handler = function(dlg, e){
29759 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
29760 var k = e.getKey();
29761 if(keyCode instanceof Array){
29762 for(var i = 0, len = keyCode.length; i < len; i++){
29763 if(keyCode[i] == k){
29764 fn.call(scope || window, dlg, k, e);
29770 fn.call(scope || window, dlg, k, e);
29775 this.on("keydown", handler);
29780 * Returns the TabPanel component (creates it if it doesn't exist).
29781 * Note: If you wish to simply check for the existence of tabs without creating them,
29782 * check for a null 'tabs' property.
29783 * @return {Roo.TabPanel} The tabs component
29785 getTabs : function(){
29787 this.el.addClass("x-dlg-auto-tabs");
29788 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
29789 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
29795 * Adds a button to the footer section of the dialog.
29796 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
29797 * object or a valid Roo.DomHelper element config
29798 * @param {Function} handler The function called when the button is clicked
29799 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
29800 * @return {Roo.Button} The new button
29802 addButton : function(config, handler, scope){
29803 var dh = Roo.DomHelper;
29805 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
29807 if(!this.btnContainer){
29808 var tb = this.footer.createChild({
29810 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
29811 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
29813 this.btnContainer = tb.firstChild.firstChild.firstChild;
29818 minWidth: this.minButtonWidth,
29821 if(typeof config == "string"){
29822 bconfig.text = config;
29825 bconfig.dhconfig = config;
29827 Roo.apply(bconfig, config);
29831 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
29832 bconfig.position = Math.max(0, bconfig.position);
29833 fc = this.btnContainer.childNodes[bconfig.position];
29836 var btn = new Roo.Button(
29838 this.btnContainer.insertBefore(document.createElement("td"),fc)
29839 : this.btnContainer.appendChild(document.createElement("td")),
29840 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
29843 this.syncBodyHeight();
29846 * Array of all the buttons that have been added to this dialog via addButton
29851 this.buttons.push(btn);
29856 * Sets the default button to be focused when the dialog is displayed.
29857 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
29858 * @return {Roo.BasicDialog} this
29860 setDefaultButton : function(btn){
29861 this.defaultButton = btn;
29866 getHeaderFooterHeight : function(safe){
29869 height += this.header.getHeight();
29872 var fm = this.footer.getMargins();
29873 height += (this.footer.getHeight()+fm.top+fm.bottom);
29875 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
29876 height += this.centerBg.getPadding("tb");
29881 syncBodyHeight : function()
29883 var bd = this.body, // the text
29884 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
29886 var height = this.size.height - this.getHeaderFooterHeight(false);
29887 bd.setHeight(height-bd.getMargins("tb"));
29888 var hh = this.header.getHeight();
29889 var h = this.size.height-hh;
29892 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
29893 bw.setHeight(h-cb.getPadding("tb"));
29895 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
29896 bd.setWidth(bw.getWidth(true));
29898 this.tabs.syncHeight();
29900 this.tabs.el.repaint();
29906 * Restores the previous state of the dialog if Roo.state is configured.
29907 * @return {Roo.BasicDialog} this
29909 restoreState : function(){
29910 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
29911 if(box && box.width){
29912 this.xy = [box.x, box.y];
29913 this.resizeTo(box.width, box.height);
29919 beforeShow : function(){
29921 if(this.fixedcenter){
29922 this.xy = this.el.getCenterXY(true);
29925 Roo.get(document.body).addClass("x-body-masked");
29926 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
29929 this.constrainXY();
29933 animShow : function(){
29934 var b = Roo.get(this.animateTarget).getBox();
29935 this.proxy.setSize(b.width, b.height);
29936 this.proxy.setLocation(b.x, b.y);
29938 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
29939 true, .35, this.showEl.createDelegate(this));
29943 * Shows the dialog.
29944 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
29945 * @return {Roo.BasicDialog} this
29947 show : function(animateTarget){
29948 if (this.fireEvent("beforeshow", this) === false){
29951 if(this.syncHeightBeforeShow){
29952 this.syncBodyHeight();
29953 }else if(this.firstShow){
29954 this.firstShow = false;
29955 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
29957 this.animateTarget = animateTarget || this.animateTarget;
29958 if(!this.el.isVisible()){
29960 if(this.animateTarget && Roo.get(this.animateTarget)){
29970 showEl : function(){
29972 this.el.setXY(this.xy);
29974 this.adjustAssets(true);
29977 // IE peekaboo bug - fix found by Dave Fenwick
29981 this.fireEvent("show", this);
29985 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
29986 * dialog itself will receive focus.
29988 focus : function(){
29989 if(this.defaultButton){
29990 this.defaultButton.focus();
29992 this.focusEl.focus();
29997 constrainXY : function(){
29998 if(this.constraintoviewport !== false){
29999 if(!this.viewSize){
30000 if(this.container){
30001 var s = this.container.getSize();
30002 this.viewSize = [s.width, s.height];
30004 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
30007 var s = Roo.get(this.container||document).getScroll();
30009 var x = this.xy[0], y = this.xy[1];
30010 var w = this.size.width, h = this.size.height;
30011 var vw = this.viewSize[0], vh = this.viewSize[1];
30012 // only move it if it needs it
30014 // first validate right/bottom
30015 if(x + w > vw+s.left){
30019 if(y + h > vh+s.top){
30023 // then make sure top/left isn't negative
30035 if(this.isVisible()){
30036 this.el.setLocation(x, y);
30037 this.adjustAssets();
30044 onDrag : function(){
30045 if(!this.proxyDrag){
30046 this.xy = this.el.getXY();
30047 this.adjustAssets();
30052 adjustAssets : function(doShow){
30053 var x = this.xy[0], y = this.xy[1];
30054 var w = this.size.width, h = this.size.height;
30055 if(doShow === true){
30057 this.shadow.show(this.el);
30063 if(this.shadow && this.shadow.isVisible()){
30064 this.shadow.show(this.el);
30066 if(this.shim && this.shim.isVisible()){
30067 this.shim.setBounds(x, y, w, h);
30072 adjustViewport : function(w, h){
30074 w = Roo.lib.Dom.getViewWidth();
30075 h = Roo.lib.Dom.getViewHeight();
30078 this.viewSize = [w, h];
30079 if(this.modal && this.mask.isVisible()){
30080 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
30081 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
30083 if(this.isVisible()){
30084 this.constrainXY();
30089 * Destroys this dialog and all its supporting elements (including any tabs, shim,
30090 * shadow, proxy, mask, etc.) Also removes all event listeners.
30091 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
30093 destroy : function(removeEl){
30094 if(this.isVisible()){
30095 this.animateTarget = null;
30098 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
30100 this.tabs.destroy(removeEl);
30113 for(var i = 0, len = this.buttons.length; i < len; i++){
30114 this.buttons[i].destroy();
30117 this.el.removeAllListeners();
30118 if(removeEl === true){
30119 this.el.update("");
30122 Roo.DialogManager.unregister(this);
30126 startMove : function(){
30127 if(this.proxyDrag){
30130 if(this.constraintoviewport !== false){
30131 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
30136 endMove : function(){
30137 if(!this.proxyDrag){
30138 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
30140 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
30143 this.refreshSize();
30144 this.adjustAssets();
30146 this.fireEvent("move", this, this.xy[0], this.xy[1]);
30150 * Brings this dialog to the front of any other visible dialogs
30151 * @return {Roo.BasicDialog} this
30153 toFront : function(){
30154 Roo.DialogManager.bringToFront(this);
30159 * Sends this dialog to the back (under) of any other visible dialogs
30160 * @return {Roo.BasicDialog} this
30162 toBack : function(){
30163 Roo.DialogManager.sendToBack(this);
30168 * Centers this dialog in the viewport
30169 * @return {Roo.BasicDialog} this
30171 center : function(){
30172 var xy = this.el.getCenterXY(true);
30173 this.moveTo(xy[0], xy[1]);
30178 * Moves the dialog's top-left corner to the specified point
30179 * @param {Number} x
30180 * @param {Number} y
30181 * @return {Roo.BasicDialog} this
30183 moveTo : function(x, y){
30185 if(this.isVisible()){
30186 this.el.setXY(this.xy);
30187 this.adjustAssets();
30193 * Aligns the dialog to the specified element
30194 * @param {String/HTMLElement/Roo.Element} element The element to align to.
30195 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
30196 * @param {Array} offsets (optional) Offset the positioning by [x, y]
30197 * @return {Roo.BasicDialog} this
30199 alignTo : function(element, position, offsets){
30200 this.xy = this.el.getAlignToXY(element, position, offsets);
30201 if(this.isVisible()){
30202 this.el.setXY(this.xy);
30203 this.adjustAssets();
30209 * Anchors an element to another element and realigns it when the window is resized.
30210 * @param {String/HTMLElement/Roo.Element} element The element to align to.
30211 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
30212 * @param {Array} offsets (optional) Offset the positioning by [x, y]
30213 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
30214 * is a number, it is used as the buffer delay (defaults to 50ms).
30215 * @return {Roo.BasicDialog} this
30217 anchorTo : function(el, alignment, offsets, monitorScroll){
30218 var action = function(){
30219 this.alignTo(el, alignment, offsets);
30221 Roo.EventManager.onWindowResize(action, this);
30222 var tm = typeof monitorScroll;
30223 if(tm != 'undefined'){
30224 Roo.EventManager.on(window, 'scroll', action, this,
30225 {buffer: tm == 'number' ? monitorScroll : 50});
30232 * Returns true if the dialog is visible
30233 * @return {Boolean}
30235 isVisible : function(){
30236 return this.el.isVisible();
30240 animHide : function(callback){
30241 var b = Roo.get(this.animateTarget).getBox();
30243 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
30245 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
30246 this.hideEl.createDelegate(this, [callback]));
30250 * Hides the dialog.
30251 * @param {Function} callback (optional) Function to call when the dialog is hidden
30252 * @return {Roo.BasicDialog} this
30254 hide : function(callback){
30255 if (this.fireEvent("beforehide", this) === false){
30259 this.shadow.hide();
30264 // sometimes animateTarget seems to get set.. causing problems...
30265 // this just double checks..
30266 if(this.animateTarget && Roo.get(this.animateTarget)) {
30267 this.animHide(callback);
30270 this.hideEl(callback);
30276 hideEl : function(callback){
30280 Roo.get(document.body).removeClass("x-body-masked");
30282 this.fireEvent("hide", this);
30283 if(typeof callback == "function"){
30289 hideAction : function(){
30290 this.setLeft("-10000px");
30291 this.setTop("-10000px");
30292 this.setStyle("visibility", "hidden");
30296 refreshSize : function(){
30297 this.size = this.el.getSize();
30298 this.xy = this.el.getXY();
30299 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
30303 // z-index is managed by the DialogManager and may be overwritten at any time
30304 setZIndex : function(index){
30306 this.mask.setStyle("z-index", index);
30309 this.shim.setStyle("z-index", ++index);
30312 this.shadow.setZIndex(++index);
30314 this.el.setStyle("z-index", ++index);
30316 this.proxy.setStyle("z-index", ++index);
30319 this.resizer.proxy.setStyle("z-index", ++index);
30322 this.lastZIndex = index;
30326 * Returns the element for this dialog
30327 * @return {Roo.Element} The underlying dialog Element
30329 getEl : function(){
30335 * @class Roo.DialogManager
30336 * Provides global access to BasicDialogs that have been created and
30337 * support for z-indexing (layering) multiple open dialogs.
30339 Roo.DialogManager = function(){
30341 var accessList = [];
30345 var sortDialogs = function(d1, d2){
30346 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
30350 var orderDialogs = function(){
30351 accessList.sort(sortDialogs);
30352 var seed = Roo.DialogManager.zseed;
30353 for(var i = 0, len = accessList.length; i < len; i++){
30354 var dlg = accessList[i];
30356 dlg.setZIndex(seed + (i*10));
30363 * The starting z-index for BasicDialogs (defaults to 9000)
30364 * @type Number The z-index value
30369 register : function(dlg){
30370 list[dlg.id] = dlg;
30371 accessList.push(dlg);
30375 unregister : function(dlg){
30376 delete list[dlg.id];
30379 if(!accessList.indexOf){
30380 for( i = 0, len = accessList.length; i < len; i++){
30381 if(accessList[i] == dlg){
30382 accessList.splice(i, 1);
30387 i = accessList.indexOf(dlg);
30389 accessList.splice(i, 1);
30395 * Gets a registered dialog by id
30396 * @param {String/Object} id The id of the dialog or a dialog
30397 * @return {Roo.BasicDialog} this
30399 get : function(id){
30400 return typeof id == "object" ? id : list[id];
30404 * Brings the specified dialog to the front
30405 * @param {String/Object} dlg The id of the dialog or a dialog
30406 * @return {Roo.BasicDialog} this
30408 bringToFront : function(dlg){
30409 dlg = this.get(dlg);
30412 dlg._lastAccess = new Date().getTime();
30419 * Sends the specified dialog to the back
30420 * @param {String/Object} dlg The id of the dialog or a dialog
30421 * @return {Roo.BasicDialog} this
30423 sendToBack : function(dlg){
30424 dlg = this.get(dlg);
30425 dlg._lastAccess = -(new Date().getTime());
30431 * Hides all dialogs
30433 hideAll : function(){
30434 for(var id in list){
30435 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
30444 * @class Roo.LayoutDialog
30445 * @extends Roo.BasicDialog
30446 * Dialog which provides adjustments for working with a layout in a Dialog.
30447 * Add your necessary layout config options to the dialog's config.<br>
30448 * Example usage (including a nested layout):
30451 dialog = new Roo.LayoutDialog("download-dlg", {
30460 // layout config merges with the dialog config
30462 tabPosition: "top",
30463 alwaysShowTabs: true
30466 dialog.addKeyListener(27, dialog.hide, dialog);
30467 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
30468 dialog.addButton("Build It!", this.getDownload, this);
30470 // we can even add nested layouts
30471 var innerLayout = new Roo.BorderLayout("dl-inner", {
30481 innerLayout.beginUpdate();
30482 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
30483 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
30484 innerLayout.endUpdate(true);
30486 var layout = dialog.getLayout();
30487 layout.beginUpdate();
30488 layout.add("center", new Roo.ContentPanel("standard-panel",
30489 {title: "Download the Source", fitToFrame:true}));
30490 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
30491 {title: "Build your own roo.js"}));
30492 layout.getRegion("center").showPanel(sp);
30493 layout.endUpdate();
30497 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
30498 * @param {Object} config configuration options
30500 Roo.LayoutDialog = function(el, cfg){
30503 if (typeof(cfg) == 'undefined') {
30504 config = Roo.apply({}, el);
30505 // not sure why we use documentElement here.. - it should always be body.
30506 // IE7 borks horribly if we use documentElement.
30507 // webkit also does not like documentElement - it creates a body element...
30508 el = Roo.get( document.body || document.documentElement ).createChild();
30509 //config.autoCreate = true;
30513 config.autoTabs = false;
30514 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
30515 this.body.setStyle({overflow:"hidden", position:"relative"});
30516 this.layout = new Roo.BorderLayout(this.body.dom, config);
30517 this.layout.monitorWindowResize = false;
30518 this.el.addClass("x-dlg-auto-layout");
30519 // fix case when center region overwrites center function
30520 this.center = Roo.BasicDialog.prototype.center;
30521 this.on("show", this.layout.layout, this.layout, true);
30522 if (config.items) {
30523 var xitems = config.items;
30524 delete config.items;
30525 Roo.each(xitems, this.addxtype, this);
30530 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
30532 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
30535 endUpdate : function(){
30536 this.layout.endUpdate();
30540 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
30543 beginUpdate : function(){
30544 this.layout.beginUpdate();
30548 * Get the BorderLayout for this dialog
30549 * @return {Roo.BorderLayout}
30551 getLayout : function(){
30552 return this.layout;
30555 showEl : function(){
30556 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
30558 this.layout.layout();
30563 // Use the syncHeightBeforeShow config option to control this automatically
30564 syncBodyHeight : function(){
30565 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
30566 if(this.layout){this.layout.layout();}
30570 * Add an xtype element (actually adds to the layout.)
30571 * @return {Object} xdata xtype object data.
30574 addxtype : function(c) {
30575 return this.layout.addxtype(c);
30579 * Ext JS Library 1.1.1
30580 * Copyright(c) 2006-2007, Ext JS, LLC.
30582 * Originally Released Under LGPL - original licence link has changed is not relivant.
30585 * <script type="text/javascript">
30589 * @class Roo.MessageBox
30590 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
30594 Roo.Msg.alert('Status', 'Changes saved successfully.');
30596 // Prompt for user data:
30597 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
30599 // process text value...
30603 // Show a dialog using config options:
30605 title:'Save Changes?',
30606 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
30607 buttons: Roo.Msg.YESNOCANCEL,
30614 Roo.MessageBox = function(){
30615 var dlg, opt, mask, waitTimer;
30616 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
30617 var buttons, activeTextEl, bwidth;
30620 var handleButton = function(button){
30622 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
30626 var handleHide = function(){
30627 if(opt && opt.cls){
30628 dlg.el.removeClass(opt.cls);
30631 Roo.TaskMgr.stop(waitTimer);
30637 var updateButtons = function(b){
30640 buttons["ok"].hide();
30641 buttons["cancel"].hide();
30642 buttons["yes"].hide();
30643 buttons["no"].hide();
30644 dlg.footer.dom.style.display = 'none';
30647 dlg.footer.dom.style.display = '';
30648 for(var k in buttons){
30649 if(typeof buttons[k] != "function"){
30652 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
30653 width += buttons[k].el.getWidth()+15;
30663 var handleEsc = function(d, k, e){
30664 if(opt && opt.closable !== false){
30674 * Returns a reference to the underlying {@link Roo.BasicDialog} element
30675 * @return {Roo.BasicDialog} The BasicDialog element
30677 getDialog : function(){
30679 dlg = new Roo.BasicDialog("x-msg-box", {
30684 constraintoviewport:false,
30686 collapsible : false,
30689 width:400, height:100,
30690 buttonAlign:"center",
30691 closeClick : function(){
30692 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
30693 handleButton("no");
30695 handleButton("cancel");
30699 dlg.on("hide", handleHide);
30701 dlg.addKeyListener(27, handleEsc);
30703 var bt = this.buttonText;
30704 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
30705 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
30706 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
30707 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
30708 bodyEl = dlg.body.createChild({
30710 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>'
30712 msgEl = bodyEl.dom.firstChild;
30713 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
30714 textboxEl.enableDisplayMode();
30715 textboxEl.addKeyListener([10,13], function(){
30716 if(dlg.isVisible() && opt && opt.buttons){
30717 if(opt.buttons.ok){
30718 handleButton("ok");
30719 }else if(opt.buttons.yes){
30720 handleButton("yes");
30724 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
30725 textareaEl.enableDisplayMode();
30726 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
30727 progressEl.enableDisplayMode();
30728 var pf = progressEl.dom.firstChild;
30730 pp = Roo.get(pf.firstChild);
30731 pp.setHeight(pf.offsetHeight);
30739 * Updates the message box body text
30740 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
30741 * the XHTML-compliant non-breaking space character '&#160;')
30742 * @return {Roo.MessageBox} This message box
30744 updateText : function(text){
30745 if(!dlg.isVisible() && !opt.width){
30746 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
30748 msgEl.innerHTML = text || ' ';
30750 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
30751 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
30753 Math.min(opt.width || cw , this.maxWidth),
30754 Math.max(opt.minWidth || this.minWidth, bwidth)
30757 activeTextEl.setWidth(w);
30759 if(dlg.isVisible()){
30760 dlg.fixedcenter = false;
30762 // to big, make it scroll. = But as usual stupid IE does not support
30765 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
30766 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
30767 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
30769 bodyEl.dom.style.height = '';
30770 bodyEl.dom.style.overflowY = '';
30773 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
30775 bodyEl.dom.style.overflowX = '';
30778 dlg.setContentSize(w, bodyEl.getHeight());
30779 if(dlg.isVisible()){
30780 dlg.fixedcenter = true;
30786 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
30787 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
30788 * @param {Number} value Any number between 0 and 1 (e.g., .5)
30789 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
30790 * @return {Roo.MessageBox} This message box
30792 updateProgress : function(value, text){
30794 this.updateText(text);
30796 if (pp) { // weird bug on my firefox - for some reason this is not defined
30797 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
30803 * Returns true if the message box is currently displayed
30804 * @return {Boolean} True if the message box is visible, else false
30806 isVisible : function(){
30807 return dlg && dlg.isVisible();
30811 * Hides the message box if it is displayed
30814 if(this.isVisible()){
30820 * Displays a new message box, or reinitializes an existing message box, based on the config options
30821 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
30822 * The following config object properties are supported:
30824 Property Type Description
30825 ---------- --------------- ------------------------------------------------------------------------------------
30826 animEl String/Element An id or Element from which the message box should animate as it opens and
30827 closes (defaults to undefined)
30828 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
30829 cancel:'Bar'}), or false to not show any buttons (defaults to false)
30830 closable Boolean False to hide the top-right close button (defaults to true). Note that
30831 progress and wait dialogs will ignore this property and always hide the
30832 close button as they can only be closed programmatically.
30833 cls String A custom CSS class to apply to the message box element
30834 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
30835 displayed (defaults to 75)
30836 fn Function A callback function to execute after closing the dialog. The arguments to the
30837 function will be btn (the name of the button that was clicked, if applicable,
30838 e.g. "ok"), and text (the value of the active text field, if applicable).
30839 Progress and wait dialogs will ignore this option since they do not respond to
30840 user actions and can only be closed programmatically, so any required function
30841 should be called by the same code after it closes the dialog.
30842 icon String A CSS class that provides a background image to be used as an icon for
30843 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
30844 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
30845 minWidth Number The minimum width in pixels of the message box (defaults to 100)
30846 modal Boolean False to allow user interaction with the page while the message box is
30847 displayed (defaults to true)
30848 msg String A string that will replace the existing message box body text (defaults
30849 to the XHTML-compliant non-breaking space character ' ')
30850 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
30851 progress Boolean True to display a progress bar (defaults to false)
30852 progressText String The text to display inside the progress bar if progress = true (defaults to '')
30853 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
30854 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
30855 title String The title text
30856 value String The string value to set into the active textbox element if displayed
30857 wait Boolean True to display a progress bar (defaults to false)
30858 width Number The width of the dialog in pixels
30865 msg: 'Please enter your address:',
30867 buttons: Roo.MessageBox.OKCANCEL,
30870 animEl: 'addAddressBtn'
30873 * @param {Object} config Configuration options
30874 * @return {Roo.MessageBox} This message box
30876 show : function(options)
30879 // this causes nightmares if you show one dialog after another
30880 // especially on callbacks..
30882 if(this.isVisible()){
30885 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
30886 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
30887 Roo.log("New Dialog Message:" + options.msg )
30888 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
30889 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
30892 var d = this.getDialog();
30894 d.setTitle(opt.title || " ");
30895 d.close.setDisplayed(opt.closable !== false);
30896 activeTextEl = textboxEl;
30897 opt.prompt = opt.prompt || (opt.multiline ? true : false);
30902 textareaEl.setHeight(typeof opt.multiline == "number" ?
30903 opt.multiline : this.defaultTextHeight);
30904 activeTextEl = textareaEl;
30913 progressEl.setDisplayed(opt.progress === true);
30914 this.updateProgress(0);
30915 activeTextEl.dom.value = opt.value || "";
30917 dlg.setDefaultButton(activeTextEl);
30919 var bs = opt.buttons;
30922 db = buttons["ok"];
30923 }else if(bs && bs.yes){
30924 db = buttons["yes"];
30926 dlg.setDefaultButton(db);
30928 bwidth = updateButtons(opt.buttons);
30929 this.updateText(opt.msg);
30931 d.el.addClass(opt.cls);
30933 d.proxyDrag = opt.proxyDrag === true;
30934 d.modal = opt.modal !== false;
30935 d.mask = opt.modal !== false ? mask : false;
30936 if(!d.isVisible()){
30937 // force it to the end of the z-index stack so it gets a cursor in FF
30938 document.body.appendChild(dlg.el.dom);
30939 d.animateTarget = null;
30940 d.show(options.animEl);
30946 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
30947 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
30948 * and closing the message box when the process is complete.
30949 * @param {String} title The title bar text
30950 * @param {String} msg The message box body text
30951 * @return {Roo.MessageBox} This message box
30953 progress : function(title, msg){
30960 minWidth: this.minProgressWidth,
30967 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
30968 * If a callback function is passed it will be called after the user clicks the button, and the
30969 * id of the button that was clicked will be passed as the only parameter to the callback
30970 * (could also be the top-right close button).
30971 * @param {String} title The title bar text
30972 * @param {String} msg The message box body text
30973 * @param {Function} fn (optional) The callback function invoked after the message box is closed
30974 * @param {Object} scope (optional) The scope of the callback function
30975 * @return {Roo.MessageBox} This message box
30977 alert : function(title, msg, fn, scope){
30990 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
30991 * interaction while waiting for a long-running process to complete that does not have defined intervals.
30992 * You are responsible for closing the message box when the process is complete.
30993 * @param {String} msg The message box body text
30994 * @param {String} title (optional) The title bar text
30995 * @return {Roo.MessageBox} This message box
30997 wait : function(msg, title){
31008 waitTimer = Roo.TaskMgr.start({
31010 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
31018 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
31019 * If a callback function is passed it will be called after the user clicks either button, and the id of the
31020 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
31021 * @param {String} title The title bar text
31022 * @param {String} msg The message box body text
31023 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31024 * @param {Object} scope (optional) The scope of the callback function
31025 * @return {Roo.MessageBox} This message box
31027 confirm : function(title, msg, fn, scope){
31031 buttons: this.YESNO,
31040 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
31041 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
31042 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
31043 * (could also be the top-right close button) and the text that was entered will be passed as the two
31044 * parameters to the callback.
31045 * @param {String} title The title bar text
31046 * @param {String} msg The message box body text
31047 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31048 * @param {Object} scope (optional) The scope of the callback function
31049 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
31050 * property, or the height in pixels to create the textbox (defaults to false / single-line)
31051 * @return {Roo.MessageBox} This message box
31053 prompt : function(title, msg, fn, scope, multiline){
31057 buttons: this.OKCANCEL,
31062 multiline: multiline,
31069 * Button config that displays a single OK button
31074 * Button config that displays Yes and No buttons
31077 YESNO : {yes:true, no:true},
31079 * Button config that displays OK and Cancel buttons
31082 OKCANCEL : {ok:true, cancel:true},
31084 * Button config that displays Yes, No and Cancel buttons
31087 YESNOCANCEL : {yes:true, no:true, cancel:true},
31090 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
31093 defaultTextHeight : 75,
31095 * The maximum width in pixels of the message box (defaults to 600)
31100 * The minimum width in pixels of the message box (defaults to 100)
31105 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
31106 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
31109 minProgressWidth : 250,
31111 * An object containing the default button text strings that can be overriden for localized language support.
31112 * Supported properties are: ok, cancel, yes and no.
31113 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
31126 * Shorthand for {@link Roo.MessageBox}
31128 Roo.Msg = Roo.MessageBox;/*
31130 * Ext JS Library 1.1.1
31131 * Copyright(c) 2006-2007, Ext JS, LLC.
31133 * Originally Released Under LGPL - original licence link has changed is not relivant.
31136 * <script type="text/javascript">
31139 * @class Roo.QuickTips
31140 * Provides attractive and customizable tooltips for any element.
31143 Roo.QuickTips = function(){
31144 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
31145 var ce, bd, xy, dd;
31146 var visible = false, disabled = true, inited = false;
31147 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
31149 var onOver = function(e){
31153 var t = e.getTarget();
31154 if(!t || t.nodeType !== 1 || t == document || t == document.body){
31157 if(ce && t == ce.el){
31158 clearTimeout(hideProc);
31161 if(t && tagEls[t.id]){
31162 tagEls[t.id].el = t;
31163 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
31166 var ttp, et = Roo.fly(t);
31167 var ns = cfg.namespace;
31168 if(tm.interceptTitles && t.title){
31171 t.removeAttribute("title");
31172 e.preventDefault();
31174 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
31177 showProc = show.defer(tm.showDelay, tm, [{
31180 width: et.getAttributeNS(ns, cfg.width),
31181 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
31182 title: et.getAttributeNS(ns, cfg.title),
31183 cls: et.getAttributeNS(ns, cfg.cls)
31188 var onOut = function(e){
31189 clearTimeout(showProc);
31190 var t = e.getTarget();
31191 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
31192 hideProc = setTimeout(hide, tm.hideDelay);
31196 var onMove = function(e){
31202 if(tm.trackMouse && ce){
31207 var onDown = function(e){
31208 clearTimeout(showProc);
31209 clearTimeout(hideProc);
31211 if(tm.hideOnClick){
31214 tm.enable.defer(100, tm);
31219 var getPad = function(){
31220 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
31223 var show = function(o){
31227 clearTimeout(dismissProc);
31229 if(removeCls){ // in case manually hidden
31230 el.removeClass(removeCls);
31234 el.addClass(ce.cls);
31235 removeCls = ce.cls;
31238 tipTitle.update(ce.title);
31241 tipTitle.update('');
31244 el.dom.style.width = tm.maxWidth+'px';
31245 //tipBody.dom.style.width = '';
31246 tipBodyText.update(o.text);
31247 var p = getPad(), w = ce.width;
31249 var td = tipBodyText.dom;
31250 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
31251 if(aw > tm.maxWidth){
31253 }else if(aw < tm.minWidth){
31259 //tipBody.setWidth(w);
31260 el.setWidth(parseInt(w, 10) + p);
31261 if(ce.autoHide === false){
31262 close.setDisplayed(true);
31267 close.setDisplayed(false);
31273 el.avoidY = xy[1]-18;
31278 el.setStyle("visibility", "visible");
31279 el.fadeIn({callback: afterShow});
31285 var afterShow = function(){
31289 if(tm.autoDismiss && ce.autoHide !== false){
31290 dismissProc = setTimeout(hide, tm.autoDismissDelay);
31295 var hide = function(noanim){
31296 clearTimeout(dismissProc);
31297 clearTimeout(hideProc);
31299 if(el.isVisible()){
31301 if(noanim !== true && tm.animate){
31302 el.fadeOut({callback: afterHide});
31309 var afterHide = function(){
31312 el.removeClass(removeCls);
31319 * @cfg {Number} minWidth
31320 * The minimum width of the quick tip (defaults to 40)
31324 * @cfg {Number} maxWidth
31325 * The maximum width of the quick tip (defaults to 300)
31329 * @cfg {Boolean} interceptTitles
31330 * True to automatically use the element's DOM title value if available (defaults to false)
31332 interceptTitles : false,
31334 * @cfg {Boolean} trackMouse
31335 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
31337 trackMouse : false,
31339 * @cfg {Boolean} hideOnClick
31340 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
31342 hideOnClick : true,
31344 * @cfg {Number} showDelay
31345 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
31349 * @cfg {Number} hideDelay
31350 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
31354 * @cfg {Boolean} autoHide
31355 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
31356 * Used in conjunction with hideDelay.
31361 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
31362 * (defaults to true). Used in conjunction with autoDismissDelay.
31364 autoDismiss : true,
31367 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
31369 autoDismissDelay : 5000,
31371 * @cfg {Boolean} animate
31372 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
31377 * @cfg {String} title
31378 * Title text to display (defaults to ''). This can be any valid HTML markup.
31382 * @cfg {String} text
31383 * Body text to display (defaults to ''). This can be any valid HTML markup.
31387 * @cfg {String} cls
31388 * A CSS class to apply to the base quick tip element (defaults to '').
31392 * @cfg {Number} width
31393 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
31394 * minWidth or maxWidth.
31399 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
31400 * or display QuickTips in a page.
31403 tm = Roo.QuickTips;
31404 cfg = tm.tagConfig;
31406 if(!Roo.isReady){ // allow calling of init() before onReady
31407 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
31410 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
31411 el.fxDefaults = {stopFx: true};
31412 // maximum custom styling
31413 //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>');
31414 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>');
31415 tipTitle = el.child('h3');
31416 tipTitle.enableDisplayMode("block");
31417 tipBody = el.child('div.x-tip-bd');
31418 tipBodyText = el.child('div.x-tip-bd-inner');
31419 //bdLeft = el.child('div.x-tip-bd-left');
31420 //bdRight = el.child('div.x-tip-bd-right');
31421 close = el.child('div.x-tip-close');
31422 close.enableDisplayMode("block");
31423 close.on("click", hide);
31424 var d = Roo.get(document);
31425 d.on("mousedown", onDown);
31426 d.on("mouseover", onOver);
31427 d.on("mouseout", onOut);
31428 d.on("mousemove", onMove);
31429 esc = d.addKeyListener(27, hide);
31432 dd = el.initDD("default", null, {
31433 onDrag : function(){
31437 dd.setHandleElId(tipTitle.id);
31446 * Configures a new quick tip instance and assigns it to a target element. The following config options
31449 Property Type Description
31450 ---------- --------------------- ------------------------------------------------------------------------
31451 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
31453 * @param {Object} config The config object
31455 register : function(config){
31456 var cs = config instanceof Array ? config : arguments;
31457 for(var i = 0, len = cs.length; i < len; i++) {
31459 var target = c.target;
31461 if(target instanceof Array){
31462 for(var j = 0, jlen = target.length; j < jlen; j++){
31463 tagEls[target[j]] = c;
31466 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
31473 * Removes this quick tip from its element and destroys it.
31474 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
31476 unregister : function(el){
31477 delete tagEls[Roo.id(el)];
31481 * Enable this quick tip.
31483 enable : function(){
31484 if(inited && disabled){
31486 if(locks.length < 1){
31493 * Disable this quick tip.
31495 disable : function(){
31497 clearTimeout(showProc);
31498 clearTimeout(hideProc);
31499 clearTimeout(dismissProc);
31507 * Returns true if the quick tip is enabled, else false.
31509 isEnabled : function(){
31516 attribute : "qtip",
31526 // backwards compat
31527 Roo.QuickTips.tips = Roo.QuickTips.register;/*
31529 * Ext JS Library 1.1.1
31530 * Copyright(c) 2006-2007, Ext JS, LLC.
31532 * Originally Released Under LGPL - original licence link has changed is not relivant.
31535 * <script type="text/javascript">
31540 * @class Roo.tree.TreePanel
31541 * @extends Roo.data.Tree
31543 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
31544 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
31545 * @cfg {Boolean} enableDD true to enable drag and drop
31546 * @cfg {Boolean} enableDrag true to enable just drag
31547 * @cfg {Boolean} enableDrop true to enable just drop
31548 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
31549 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
31550 * @cfg {String} ddGroup The DD group this TreePanel belongs to
31551 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
31552 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
31553 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
31554 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
31555 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
31556 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
31557 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
31558 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
31559 * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
31560 * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
31561 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
31562 * @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>
31563 * @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>
31566 * @param {String/HTMLElement/Element} el The container element
31567 * @param {Object} config
31569 Roo.tree.TreePanel = function(el, config){
31571 var loader = false;
31573 root = config.root;
31574 delete config.root;
31576 if (config.loader) {
31577 loader = config.loader;
31578 delete config.loader;
31581 Roo.apply(this, config);
31582 Roo.tree.TreePanel.superclass.constructor.call(this);
31583 this.el = Roo.get(el);
31584 this.el.addClass('x-tree');
31585 //console.log(root);
31587 this.setRootNode( Roo.factory(root, Roo.tree));
31590 this.loader = Roo.factory(loader, Roo.tree);
31593 * Read-only. The id of the container element becomes this TreePanel's id.
31595 this.id = this.el.id;
31598 * @event beforeload
31599 * Fires before a node is loaded, return false to cancel
31600 * @param {Node} node The node being loaded
31602 "beforeload" : true,
31605 * Fires when a node is loaded
31606 * @param {Node} node The node that was loaded
31610 * @event textchange
31611 * Fires when the text for a node is changed
31612 * @param {Node} node The node
31613 * @param {String} text The new text
31614 * @param {String} oldText The old text
31616 "textchange" : true,
31618 * @event beforeexpand
31619 * Fires before a node is expanded, return false to cancel.
31620 * @param {Node} node The node
31621 * @param {Boolean} deep
31622 * @param {Boolean} anim
31624 "beforeexpand" : true,
31626 * @event beforecollapse
31627 * Fires before a node is collapsed, return false to cancel.
31628 * @param {Node} node The node
31629 * @param {Boolean} deep
31630 * @param {Boolean} anim
31632 "beforecollapse" : true,
31635 * Fires when a node is expanded
31636 * @param {Node} node The node
31640 * @event disabledchange
31641 * Fires when the disabled status of a node changes
31642 * @param {Node} node The node
31643 * @param {Boolean} disabled
31645 "disabledchange" : true,
31648 * Fires when a node is collapsed
31649 * @param {Node} node The node
31653 * @event beforeclick
31654 * Fires before click processing on a node. Return false to cancel the default action.
31655 * @param {Node} node The node
31656 * @param {Roo.EventObject} e The event object
31658 "beforeclick":true,
31660 * @event checkchange
31661 * Fires when a node with a checkbox's checked property changes
31662 * @param {Node} this This node
31663 * @param {Boolean} checked
31665 "checkchange":true,
31668 * Fires when a node is clicked
31669 * @param {Node} node The node
31670 * @param {Roo.EventObject} e The event object
31675 * Fires when a node is double clicked
31676 * @param {Node} node The node
31677 * @param {Roo.EventObject} e The event object
31681 * @event contextmenu
31682 * Fires when a node is right clicked
31683 * @param {Node} node The node
31684 * @param {Roo.EventObject} e The event object
31686 "contextmenu":true,
31688 * @event beforechildrenrendered
31689 * Fires right before the child nodes for a node are rendered
31690 * @param {Node} node The node
31692 "beforechildrenrendered":true,
31695 * Fires when a node starts being dragged
31696 * @param {Roo.tree.TreePanel} this
31697 * @param {Roo.tree.TreeNode} node
31698 * @param {event} e The raw browser event
31700 "startdrag" : true,
31703 * Fires when a drag operation is complete
31704 * @param {Roo.tree.TreePanel} this
31705 * @param {Roo.tree.TreeNode} node
31706 * @param {event} e The raw browser event
31711 * Fires when a dragged node is dropped on a valid DD target
31712 * @param {Roo.tree.TreePanel} this
31713 * @param {Roo.tree.TreeNode} node
31714 * @param {DD} dd The dd it was dropped on
31715 * @param {event} e The raw browser event
31719 * @event beforenodedrop
31720 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
31721 * passed to handlers has the following properties:<br />
31722 * <ul style="padding:5px;padding-left:16px;">
31723 * <li>tree - The TreePanel</li>
31724 * <li>target - The node being targeted for the drop</li>
31725 * <li>data - The drag data from the drag source</li>
31726 * <li>point - The point of the drop - append, above or below</li>
31727 * <li>source - The drag source</li>
31728 * <li>rawEvent - Raw mouse event</li>
31729 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
31730 * to be inserted by setting them on this object.</li>
31731 * <li>cancel - Set this to true to cancel the drop.</li>
31733 * @param {Object} dropEvent
31735 "beforenodedrop" : true,
31738 * Fires after a DD object is dropped on a node in this tree. The dropEvent
31739 * passed to handlers has the following properties:<br />
31740 * <ul style="padding:5px;padding-left:16px;">
31741 * <li>tree - The TreePanel</li>
31742 * <li>target - The node being targeted for the drop</li>
31743 * <li>data - The drag data from the drag source</li>
31744 * <li>point - The point of the drop - append, above or below</li>
31745 * <li>source - The drag source</li>
31746 * <li>rawEvent - Raw mouse event</li>
31747 * <li>dropNode - Dropped node(s).</li>
31749 * @param {Object} dropEvent
31753 * @event nodedragover
31754 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
31755 * passed to handlers has the following properties:<br />
31756 * <ul style="padding:5px;padding-left:16px;">
31757 * <li>tree - The TreePanel</li>
31758 * <li>target - The node being targeted for the drop</li>
31759 * <li>data - The drag data from the drag source</li>
31760 * <li>point - The point of the drop - append, above or below</li>
31761 * <li>source - The drag source</li>
31762 * <li>rawEvent - Raw mouse event</li>
31763 * <li>dropNode - Drop node(s) provided by the source.</li>
31764 * <li>cancel - Set this to true to signal drop not allowed.</li>
31766 * @param {Object} dragOverEvent
31768 "nodedragover" : true
31771 if(this.singleExpand){
31772 this.on("beforeexpand", this.restrictExpand, this);
31775 this.editor.tree = this;
31776 this.editor = Roo.factory(this.editor, Roo.tree);
31779 if (this.selModel) {
31780 this.selModel = Roo.factory(this.selModel, Roo.tree);
31784 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
31785 rootVisible : true,
31786 animate: Roo.enableFx,
31789 hlDrop : Roo.enableFx,
31793 rendererTip: false,
31795 restrictExpand : function(node){
31796 var p = node.parentNode;
31798 if(p.expandedChild && p.expandedChild.parentNode == p){
31799 p.expandedChild.collapse();
31801 p.expandedChild = node;
31805 // private override
31806 setRootNode : function(node){
31807 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
31808 if(!this.rootVisible){
31809 node.ui = new Roo.tree.RootTreeNodeUI(node);
31815 * Returns the container element for this TreePanel
31817 getEl : function(){
31822 * Returns the default TreeLoader for this TreePanel
31824 getLoader : function(){
31825 return this.loader;
31831 expandAll : function(){
31832 this.root.expand(true);
31836 * Collapse all nodes
31838 collapseAll : function(){
31839 this.root.collapse(true);
31843 * Returns the selection model used by this TreePanel
31845 getSelectionModel : function(){
31846 if(!this.selModel){
31847 this.selModel = new Roo.tree.DefaultSelectionModel();
31849 return this.selModel;
31853 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
31854 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
31855 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
31858 getChecked : function(a, startNode){
31859 startNode = startNode || this.root;
31861 var f = function(){
31862 if(this.attributes.checked){
31863 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
31866 startNode.cascade(f);
31871 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
31872 * @param {String} path
31873 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
31874 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
31875 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
31877 expandPath : function(path, attr, callback){
31878 attr = attr || "id";
31879 var keys = path.split(this.pathSeparator);
31880 var curNode = this.root;
31881 if(curNode.attributes[attr] != keys[1]){ // invalid root
31883 callback(false, null);
31888 var f = function(){
31889 if(++index == keys.length){
31891 callback(true, curNode);
31895 var c = curNode.findChild(attr, keys[index]);
31898 callback(false, curNode);
31903 c.expand(false, false, f);
31905 curNode.expand(false, false, f);
31909 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
31910 * @param {String} path
31911 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
31912 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
31913 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
31915 selectPath : function(path, attr, callback){
31916 attr = attr || "id";
31917 var keys = path.split(this.pathSeparator);
31918 var v = keys.pop();
31919 if(keys.length > 0){
31920 var f = function(success, node){
31921 if(success && node){
31922 var n = node.findChild(attr, v);
31928 }else if(callback){
31929 callback(false, n);
31933 callback(false, n);
31937 this.expandPath(keys.join(this.pathSeparator), attr, f);
31939 this.root.select();
31941 callback(true, this.root);
31946 getTreeEl : function(){
31951 * Trigger rendering of this TreePanel
31953 render : function(){
31954 if (this.innerCt) {
31955 return this; // stop it rendering more than once!!
31958 this.innerCt = this.el.createChild({tag:"ul",
31959 cls:"x-tree-root-ct " +
31960 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
31962 if(this.containerScroll){
31963 Roo.dd.ScrollManager.register(this.el);
31965 if((this.enableDD || this.enableDrop) && !this.dropZone){
31967 * The dropZone used by this tree if drop is enabled
31968 * @type Roo.tree.TreeDropZone
31970 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
31971 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
31974 if((this.enableDD || this.enableDrag) && !this.dragZone){
31976 * The dragZone used by this tree if drag is enabled
31977 * @type Roo.tree.TreeDragZone
31979 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
31980 ddGroup: this.ddGroup || "TreeDD",
31981 scroll: this.ddScroll
31984 this.getSelectionModel().init(this);
31986 Roo.log("ROOT not set in tree");
31989 this.root.render();
31990 if(!this.rootVisible){
31991 this.root.renderChildren();
31997 * Ext JS Library 1.1.1
31998 * Copyright(c) 2006-2007, Ext JS, LLC.
32000 * Originally Released Under LGPL - original licence link has changed is not relivant.
32003 * <script type="text/javascript">
32008 * @class Roo.tree.DefaultSelectionModel
32009 * @extends Roo.util.Observable
32010 * The default single selection for a TreePanel.
32011 * @param {Object} cfg Configuration
32013 Roo.tree.DefaultSelectionModel = function(cfg){
32014 this.selNode = null;
32020 * @event selectionchange
32021 * Fires when the selected node changes
32022 * @param {DefaultSelectionModel} this
32023 * @param {TreeNode} node the new selection
32025 "selectionchange" : true,
32028 * @event beforeselect
32029 * Fires before the selected node changes, return false to cancel the change
32030 * @param {DefaultSelectionModel} this
32031 * @param {TreeNode} node the new selection
32032 * @param {TreeNode} node the old selection
32034 "beforeselect" : true
32037 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
32040 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
32041 init : function(tree){
32043 tree.getTreeEl().on("keydown", this.onKeyDown, this);
32044 tree.on("click", this.onNodeClick, this);
32047 onNodeClick : function(node, e){
32048 if (e.ctrlKey && this.selNode == node) {
32049 this.unselect(node);
32057 * @param {TreeNode} node The node to select
32058 * @return {TreeNode} The selected node
32060 select : function(node){
32061 var last = this.selNode;
32062 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
32064 last.ui.onSelectedChange(false);
32066 this.selNode = node;
32067 node.ui.onSelectedChange(true);
32068 this.fireEvent("selectionchange", this, node, last);
32075 * @param {TreeNode} node The node to unselect
32077 unselect : function(node){
32078 if(this.selNode == node){
32079 this.clearSelections();
32084 * Clear all selections
32086 clearSelections : function(){
32087 var n = this.selNode;
32089 n.ui.onSelectedChange(false);
32090 this.selNode = null;
32091 this.fireEvent("selectionchange", this, null);
32097 * Get the selected node
32098 * @return {TreeNode} The selected node
32100 getSelectedNode : function(){
32101 return this.selNode;
32105 * Returns true if the node is selected
32106 * @param {TreeNode} node The node to check
32107 * @return {Boolean}
32109 isSelected : function(node){
32110 return this.selNode == node;
32114 * Selects the node above the selected node in the tree, intelligently walking the nodes
32115 * @return TreeNode The new selection
32117 selectPrevious : function(){
32118 var s = this.selNode || this.lastSelNode;
32122 var ps = s.previousSibling;
32124 if(!ps.isExpanded() || ps.childNodes.length < 1){
32125 return this.select(ps);
32127 var lc = ps.lastChild;
32128 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
32131 return this.select(lc);
32133 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
32134 return this.select(s.parentNode);
32140 * Selects the node above the selected node in the tree, intelligently walking the nodes
32141 * @return TreeNode The new selection
32143 selectNext : function(){
32144 var s = this.selNode || this.lastSelNode;
32148 if(s.firstChild && s.isExpanded()){
32149 return this.select(s.firstChild);
32150 }else if(s.nextSibling){
32151 return this.select(s.nextSibling);
32152 }else if(s.parentNode){
32154 s.parentNode.bubble(function(){
32155 if(this.nextSibling){
32156 newS = this.getOwnerTree().selModel.select(this.nextSibling);
32165 onKeyDown : function(e){
32166 var s = this.selNode || this.lastSelNode;
32167 // undesirable, but required
32172 var k = e.getKey();
32180 this.selectPrevious();
32183 e.preventDefault();
32184 if(s.hasChildNodes()){
32185 if(!s.isExpanded()){
32187 }else if(s.firstChild){
32188 this.select(s.firstChild, e);
32193 e.preventDefault();
32194 if(s.hasChildNodes() && s.isExpanded()){
32196 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
32197 this.select(s.parentNode, e);
32205 * @class Roo.tree.MultiSelectionModel
32206 * @extends Roo.util.Observable
32207 * Multi selection for a TreePanel.
32208 * @param {Object} cfg Configuration
32210 Roo.tree.MultiSelectionModel = function(){
32211 this.selNodes = [];
32215 * @event selectionchange
32216 * Fires when the selected nodes change
32217 * @param {MultiSelectionModel} this
32218 * @param {Array} nodes Array of the selected nodes
32220 "selectionchange" : true
32222 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
32226 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
32227 init : function(tree){
32229 tree.getTreeEl().on("keydown", this.onKeyDown, this);
32230 tree.on("click", this.onNodeClick, this);
32233 onNodeClick : function(node, e){
32234 this.select(node, e, e.ctrlKey);
32239 * @param {TreeNode} node The node to select
32240 * @param {EventObject} e (optional) An event associated with the selection
32241 * @param {Boolean} keepExisting True to retain existing selections
32242 * @return {TreeNode} The selected node
32244 select : function(node, e, keepExisting){
32245 if(keepExisting !== true){
32246 this.clearSelections(true);
32248 if(this.isSelected(node)){
32249 this.lastSelNode = node;
32252 this.selNodes.push(node);
32253 this.selMap[node.id] = node;
32254 this.lastSelNode = node;
32255 node.ui.onSelectedChange(true);
32256 this.fireEvent("selectionchange", this, this.selNodes);
32262 * @param {TreeNode} node The node to unselect
32264 unselect : function(node){
32265 if(this.selMap[node.id]){
32266 node.ui.onSelectedChange(false);
32267 var sn = this.selNodes;
32270 index = sn.indexOf(node);
32272 for(var i = 0, len = sn.length; i < len; i++){
32280 this.selNodes.splice(index, 1);
32282 delete this.selMap[node.id];
32283 this.fireEvent("selectionchange", this, this.selNodes);
32288 * Clear all selections
32290 clearSelections : function(suppressEvent){
32291 var sn = this.selNodes;
32293 for(var i = 0, len = sn.length; i < len; i++){
32294 sn[i].ui.onSelectedChange(false);
32296 this.selNodes = [];
32298 if(suppressEvent !== true){
32299 this.fireEvent("selectionchange", this, this.selNodes);
32305 * Returns true if the node is selected
32306 * @param {TreeNode} node The node to check
32307 * @return {Boolean}
32309 isSelected : function(node){
32310 return this.selMap[node.id] ? true : false;
32314 * Returns an array of the selected nodes
32317 getSelectedNodes : function(){
32318 return this.selNodes;
32321 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
32323 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
32325 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
32328 * Ext JS Library 1.1.1
32329 * Copyright(c) 2006-2007, Ext JS, LLC.
32331 * Originally Released Under LGPL - original licence link has changed is not relivant.
32334 * <script type="text/javascript">
32338 * @class Roo.tree.TreeNode
32339 * @extends Roo.data.Node
32340 * @cfg {String} text The text for this node
32341 * @cfg {Boolean} expanded true to start the node expanded
32342 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
32343 * @cfg {Boolean} allowDrop false if this node cannot be drop on
32344 * @cfg {Boolean} disabled true to start the node disabled
32345 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
32346 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
32347 * @cfg {String} cls A css class to be added to the node
32348 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
32349 * @cfg {String} href URL of the link used for the node (defaults to #)
32350 * @cfg {String} hrefTarget target frame for the link
32351 * @cfg {String} qtip An Ext QuickTip for the node
32352 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
32353 * @cfg {Boolean} singleClickExpand True for single click expand on this node
32354 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
32355 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
32356 * (defaults to undefined with no checkbox rendered)
32358 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
32360 Roo.tree.TreeNode = function(attributes){
32361 attributes = attributes || {};
32362 if(typeof attributes == "string"){
32363 attributes = {text: attributes};
32365 this.childrenRendered = false;
32366 this.rendered = false;
32367 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
32368 this.expanded = attributes.expanded === true;
32369 this.isTarget = attributes.isTarget !== false;
32370 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
32371 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
32374 * Read-only. The text for this node. To change it use setText().
32377 this.text = attributes.text;
32379 * True if this node is disabled.
32382 this.disabled = attributes.disabled === true;
32386 * @event textchange
32387 * Fires when the text for this node is changed
32388 * @param {Node} this This node
32389 * @param {String} text The new text
32390 * @param {String} oldText The old text
32392 "textchange" : true,
32394 * @event beforeexpand
32395 * Fires before this node is expanded, return false to cancel.
32396 * @param {Node} this This node
32397 * @param {Boolean} deep
32398 * @param {Boolean} anim
32400 "beforeexpand" : true,
32402 * @event beforecollapse
32403 * Fires before this node is collapsed, return false to cancel.
32404 * @param {Node} this This node
32405 * @param {Boolean} deep
32406 * @param {Boolean} anim
32408 "beforecollapse" : true,
32411 * Fires when this node is expanded
32412 * @param {Node} this This node
32416 * @event disabledchange
32417 * Fires when the disabled status of this node changes
32418 * @param {Node} this This node
32419 * @param {Boolean} disabled
32421 "disabledchange" : true,
32424 * Fires when this node is collapsed
32425 * @param {Node} this This node
32429 * @event beforeclick
32430 * Fires before click processing. Return false to cancel the default action.
32431 * @param {Node} this This node
32432 * @param {Roo.EventObject} e The event object
32434 "beforeclick":true,
32436 * @event checkchange
32437 * Fires when a node with a checkbox's checked property changes
32438 * @param {Node} this This node
32439 * @param {Boolean} checked
32441 "checkchange":true,
32444 * Fires when this node is clicked
32445 * @param {Node} this This node
32446 * @param {Roo.EventObject} e The event object
32451 * Fires when this node is double clicked
32452 * @param {Node} this This node
32453 * @param {Roo.EventObject} e The event object
32457 * @event contextmenu
32458 * Fires when this node is right clicked
32459 * @param {Node} this This node
32460 * @param {Roo.EventObject} e The event object
32462 "contextmenu":true,
32464 * @event beforechildrenrendered
32465 * Fires right before the child nodes for this node are rendered
32466 * @param {Node} this This node
32468 "beforechildrenrendered":true
32471 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
32474 * Read-only. The UI for this node
32477 this.ui = new uiClass(this);
32479 // finally support items[]
32480 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
32485 Roo.each(this.attributes.items, function(c) {
32486 this.appendChild(Roo.factory(c,Roo.Tree));
32488 delete this.attributes.items;
32493 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
32494 preventHScroll: true,
32496 * Returns true if this node is expanded
32497 * @return {Boolean}
32499 isExpanded : function(){
32500 return this.expanded;
32504 * Returns the UI object for this node
32505 * @return {TreeNodeUI}
32507 getUI : function(){
32511 // private override
32512 setFirstChild : function(node){
32513 var of = this.firstChild;
32514 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
32515 if(this.childrenRendered && of && node != of){
32516 of.renderIndent(true, true);
32519 this.renderIndent(true, true);
32523 // private override
32524 setLastChild : function(node){
32525 var ol = this.lastChild;
32526 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
32527 if(this.childrenRendered && ol && node != ol){
32528 ol.renderIndent(true, true);
32531 this.renderIndent(true, true);
32535 // these methods are overridden to provide lazy rendering support
32536 // private override
32537 appendChild : function()
32539 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
32540 if(node && this.childrenRendered){
32543 this.ui.updateExpandIcon();
32547 // private override
32548 removeChild : function(node){
32549 this.ownerTree.getSelectionModel().unselect(node);
32550 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
32551 // if it's been rendered remove dom node
32552 if(this.childrenRendered){
32555 if(this.childNodes.length < 1){
32556 this.collapse(false, false);
32558 this.ui.updateExpandIcon();
32560 if(!this.firstChild) {
32561 this.childrenRendered = false;
32566 // private override
32567 insertBefore : function(node, refNode){
32568 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
32569 if(newNode && refNode && this.childrenRendered){
32572 this.ui.updateExpandIcon();
32577 * Sets the text for this node
32578 * @param {String} text
32580 setText : function(text){
32581 var oldText = this.text;
32583 this.attributes.text = text;
32584 if(this.rendered){ // event without subscribing
32585 this.ui.onTextChange(this, text, oldText);
32587 this.fireEvent("textchange", this, text, oldText);
32591 * Triggers selection of this node
32593 select : function(){
32594 this.getOwnerTree().getSelectionModel().select(this);
32598 * Triggers deselection of this node
32600 unselect : function(){
32601 this.getOwnerTree().getSelectionModel().unselect(this);
32605 * Returns true if this node is selected
32606 * @return {Boolean}
32608 isSelected : function(){
32609 return this.getOwnerTree().getSelectionModel().isSelected(this);
32613 * Expand this node.
32614 * @param {Boolean} deep (optional) True to expand all children as well
32615 * @param {Boolean} anim (optional) false to cancel the default animation
32616 * @param {Function} callback (optional) A callback to be called when
32617 * expanding this node completes (does not wait for deep expand to complete).
32618 * Called with 1 parameter, this node.
32620 expand : function(deep, anim, callback){
32621 if(!this.expanded){
32622 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
32625 if(!this.childrenRendered){
32626 this.renderChildren();
32628 this.expanded = true;
32629 if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
32630 this.ui.animExpand(function(){
32631 this.fireEvent("expand", this);
32632 if(typeof callback == "function"){
32636 this.expandChildNodes(true);
32638 }.createDelegate(this));
32642 this.fireEvent("expand", this);
32643 if(typeof callback == "function"){
32648 if(typeof callback == "function"){
32653 this.expandChildNodes(true);
32657 isHiddenRoot : function(){
32658 return this.isRoot && !this.getOwnerTree().rootVisible;
32662 * Collapse this node.
32663 * @param {Boolean} deep (optional) True to collapse all children as well
32664 * @param {Boolean} anim (optional) false to cancel the default animation
32666 collapse : function(deep, anim){
32667 if(this.expanded && !this.isHiddenRoot()){
32668 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
32671 this.expanded = false;
32672 if((this.getOwnerTree().animate && anim !== false) || anim){
32673 this.ui.animCollapse(function(){
32674 this.fireEvent("collapse", this);
32676 this.collapseChildNodes(true);
32678 }.createDelegate(this));
32681 this.ui.collapse();
32682 this.fireEvent("collapse", this);
32686 var cs = this.childNodes;
32687 for(var i = 0, len = cs.length; i < len; i++) {
32688 cs[i].collapse(true, false);
32694 delayedExpand : function(delay){
32695 if(!this.expandProcId){
32696 this.expandProcId = this.expand.defer(delay, this);
32701 cancelExpand : function(){
32702 if(this.expandProcId){
32703 clearTimeout(this.expandProcId);
32705 this.expandProcId = false;
32709 * Toggles expanded/collapsed state of the node
32711 toggle : function(){
32720 * Ensures all parent nodes are expanded
32722 ensureVisible : function(callback){
32723 var tree = this.getOwnerTree();
32724 tree.expandPath(this.parentNode.getPath(), false, function(){
32725 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
32726 Roo.callback(callback);
32727 }.createDelegate(this));
32731 * Expand all child nodes
32732 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
32734 expandChildNodes : function(deep){
32735 var cs = this.childNodes;
32736 for(var i = 0, len = cs.length; i < len; i++) {
32737 cs[i].expand(deep);
32742 * Collapse all child nodes
32743 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
32745 collapseChildNodes : function(deep){
32746 var cs = this.childNodes;
32747 for(var i = 0, len = cs.length; i < len; i++) {
32748 cs[i].collapse(deep);
32753 * Disables this node
32755 disable : function(){
32756 this.disabled = true;
32758 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
32759 this.ui.onDisableChange(this, true);
32761 this.fireEvent("disabledchange", this, true);
32765 * Enables this node
32767 enable : function(){
32768 this.disabled = false;
32769 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
32770 this.ui.onDisableChange(this, false);
32772 this.fireEvent("disabledchange", this, false);
32776 renderChildren : function(suppressEvent){
32777 if(suppressEvent !== false){
32778 this.fireEvent("beforechildrenrendered", this);
32780 var cs = this.childNodes;
32781 for(var i = 0, len = cs.length; i < len; i++){
32782 cs[i].render(true);
32784 this.childrenRendered = true;
32788 sort : function(fn, scope){
32789 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
32790 if(this.childrenRendered){
32791 var cs = this.childNodes;
32792 for(var i = 0, len = cs.length; i < len; i++){
32793 cs[i].render(true);
32799 render : function(bulkRender){
32800 this.ui.render(bulkRender);
32801 if(!this.rendered){
32802 this.rendered = true;
32804 this.expanded = false;
32805 this.expand(false, false);
32811 renderIndent : function(deep, refresh){
32813 this.ui.childIndent = null;
32815 this.ui.renderIndent();
32816 if(deep === true && this.childrenRendered){
32817 var cs = this.childNodes;
32818 for(var i = 0, len = cs.length; i < len; i++){
32819 cs[i].renderIndent(true, refresh);
32825 * Ext JS Library 1.1.1
32826 * Copyright(c) 2006-2007, Ext JS, LLC.
32828 * Originally Released Under LGPL - original licence link has changed is not relivant.
32831 * <script type="text/javascript">
32835 * @class Roo.tree.AsyncTreeNode
32836 * @extends Roo.tree.TreeNode
32837 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
32839 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
32841 Roo.tree.AsyncTreeNode = function(config){
32842 this.loaded = false;
32843 this.loading = false;
32844 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
32846 * @event beforeload
32847 * Fires before this node is loaded, return false to cancel
32848 * @param {Node} this This node
32850 this.addEvents({'beforeload':true, 'load': true});
32853 * Fires when this node is loaded
32854 * @param {Node} this This node
32857 * The loader used by this node (defaults to using the tree's defined loader)
32862 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
32863 expand : function(deep, anim, callback){
32864 if(this.loading){ // if an async load is already running, waiting til it's done
32866 var f = function(){
32867 if(!this.loading){ // done loading
32868 clearInterval(timer);
32869 this.expand(deep, anim, callback);
32871 }.createDelegate(this);
32872 timer = setInterval(f, 200);
32876 if(this.fireEvent("beforeload", this) === false){
32879 this.loading = true;
32880 this.ui.beforeLoad(this);
32881 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
32883 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
32887 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
32891 * Returns true if this node is currently loading
32892 * @return {Boolean}
32894 isLoading : function(){
32895 return this.loading;
32898 loadComplete : function(deep, anim, callback){
32899 this.loading = false;
32900 this.loaded = true;
32901 this.ui.afterLoad(this);
32902 this.fireEvent("load", this);
32903 this.expand(deep, anim, callback);
32907 * Returns true if this node has been loaded
32908 * @return {Boolean}
32910 isLoaded : function(){
32911 return this.loaded;
32914 hasChildNodes : function(){
32915 if(!this.isLeaf() && !this.loaded){
32918 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
32923 * Trigger a reload for this node
32924 * @param {Function} callback
32926 reload : function(callback){
32927 this.collapse(false, false);
32928 while(this.firstChild){
32929 this.removeChild(this.firstChild);
32931 this.childrenRendered = false;
32932 this.loaded = false;
32933 if(this.isHiddenRoot()){
32934 this.expanded = false;
32936 this.expand(false, false, callback);
32940 * Ext JS Library 1.1.1
32941 * Copyright(c) 2006-2007, Ext JS, LLC.
32943 * Originally Released Under LGPL - original licence link has changed is not relivant.
32946 * <script type="text/javascript">
32950 * @class Roo.tree.TreeNodeUI
32952 * @param {Object} node The node to render
32953 * The TreeNode UI implementation is separate from the
32954 * tree implementation. Unless you are customizing the tree UI,
32955 * you should never have to use this directly.
32957 Roo.tree.TreeNodeUI = function(node){
32959 this.rendered = false;
32960 this.animating = false;
32961 this.emptyIcon = Roo.BLANK_IMAGE_URL;
32964 Roo.tree.TreeNodeUI.prototype = {
32965 removeChild : function(node){
32967 this.ctNode.removeChild(node.ui.getEl());
32971 beforeLoad : function(){
32972 this.addClass("x-tree-node-loading");
32975 afterLoad : function(){
32976 this.removeClass("x-tree-node-loading");
32979 onTextChange : function(node, text, oldText){
32981 this.textNode.innerHTML = text;
32985 onDisableChange : function(node, state){
32986 this.disabled = state;
32988 this.addClass("x-tree-node-disabled");
32990 this.removeClass("x-tree-node-disabled");
32994 onSelectedChange : function(state){
32997 this.addClass("x-tree-selected");
33000 this.removeClass("x-tree-selected");
33004 onMove : function(tree, node, oldParent, newParent, index, refNode){
33005 this.childIndent = null;
33007 var targetNode = newParent.ui.getContainer();
33008 if(!targetNode){//target not rendered
33009 this.holder = document.createElement("div");
33010 this.holder.appendChild(this.wrap);
33013 var insertBefore = refNode ? refNode.ui.getEl() : null;
33015 targetNode.insertBefore(this.wrap, insertBefore);
33017 targetNode.appendChild(this.wrap);
33019 this.node.renderIndent(true);
33023 addClass : function(cls){
33025 Roo.fly(this.elNode).addClass(cls);
33029 removeClass : function(cls){
33031 Roo.fly(this.elNode).removeClass(cls);
33035 remove : function(){
33037 this.holder = document.createElement("div");
33038 this.holder.appendChild(this.wrap);
33042 fireEvent : function(){
33043 return this.node.fireEvent.apply(this.node, arguments);
33046 initEvents : function(){
33047 this.node.on("move", this.onMove, this);
33048 var E = Roo.EventManager;
33049 var a = this.anchor;
33051 var el = Roo.fly(a, '_treeui');
33053 if(Roo.isOpera){ // opera render bug ignores the CSS
33054 el.setStyle("text-decoration", "none");
33057 el.on("click", this.onClick, this);
33058 el.on("dblclick", this.onDblClick, this);
33061 Roo.EventManager.on(this.checkbox,
33062 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
33065 el.on("contextmenu", this.onContextMenu, this);
33067 var icon = Roo.fly(this.iconNode);
33068 icon.on("click", this.onClick, this);
33069 icon.on("dblclick", this.onDblClick, this);
33070 icon.on("contextmenu", this.onContextMenu, this);
33071 E.on(this.ecNode, "click", this.ecClick, this, true);
33073 if(this.node.disabled){
33074 this.addClass("x-tree-node-disabled");
33076 if(this.node.hidden){
33077 this.addClass("x-tree-node-disabled");
33079 var ot = this.node.getOwnerTree();
33080 var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
33081 if(dd && (!this.node.isRoot || ot.rootVisible)){
33082 Roo.dd.Registry.register(this.elNode, {
33084 handles: this.getDDHandles(),
33090 getDDHandles : function(){
33091 return [this.iconNode, this.textNode];
33096 this.wrap.style.display = "none";
33102 this.wrap.style.display = "";
33106 onContextMenu : function(e){
33107 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
33108 e.preventDefault();
33110 this.fireEvent("contextmenu", this.node, e);
33114 onClick : function(e){
33119 if(this.fireEvent("beforeclick", this.node, e) !== false){
33120 if(!this.disabled && this.node.attributes.href){
33121 this.fireEvent("click", this.node, e);
33124 e.preventDefault();
33129 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
33130 this.node.toggle();
33133 this.fireEvent("click", this.node, e);
33139 onDblClick : function(e){
33140 e.preventDefault();
33145 this.toggleCheck();
33147 if(!this.animating && this.node.hasChildNodes()){
33148 this.node.toggle();
33150 this.fireEvent("dblclick", this.node, e);
33153 onCheckChange : function(){
33154 var checked = this.checkbox.checked;
33155 this.node.attributes.checked = checked;
33156 this.fireEvent('checkchange', this.node, checked);
33159 ecClick : function(e){
33160 if(!this.animating && this.node.hasChildNodes()){
33161 this.node.toggle();
33165 startDrop : function(){
33166 this.dropping = true;
33169 // delayed drop so the click event doesn't get fired on a drop
33170 endDrop : function(){
33171 setTimeout(function(){
33172 this.dropping = false;
33173 }.createDelegate(this), 50);
33176 expand : function(){
33177 this.updateExpandIcon();
33178 this.ctNode.style.display = "";
33181 focus : function(){
33182 if(!this.node.preventHScroll){
33183 try{this.anchor.focus();
33185 }else if(!Roo.isIE){
33187 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
33188 var l = noscroll.scrollLeft;
33189 this.anchor.focus();
33190 noscroll.scrollLeft = l;
33195 toggleCheck : function(value){
33196 var cb = this.checkbox;
33198 cb.checked = (value === undefined ? !cb.checked : value);
33204 this.anchor.blur();
33208 animExpand : function(callback){
33209 var ct = Roo.get(this.ctNode);
33211 if(!this.node.hasChildNodes()){
33212 this.updateExpandIcon();
33213 this.ctNode.style.display = "";
33214 Roo.callback(callback);
33217 this.animating = true;
33218 this.updateExpandIcon();
33221 callback : function(){
33222 this.animating = false;
33223 Roo.callback(callback);
33226 duration: this.node.ownerTree.duration || .25
33230 highlight : function(){
33231 var tree = this.node.getOwnerTree();
33232 Roo.fly(this.wrap).highlight(
33233 tree.hlColor || "C3DAF9",
33234 {endColor: tree.hlBaseColor}
33238 collapse : function(){
33239 this.updateExpandIcon();
33240 this.ctNode.style.display = "none";
33243 animCollapse : function(callback){
33244 var ct = Roo.get(this.ctNode);
33245 ct.enableDisplayMode('block');
33248 this.animating = true;
33249 this.updateExpandIcon();
33252 callback : function(){
33253 this.animating = false;
33254 Roo.callback(callback);
33257 duration: this.node.ownerTree.duration || .25
33261 getContainer : function(){
33262 return this.ctNode;
33265 getEl : function(){
33269 appendDDGhost : function(ghostNode){
33270 ghostNode.appendChild(this.elNode.cloneNode(true));
33273 getDDRepairXY : function(){
33274 return Roo.lib.Dom.getXY(this.iconNode);
33277 onRender : function(){
33281 render : function(bulkRender){
33282 var n = this.node, a = n.attributes;
33283 var targetNode = n.parentNode ?
33284 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
33286 if(!this.rendered){
33287 this.rendered = true;
33289 this.renderElements(n, a, targetNode, bulkRender);
33292 if(this.textNode.setAttributeNS){
33293 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
33295 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
33298 this.textNode.setAttribute("ext:qtip", a.qtip);
33300 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
33303 }else if(a.qtipCfg){
33304 a.qtipCfg.target = Roo.id(this.textNode);
33305 Roo.QuickTips.register(a.qtipCfg);
33308 if(!this.node.expanded){
33309 this.updateExpandIcon();
33312 if(bulkRender === true) {
33313 targetNode.appendChild(this.wrap);
33318 renderElements : function(n, a, targetNode, bulkRender)
33320 // add some indent caching, this helps performance when rendering a large tree
33321 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
33322 var t = n.getOwnerTree();
33323 var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
33324 if (typeof(n.attributes.html) != 'undefined') {
33325 txt = n.attributes.html;
33327 var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
33328 var cb = typeof a.checked == 'boolean';
33329 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
33330 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
33331 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
33332 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
33333 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
33334 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
33335 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
33336 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
33337 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
33338 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
33341 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
33342 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
33343 n.nextSibling.ui.getEl(), buf.join(""));
33345 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
33348 this.elNode = this.wrap.childNodes[0];
33349 this.ctNode = this.wrap.childNodes[1];
33350 var cs = this.elNode.childNodes;
33351 this.indentNode = cs[0];
33352 this.ecNode = cs[1];
33353 this.iconNode = cs[2];
33356 this.checkbox = cs[3];
33359 this.anchor = cs[index];
33360 this.textNode = cs[index].firstChild;
33363 getAnchor : function(){
33364 return this.anchor;
33367 getTextEl : function(){
33368 return this.textNode;
33371 getIconEl : function(){
33372 return this.iconNode;
33375 isChecked : function(){
33376 return this.checkbox ? this.checkbox.checked : false;
33379 updateExpandIcon : function(){
33381 var n = this.node, c1, c2;
33382 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
33383 var hasChild = n.hasChildNodes();
33387 c1 = "x-tree-node-collapsed";
33388 c2 = "x-tree-node-expanded";
33391 c1 = "x-tree-node-expanded";
33392 c2 = "x-tree-node-collapsed";
33395 this.removeClass("x-tree-node-leaf");
33396 this.wasLeaf = false;
33398 if(this.c1 != c1 || this.c2 != c2){
33399 Roo.fly(this.elNode).replaceClass(c1, c2);
33400 this.c1 = c1; this.c2 = c2;
33403 // this changes non-leafs into leafs if they have no children.
33404 // it's not very rational behaviour..
33406 if(!this.wasLeaf && this.node.leaf){
33407 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
33410 this.wasLeaf = true;
33413 var ecc = "x-tree-ec-icon "+cls;
33414 if(this.ecc != ecc){
33415 this.ecNode.className = ecc;
33421 getChildIndent : function(){
33422 if(!this.childIndent){
33426 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
33428 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
33430 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
33435 this.childIndent = buf.join("");
33437 return this.childIndent;
33440 renderIndent : function(){
33443 var p = this.node.parentNode;
33445 indent = p.ui.getChildIndent();
33447 if(this.indentMarkup != indent){ // don't rerender if not required
33448 this.indentNode.innerHTML = indent;
33449 this.indentMarkup = indent;
33451 this.updateExpandIcon();
33456 Roo.tree.RootTreeNodeUI = function(){
33457 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
33459 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
33460 render : function(){
33461 if(!this.rendered){
33462 var targetNode = this.node.ownerTree.innerCt.dom;
33463 this.node.expanded = true;
33464 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
33465 this.wrap = this.ctNode = targetNode.firstChild;
33468 collapse : function(){
33470 expand : function(){
33474 * Ext JS Library 1.1.1
33475 * Copyright(c) 2006-2007, Ext JS, LLC.
33477 * Originally Released Under LGPL - original licence link has changed is not relivant.
33480 * <script type="text/javascript">
33483 * @class Roo.tree.TreeLoader
33484 * @extends Roo.util.Observable
33485 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
33486 * nodes from a specified URL. The response must be a javascript Array definition
33487 * who's elements are node definition objects. eg:
33492 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
33493 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
33500 * The old style respose with just an array is still supported, but not recommended.
33503 * A server request is sent, and child nodes are loaded only when a node is expanded.
33504 * The loading node's id is passed to the server under the parameter name "node" to
33505 * enable the server to produce the correct child nodes.
33507 * To pass extra parameters, an event handler may be attached to the "beforeload"
33508 * event, and the parameters specified in the TreeLoader's baseParams property:
33510 myTreeLoader.on("beforeload", function(treeLoader, node) {
33511 this.baseParams.category = node.attributes.category;
33514 * This would pass an HTTP parameter called "category" to the server containing
33515 * the value of the Node's "category" attribute.
33517 * Creates a new Treeloader.
33518 * @param {Object} config A config object containing config properties.
33520 Roo.tree.TreeLoader = function(config){
33521 this.baseParams = {};
33522 this.requestMethod = "POST";
33523 Roo.apply(this, config);
33528 * @event beforeload
33529 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
33530 * @param {Object} This TreeLoader object.
33531 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
33532 * @param {Object} callback The callback function specified in the {@link #load} call.
33537 * Fires when the node has been successfuly loaded.
33538 * @param {Object} This TreeLoader object.
33539 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
33540 * @param {Object} response The response object containing the data from the server.
33544 * @event loadexception
33545 * Fires if the network request failed.
33546 * @param {Object} This TreeLoader object.
33547 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
33548 * @param {Object} response The response object containing the data from the server.
33550 loadexception : true,
33553 * Fires before a node is created, enabling you to return custom Node types
33554 * @param {Object} This TreeLoader object.
33555 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
33560 Roo.tree.TreeLoader.superclass.constructor.call(this);
33563 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
33565 * @cfg {String} dataUrl The URL from which to request a Json string which
33566 * specifies an array of node definition object representing the child nodes
33570 * @cfg {String} requestMethod either GET or POST
33571 * defaults to POST (due to BC)
33575 * @cfg {Object} baseParams (optional) An object containing properties which
33576 * specify HTTP parameters to be passed to each request for child nodes.
33579 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
33580 * created by this loader. If the attributes sent by the server have an attribute in this object,
33581 * they take priority.
33584 * @cfg {Object} uiProviders (optional) An object containing properties which
33586 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
33587 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
33588 * <i>uiProvider</i> attribute of a returned child node is a string rather
33589 * than a reference to a TreeNodeUI implementation, this that string value
33590 * is used as a property name in the uiProviders object. You can define the provider named
33591 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
33596 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
33597 * child nodes before loading.
33599 clearOnLoad : true,
33602 * @cfg {String} root (optional) Default to false. Use this to read data from an object
33603 * property on loading, rather than expecting an array. (eg. more compatible to a standard
33604 * Grid query { data : [ .....] }
33609 * @cfg {String} queryParam (optional)
33610 * Name of the query as it will be passed on the querystring (defaults to 'node')
33611 * eg. the request will be ?node=[id]
33618 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
33619 * This is called automatically when a node is expanded, but may be used to reload
33620 * a node (or append new children if the {@link #clearOnLoad} option is false.)
33621 * @param {Roo.tree.TreeNode} node
33622 * @param {Function} callback
33624 load : function(node, callback){
33625 if(this.clearOnLoad){
33626 while(node.firstChild){
33627 node.removeChild(node.firstChild);
33630 if(node.attributes.children){ // preloaded json children
33631 var cs = node.attributes.children;
33632 for(var i = 0, len = cs.length; i < len; i++){
33633 node.appendChild(this.createNode(cs[i]));
33635 if(typeof callback == "function"){
33638 }else if(this.dataUrl){
33639 this.requestData(node, callback);
33643 getParams: function(node){
33644 var buf = [], bp = this.baseParams;
33645 for(var key in bp){
33646 if(typeof bp[key] != "function"){
33647 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
33650 var n = this.queryParam === false ? 'node' : this.queryParam;
33651 buf.push(n + "=", encodeURIComponent(node.id));
33652 return buf.join("");
33655 requestData : function(node, callback){
33656 if(this.fireEvent("beforeload", this, node, callback) !== false){
33657 this.transId = Roo.Ajax.request({
33658 method:this.requestMethod,
33659 url: this.dataUrl||this.url,
33660 success: this.handleResponse,
33661 failure: this.handleFailure,
33663 argument: {callback: callback, node: node},
33664 params: this.getParams(node)
33667 // if the load is cancelled, make sure we notify
33668 // the node that we are done
33669 if(typeof callback == "function"){
33675 isLoading : function(){
33676 return this.transId ? true : false;
33679 abort : function(){
33680 if(this.isLoading()){
33681 Roo.Ajax.abort(this.transId);
33686 createNode : function(attr)
33688 // apply baseAttrs, nice idea Corey!
33689 if(this.baseAttrs){
33690 Roo.applyIf(attr, this.baseAttrs);
33692 if(this.applyLoader !== false){
33693 attr.loader = this;
33695 // uiProvider = depreciated..
33697 if(typeof(attr.uiProvider) == 'string'){
33698 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
33699 /** eval:var:attr */ eval(attr.uiProvider);
33701 if(typeof(this.uiProviders['default']) != 'undefined') {
33702 attr.uiProvider = this.uiProviders['default'];
33705 this.fireEvent('create', this, attr);
33707 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
33709 new Roo.tree.TreeNode(attr) :
33710 new Roo.tree.AsyncTreeNode(attr));
33713 processResponse : function(response, node, callback)
33715 var json = response.responseText;
33718 var o = Roo.decode(json);
33720 if (this.root === false && typeof(o.success) != undefined) {
33721 this.root = 'data'; // the default behaviour for list like data..
33724 if (this.root !== false && !o.success) {
33725 // it's a failure condition.
33726 var a = response.argument;
33727 this.fireEvent("loadexception", this, a.node, response);
33728 Roo.log("Load failed - should have a handler really");
33734 if (this.root !== false) {
33738 for(var i = 0, len = o.length; i < len; i++){
33739 var n = this.createNode(o[i]);
33741 node.appendChild(n);
33744 if(typeof callback == "function"){
33745 callback(this, node);
33748 this.handleFailure(response);
33752 handleResponse : function(response){
33753 this.transId = false;
33754 var a = response.argument;
33755 this.processResponse(response, a.node, a.callback);
33756 this.fireEvent("load", this, a.node, response);
33759 handleFailure : function(response)
33761 // should handle failure better..
33762 this.transId = false;
33763 var a = response.argument;
33764 this.fireEvent("loadexception", this, a.node, response);
33765 if(typeof a.callback == "function"){
33766 a.callback(this, a.node);
33771 * Ext JS Library 1.1.1
33772 * Copyright(c) 2006-2007, Ext JS, LLC.
33774 * Originally Released Under LGPL - original licence link has changed is not relivant.
33777 * <script type="text/javascript">
33781 * @class Roo.tree.TreeFilter
33782 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
33783 * @param {TreePanel} tree
33784 * @param {Object} config (optional)
33786 Roo.tree.TreeFilter = function(tree, config){
33788 this.filtered = {};
33789 Roo.apply(this, config);
33792 Roo.tree.TreeFilter.prototype = {
33799 * Filter the data by a specific attribute.
33800 * @param {String/RegExp} value Either string that the attribute value
33801 * should start with or a RegExp to test against the attribute
33802 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
33803 * @param {TreeNode} startNode (optional) The node to start the filter at.
33805 filter : function(value, attr, startNode){
33806 attr = attr || "text";
33808 if(typeof value == "string"){
33809 var vlen = value.length;
33810 // auto clear empty filter
33811 if(vlen == 0 && this.clearBlank){
33815 value = value.toLowerCase();
33817 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
33819 }else if(value.exec){ // regex?
33821 return value.test(n.attributes[attr]);
33824 throw 'Illegal filter type, must be string or regex';
33826 this.filterBy(f, null, startNode);
33830 * Filter by a function. The passed function will be called with each
33831 * node in the tree (or from the startNode). If the function returns true, the node is kept
33832 * otherwise it is filtered. If a node is filtered, its children are also filtered.
33833 * @param {Function} fn The filter function
33834 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
33836 filterBy : function(fn, scope, startNode){
33837 startNode = startNode || this.tree.root;
33838 if(this.autoClear){
33841 var af = this.filtered, rv = this.reverse;
33842 var f = function(n){
33843 if(n == startNode){
33849 var m = fn.call(scope || n, n);
33857 startNode.cascade(f);
33860 if(typeof id != "function"){
33862 if(n && n.parentNode){
33863 n.parentNode.removeChild(n);
33871 * Clears the current filter. Note: with the "remove" option
33872 * set a filter cannot be cleared.
33874 clear : function(){
33876 var af = this.filtered;
33878 if(typeof id != "function"){
33885 this.filtered = {};
33890 * Ext JS Library 1.1.1
33891 * Copyright(c) 2006-2007, Ext JS, LLC.
33893 * Originally Released Under LGPL - original licence link has changed is not relivant.
33896 * <script type="text/javascript">
33901 * @class Roo.tree.TreeSorter
33902 * Provides sorting of nodes in a TreePanel
33904 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
33905 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
33906 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
33907 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
33908 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
33909 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
33911 * @param {TreePanel} tree
33912 * @param {Object} config
33914 Roo.tree.TreeSorter = function(tree, config){
33915 Roo.apply(this, config);
33916 tree.on("beforechildrenrendered", this.doSort, this);
33917 tree.on("append", this.updateSort, this);
33918 tree.on("insert", this.updateSort, this);
33920 var dsc = this.dir && this.dir.toLowerCase() == "desc";
33921 var p = this.property || "text";
33922 var sortType = this.sortType;
33923 var fs = this.folderSort;
33924 var cs = this.caseSensitive === true;
33925 var leafAttr = this.leafAttr || 'leaf';
33927 this.sortFn = function(n1, n2){
33929 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
33932 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
33936 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
33937 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
33939 return dsc ? +1 : -1;
33941 return dsc ? -1 : +1;
33948 Roo.tree.TreeSorter.prototype = {
33949 doSort : function(node){
33950 node.sort(this.sortFn);
33953 compareNodes : function(n1, n2){
33954 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
33957 updateSort : function(tree, node){
33958 if(node.childrenRendered){
33959 this.doSort.defer(1, this, [node]);
33964 * Ext JS Library 1.1.1
33965 * Copyright(c) 2006-2007, Ext JS, LLC.
33967 * Originally Released Under LGPL - original licence link has changed is not relivant.
33970 * <script type="text/javascript">
33973 if(Roo.dd.DropZone){
33975 Roo.tree.TreeDropZone = function(tree, config){
33976 this.allowParentInsert = false;
33977 this.allowContainerDrop = false;
33978 this.appendOnly = false;
33979 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
33981 this.lastInsertClass = "x-tree-no-status";
33982 this.dragOverData = {};
33985 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
33986 ddGroup : "TreeDD",
33989 expandDelay : 1000,
33991 expandNode : function(node){
33992 if(node.hasChildNodes() && !node.isExpanded()){
33993 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
33997 queueExpand : function(node){
33998 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
34001 cancelExpand : function(){
34002 if(this.expandProcId){
34003 clearTimeout(this.expandProcId);
34004 this.expandProcId = false;
34008 isValidDropPoint : function(n, pt, dd, e, data){
34009 if(!n || !data){ return false; }
34010 var targetNode = n.node;
34011 var dropNode = data.node;
34012 // default drop rules
34013 if(!(targetNode && targetNode.isTarget && pt)){
34016 if(pt == "append" && targetNode.allowChildren === false){
34019 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
34022 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
34025 // reuse the object
34026 var overEvent = this.dragOverData;
34027 overEvent.tree = this.tree;
34028 overEvent.target = targetNode;
34029 overEvent.data = data;
34030 overEvent.point = pt;
34031 overEvent.source = dd;
34032 overEvent.rawEvent = e;
34033 overEvent.dropNode = dropNode;
34034 overEvent.cancel = false;
34035 var result = this.tree.fireEvent("nodedragover", overEvent);
34036 return overEvent.cancel === false && result !== false;
34039 getDropPoint : function(e, n, dd)
34043 return tn.allowChildren !== false ? "append" : false; // always append for root
34045 var dragEl = n.ddel;
34046 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
34047 var y = Roo.lib.Event.getPageY(e);
34048 //var noAppend = tn.allowChildren === false || tn.isLeaf();
34050 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
34051 var noAppend = tn.allowChildren === false;
34052 if(this.appendOnly || tn.parentNode.allowChildren === false){
34053 return noAppend ? false : "append";
34055 var noBelow = false;
34056 if(!this.allowParentInsert){
34057 noBelow = tn.hasChildNodes() && tn.isExpanded();
34059 var q = (b - t) / (noAppend ? 2 : 3);
34060 if(y >= t && y < (t + q)){
34062 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
34069 onNodeEnter : function(n, dd, e, data)
34071 this.cancelExpand();
34074 onNodeOver : function(n, dd, e, data)
34077 var pt = this.getDropPoint(e, n, dd);
34080 // auto node expand check
34081 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
34082 this.queueExpand(node);
34083 }else if(pt != "append"){
34084 this.cancelExpand();
34087 // set the insert point style on the target node
34088 var returnCls = this.dropNotAllowed;
34089 if(this.isValidDropPoint(n, pt, dd, e, data)){
34094 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
34095 cls = "x-tree-drag-insert-above";
34096 }else if(pt == "below"){
34097 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
34098 cls = "x-tree-drag-insert-below";
34100 returnCls = "x-tree-drop-ok-append";
34101 cls = "x-tree-drag-append";
34103 if(this.lastInsertClass != cls){
34104 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
34105 this.lastInsertClass = cls;
34112 onNodeOut : function(n, dd, e, data){
34114 this.cancelExpand();
34115 this.removeDropIndicators(n);
34118 onNodeDrop : function(n, dd, e, data){
34119 var point = this.getDropPoint(e, n, dd);
34120 var targetNode = n.node;
34121 targetNode.ui.startDrop();
34122 if(!this.isValidDropPoint(n, point, dd, e, data)){
34123 targetNode.ui.endDrop();
34126 // first try to find the drop node
34127 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
34130 target: targetNode,
34135 dropNode: dropNode,
34138 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
34139 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
34140 targetNode.ui.endDrop();
34143 // allow target changing
34144 targetNode = dropEvent.target;
34145 if(point == "append" && !targetNode.isExpanded()){
34146 targetNode.expand(false, null, function(){
34147 this.completeDrop(dropEvent);
34148 }.createDelegate(this));
34150 this.completeDrop(dropEvent);
34155 completeDrop : function(de){
34156 var ns = de.dropNode, p = de.point, t = de.target;
34157 if(!(ns instanceof Array)){
34161 for(var i = 0, len = ns.length; i < len; i++){
34164 t.parentNode.insertBefore(n, t);
34165 }else if(p == "below"){
34166 t.parentNode.insertBefore(n, t.nextSibling);
34172 if(this.tree.hlDrop){
34176 this.tree.fireEvent("nodedrop", de);
34179 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
34180 if(this.tree.hlDrop){
34181 dropNode.ui.focus();
34182 dropNode.ui.highlight();
34184 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
34187 getTree : function(){
34191 removeDropIndicators : function(n){
34194 Roo.fly(el).removeClass([
34195 "x-tree-drag-insert-above",
34196 "x-tree-drag-insert-below",
34197 "x-tree-drag-append"]);
34198 this.lastInsertClass = "_noclass";
34202 beforeDragDrop : function(target, e, id){
34203 this.cancelExpand();
34207 afterRepair : function(data){
34208 if(data && Roo.enableFx){
34209 data.node.ui.highlight();
34219 * Ext JS Library 1.1.1
34220 * Copyright(c) 2006-2007, Ext JS, LLC.
34222 * Originally Released Under LGPL - original licence link has changed is not relivant.
34225 * <script type="text/javascript">
34229 if(Roo.dd.DragZone){
34230 Roo.tree.TreeDragZone = function(tree, config){
34231 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
34235 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
34236 ddGroup : "TreeDD",
34238 onBeforeDrag : function(data, e){
34240 return n && n.draggable && !n.disabled;
34244 onInitDrag : function(e){
34245 var data = this.dragData;
34246 this.tree.getSelectionModel().select(data.node);
34247 this.proxy.update("");
34248 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
34249 this.tree.fireEvent("startdrag", this.tree, data.node, e);
34252 getRepairXY : function(e, data){
34253 return data.node.ui.getDDRepairXY();
34256 onEndDrag : function(data, e){
34257 this.tree.fireEvent("enddrag", this.tree, data.node, e);
34262 onValidDrop : function(dd, e, id){
34263 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
34267 beforeInvalidDrop : function(e, id){
34268 // this scrolls the original position back into view
34269 var sm = this.tree.getSelectionModel();
34270 sm.clearSelections();
34271 sm.select(this.dragData.node);
34276 * Ext JS Library 1.1.1
34277 * Copyright(c) 2006-2007, Ext JS, LLC.
34279 * Originally Released Under LGPL - original licence link has changed is not relivant.
34282 * <script type="text/javascript">
34285 * @class Roo.tree.TreeEditor
34286 * @extends Roo.Editor
34287 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
34288 * as the editor field.
34290 * @param {Object} config (used to be the tree panel.)
34291 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
34293 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
34294 * @cfg {Roo.form.TextField|Object} field The field configuration
34298 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
34301 if (oldconfig) { // old style..
34302 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
34305 tree = config.tree;
34306 config.field = config.field || {};
34307 config.field.xtype = 'TextField';
34308 field = Roo.factory(config.field, Roo.form);
34310 config = config || {};
34315 * @event beforenodeedit
34316 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
34317 * false from the handler of this event.
34318 * @param {Editor} this
34319 * @param {Roo.tree.Node} node
34321 "beforenodeedit" : true
34325 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
34329 tree.on('beforeclick', this.beforeNodeClick, this);
34330 tree.getTreeEl().on('mousedown', this.hide, this);
34331 this.on('complete', this.updateNode, this);
34332 this.on('beforestartedit', this.fitToTree, this);
34333 this.on('startedit', this.bindScroll, this, {delay:10});
34334 this.on('specialkey', this.onSpecialKey, this);
34337 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
34339 * @cfg {String} alignment
34340 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
34346 * @cfg {Boolean} hideEl
34347 * True to hide the bound element while the editor is displayed (defaults to false)
34351 * @cfg {String} cls
34352 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
34354 cls: "x-small-editor x-tree-editor",
34356 * @cfg {Boolean} shim
34357 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
34363 * @cfg {Number} maxWidth
34364 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
34365 * the containing tree element's size, it will be automatically limited for you to the container width, taking
34366 * scroll and client offsets into account prior to each edit.
34373 fitToTree : function(ed, el){
34374 var td = this.tree.getTreeEl().dom, nd = el.dom;
34375 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
34376 td.scrollLeft = nd.offsetLeft;
34380 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
34381 this.setSize(w, '');
34383 return this.fireEvent('beforenodeedit', this, this.editNode);
34388 triggerEdit : function(node){
34389 this.completeEdit();
34390 this.editNode = node;
34391 this.startEdit(node.ui.textNode, node.text);
34395 bindScroll : function(){
34396 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
34400 beforeNodeClick : function(node, e){
34401 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
34402 this.lastClick = new Date();
34403 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
34405 this.triggerEdit(node);
34412 updateNode : function(ed, value){
34413 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
34414 this.editNode.setText(value);
34418 onHide : function(){
34419 Roo.tree.TreeEditor.superclass.onHide.call(this);
34421 this.editNode.ui.focus();
34426 onSpecialKey : function(field, e){
34427 var k = e.getKey();
34431 }else if(k == e.ENTER && !e.hasModifier()){
34433 this.completeEdit();
34436 });//<Script type="text/javascript">
34439 * Ext JS Library 1.1.1
34440 * Copyright(c) 2006-2007, Ext JS, LLC.
34442 * Originally Released Under LGPL - original licence link has changed is not relivant.
34445 * <script type="text/javascript">
34449 * Not documented??? - probably should be...
34452 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
34453 //focus: Roo.emptyFn, // prevent odd scrolling behavior
34455 renderElements : function(n, a, targetNode, bulkRender){
34456 //consel.log("renderElements?");
34457 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
34459 var t = n.getOwnerTree();
34460 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
34462 var cols = t.columns;
34463 var bw = t.borderWidth;
34465 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
34466 var cb = typeof a.checked == "boolean";
34467 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
34468 var colcls = 'x-t-' + tid + '-c0';
34470 '<li class="x-tree-node">',
34473 '<div class="x-tree-node-el ', a.cls,'">',
34475 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
34478 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
34479 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
34480 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
34481 (a.icon ? ' x-tree-node-inline-icon' : ''),
34482 (a.iconCls ? ' '+a.iconCls : ''),
34483 '" unselectable="on" />',
34484 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
34485 (a.checked ? 'checked="checked" />' : ' />')) : ''),
34487 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
34488 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
34489 '<span unselectable="on" qtip="' + tx + '">',
34493 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
34494 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
34496 for(var i = 1, len = cols.length; i < len; i++){
34498 colcls = 'x-t-' + tid + '-c' +i;
34499 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
34500 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
34501 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
34507 '<div class="x-clear"></div></div>',
34508 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
34511 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
34512 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
34513 n.nextSibling.ui.getEl(), buf.join(""));
34515 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
34517 var el = this.wrap.firstChild;
34519 this.elNode = el.firstChild;
34520 this.ranchor = el.childNodes[1];
34521 this.ctNode = this.wrap.childNodes[1];
34522 var cs = el.firstChild.childNodes;
34523 this.indentNode = cs[0];
34524 this.ecNode = cs[1];
34525 this.iconNode = cs[2];
34528 this.checkbox = cs[3];
34531 this.anchor = cs[index];
34533 this.textNode = cs[index].firstChild;
34535 //el.on("click", this.onClick, this);
34536 //el.on("dblclick", this.onDblClick, this);
34539 // console.log(this);
34541 initEvents : function(){
34542 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
34545 var a = this.ranchor;
34547 var el = Roo.get(a);
34549 if(Roo.isOpera){ // opera render bug ignores the CSS
34550 el.setStyle("text-decoration", "none");
34553 el.on("click", this.onClick, this);
34554 el.on("dblclick", this.onDblClick, this);
34555 el.on("contextmenu", this.onContextMenu, this);
34559 /*onSelectedChange : function(state){
34562 this.addClass("x-tree-selected");
34565 this.removeClass("x-tree-selected");
34568 addClass : function(cls){
34570 Roo.fly(this.elRow).addClass(cls);
34576 removeClass : function(cls){
34578 Roo.fly(this.elRow).removeClass(cls);
34584 });//<Script type="text/javascript">
34588 * Ext JS Library 1.1.1
34589 * Copyright(c) 2006-2007, Ext JS, LLC.
34591 * Originally Released Under LGPL - original licence link has changed is not relivant.
34594 * <script type="text/javascript">
34599 * @class Roo.tree.ColumnTree
34600 * @extends Roo.data.TreePanel
34601 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
34602 * @cfg {int} borderWidth compined right/left border allowance
34604 * @param {String/HTMLElement/Element} el The container element
34605 * @param {Object} config
34607 Roo.tree.ColumnTree = function(el, config)
34609 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
34613 * Fire this event on a container when it resizes
34614 * @param {int} w Width
34615 * @param {int} h Height
34619 this.on('resize', this.onResize, this);
34622 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
34626 borderWidth: Roo.isBorderBox ? 0 : 2,
34629 render : function(){
34630 // add the header.....
34632 Roo.tree.ColumnTree.superclass.render.apply(this);
34634 this.el.addClass('x-column-tree');
34636 this.headers = this.el.createChild(
34637 {cls:'x-tree-headers'},this.innerCt.dom);
34639 var cols = this.columns, c;
34640 var totalWidth = 0;
34642 var len = cols.length;
34643 for(var i = 0; i < len; i++){
34645 totalWidth += c.width;
34646 this.headEls.push(this.headers.createChild({
34647 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
34649 cls:'x-tree-hd-text',
34652 style:'width:'+(c.width-this.borderWidth)+'px;'
34655 this.headers.createChild({cls:'x-clear'});
34656 // prevent floats from wrapping when clipped
34657 this.headers.setWidth(totalWidth);
34658 //this.innerCt.setWidth(totalWidth);
34659 this.innerCt.setStyle({ overflow: 'auto' });
34660 this.onResize(this.width, this.height);
34664 onResize : function(w,h)
34669 this.innerCt.setWidth(this.width);
34670 this.innerCt.setHeight(this.height-20);
34673 var cols = this.columns, c;
34674 var totalWidth = 0;
34676 var len = cols.length;
34677 for(var i = 0; i < len; i++){
34679 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
34680 // it's the expander..
34681 expEl = this.headEls[i];
34684 totalWidth += c.width;
34688 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
34690 this.headers.setWidth(w-20);
34699 * Ext JS Library 1.1.1
34700 * Copyright(c) 2006-2007, Ext JS, LLC.
34702 * Originally Released Under LGPL - original licence link has changed is not relivant.
34705 * <script type="text/javascript">
34709 * @class Roo.menu.Menu
34710 * @extends Roo.util.Observable
34711 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
34712 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
34714 * Creates a new Menu
34715 * @param {Object} config Configuration options
34717 Roo.menu.Menu = function(config){
34718 Roo.apply(this, config);
34719 this.id = this.id || Roo.id();
34722 * @event beforeshow
34723 * Fires before this menu is displayed
34724 * @param {Roo.menu.Menu} this
34728 * @event beforehide
34729 * Fires before this menu is hidden
34730 * @param {Roo.menu.Menu} this
34735 * Fires after this menu is displayed
34736 * @param {Roo.menu.Menu} this
34741 * Fires after this menu is hidden
34742 * @param {Roo.menu.Menu} this
34747 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
34748 * @param {Roo.menu.Menu} this
34749 * @param {Roo.menu.Item} menuItem The menu item that was clicked
34750 * @param {Roo.EventObject} e
34755 * Fires when the mouse is hovering over this menu
34756 * @param {Roo.menu.Menu} this
34757 * @param {Roo.EventObject} e
34758 * @param {Roo.menu.Item} menuItem The menu item that was clicked
34763 * Fires when the mouse exits this menu
34764 * @param {Roo.menu.Menu} this
34765 * @param {Roo.EventObject} e
34766 * @param {Roo.menu.Item} menuItem The menu item that was clicked
34771 * Fires when a menu item contained in this menu is clicked
34772 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
34773 * @param {Roo.EventObject} e
34777 if (this.registerMenu) {
34778 Roo.menu.MenuMgr.register(this);
34781 var mis = this.items;
34782 this.items = new Roo.util.MixedCollection();
34784 this.add.apply(this, mis);
34788 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
34790 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
34794 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
34795 * for bottom-right shadow (defaults to "sides")
34799 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
34800 * this menu (defaults to "tl-tr?")
34802 subMenuAlign : "tl-tr?",
34804 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
34805 * relative to its element of origin (defaults to "tl-bl?")
34807 defaultAlign : "tl-bl?",
34809 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
34811 allowOtherMenus : false,
34813 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
34815 registerMenu : true,
34820 render : function(){
34824 var el = this.el = new Roo.Layer({
34826 shadow:this.shadow,
34828 parentEl: this.parentEl || document.body,
34832 this.keyNav = new Roo.menu.MenuNav(this);
34835 el.addClass("x-menu-plain");
34838 el.addClass(this.cls);
34840 // generic focus element
34841 this.focusEl = el.createChild({
34842 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
34844 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
34845 ul.on("click", this.onClick, this);
34846 ul.on("mouseover", this.onMouseOver, this);
34847 ul.on("mouseout", this.onMouseOut, this);
34848 this.items.each(function(item){
34853 var li = document.createElement("li");
34854 li.className = "x-menu-list-item";
34855 ul.dom.appendChild(li);
34856 item.render(li, this);
34863 autoWidth : function(){
34864 var el = this.el, ul = this.ul;
34868 var w = this.width;
34871 }else if(Roo.isIE){
34872 el.setWidth(this.minWidth);
34873 var t = el.dom.offsetWidth; // force recalc
34874 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
34879 delayAutoWidth : function(){
34882 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
34884 this.awTask.delay(20);
34889 findTargetItem : function(e){
34890 var t = e.getTarget(".x-menu-list-item", this.ul, true);
34891 if(t && t.menuItemId){
34892 return this.items.get(t.menuItemId);
34897 onClick : function(e){
34899 if(t = this.findTargetItem(e)){
34901 this.fireEvent("click", this, t, e);
34906 setActiveItem : function(item, autoExpand){
34907 if(item != this.activeItem){
34908 if(this.activeItem){
34909 this.activeItem.deactivate();
34911 this.activeItem = item;
34912 item.activate(autoExpand);
34913 }else if(autoExpand){
34919 tryActivate : function(start, step){
34920 var items = this.items;
34921 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
34922 var item = items.get(i);
34923 if(!item.disabled && item.canActivate){
34924 this.setActiveItem(item, false);
34932 onMouseOver : function(e){
34934 if(t = this.findTargetItem(e)){
34935 if(t.canActivate && !t.disabled){
34936 this.setActiveItem(t, true);
34939 this.fireEvent("mouseover", this, e, t);
34943 onMouseOut : function(e){
34945 if(t = this.findTargetItem(e)){
34946 if(t == this.activeItem && t.shouldDeactivate(e)){
34947 this.activeItem.deactivate();
34948 delete this.activeItem;
34951 this.fireEvent("mouseout", this, e, t);
34955 * Read-only. Returns true if the menu is currently displayed, else false.
34958 isVisible : function(){
34959 return this.el && !this.hidden;
34963 * Displays this menu relative to another element
34964 * @param {String/HTMLElement/Roo.Element} element The element to align to
34965 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
34966 * the element (defaults to this.defaultAlign)
34967 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
34969 show : function(el, pos, parentMenu){
34970 this.parentMenu = parentMenu;
34974 this.fireEvent("beforeshow", this);
34975 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
34979 * Displays this menu at a specific xy position
34980 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
34981 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
34983 showAt : function(xy, parentMenu, /* private: */_e){
34984 this.parentMenu = parentMenu;
34989 this.fireEvent("beforeshow", this);
34990 xy = this.el.adjustForConstraints(xy);
34994 this.hidden = false;
34996 this.fireEvent("show", this);
34999 focus : function(){
35001 this.doFocus.defer(50, this);
35005 doFocus : function(){
35007 this.focusEl.focus();
35012 * Hides this menu and optionally all parent menus
35013 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
35015 hide : function(deep){
35016 if(this.el && this.isVisible()){
35017 this.fireEvent("beforehide", this);
35018 if(this.activeItem){
35019 this.activeItem.deactivate();
35020 this.activeItem = null;
35023 this.hidden = true;
35024 this.fireEvent("hide", this);
35026 if(deep === true && this.parentMenu){
35027 this.parentMenu.hide(true);
35032 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
35033 * Any of the following are valid:
35035 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
35036 * <li>An HTMLElement object which will be converted to a menu item</li>
35037 * <li>A menu item config object that will be created as a new menu item</li>
35038 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
35039 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
35044 var menu = new Roo.menu.Menu();
35046 // Create a menu item to add by reference
35047 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
35049 // Add a bunch of items at once using different methods.
35050 // Only the last item added will be returned.
35051 var item = menu.add(
35052 menuItem, // add existing item by ref
35053 'Dynamic Item', // new TextItem
35054 '-', // new separator
35055 { text: 'Config Item' } // new item by config
35058 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
35059 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
35062 var a = arguments, l = a.length, item;
35063 for(var i = 0; i < l; i++){
35065 if ((typeof(el) == "object") && el.xtype && el.xns) {
35066 el = Roo.factory(el, Roo.menu);
35069 if(el.render){ // some kind of Item
35070 item = this.addItem(el);
35071 }else if(typeof el == "string"){ // string
35072 if(el == "separator" || el == "-"){
35073 item = this.addSeparator();
35075 item = this.addText(el);
35077 }else if(el.tagName || el.el){ // element
35078 item = this.addElement(el);
35079 }else if(typeof el == "object"){ // must be menu item config?
35080 item = this.addMenuItem(el);
35087 * Returns this menu's underlying {@link Roo.Element} object
35088 * @return {Roo.Element} The element
35090 getEl : function(){
35098 * Adds a separator bar to the menu
35099 * @return {Roo.menu.Item} The menu item that was added
35101 addSeparator : function(){
35102 return this.addItem(new Roo.menu.Separator());
35106 * Adds an {@link Roo.Element} object to the menu
35107 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
35108 * @return {Roo.menu.Item} The menu item that was added
35110 addElement : function(el){
35111 return this.addItem(new Roo.menu.BaseItem(el));
35115 * Adds an existing object based on {@link Roo.menu.Item} to the menu
35116 * @param {Roo.menu.Item} item The menu item to add
35117 * @return {Roo.menu.Item} The menu item that was added
35119 addItem : function(item){
35120 this.items.add(item);
35122 var li = document.createElement("li");
35123 li.className = "x-menu-list-item";
35124 this.ul.dom.appendChild(li);
35125 item.render(li, this);
35126 this.delayAutoWidth();
35132 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
35133 * @param {Object} config A MenuItem config object
35134 * @return {Roo.menu.Item} The menu item that was added
35136 addMenuItem : function(config){
35137 if(!(config instanceof Roo.menu.Item)){
35138 if(typeof config.checked == "boolean"){ // must be check menu item config?
35139 config = new Roo.menu.CheckItem(config);
35141 config = new Roo.menu.Item(config);
35144 return this.addItem(config);
35148 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
35149 * @param {String} text The text to display in the menu item
35150 * @return {Roo.menu.Item} The menu item that was added
35152 addText : function(text){
35153 return this.addItem(new Roo.menu.TextItem({ text : text }));
35157 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
35158 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
35159 * @param {Roo.menu.Item} item The menu item to add
35160 * @return {Roo.menu.Item} The menu item that was added
35162 insert : function(index, item){
35163 this.items.insert(index, item);
35165 var li = document.createElement("li");
35166 li.className = "x-menu-list-item";
35167 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
35168 item.render(li, this);
35169 this.delayAutoWidth();
35175 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
35176 * @param {Roo.menu.Item} item The menu item to remove
35178 remove : function(item){
35179 this.items.removeKey(item.id);
35184 * Removes and destroys all items in the menu
35186 removeAll : function(){
35188 while(f = this.items.first()){
35194 // MenuNav is a private utility class used internally by the Menu
35195 Roo.menu.MenuNav = function(menu){
35196 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
35197 this.scope = this.menu = menu;
35200 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
35201 doRelay : function(e, h){
35202 var k = e.getKey();
35203 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
35204 this.menu.tryActivate(0, 1);
35207 return h.call(this.scope || this, e, this.menu);
35210 up : function(e, m){
35211 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
35212 m.tryActivate(m.items.length-1, -1);
35216 down : function(e, m){
35217 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
35218 m.tryActivate(0, 1);
35222 right : function(e, m){
35224 m.activeItem.expandMenu(true);
35228 left : function(e, m){
35230 if(m.parentMenu && m.parentMenu.activeItem){
35231 m.parentMenu.activeItem.activate();
35235 enter : function(e, m){
35237 e.stopPropagation();
35238 m.activeItem.onClick(e);
35239 m.fireEvent("click", this, m.activeItem);
35245 * Ext JS Library 1.1.1
35246 * Copyright(c) 2006-2007, Ext JS, LLC.
35248 * Originally Released Under LGPL - original licence link has changed is not relivant.
35251 * <script type="text/javascript">
35255 * @class Roo.menu.MenuMgr
35256 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
35259 Roo.menu.MenuMgr = function(){
35260 var menus, active, groups = {}, attached = false, lastShow = new Date();
35262 // private - called when first menu is created
35265 active = new Roo.util.MixedCollection();
35266 Roo.get(document).addKeyListener(27, function(){
35267 if(active.length > 0){
35274 function hideAll(){
35275 if(active && active.length > 0){
35276 var c = active.clone();
35277 c.each(function(m){
35284 function onHide(m){
35286 if(active.length < 1){
35287 Roo.get(document).un("mousedown", onMouseDown);
35293 function onShow(m){
35294 var last = active.last();
35295 lastShow = new Date();
35298 Roo.get(document).on("mousedown", onMouseDown);
35302 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
35303 m.parentMenu.activeChild = m;
35304 }else if(last && last.isVisible()){
35305 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
35310 function onBeforeHide(m){
35312 m.activeChild.hide();
35314 if(m.autoHideTimer){
35315 clearTimeout(m.autoHideTimer);
35316 delete m.autoHideTimer;
35321 function onBeforeShow(m){
35322 var pm = m.parentMenu;
35323 if(!pm && !m.allowOtherMenus){
35325 }else if(pm && pm.activeChild && active != m){
35326 pm.activeChild.hide();
35331 function onMouseDown(e){
35332 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
35338 function onBeforeCheck(mi, state){
35340 var g = groups[mi.group];
35341 for(var i = 0, l = g.length; i < l; i++){
35343 g[i].setChecked(false);
35352 * Hides all menus that are currently visible
35354 hideAll : function(){
35359 register : function(menu){
35363 menus[menu.id] = menu;
35364 menu.on("beforehide", onBeforeHide);
35365 menu.on("hide", onHide);
35366 menu.on("beforeshow", onBeforeShow);
35367 menu.on("show", onShow);
35368 var g = menu.group;
35369 if(g && menu.events["checkchange"]){
35373 groups[g].push(menu);
35374 menu.on("checkchange", onCheck);
35379 * Returns a {@link Roo.menu.Menu} object
35380 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
35381 * be used to generate and return a new Menu instance.
35383 get : function(menu){
35384 if(typeof menu == "string"){ // menu id
35385 return menus[menu];
35386 }else if(menu.events){ // menu instance
35388 }else if(typeof menu.length == 'number'){ // array of menu items?
35389 return new Roo.menu.Menu({items:menu});
35390 }else{ // otherwise, must be a config
35391 return new Roo.menu.Menu(menu);
35396 unregister : function(menu){
35397 delete menus[menu.id];
35398 menu.un("beforehide", onBeforeHide);
35399 menu.un("hide", onHide);
35400 menu.un("beforeshow", onBeforeShow);
35401 menu.un("show", onShow);
35402 var g = menu.group;
35403 if(g && menu.events["checkchange"]){
35404 groups[g].remove(menu);
35405 menu.un("checkchange", onCheck);
35410 registerCheckable : function(menuItem){
35411 var g = menuItem.group;
35416 groups[g].push(menuItem);
35417 menuItem.on("beforecheckchange", onBeforeCheck);
35422 unregisterCheckable : function(menuItem){
35423 var g = menuItem.group;
35425 groups[g].remove(menuItem);
35426 menuItem.un("beforecheckchange", onBeforeCheck);
35432 * Ext JS Library 1.1.1
35433 * Copyright(c) 2006-2007, Ext JS, LLC.
35435 * Originally Released Under LGPL - original licence link has changed is not relivant.
35438 * <script type="text/javascript">
35443 * @class Roo.menu.BaseItem
35444 * @extends Roo.Component
35445 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
35446 * management and base configuration options shared by all menu components.
35448 * Creates a new BaseItem
35449 * @param {Object} config Configuration options
35451 Roo.menu.BaseItem = function(config){
35452 Roo.menu.BaseItem.superclass.constructor.call(this, config);
35457 * Fires when this item is clicked
35458 * @param {Roo.menu.BaseItem} this
35459 * @param {Roo.EventObject} e
35464 * Fires when this item is activated
35465 * @param {Roo.menu.BaseItem} this
35469 * @event deactivate
35470 * Fires when this item is deactivated
35471 * @param {Roo.menu.BaseItem} this
35477 this.on("click", this.handler, this.scope, true);
35481 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
35483 * @cfg {Function} handler
35484 * A function that will handle the click event of this menu item (defaults to undefined)
35487 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
35489 canActivate : false,
35492 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
35497 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
35499 activeClass : "x-menu-item-active",
35501 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
35503 hideOnClick : true,
35505 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
35510 ctype: "Roo.menu.BaseItem",
35513 actionMode : "container",
35516 render : function(container, parentMenu){
35517 this.parentMenu = parentMenu;
35518 Roo.menu.BaseItem.superclass.render.call(this, container);
35519 this.container.menuItemId = this.id;
35523 onRender : function(container, position){
35524 this.el = Roo.get(this.el);
35525 container.dom.appendChild(this.el.dom);
35529 onClick : function(e){
35530 if(!this.disabled && this.fireEvent("click", this, e) !== false
35531 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
35532 this.handleClick(e);
35539 activate : function(){
35543 var li = this.container;
35544 li.addClass(this.activeClass);
35545 this.region = li.getRegion().adjust(2, 2, -2, -2);
35546 this.fireEvent("activate", this);
35551 deactivate : function(){
35552 this.container.removeClass(this.activeClass);
35553 this.fireEvent("deactivate", this);
35557 shouldDeactivate : function(e){
35558 return !this.region || !this.region.contains(e.getPoint());
35562 handleClick : function(e){
35563 if(this.hideOnClick){
35564 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
35569 expandMenu : function(autoActivate){
35574 hideMenu : function(){
35579 * Ext JS Library 1.1.1
35580 * Copyright(c) 2006-2007, Ext JS, LLC.
35582 * Originally Released Under LGPL - original licence link has changed is not relivant.
35585 * <script type="text/javascript">
35589 * @class Roo.menu.Adapter
35590 * @extends Roo.menu.BaseItem
35591 * 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.
35592 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
35594 * Creates a new Adapter
35595 * @param {Object} config Configuration options
35597 Roo.menu.Adapter = function(component, config){
35598 Roo.menu.Adapter.superclass.constructor.call(this, config);
35599 this.component = component;
35601 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
35603 canActivate : true,
35606 onRender : function(container, position){
35607 this.component.render(container);
35608 this.el = this.component.getEl();
35612 activate : function(){
35616 this.component.focus();
35617 this.fireEvent("activate", this);
35622 deactivate : function(){
35623 this.fireEvent("deactivate", this);
35627 disable : function(){
35628 this.component.disable();
35629 Roo.menu.Adapter.superclass.disable.call(this);
35633 enable : function(){
35634 this.component.enable();
35635 Roo.menu.Adapter.superclass.enable.call(this);
35639 * Ext JS Library 1.1.1
35640 * Copyright(c) 2006-2007, Ext JS, LLC.
35642 * Originally Released Under LGPL - original licence link has changed is not relivant.
35645 * <script type="text/javascript">
35649 * @class Roo.menu.TextItem
35650 * @extends Roo.menu.BaseItem
35651 * Adds a static text string to a menu, usually used as either a heading or group separator.
35652 * Note: old style constructor with text is still supported.
35655 * Creates a new TextItem
35656 * @param {Object} cfg Configuration
35658 Roo.menu.TextItem = function(cfg){
35659 if (typeof(cfg) == 'string') {
35662 Roo.apply(this,cfg);
35665 Roo.menu.TextItem.superclass.constructor.call(this);
35668 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
35670 * @cfg {Boolean} text Text to show on item.
35675 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
35677 hideOnClick : false,
35679 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
35681 itemCls : "x-menu-text",
35684 onRender : function(){
35685 var s = document.createElement("span");
35686 s.className = this.itemCls;
35687 s.innerHTML = this.text;
35689 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
35693 * Ext JS Library 1.1.1
35694 * Copyright(c) 2006-2007, Ext JS, LLC.
35696 * Originally Released Under LGPL - original licence link has changed is not relivant.
35699 * <script type="text/javascript">
35703 * @class Roo.menu.Separator
35704 * @extends Roo.menu.BaseItem
35705 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
35706 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
35708 * @param {Object} config Configuration options
35710 Roo.menu.Separator = function(config){
35711 Roo.menu.Separator.superclass.constructor.call(this, config);
35714 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
35716 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
35718 itemCls : "x-menu-sep",
35720 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
35722 hideOnClick : false,
35725 onRender : function(li){
35726 var s = document.createElement("span");
35727 s.className = this.itemCls;
35728 s.innerHTML = " ";
35730 li.addClass("x-menu-sep-li");
35731 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
35735 * Ext JS Library 1.1.1
35736 * Copyright(c) 2006-2007, Ext JS, LLC.
35738 * Originally Released Under LGPL - original licence link has changed is not relivant.
35741 * <script type="text/javascript">
35744 * @class Roo.menu.Item
35745 * @extends Roo.menu.BaseItem
35746 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
35747 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
35748 * activation and click handling.
35750 * Creates a new Item
35751 * @param {Object} config Configuration options
35753 Roo.menu.Item = function(config){
35754 Roo.menu.Item.superclass.constructor.call(this, config);
35756 this.menu = Roo.menu.MenuMgr.get(this.menu);
35759 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
35762 * @cfg {String} text
35763 * The text to show on the menu item.
35767 * @cfg {String} HTML to render in menu
35768 * The text to show on the menu item (HTML version).
35772 * @cfg {String} icon
35773 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
35777 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
35779 itemCls : "x-menu-item",
35781 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
35783 canActivate : true,
35785 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
35788 // doc'd in BaseItem
35792 ctype: "Roo.menu.Item",
35795 onRender : function(container, position){
35796 var el = document.createElement("a");
35797 el.hideFocus = true;
35798 el.unselectable = "on";
35799 el.href = this.href || "#";
35800 if(this.hrefTarget){
35801 el.target = this.hrefTarget;
35803 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
35805 var html = this.html.length ? this.html : String.format('{0}',this.text);
35807 el.innerHTML = String.format(
35808 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
35809 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
35811 Roo.menu.Item.superclass.onRender.call(this, container, position);
35815 * Sets the text to display in this menu item
35816 * @param {String} text The text to display
35817 * @param {Boolean} isHTML true to indicate text is pure html.
35819 setText : function(text, isHTML){
35827 var html = this.html.length ? this.html : String.format('{0}',this.text);
35829 this.el.update(String.format(
35830 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
35831 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
35832 this.parentMenu.autoWidth();
35837 handleClick : function(e){
35838 if(!this.href){ // if no link defined, stop the event automatically
35841 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
35845 activate : function(autoExpand){
35846 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
35856 shouldDeactivate : function(e){
35857 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
35858 if(this.menu && this.menu.isVisible()){
35859 return !this.menu.getEl().getRegion().contains(e.getPoint());
35867 deactivate : function(){
35868 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
35873 expandMenu : function(autoActivate){
35874 if(!this.disabled && this.menu){
35875 clearTimeout(this.hideTimer);
35876 delete this.hideTimer;
35877 if(!this.menu.isVisible() && !this.showTimer){
35878 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
35879 }else if (this.menu.isVisible() && autoActivate){
35880 this.menu.tryActivate(0, 1);
35886 deferExpand : function(autoActivate){
35887 delete this.showTimer;
35888 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
35890 this.menu.tryActivate(0, 1);
35895 hideMenu : function(){
35896 clearTimeout(this.showTimer);
35897 delete this.showTimer;
35898 if(!this.hideTimer && this.menu && this.menu.isVisible()){
35899 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
35904 deferHide : function(){
35905 delete this.hideTimer;
35910 * Ext JS Library 1.1.1
35911 * Copyright(c) 2006-2007, Ext JS, LLC.
35913 * Originally Released Under LGPL - original licence link has changed is not relivant.
35916 * <script type="text/javascript">
35920 * @class Roo.menu.CheckItem
35921 * @extends Roo.menu.Item
35922 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
35924 * Creates a new CheckItem
35925 * @param {Object} config Configuration options
35927 Roo.menu.CheckItem = function(config){
35928 Roo.menu.CheckItem.superclass.constructor.call(this, config);
35931 * @event beforecheckchange
35932 * Fires before the checked value is set, providing an opportunity to cancel if needed
35933 * @param {Roo.menu.CheckItem} this
35934 * @param {Boolean} checked The new checked value that will be set
35936 "beforecheckchange" : true,
35938 * @event checkchange
35939 * Fires after the checked value has been set
35940 * @param {Roo.menu.CheckItem} this
35941 * @param {Boolean} checked The checked value that was set
35943 "checkchange" : true
35945 if(this.checkHandler){
35946 this.on('checkchange', this.checkHandler, this.scope);
35949 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
35951 * @cfg {String} group
35952 * All check items with the same group name will automatically be grouped into a single-select
35953 * radio button group (defaults to '')
35956 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
35958 itemCls : "x-menu-item x-menu-check-item",
35960 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
35962 groupClass : "x-menu-group-item",
35965 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
35966 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
35967 * initialized with checked = true will be rendered as checked.
35972 ctype: "Roo.menu.CheckItem",
35975 onRender : function(c){
35976 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
35978 this.el.addClass(this.groupClass);
35980 Roo.menu.MenuMgr.registerCheckable(this);
35982 this.checked = false;
35983 this.setChecked(true, true);
35988 destroy : function(){
35990 Roo.menu.MenuMgr.unregisterCheckable(this);
35992 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
35996 * Set the checked state of this item
35997 * @param {Boolean} checked The new checked value
35998 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
36000 setChecked : function(state, suppressEvent){
36001 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
36002 if(this.container){
36003 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
36005 this.checked = state;
36006 if(suppressEvent !== true){
36007 this.fireEvent("checkchange", this, state);
36013 handleClick : function(e){
36014 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
36015 this.setChecked(!this.checked);
36017 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
36021 * Ext JS Library 1.1.1
36022 * Copyright(c) 2006-2007, Ext JS, LLC.
36024 * Originally Released Under LGPL - original licence link has changed is not relivant.
36027 * <script type="text/javascript">
36031 * @class Roo.menu.DateItem
36032 * @extends Roo.menu.Adapter
36033 * A menu item that wraps the {@link Roo.DatPicker} component.
36035 * Creates a new DateItem
36036 * @param {Object} config Configuration options
36038 Roo.menu.DateItem = function(config){
36039 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
36040 /** The Roo.DatePicker object @type Roo.DatePicker */
36041 this.picker = this.component;
36042 this.addEvents({select: true});
36044 this.picker.on("render", function(picker){
36045 picker.getEl().swallowEvent("click");
36046 picker.container.addClass("x-menu-date-item");
36049 this.picker.on("select", this.onSelect, this);
36052 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
36054 onSelect : function(picker, date){
36055 this.fireEvent("select", this, date, picker);
36056 Roo.menu.DateItem.superclass.handleClick.call(this);
36060 * Ext JS Library 1.1.1
36061 * Copyright(c) 2006-2007, Ext JS, LLC.
36063 * Originally Released Under LGPL - original licence link has changed is not relivant.
36066 * <script type="text/javascript">
36070 * @class Roo.menu.ColorItem
36071 * @extends Roo.menu.Adapter
36072 * A menu item that wraps the {@link Roo.ColorPalette} component.
36074 * Creates a new ColorItem
36075 * @param {Object} config Configuration options
36077 Roo.menu.ColorItem = function(config){
36078 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
36079 /** The Roo.ColorPalette object @type Roo.ColorPalette */
36080 this.palette = this.component;
36081 this.relayEvents(this.palette, ["select"]);
36082 if(this.selectHandler){
36083 this.on('select', this.selectHandler, this.scope);
36086 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
36088 * Ext JS Library 1.1.1
36089 * Copyright(c) 2006-2007, Ext JS, LLC.
36091 * Originally Released Under LGPL - original licence link has changed is not relivant.
36094 * <script type="text/javascript">
36099 * @class Roo.menu.DateMenu
36100 * @extends Roo.menu.Menu
36101 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
36103 * Creates a new DateMenu
36104 * @param {Object} config Configuration options
36106 Roo.menu.DateMenu = function(config){
36107 Roo.menu.DateMenu.superclass.constructor.call(this, config);
36109 var di = new Roo.menu.DateItem(config);
36112 * The {@link Roo.DatePicker} instance for this DateMenu
36115 this.picker = di.picker;
36118 * @param {DatePicker} picker
36119 * @param {Date} date
36121 this.relayEvents(di, ["select"]);
36122 this.on('beforeshow', function(){
36124 this.picker.hideMonthPicker(false);
36128 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
36132 * Ext JS Library 1.1.1
36133 * Copyright(c) 2006-2007, Ext JS, LLC.
36135 * Originally Released Under LGPL - original licence link has changed is not relivant.
36138 * <script type="text/javascript">
36143 * @class Roo.menu.ColorMenu
36144 * @extends Roo.menu.Menu
36145 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
36147 * Creates a new ColorMenu
36148 * @param {Object} config Configuration options
36150 Roo.menu.ColorMenu = function(config){
36151 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
36153 var ci = new Roo.menu.ColorItem(config);
36156 * The {@link Roo.ColorPalette} instance for this ColorMenu
36157 * @type ColorPalette
36159 this.palette = ci.palette;
36162 * @param {ColorPalette} palette
36163 * @param {String} color
36165 this.relayEvents(ci, ["select"]);
36167 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
36169 * Ext JS Library 1.1.1
36170 * Copyright(c) 2006-2007, Ext JS, LLC.
36172 * Originally Released Under LGPL - original licence link has changed is not relivant.
36175 * <script type="text/javascript">
36179 * @class Roo.form.Field
36180 * @extends Roo.BoxComponent
36181 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
36183 * Creates a new Field
36184 * @param {Object} config Configuration options
36186 Roo.form.Field = function(config){
36187 Roo.form.Field.superclass.constructor.call(this, config);
36190 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
36192 * @cfg {String} fieldLabel Label to use when rendering a form.
36195 * @cfg {String} qtip Mouse over tip
36199 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
36201 invalidClass : "x-form-invalid",
36203 * @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")
36205 invalidText : "The value in this field is invalid",
36207 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
36209 focusClass : "x-form-focus",
36211 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
36212 automatic validation (defaults to "keyup").
36214 validationEvent : "keyup",
36216 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
36218 validateOnBlur : true,
36220 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
36222 validationDelay : 250,
36224 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
36225 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
36227 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
36229 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
36231 fieldClass : "x-form-field",
36233 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
36236 ----------- ----------------------------------------------------------------------
36237 qtip Display a quick tip when the user hovers over the field
36238 title Display a default browser title attribute popup
36239 under Add a block div beneath the field containing the error text
36240 side Add an error icon to the right of the field with a popup on hover
36241 [element id] Add the error text directly to the innerHTML of the specified element
36244 msgTarget : 'qtip',
36246 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
36251 * @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.
36256 * @cfg {Boolean} disabled True to disable the field (defaults to false).
36261 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
36263 inputType : undefined,
36266 * @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).
36268 tabIndex : undefined,
36271 isFormField : true,
36276 * @property {Roo.Element} fieldEl
36277 * Element Containing the rendered Field (with label etc.)
36280 * @cfg {Mixed} value A value to initialize this field with.
36285 * @cfg {String} name The field's HTML name attribute.
36288 * @cfg {String} cls A CSS class to apply to the field's underlying element.
36292 initComponent : function(){
36293 Roo.form.Field.superclass.initComponent.call(this);
36297 * Fires when this field receives input focus.
36298 * @param {Roo.form.Field} this
36303 * Fires when this field loses input focus.
36304 * @param {Roo.form.Field} this
36308 * @event specialkey
36309 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
36310 * {@link Roo.EventObject#getKey} to determine which key was pressed.
36311 * @param {Roo.form.Field} this
36312 * @param {Roo.EventObject} e The event object
36317 * Fires just before the field blurs if the field value has changed.
36318 * @param {Roo.form.Field} this
36319 * @param {Mixed} newValue The new value
36320 * @param {Mixed} oldValue The original value
36325 * Fires after the field has been marked as invalid.
36326 * @param {Roo.form.Field} this
36327 * @param {String} msg The validation message
36332 * Fires after the field has been validated with no errors.
36333 * @param {Roo.form.Field} this
36338 * Fires after the key up
36339 * @param {Roo.form.Field} this
36340 * @param {Roo.EventObject} e The event Object
36347 * Returns the name attribute of the field if available
36348 * @return {String} name The field name
36350 getName: function(){
36351 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
36355 onRender : function(ct, position){
36356 Roo.form.Field.superclass.onRender.call(this, ct, position);
36358 var cfg = this.getAutoCreate();
36360 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
36362 if (!cfg.name.length) {
36365 if(this.inputType){
36366 cfg.type = this.inputType;
36368 this.el = ct.createChild(cfg, position);
36370 var type = this.el.dom.type;
36372 if(type == 'password'){
36375 this.el.addClass('x-form-'+type);
36378 this.el.dom.readOnly = true;
36380 if(this.tabIndex !== undefined){
36381 this.el.dom.setAttribute('tabIndex', this.tabIndex);
36384 this.el.addClass([this.fieldClass, this.cls]);
36389 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
36390 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
36391 * @return {Roo.form.Field} this
36393 applyTo : function(target){
36394 this.allowDomMove = false;
36395 this.el = Roo.get(target);
36396 this.render(this.el.dom.parentNode);
36401 initValue : function(){
36402 if(this.value !== undefined){
36403 this.setValue(this.value);
36404 }else if(this.el.dom.value.length > 0){
36405 this.setValue(this.el.dom.value);
36410 * Returns true if this field has been changed since it was originally loaded and is not disabled.
36412 isDirty : function() {
36413 if(this.disabled) {
36416 return String(this.getValue()) !== String(this.originalValue);
36420 afterRender : function(){
36421 Roo.form.Field.superclass.afterRender.call(this);
36426 fireKey : function(e){
36427 //Roo.log('field ' + e.getKey());
36428 if(e.isNavKeyPress()){
36429 this.fireEvent("specialkey", this, e);
36434 * Resets the current field value to the originally loaded value and clears any validation messages
36436 reset : function(){
36437 this.setValue(this.originalValue);
36438 this.clearInvalid();
36442 initEvents : function(){
36443 // safari killled keypress - so keydown is now used..
36444 this.el.on("keydown" , this.fireKey, this);
36445 this.el.on("focus", this.onFocus, this);
36446 this.el.on("blur", this.onBlur, this);
36447 this.el.relayEvent('keyup', this);
36449 // reference to original value for reset
36450 this.originalValue = this.getValue();
36454 onFocus : function(){
36455 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
36456 this.el.addClass(this.focusClass);
36458 if(!this.hasFocus){
36459 this.hasFocus = true;
36460 this.startValue = this.getValue();
36461 this.fireEvent("focus", this);
36465 beforeBlur : Roo.emptyFn,
36468 onBlur : function(){
36470 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
36471 this.el.removeClass(this.focusClass);
36473 this.hasFocus = false;
36474 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
36477 var v = this.getValue();
36478 if(String(v) !== String(this.startValue)){
36479 this.fireEvent('change', this, v, this.startValue);
36481 this.fireEvent("blur", this);
36485 * Returns whether or not the field value is currently valid
36486 * @param {Boolean} preventMark True to disable marking the field invalid
36487 * @return {Boolean} True if the value is valid, else false
36489 isValid : function(preventMark){
36493 var restore = this.preventMark;
36494 this.preventMark = preventMark === true;
36495 var v = this.validateValue(this.processValue(this.getRawValue()));
36496 this.preventMark = restore;
36501 * Validates the field value
36502 * @return {Boolean} True if the value is valid, else false
36504 validate : function(){
36505 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
36506 this.clearInvalid();
36512 processValue : function(value){
36517 // Subclasses should provide the validation implementation by overriding this
36518 validateValue : function(value){
36523 * Mark this field as invalid
36524 * @param {String} msg The validation message
36526 markInvalid : function(msg){
36527 if(!this.rendered || this.preventMark){ // not rendered
36530 this.el.addClass(this.invalidClass);
36531 msg = msg || this.invalidText;
36532 switch(this.msgTarget){
36534 this.el.dom.qtip = msg;
36535 this.el.dom.qclass = 'x-form-invalid-tip';
36536 if(Roo.QuickTips){ // fix for floating editors interacting with DND
36537 Roo.QuickTips.enable();
36541 this.el.dom.title = msg;
36545 var elp = this.el.findParent('.x-form-element', 5, true);
36546 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
36547 this.errorEl.setWidth(elp.getWidth(true)-20);
36549 this.errorEl.update(msg);
36550 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
36553 if(!this.errorIcon){
36554 var elp = this.el.findParent('.x-form-element', 5, true);
36555 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
36557 this.alignErrorIcon();
36558 this.errorIcon.dom.qtip = msg;
36559 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
36560 this.errorIcon.show();
36561 this.on('resize', this.alignErrorIcon, this);
36564 var t = Roo.getDom(this.msgTarget);
36566 t.style.display = this.msgDisplay;
36569 this.fireEvent('invalid', this, msg);
36573 alignErrorIcon : function(){
36574 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
36578 * Clear any invalid styles/messages for this field
36580 clearInvalid : function(){
36581 if(!this.rendered || this.preventMark){ // not rendered
36584 this.el.removeClass(this.invalidClass);
36585 switch(this.msgTarget){
36587 this.el.dom.qtip = '';
36590 this.el.dom.title = '';
36594 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
36598 if(this.errorIcon){
36599 this.errorIcon.dom.qtip = '';
36600 this.errorIcon.hide();
36601 this.un('resize', this.alignErrorIcon, this);
36605 var t = Roo.getDom(this.msgTarget);
36607 t.style.display = 'none';
36610 this.fireEvent('valid', this);
36614 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
36615 * @return {Mixed} value The field value
36617 getRawValue : function(){
36618 var v = this.el.getValue();
36624 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
36625 * @return {Mixed} value The field value
36627 getValue : function(){
36628 var v = this.el.getValue();
36634 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
36635 * @param {Mixed} value The value to set
36637 setRawValue : function(v){
36638 return this.el.dom.value = (v === null || v === undefined ? '' : v);
36642 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
36643 * @param {Mixed} value The value to set
36645 setValue : function(v){
36648 this.el.dom.value = (v === null || v === undefined ? '' : v);
36653 adjustSize : function(w, h){
36654 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
36655 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
36659 adjustWidth : function(tag, w){
36660 tag = tag.toLowerCase();
36661 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
36662 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
36663 if(tag == 'input'){
36666 if(tag == 'textarea'){
36669 }else if(Roo.isOpera){
36670 if(tag == 'input'){
36673 if(tag == 'textarea'){
36683 // anything other than normal should be considered experimental
36684 Roo.form.Field.msgFx = {
36686 show: function(msgEl, f){
36687 msgEl.setDisplayed('block');
36690 hide : function(msgEl, f){
36691 msgEl.setDisplayed(false).update('');
36696 show: function(msgEl, f){
36697 msgEl.slideIn('t', {stopFx:true});
36700 hide : function(msgEl, f){
36701 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
36706 show: function(msgEl, f){
36707 msgEl.fixDisplay();
36708 msgEl.alignTo(f.el, 'tl-tr');
36709 msgEl.slideIn('l', {stopFx:true});
36712 hide : function(msgEl, f){
36713 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
36718 * Ext JS Library 1.1.1
36719 * Copyright(c) 2006-2007, Ext JS, LLC.
36721 * Originally Released Under LGPL - original licence link has changed is not relivant.
36724 * <script type="text/javascript">
36729 * @class Roo.form.TextField
36730 * @extends Roo.form.Field
36731 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
36732 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
36734 * Creates a new TextField
36735 * @param {Object} config Configuration options
36737 Roo.form.TextField = function(config){
36738 Roo.form.TextField.superclass.constructor.call(this, config);
36742 * Fires when the autosize function is triggered. The field may or may not have actually changed size
36743 * according to the default logic, but this event provides a hook for the developer to apply additional
36744 * logic at runtime to resize the field if needed.
36745 * @param {Roo.form.Field} this This text field
36746 * @param {Number} width The new field width
36752 Roo.extend(Roo.form.TextField, Roo.form.Field, {
36754 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
36758 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
36762 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
36766 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
36770 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
36774 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
36776 disableKeyFilter : false,
36778 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
36782 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
36786 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
36788 maxLength : Number.MAX_VALUE,
36790 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
36792 minLengthText : "The minimum length for this field is {0}",
36794 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
36796 maxLengthText : "The maximum length for this field is {0}",
36798 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
36800 selectOnFocus : false,
36802 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
36804 blankText : "This field is required",
36806 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
36807 * If available, this function will be called only after the basic validators all return true, and will be passed the
36808 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
36812 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
36813 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
36814 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
36818 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
36822 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
36828 initEvents : function()
36830 if (this.emptyText) {
36831 this.el.attr('placeholder', this.emptyText);
36834 Roo.form.TextField.superclass.initEvents.call(this);
36835 if(this.validationEvent == 'keyup'){
36836 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
36837 this.el.on('keyup', this.filterValidation, this);
36839 else if(this.validationEvent !== false){
36840 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
36843 if(this.selectOnFocus){
36844 this.on("focus", this.preFocus, this);
36847 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
36848 this.el.on("keypress", this.filterKeys, this);
36851 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
36852 this.el.on("click", this.autoSize, this);
36854 if(this.el.is('input[type=password]') && Roo.isSafari){
36855 this.el.on('keydown', this.SafariOnKeyDown, this);
36859 processValue : function(value){
36860 if(this.stripCharsRe){
36861 var newValue = value.replace(this.stripCharsRe, '');
36862 if(newValue !== value){
36863 this.setRawValue(newValue);
36870 filterValidation : function(e){
36871 if(!e.isNavKeyPress()){
36872 this.validationTask.delay(this.validationDelay);
36877 onKeyUp : function(e){
36878 if(!e.isNavKeyPress()){
36884 * Resets the current field value to the originally-loaded value and clears any validation messages.
36887 reset : function(){
36888 Roo.form.TextField.superclass.reset.call(this);
36894 preFocus : function(){
36896 if(this.selectOnFocus){
36897 this.el.dom.select();
36903 filterKeys : function(e){
36904 var k = e.getKey();
36905 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
36908 var c = e.getCharCode(), cc = String.fromCharCode(c);
36909 if(Roo.isIE && (e.isSpecialKey() || !cc)){
36912 if(!this.maskRe.test(cc)){
36917 setValue : function(v){
36919 Roo.form.TextField.superclass.setValue.apply(this, arguments);
36925 * Validates a value according to the field's validation rules and marks the field as invalid
36926 * if the validation fails
36927 * @param {Mixed} value The value to validate
36928 * @return {Boolean} True if the value is valid, else false
36930 validateValue : function(value){
36931 if(value.length < 1) { // if it's blank
36932 if(this.allowBlank){
36933 this.clearInvalid();
36936 this.markInvalid(this.blankText);
36940 if(value.length < this.minLength){
36941 this.markInvalid(String.format(this.minLengthText, this.minLength));
36944 if(value.length > this.maxLength){
36945 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
36949 var vt = Roo.form.VTypes;
36950 if(!vt[this.vtype](value, this)){
36951 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
36955 if(typeof this.validator == "function"){
36956 var msg = this.validator(value);
36958 this.markInvalid(msg);
36962 if(this.regex && !this.regex.test(value)){
36963 this.markInvalid(this.regexText);
36970 * Selects text in this field
36971 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
36972 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
36974 selectText : function(start, end){
36975 var v = this.getRawValue();
36977 start = start === undefined ? 0 : start;
36978 end = end === undefined ? v.length : end;
36979 var d = this.el.dom;
36980 if(d.setSelectionRange){
36981 d.setSelectionRange(start, end);
36982 }else if(d.createTextRange){
36983 var range = d.createTextRange();
36984 range.moveStart("character", start);
36985 range.moveEnd("character", v.length-end);
36992 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
36993 * This only takes effect if grow = true, and fires the autosize event.
36995 autoSize : function(){
36996 if(!this.grow || !this.rendered){
37000 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
37003 var v = el.dom.value;
37004 var d = document.createElement('div');
37005 d.appendChild(document.createTextNode(v));
37009 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
37010 this.el.setWidth(w);
37011 this.fireEvent("autosize", this, w);
37015 SafariOnKeyDown : function(event)
37017 // this is a workaround for a password hang bug on chrome/ webkit.
37019 var isSelectAll = false;
37021 if(this.el.dom.selectionEnd > 0){
37022 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
37024 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
37025 event.preventDefault();
37030 if(isSelectAll){ // backspace and delete key
37032 event.preventDefault();
37033 // this is very hacky as keydown always get's upper case.
37035 var cc = String.fromCharCode(event.getCharCode());
37036 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
37044 * Ext JS Library 1.1.1
37045 * Copyright(c) 2006-2007, Ext JS, LLC.
37047 * Originally Released Under LGPL - original licence link has changed is not relivant.
37050 * <script type="text/javascript">
37054 * @class Roo.form.Hidden
37055 * @extends Roo.form.TextField
37056 * Simple Hidden element used on forms
37058 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
37061 * Creates a new Hidden form element.
37062 * @param {Object} config Configuration options
37067 // easy hidden field...
37068 Roo.form.Hidden = function(config){
37069 Roo.form.Hidden.superclass.constructor.call(this, config);
37072 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
37074 inputType: 'hidden',
37077 labelSeparator: '',
37079 itemCls : 'x-form-item-display-none'
37087 * Ext JS Library 1.1.1
37088 * Copyright(c) 2006-2007, Ext JS, LLC.
37090 * Originally Released Under LGPL - original licence link has changed is not relivant.
37093 * <script type="text/javascript">
37097 * @class Roo.form.TriggerField
37098 * @extends Roo.form.TextField
37099 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
37100 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
37101 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
37102 * for which you can provide a custom implementation. For example:
37104 var trigger = new Roo.form.TriggerField();
37105 trigger.onTriggerClick = myTriggerFn;
37106 trigger.applyTo('my-field');
37109 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
37110 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
37111 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
37112 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
37114 * Create a new TriggerField.
37115 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
37116 * to the base TextField)
37118 Roo.form.TriggerField = function(config){
37119 this.mimicing = false;
37120 Roo.form.TriggerField.superclass.constructor.call(this, config);
37123 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
37125 * @cfg {String} triggerClass A CSS class to apply to the trigger
37128 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
37129 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
37131 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
37133 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
37137 /** @cfg {Boolean} grow @hide */
37138 /** @cfg {Number} growMin @hide */
37139 /** @cfg {Number} growMax @hide */
37145 autoSize: Roo.emptyFn,
37149 deferHeight : true,
37152 actionMode : 'wrap',
37154 onResize : function(w, h){
37155 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
37156 if(typeof w == 'number'){
37157 var x = w - this.trigger.getWidth();
37158 this.el.setWidth(this.adjustWidth('input', x));
37159 this.trigger.setStyle('left', x+'px');
37164 adjustSize : Roo.BoxComponent.prototype.adjustSize,
37167 getResizeEl : function(){
37172 getPositionEl : function(){
37177 alignErrorIcon : function(){
37178 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
37182 onRender : function(ct, position){
37183 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
37184 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
37185 this.trigger = this.wrap.createChild(this.triggerConfig ||
37186 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
37187 if(this.hideTrigger){
37188 this.trigger.setDisplayed(false);
37190 this.initTrigger();
37192 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
37197 initTrigger : function(){
37198 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
37199 this.trigger.addClassOnOver('x-form-trigger-over');
37200 this.trigger.addClassOnClick('x-form-trigger-click');
37204 onDestroy : function(){
37206 this.trigger.removeAllListeners();
37207 this.trigger.remove();
37210 this.wrap.remove();
37212 Roo.form.TriggerField.superclass.onDestroy.call(this);
37216 onFocus : function(){
37217 Roo.form.TriggerField.superclass.onFocus.call(this);
37218 if(!this.mimicing){
37219 this.wrap.addClass('x-trigger-wrap-focus');
37220 this.mimicing = true;
37221 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
37222 if(this.monitorTab){
37223 this.el.on("keydown", this.checkTab, this);
37229 checkTab : function(e){
37230 if(e.getKey() == e.TAB){
37231 this.triggerBlur();
37236 onBlur : function(){
37241 mimicBlur : function(e, t){
37242 if(!this.wrap.contains(t) && this.validateBlur()){
37243 this.triggerBlur();
37248 triggerBlur : function(){
37249 this.mimicing = false;
37250 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
37251 if(this.monitorTab){
37252 this.el.un("keydown", this.checkTab, this);
37254 this.wrap.removeClass('x-trigger-wrap-focus');
37255 Roo.form.TriggerField.superclass.onBlur.call(this);
37259 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
37260 validateBlur : function(e, t){
37265 onDisable : function(){
37266 Roo.form.TriggerField.superclass.onDisable.call(this);
37268 this.wrap.addClass('x-item-disabled');
37273 onEnable : function(){
37274 Roo.form.TriggerField.superclass.onEnable.call(this);
37276 this.wrap.removeClass('x-item-disabled');
37281 onShow : function(){
37282 var ae = this.getActionEl();
37285 ae.dom.style.display = '';
37286 ae.dom.style.visibility = 'visible';
37292 onHide : function(){
37293 var ae = this.getActionEl();
37294 ae.dom.style.display = 'none';
37298 * The function that should handle the trigger's click event. This method does nothing by default until overridden
37299 * by an implementing function.
37301 * @param {EventObject} e
37303 onTriggerClick : Roo.emptyFn
37306 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
37307 // to be extended by an implementing class. For an example of implementing this class, see the custom
37308 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
37309 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
37310 initComponent : function(){
37311 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
37313 this.triggerConfig = {
37314 tag:'span', cls:'x-form-twin-triggers', cn:[
37315 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
37316 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
37320 getTrigger : function(index){
37321 return this.triggers[index];
37324 initTrigger : function(){
37325 var ts = this.trigger.select('.x-form-trigger', true);
37326 this.wrap.setStyle('overflow', 'hidden');
37327 var triggerField = this;
37328 ts.each(function(t, all, index){
37329 t.hide = function(){
37330 var w = triggerField.wrap.getWidth();
37331 this.dom.style.display = 'none';
37332 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
37334 t.show = function(){
37335 var w = triggerField.wrap.getWidth();
37336 this.dom.style.display = '';
37337 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
37339 var triggerIndex = 'Trigger'+(index+1);
37341 if(this['hide'+triggerIndex]){
37342 t.dom.style.display = 'none';
37344 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
37345 t.addClassOnOver('x-form-trigger-over');
37346 t.addClassOnClick('x-form-trigger-click');
37348 this.triggers = ts.elements;
37351 onTrigger1Click : Roo.emptyFn,
37352 onTrigger2Click : Roo.emptyFn
37355 * Ext JS Library 1.1.1
37356 * Copyright(c) 2006-2007, Ext JS, LLC.
37358 * Originally Released Under LGPL - original licence link has changed is not relivant.
37361 * <script type="text/javascript">
37365 * @class Roo.form.TextArea
37366 * @extends Roo.form.TextField
37367 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
37368 * support for auto-sizing.
37370 * Creates a new TextArea
37371 * @param {Object} config Configuration options
37373 Roo.form.TextArea = function(config){
37374 Roo.form.TextArea.superclass.constructor.call(this, config);
37375 // these are provided exchanges for backwards compat
37376 // minHeight/maxHeight were replaced by growMin/growMax to be
37377 // compatible with TextField growing config values
37378 if(this.minHeight !== undefined){
37379 this.growMin = this.minHeight;
37381 if(this.maxHeight !== undefined){
37382 this.growMax = this.maxHeight;
37386 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
37388 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
37392 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
37396 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
37397 * in the field (equivalent to setting overflow: hidden, defaults to false)
37399 preventScrollbars: false,
37401 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
37402 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
37406 onRender : function(ct, position){
37408 this.defaultAutoCreate = {
37410 style:"width:300px;height:60px;",
37411 autocomplete: "off"
37414 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
37416 this.textSizeEl = Roo.DomHelper.append(document.body, {
37417 tag: "pre", cls: "x-form-grow-sizer"
37419 if(this.preventScrollbars){
37420 this.el.setStyle("overflow", "hidden");
37422 this.el.setHeight(this.growMin);
37426 onDestroy : function(){
37427 if(this.textSizeEl){
37428 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
37430 Roo.form.TextArea.superclass.onDestroy.call(this);
37434 onKeyUp : function(e){
37435 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
37441 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
37442 * This only takes effect if grow = true, and fires the autosize event if the height changes.
37444 autoSize : function(){
37445 if(!this.grow || !this.textSizeEl){
37449 var v = el.dom.value;
37450 var ts = this.textSizeEl;
37453 ts.appendChild(document.createTextNode(v));
37456 Roo.fly(ts).setWidth(this.el.getWidth());
37458 v = "  ";
37461 v = v.replace(/\n/g, '<p> </p>');
37463 v += " \n ";
37466 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
37467 if(h != this.lastHeight){
37468 this.lastHeight = h;
37469 this.el.setHeight(h);
37470 this.fireEvent("autosize", this, h);
37475 * Ext JS Library 1.1.1
37476 * Copyright(c) 2006-2007, Ext JS, LLC.
37478 * Originally Released Under LGPL - original licence link has changed is not relivant.
37481 * <script type="text/javascript">
37486 * @class Roo.form.NumberField
37487 * @extends Roo.form.TextField
37488 * Numeric text field that provides automatic keystroke filtering and numeric validation.
37490 * Creates a new NumberField
37491 * @param {Object} config Configuration options
37493 Roo.form.NumberField = function(config){
37494 Roo.form.NumberField.superclass.constructor.call(this, config);
37497 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
37499 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
37501 fieldClass: "x-form-field x-form-num-field",
37503 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
37505 allowDecimals : true,
37507 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
37509 decimalSeparator : ".",
37511 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
37513 decimalPrecision : 2,
37515 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
37517 allowNegative : true,
37519 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
37521 minValue : Number.NEGATIVE_INFINITY,
37523 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
37525 maxValue : Number.MAX_VALUE,
37527 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
37529 minText : "The minimum value for this field is {0}",
37531 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
37533 maxText : "The maximum value for this field is {0}",
37535 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
37536 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
37538 nanText : "{0} is not a valid number",
37541 initEvents : function(){
37542 Roo.form.NumberField.superclass.initEvents.call(this);
37543 var allowed = "0123456789";
37544 if(this.allowDecimals){
37545 allowed += this.decimalSeparator;
37547 if(this.allowNegative){
37550 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
37551 var keyPress = function(e){
37552 var k = e.getKey();
37553 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
37556 var c = e.getCharCode();
37557 if(allowed.indexOf(String.fromCharCode(c)) === -1){
37561 this.el.on("keypress", keyPress, this);
37565 validateValue : function(value){
37566 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
37569 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
37572 var num = this.parseValue(value);
37574 this.markInvalid(String.format(this.nanText, value));
37577 if(num < this.minValue){
37578 this.markInvalid(String.format(this.minText, this.minValue));
37581 if(num > this.maxValue){
37582 this.markInvalid(String.format(this.maxText, this.maxValue));
37588 getValue : function(){
37589 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
37593 parseValue : function(value){
37594 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
37595 return isNaN(value) ? '' : value;
37599 fixPrecision : function(value){
37600 var nan = isNaN(value);
37601 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
37602 return nan ? '' : value;
37604 return parseFloat(value).toFixed(this.decimalPrecision);
37607 setValue : function(v){
37608 v = this.fixPrecision(v);
37609 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
37613 decimalPrecisionFcn : function(v){
37614 return Math.floor(v);
37617 beforeBlur : function(){
37618 var v = this.parseValue(this.getRawValue());
37625 * Ext JS Library 1.1.1
37626 * Copyright(c) 2006-2007, Ext JS, LLC.
37628 * Originally Released Under LGPL - original licence link has changed is not relivant.
37631 * <script type="text/javascript">
37635 * @class Roo.form.DateField
37636 * @extends Roo.form.TriggerField
37637 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
37639 * Create a new DateField
37640 * @param {Object} config
37642 Roo.form.DateField = function(config){
37643 Roo.form.DateField.superclass.constructor.call(this, config);
37649 * Fires when a date is selected
37650 * @param {Roo.form.DateField} combo This combo box
37651 * @param {Date} date The date selected
37658 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
37659 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
37660 this.ddMatch = null;
37661 if(this.disabledDates){
37662 var dd = this.disabledDates;
37664 for(var i = 0; i < dd.length; i++){
37666 if(i != dd.length-1) re += "|";
37668 this.ddMatch = new RegExp(re + ")");
37672 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
37674 * @cfg {String} format
37675 * The default date format string which can be overriden for localization support. The format must be
37676 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
37680 * @cfg {String} altFormats
37681 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
37682 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
37684 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
37686 * @cfg {Array} disabledDays
37687 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
37689 disabledDays : null,
37691 * @cfg {String} disabledDaysText
37692 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
37694 disabledDaysText : "Disabled",
37696 * @cfg {Array} disabledDates
37697 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
37698 * expression so they are very powerful. Some examples:
37700 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
37701 * <li>["03/08", "09/16"] would disable those days for every year</li>
37702 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
37703 * <li>["03/../2006"] would disable every day in March 2006</li>
37704 * <li>["^03"] would disable every day in every March</li>
37706 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
37707 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
37709 disabledDates : null,
37711 * @cfg {String} disabledDatesText
37712 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
37714 disabledDatesText : "Disabled",
37716 * @cfg {Date/String} minValue
37717 * The minimum allowed date. Can be either a Javascript date object or a string date in a
37718 * valid format (defaults to null).
37722 * @cfg {Date/String} maxValue
37723 * The maximum allowed date. Can be either a Javascript date object or a string date in a
37724 * valid format (defaults to null).
37728 * @cfg {String} minText
37729 * The error text to display when the date in the cell is before minValue (defaults to
37730 * 'The date in this field must be after {minValue}').
37732 minText : "The date in this field must be equal to or after {0}",
37734 * @cfg {String} maxText
37735 * The error text to display when the date in the cell is after maxValue (defaults to
37736 * 'The date in this field must be before {maxValue}').
37738 maxText : "The date in this field must be equal to or before {0}",
37740 * @cfg {String} invalidText
37741 * The error text to display when the date in the field is invalid (defaults to
37742 * '{value} is not a valid date - it must be in the format {format}').
37744 invalidText : "{0} is not a valid date - it must be in the format {1}",
37746 * @cfg {String} triggerClass
37747 * An additional CSS class used to style the trigger button. The trigger will always get the
37748 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
37749 * which displays a calendar icon).
37751 triggerClass : 'x-form-date-trigger',
37755 * @cfg {Boolean} useIso
37756 * if enabled, then the date field will use a hidden field to store the
37757 * real value as iso formated date. default (false)
37761 * @cfg {String/Object} autoCreate
37762 * A DomHelper element spec, or true for a default element spec (defaults to
37763 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
37766 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
37769 hiddenField: false,
37771 onRender : function(ct, position)
37773 Roo.form.DateField.superclass.onRender.call(this, ct, position);
37775 //this.el.dom.removeAttribute('name');
37776 Roo.log("Changing name?");
37777 this.el.dom.setAttribute('name', this.name + '____hidden___' );
37778 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
37780 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
37781 // prevent input submission
37782 this.hiddenName = this.name;
37789 validateValue : function(value)
37791 value = this.formatDate(value);
37792 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
37793 Roo.log('super failed');
37796 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
37799 var svalue = value;
37800 value = this.parseDate(value);
37802 Roo.log('parse date failed' + svalue);
37803 this.markInvalid(String.format(this.invalidText, svalue, this.format));
37806 var time = value.getTime();
37807 if(this.minValue && time < this.minValue.getTime()){
37808 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
37811 if(this.maxValue && time > this.maxValue.getTime()){
37812 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
37815 if(this.disabledDays){
37816 var day = value.getDay();
37817 for(var i = 0; i < this.disabledDays.length; i++) {
37818 if(day === this.disabledDays[i]){
37819 this.markInvalid(this.disabledDaysText);
37824 var fvalue = this.formatDate(value);
37825 if(this.ddMatch && this.ddMatch.test(fvalue)){
37826 this.markInvalid(String.format(this.disabledDatesText, fvalue));
37833 // Provides logic to override the default TriggerField.validateBlur which just returns true
37834 validateBlur : function(){
37835 return !this.menu || !this.menu.isVisible();
37838 getName: function()
37840 // returns hidden if it's set..
37841 if (!this.rendered) {return ''};
37842 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
37847 * Returns the current date value of the date field.
37848 * @return {Date} The date value
37850 getValue : function(){
37852 return this.hiddenField ?
37853 this.hiddenField.value :
37854 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
37858 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
37859 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
37860 * (the default format used is "m/d/y").
37863 //All of these calls set the same date value (May 4, 2006)
37865 //Pass a date object:
37866 var dt = new Date('5/4/06');
37867 dateField.setValue(dt);
37869 //Pass a date string (default format):
37870 dateField.setValue('5/4/06');
37872 //Pass a date string (custom format):
37873 dateField.format = 'Y-m-d';
37874 dateField.setValue('2006-5-4');
37876 * @param {String/Date} date The date or valid date string
37878 setValue : function(date){
37879 if (this.hiddenField) {
37880 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
37882 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
37883 // make sure the value field is always stored as a date..
37884 this.value = this.parseDate(date);
37890 parseDate : function(value){
37891 if(!value || value instanceof Date){
37894 var v = Date.parseDate(value, this.format);
37895 if (!v && this.useIso) {
37896 v = Date.parseDate(value, 'Y-m-d');
37898 if(!v && this.altFormats){
37899 if(!this.altFormatsArray){
37900 this.altFormatsArray = this.altFormats.split("|");
37902 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
37903 v = Date.parseDate(value, this.altFormatsArray[i]);
37910 formatDate : function(date, fmt){
37911 return (!date || !(date instanceof Date)) ?
37912 date : date.dateFormat(fmt || this.format);
37917 select: function(m, d){
37920 this.fireEvent('select', this, d);
37922 show : function(){ // retain focus styling
37926 this.focus.defer(10, this);
37927 var ml = this.menuListeners;
37928 this.menu.un("select", ml.select, this);
37929 this.menu.un("show", ml.show, this);
37930 this.menu.un("hide", ml.hide, this);
37935 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
37936 onTriggerClick : function(){
37940 if(this.menu == null){
37941 this.menu = new Roo.menu.DateMenu();
37943 Roo.apply(this.menu.picker, {
37944 showClear: this.allowBlank,
37945 minDate : this.minValue,
37946 maxDate : this.maxValue,
37947 disabledDatesRE : this.ddMatch,
37948 disabledDatesText : this.disabledDatesText,
37949 disabledDays : this.disabledDays,
37950 disabledDaysText : this.disabledDaysText,
37951 format : this.useIso ? 'Y-m-d' : this.format,
37952 minText : String.format(this.minText, this.formatDate(this.minValue)),
37953 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
37955 this.menu.on(Roo.apply({}, this.menuListeners, {
37958 this.menu.picker.setValue(this.getValue() || new Date());
37959 this.menu.show(this.el, "tl-bl?");
37962 beforeBlur : function(){
37963 var v = this.parseDate(this.getRawValue());
37969 /** @cfg {Boolean} grow @hide */
37970 /** @cfg {Number} growMin @hide */
37971 /** @cfg {Number} growMax @hide */
37978 * Ext JS Library 1.1.1
37979 * Copyright(c) 2006-2007, Ext JS, LLC.
37981 * Originally Released Under LGPL - original licence link has changed is not relivant.
37984 * <script type="text/javascript">
37988 * @class Roo.form.MonthField
37989 * @extends Roo.form.TriggerField
37990 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
37992 * Create a new MonthField
37993 * @param {Object} config
37995 Roo.form.MonthField = function(config){
37997 Roo.form.MonthField.superclass.constructor.call(this, config);
38003 * Fires when a date is selected
38004 * @param {Roo.form.MonthFieeld} combo This combo box
38005 * @param {Date} date The date selected
38012 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
38013 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
38014 this.ddMatch = null;
38015 if(this.disabledDates){
38016 var dd = this.disabledDates;
38018 for(var i = 0; i < dd.length; i++){
38020 if(i != dd.length-1) re += "|";
38022 this.ddMatch = new RegExp(re + ")");
38026 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
38028 * @cfg {String} format
38029 * The default date format string which can be overriden for localization support. The format must be
38030 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
38034 * @cfg {String} altFormats
38035 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
38036 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
38038 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
38040 * @cfg {Array} disabledDays
38041 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
38043 disabledDays : [0,1,2,3,4,5,6],
38045 * @cfg {String} disabledDaysText
38046 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
38048 disabledDaysText : "Disabled",
38050 * @cfg {Array} disabledDates
38051 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
38052 * expression so they are very powerful. Some examples:
38054 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
38055 * <li>["03/08", "09/16"] would disable those days for every year</li>
38056 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
38057 * <li>["03/../2006"] would disable every day in March 2006</li>
38058 * <li>["^03"] would disable every day in every March</li>
38060 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
38061 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
38063 disabledDates : null,
38065 * @cfg {String} disabledDatesText
38066 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
38068 disabledDatesText : "Disabled",
38070 * @cfg {Date/String} minValue
38071 * The minimum allowed date. Can be either a Javascript date object or a string date in a
38072 * valid format (defaults to null).
38076 * @cfg {Date/String} maxValue
38077 * The maximum allowed date. Can be either a Javascript date object or a string date in a
38078 * valid format (defaults to null).
38082 * @cfg {String} minText
38083 * The error text to display when the date in the cell is before minValue (defaults to
38084 * 'The date in this field must be after {minValue}').
38086 minText : "The date in this field must be equal to or after {0}",
38088 * @cfg {String} maxTextf
38089 * The error text to display when the date in the cell is after maxValue (defaults to
38090 * 'The date in this field must be before {maxValue}').
38092 maxText : "The date in this field must be equal to or before {0}",
38094 * @cfg {String} invalidText
38095 * The error text to display when the date in the field is invalid (defaults to
38096 * '{value} is not a valid date - it must be in the format {format}').
38098 invalidText : "{0} is not a valid date - it must be in the format {1}",
38100 * @cfg {String} triggerClass
38101 * An additional CSS class used to style the trigger button. The trigger will always get the
38102 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
38103 * which displays a calendar icon).
38105 triggerClass : 'x-form-date-trigger',
38109 * @cfg {Boolean} useIso
38110 * if enabled, then the date field will use a hidden field to store the
38111 * real value as iso formated date. default (true)
38115 * @cfg {String/Object} autoCreate
38116 * A DomHelper element spec, or true for a default element spec (defaults to
38117 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
38120 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
38123 hiddenField: false,
38125 hideMonthPicker : false,
38127 onRender : function(ct, position)
38129 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
38131 this.el.dom.removeAttribute('name');
38132 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
38134 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
38135 // prevent input submission
38136 this.hiddenName = this.name;
38143 validateValue : function(value)
38145 value = this.formatDate(value);
38146 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
38149 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
38152 var svalue = value;
38153 value = this.parseDate(value);
38155 this.markInvalid(String.format(this.invalidText, svalue, this.format));
38158 var time = value.getTime();
38159 if(this.minValue && time < this.minValue.getTime()){
38160 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
38163 if(this.maxValue && time > this.maxValue.getTime()){
38164 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
38167 /*if(this.disabledDays){
38168 var day = value.getDay();
38169 for(var i = 0; i < this.disabledDays.length; i++) {
38170 if(day === this.disabledDays[i]){
38171 this.markInvalid(this.disabledDaysText);
38177 var fvalue = this.formatDate(value);
38178 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
38179 this.markInvalid(String.format(this.disabledDatesText, fvalue));
38187 // Provides logic to override the default TriggerField.validateBlur which just returns true
38188 validateBlur : function(){
38189 return !this.menu || !this.menu.isVisible();
38193 * Returns the current date value of the date field.
38194 * @return {Date} The date value
38196 getValue : function(){
38200 return this.hiddenField ?
38201 this.hiddenField.value :
38202 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
38206 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
38207 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
38208 * (the default format used is "m/d/y").
38211 //All of these calls set the same date value (May 4, 2006)
38213 //Pass a date object:
38214 var dt = new Date('5/4/06');
38215 monthField.setValue(dt);
38217 //Pass a date string (default format):
38218 monthField.setValue('5/4/06');
38220 //Pass a date string (custom format):
38221 monthField.format = 'Y-m-d';
38222 monthField.setValue('2006-5-4');
38224 * @param {String/Date} date The date or valid date string
38226 setValue : function(date){
38227 Roo.log('month setValue' + date);
38228 // can only be first of month..
38230 var val = this.parseDate(date);
38232 if (this.hiddenField) {
38233 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
38235 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
38236 this.value = this.parseDate(date);
38240 parseDate : function(value){
38241 if(!value || value instanceof Date){
38242 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
38245 var v = Date.parseDate(value, this.format);
38246 if (!v && this.useIso) {
38247 v = Date.parseDate(value, 'Y-m-d');
38251 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
38255 if(!v && this.altFormats){
38256 if(!this.altFormatsArray){
38257 this.altFormatsArray = this.altFormats.split("|");
38259 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
38260 v = Date.parseDate(value, this.altFormatsArray[i]);
38267 formatDate : function(date, fmt){
38268 return (!date || !(date instanceof Date)) ?
38269 date : date.dateFormat(fmt || this.format);
38274 select: function(m, d){
38276 this.fireEvent('select', this, d);
38278 show : function(){ // retain focus styling
38282 this.focus.defer(10, this);
38283 var ml = this.menuListeners;
38284 this.menu.un("select", ml.select, this);
38285 this.menu.un("show", ml.show, this);
38286 this.menu.un("hide", ml.hide, this);
38290 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
38291 onTriggerClick : function(){
38295 if(this.menu == null){
38296 this.menu = new Roo.menu.DateMenu();
38300 Roo.apply(this.menu.picker, {
38302 showClear: this.allowBlank,
38303 minDate : this.minValue,
38304 maxDate : this.maxValue,
38305 disabledDatesRE : this.ddMatch,
38306 disabledDatesText : this.disabledDatesText,
38308 format : this.useIso ? 'Y-m-d' : this.format,
38309 minText : String.format(this.minText, this.formatDate(this.minValue)),
38310 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
38313 this.menu.on(Roo.apply({}, this.menuListeners, {
38321 // hide month picker get's called when we called by 'before hide';
38323 var ignorehide = true;
38324 p.hideMonthPicker = function(disableAnim){
38328 if(this.monthPicker){
38329 Roo.log("hideMonthPicker called");
38330 if(disableAnim === true){
38331 this.monthPicker.hide();
38333 this.monthPicker.slideOut('t', {duration:.2});
38334 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
38335 p.fireEvent("select", this, this.value);
38341 Roo.log('picker set value');
38342 Roo.log(this.getValue());
38343 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
38344 m.show(this.el, 'tl-bl?');
38345 ignorehide = false;
38346 // this will trigger hideMonthPicker..
38349 // hidden the day picker
38350 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
38356 p.showMonthPicker.defer(100, p);
38362 beforeBlur : function(){
38363 var v = this.parseDate(this.getRawValue());
38369 /** @cfg {Boolean} grow @hide */
38370 /** @cfg {Number} growMin @hide */
38371 /** @cfg {Number} growMax @hide */
38378 * Ext JS Library 1.1.1
38379 * Copyright(c) 2006-2007, Ext JS, LLC.
38381 * Originally Released Under LGPL - original licence link has changed is not relivant.
38384 * <script type="text/javascript">
38389 * @class Roo.form.ComboBox
38390 * @extends Roo.form.TriggerField
38391 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
38393 * Create a new ComboBox.
38394 * @param {Object} config Configuration options
38396 Roo.form.ComboBox = function(config){
38397 Roo.form.ComboBox.superclass.constructor.call(this, config);
38401 * Fires when the dropdown list is expanded
38402 * @param {Roo.form.ComboBox} combo This combo box
38407 * Fires when the dropdown list is collapsed
38408 * @param {Roo.form.ComboBox} combo This combo box
38412 * @event beforeselect
38413 * Fires before a list item is selected. Return false to cancel the selection.
38414 * @param {Roo.form.ComboBox} combo This combo box
38415 * @param {Roo.data.Record} record The data record returned from the underlying store
38416 * @param {Number} index The index of the selected item in the dropdown list
38418 'beforeselect' : true,
38421 * Fires when a list item is selected
38422 * @param {Roo.form.ComboBox} combo This combo box
38423 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
38424 * @param {Number} index The index of the selected item in the dropdown list
38428 * @event beforequery
38429 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
38430 * The event object passed has these properties:
38431 * @param {Roo.form.ComboBox} combo This combo box
38432 * @param {String} query The query
38433 * @param {Boolean} forceAll true to force "all" query
38434 * @param {Boolean} cancel true to cancel the query
38435 * @param {Object} e The query event object
38437 'beforequery': true,
38440 * Fires when the 'add' icon is pressed (add a listener to enable add button)
38441 * @param {Roo.form.ComboBox} combo This combo box
38446 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
38447 * @param {Roo.form.ComboBox} combo This combo box
38448 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
38454 if(this.transform){
38455 this.allowDomMove = false;
38456 var s = Roo.getDom(this.transform);
38457 if(!this.hiddenName){
38458 this.hiddenName = s.name;
38461 this.mode = 'local';
38462 var d = [], opts = s.options;
38463 for(var i = 0, len = opts.length;i < len; i++){
38465 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
38467 this.value = value;
38469 d.push([value, o.text]);
38471 this.store = new Roo.data.SimpleStore({
38473 fields: ['value', 'text'],
38476 this.valueField = 'value';
38477 this.displayField = 'text';
38479 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
38480 if(!this.lazyRender){
38481 this.target = true;
38482 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
38483 s.parentNode.removeChild(s); // remove it
38484 this.render(this.el.parentNode);
38486 s.parentNode.removeChild(s); // remove it
38491 this.store = Roo.factory(this.store, Roo.data);
38494 this.selectedIndex = -1;
38495 if(this.mode == 'local'){
38496 if(config.queryDelay === undefined){
38497 this.queryDelay = 10;
38499 if(config.minChars === undefined){
38505 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
38507 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
38510 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
38511 * rendering into an Roo.Editor, defaults to false)
38514 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
38515 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
38518 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
38521 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
38522 * the dropdown list (defaults to undefined, with no header element)
38526 * @cfg {String/Roo.Template} tpl The template to use to render the output
38530 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
38532 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
38534 listWidth: undefined,
38536 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
38537 * mode = 'remote' or 'text' if mode = 'local')
38539 displayField: undefined,
38541 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
38542 * mode = 'remote' or 'value' if mode = 'local').
38543 * Note: use of a valueField requires the user make a selection
38544 * in order for a value to be mapped.
38546 valueField: undefined,
38550 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
38551 * field's data value (defaults to the underlying DOM element's name)
38553 hiddenName: undefined,
38555 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
38559 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
38561 selectedClass: 'x-combo-selected',
38563 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
38564 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
38565 * which displays a downward arrow icon).
38567 triggerClass : 'x-form-arrow-trigger',
38569 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
38573 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
38574 * anchor positions (defaults to 'tl-bl')
38576 listAlign: 'tl-bl?',
38578 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
38582 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
38583 * query specified by the allQuery config option (defaults to 'query')
38585 triggerAction: 'query',
38587 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
38588 * (defaults to 4, does not apply if editable = false)
38592 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
38593 * delay (typeAheadDelay) if it matches a known value (defaults to false)
38597 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
38598 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
38602 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
38603 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
38607 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
38608 * when editable = true (defaults to false)
38610 selectOnFocus:false,
38612 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
38614 queryParam: 'query',
38616 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
38617 * when mode = 'remote' (defaults to 'Loading...')
38619 loadingText: 'Loading...',
38621 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
38625 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
38629 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
38630 * traditional select (defaults to true)
38634 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
38638 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
38642 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
38643 * listWidth has a higher value)
38647 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
38648 * allow the user to set arbitrary text into the field (defaults to false)
38650 forceSelection:false,
38652 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
38653 * if typeAhead = true (defaults to 250)
38655 typeAheadDelay : 250,
38657 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
38658 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
38660 valueNotFoundText : undefined,
38662 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
38664 blockFocus : false,
38667 * @cfg {Boolean} disableClear Disable showing of clear button.
38669 disableClear : false,
38671 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
38673 alwaysQuery : false,
38679 // element that contains real text value.. (when hidden is used..)
38682 onRender : function(ct, position){
38683 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
38684 if(this.hiddenName){
38685 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
38687 this.hiddenField.value =
38688 this.hiddenValue !== undefined ? this.hiddenValue :
38689 this.value !== undefined ? this.value : '';
38691 // prevent input submission
38692 this.el.dom.removeAttribute('name');
38697 this.el.dom.setAttribute('autocomplete', 'off');
38700 var cls = 'x-combo-list';
38702 this.list = new Roo.Layer({
38703 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
38706 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
38707 this.list.setWidth(lw);
38708 this.list.swallowEvent('mousewheel');
38709 this.assetHeight = 0;
38712 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
38713 this.assetHeight += this.header.getHeight();
38716 this.innerList = this.list.createChild({cls:cls+'-inner'});
38717 this.innerList.on('mouseover', this.onViewOver, this);
38718 this.innerList.on('mousemove', this.onViewMove, this);
38719 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
38721 if(this.allowBlank && !this.pageSize && !this.disableClear){
38722 this.footer = this.list.createChild({cls:cls+'-ft'});
38723 this.pageTb = new Roo.Toolbar(this.footer);
38727 this.footer = this.list.createChild({cls:cls+'-ft'});
38728 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
38729 {pageSize: this.pageSize});
38733 if (this.pageTb && this.allowBlank && !this.disableClear) {
38735 this.pageTb.add(new Roo.Toolbar.Fill(), {
38736 cls: 'x-btn-icon x-btn-clear',
38738 handler: function()
38741 _this.clearValue();
38742 _this.onSelect(false, -1);
38747 this.assetHeight += this.footer.getHeight();
38752 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
38755 this.view = new Roo.View(this.innerList, this.tpl, {
38756 singleSelect:true, store: this.store, selectedClass: this.selectedClass
38759 this.view.on('click', this.onViewClick, this);
38761 this.store.on('beforeload', this.onBeforeLoad, this);
38762 this.store.on('load', this.onLoad, this);
38763 this.store.on('loadexception', this.onLoadException, this);
38765 if(this.resizable){
38766 this.resizer = new Roo.Resizable(this.list, {
38767 pinned:true, handles:'se'
38769 this.resizer.on('resize', function(r, w, h){
38770 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
38771 this.listWidth = w;
38772 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
38773 this.restrictHeight();
38775 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
38777 if(!this.editable){
38778 this.editable = true;
38779 this.setEditable(false);
38783 if (typeof(this.events.add.listeners) != 'undefined') {
38785 this.addicon = this.wrap.createChild(
38786 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
38788 this.addicon.on('click', function(e) {
38789 this.fireEvent('add', this);
38792 if (typeof(this.events.edit.listeners) != 'undefined') {
38794 this.editicon = this.wrap.createChild(
38795 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
38796 if (this.addicon) {
38797 this.editicon.setStyle('margin-left', '40px');
38799 this.editicon.on('click', function(e) {
38801 // we fire even if inothing is selected..
38802 this.fireEvent('edit', this, this.lastData );
38812 initEvents : function(){
38813 Roo.form.ComboBox.superclass.initEvents.call(this);
38815 this.keyNav = new Roo.KeyNav(this.el, {
38816 "up" : function(e){
38817 this.inKeyMode = true;
38821 "down" : function(e){
38822 if(!this.isExpanded()){
38823 this.onTriggerClick();
38825 this.inKeyMode = true;
38830 "enter" : function(e){
38831 this.onViewClick();
38835 "esc" : function(e){
38839 "tab" : function(e){
38840 this.onViewClick(false);
38841 this.fireEvent("specialkey", this, e);
38847 doRelay : function(foo, bar, hname){
38848 if(hname == 'down' || this.scope.isExpanded()){
38849 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
38856 this.queryDelay = Math.max(this.queryDelay || 10,
38857 this.mode == 'local' ? 10 : 250);
38858 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
38859 if(this.typeAhead){
38860 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
38862 if(this.editable !== false){
38863 this.el.on("keyup", this.onKeyUp, this);
38865 if(this.forceSelection){
38866 this.on('blur', this.doForce, this);
38870 onDestroy : function(){
38872 this.view.setStore(null);
38873 this.view.el.removeAllListeners();
38874 this.view.el.remove();
38875 this.view.purgeListeners();
38878 this.list.destroy();
38881 this.store.un('beforeload', this.onBeforeLoad, this);
38882 this.store.un('load', this.onLoad, this);
38883 this.store.un('loadexception', this.onLoadException, this);
38885 Roo.form.ComboBox.superclass.onDestroy.call(this);
38889 fireKey : function(e){
38890 if(e.isNavKeyPress() && !this.list.isVisible()){
38891 this.fireEvent("specialkey", this, e);
38896 onResize: function(w, h){
38897 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
38899 if(typeof w != 'number'){
38900 // we do not handle it!?!?
38903 var tw = this.trigger.getWidth();
38904 tw += this.addicon ? this.addicon.getWidth() : 0;
38905 tw += this.editicon ? this.editicon.getWidth() : 0;
38907 this.el.setWidth( this.adjustWidth('input', x));
38909 this.trigger.setStyle('left', x+'px');
38911 if(this.list && this.listWidth === undefined){
38912 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
38913 this.list.setWidth(lw);
38914 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
38922 * Allow or prevent the user from directly editing the field text. If false is passed,
38923 * the user will only be able to select from the items defined in the dropdown list. This method
38924 * is the runtime equivalent of setting the 'editable' config option at config time.
38925 * @param {Boolean} value True to allow the user to directly edit the field text
38927 setEditable : function(value){
38928 if(value == this.editable){
38931 this.editable = value;
38933 this.el.dom.setAttribute('readOnly', true);
38934 this.el.on('mousedown', this.onTriggerClick, this);
38935 this.el.addClass('x-combo-noedit');
38937 this.el.dom.setAttribute('readOnly', false);
38938 this.el.un('mousedown', this.onTriggerClick, this);
38939 this.el.removeClass('x-combo-noedit');
38944 onBeforeLoad : function(){
38945 if(!this.hasFocus){
38948 this.innerList.update(this.loadingText ?
38949 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
38950 this.restrictHeight();
38951 this.selectedIndex = -1;
38955 onLoad : function(){
38956 if(!this.hasFocus){
38959 if(this.store.getCount() > 0){
38961 this.restrictHeight();
38962 if(this.lastQuery == this.allQuery){
38964 this.el.dom.select();
38966 if(!this.selectByValue(this.value, true)){
38967 this.select(0, true);
38971 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
38972 this.taTask.delay(this.typeAheadDelay);
38976 this.onEmptyResults();
38981 onLoadException : function()
38984 Roo.log(this.store.reader.jsonData);
38985 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
38986 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
38992 onTypeAhead : function(){
38993 if(this.store.getCount() > 0){
38994 var r = this.store.getAt(0);
38995 var newValue = r.data[this.displayField];
38996 var len = newValue.length;
38997 var selStart = this.getRawValue().length;
38998 if(selStart != len){
38999 this.setRawValue(newValue);
39000 this.selectText(selStart, newValue.length);
39006 onSelect : function(record, index){
39007 if(this.fireEvent('beforeselect', this, record, index) !== false){
39008 this.setFromData(index > -1 ? record.data : false);
39010 this.fireEvent('select', this, record, index);
39015 * Returns the currently selected field value or empty string if no value is set.
39016 * @return {String} value The selected value
39018 getValue : function(){
39019 if(this.valueField){
39020 return typeof this.value != 'undefined' ? this.value : '';
39022 return Roo.form.ComboBox.superclass.getValue.call(this);
39027 * Clears any text/value currently set in the field
39029 clearValue : function(){
39030 if(this.hiddenField){
39031 this.hiddenField.value = '';
39034 this.setRawValue('');
39035 this.lastSelectionText = '';
39040 * Sets the specified value into the field. If the value finds a match, the corresponding record text
39041 * will be displayed in the field. If the value does not match the data value of an existing item,
39042 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
39043 * Otherwise the field will be blank (although the value will still be set).
39044 * @param {String} value The value to match
39046 setValue : function(v){
39048 if(this.valueField){
39049 var r = this.findRecord(this.valueField, v);
39051 text = r.data[this.displayField];
39052 }else if(this.valueNotFoundText !== undefined){
39053 text = this.valueNotFoundText;
39056 this.lastSelectionText = text;
39057 if(this.hiddenField){
39058 this.hiddenField.value = v;
39060 Roo.form.ComboBox.superclass.setValue.call(this, text);
39064 * @property {Object} the last set data for the element
39069 * Sets the value of the field based on a object which is related to the record format for the store.
39070 * @param {Object} value the value to set as. or false on reset?
39072 setFromData : function(o){
39073 var dv = ''; // display value
39074 var vv = ''; // value value..
39076 if (this.displayField) {
39077 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
39079 // this is an error condition!!!
39080 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
39083 if(this.valueField){
39084 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
39086 if(this.hiddenField){
39087 this.hiddenField.value = vv;
39089 this.lastSelectionText = dv;
39090 Roo.form.ComboBox.superclass.setValue.call(this, dv);
39094 // no hidden field.. - we store the value in 'value', but still display
39095 // display field!!!!
39096 this.lastSelectionText = dv;
39097 Roo.form.ComboBox.superclass.setValue.call(this, dv);
39103 reset : function(){
39104 // overridden so that last data is reset..
39105 this.setValue(this.originalValue);
39106 this.clearInvalid();
39107 this.lastData = false;
39109 this.view.clearSelections();
39113 findRecord : function(prop, value){
39115 if(this.store.getCount() > 0){
39116 this.store.each(function(r){
39117 if(r.data[prop] == value){
39127 getName: function()
39129 // returns hidden if it's set..
39130 if (!this.rendered) {return ''};
39131 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
39135 onViewMove : function(e, t){
39136 this.inKeyMode = false;
39140 onViewOver : function(e, t){
39141 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
39144 var item = this.view.findItemFromChild(t);
39146 var index = this.view.indexOf(item);
39147 this.select(index, false);
39152 onViewClick : function(doFocus)
39154 var index = this.view.getSelectedIndexes()[0];
39155 var r = this.store.getAt(index);
39157 this.onSelect(r, index);
39159 if(doFocus !== false && !this.blockFocus){
39165 restrictHeight : function(){
39166 this.innerList.dom.style.height = '';
39167 var inner = this.innerList.dom;
39168 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
39169 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
39170 this.list.beginUpdate();
39171 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
39172 this.list.alignTo(this.el, this.listAlign);
39173 this.list.endUpdate();
39177 onEmptyResults : function(){
39182 * Returns true if the dropdown list is expanded, else false.
39184 isExpanded : function(){
39185 return this.list.isVisible();
39189 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
39190 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
39191 * @param {String} value The data value of the item to select
39192 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
39193 * selected item if it is not currently in view (defaults to true)
39194 * @return {Boolean} True if the value matched an item in the list, else false
39196 selectByValue : function(v, scrollIntoView){
39197 if(v !== undefined && v !== null){
39198 var r = this.findRecord(this.valueField || this.displayField, v);
39200 this.select(this.store.indexOf(r), scrollIntoView);
39208 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
39209 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
39210 * @param {Number} index The zero-based index of the list item to select
39211 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
39212 * selected item if it is not currently in view (defaults to true)
39214 select : function(index, scrollIntoView){
39215 this.selectedIndex = index;
39216 this.view.select(index);
39217 if(scrollIntoView !== false){
39218 var el = this.view.getNode(index);
39220 this.innerList.scrollChildIntoView(el, false);
39226 selectNext : function(){
39227 var ct = this.store.getCount();
39229 if(this.selectedIndex == -1){
39231 }else if(this.selectedIndex < ct-1){
39232 this.select(this.selectedIndex+1);
39238 selectPrev : function(){
39239 var ct = this.store.getCount();
39241 if(this.selectedIndex == -1){
39243 }else if(this.selectedIndex != 0){
39244 this.select(this.selectedIndex-1);
39250 onKeyUp : function(e){
39251 if(this.editable !== false && !e.isSpecialKey()){
39252 this.lastKey = e.getKey();
39253 this.dqTask.delay(this.queryDelay);
39258 validateBlur : function(){
39259 return !this.list || !this.list.isVisible();
39263 initQuery : function(){
39264 this.doQuery(this.getRawValue());
39268 doForce : function(){
39269 if(this.el.dom.value.length > 0){
39270 this.el.dom.value =
39271 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
39277 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
39278 * query allowing the query action to be canceled if needed.
39279 * @param {String} query The SQL query to execute
39280 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
39281 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
39282 * saved in the current store (defaults to false)
39284 doQuery : function(q, forceAll){
39285 if(q === undefined || q === null){
39290 forceAll: forceAll,
39294 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
39298 forceAll = qe.forceAll;
39299 if(forceAll === true || (q.length >= this.minChars)){
39300 if(this.lastQuery != q || this.alwaysQuery){
39301 this.lastQuery = q;
39302 if(this.mode == 'local'){
39303 this.selectedIndex = -1;
39305 this.store.clearFilter();
39307 this.store.filter(this.displayField, q);
39311 this.store.baseParams[this.queryParam] = q;
39313 params: this.getParams(q)
39318 this.selectedIndex = -1;
39325 getParams : function(q){
39327 //p[this.queryParam] = q;
39330 p.limit = this.pageSize;
39336 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
39338 collapse : function(){
39339 if(!this.isExpanded()){
39343 Roo.get(document).un('mousedown', this.collapseIf, this);
39344 Roo.get(document).un('mousewheel', this.collapseIf, this);
39345 if (!this.editable) {
39346 Roo.get(document).un('keydown', this.listKeyPress, this);
39348 this.fireEvent('collapse', this);
39352 collapseIf : function(e){
39353 if(!e.within(this.wrap) && !e.within(this.list)){
39359 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
39361 expand : function(){
39362 if(this.isExpanded() || !this.hasFocus){
39365 this.list.alignTo(this.el, this.listAlign);
39367 Roo.get(document).on('mousedown', this.collapseIf, this);
39368 Roo.get(document).on('mousewheel', this.collapseIf, this);
39369 if (!this.editable) {
39370 Roo.get(document).on('keydown', this.listKeyPress, this);
39373 this.fireEvent('expand', this);
39377 // Implements the default empty TriggerField.onTriggerClick function
39378 onTriggerClick : function(){
39382 if(this.isExpanded()){
39384 if (!this.blockFocus) {
39389 this.hasFocus = true;
39390 if(this.triggerAction == 'all') {
39391 this.doQuery(this.allQuery, true);
39393 this.doQuery(this.getRawValue());
39395 if (!this.blockFocus) {
39400 listKeyPress : function(e)
39402 //Roo.log('listkeypress');
39403 // scroll to first matching element based on key pres..
39404 if (e.isSpecialKey()) {
39407 var k = String.fromCharCode(e.getKey()).toUpperCase();
39410 var csel = this.view.getSelectedNodes();
39411 var cselitem = false;
39413 var ix = this.view.indexOf(csel[0]);
39414 cselitem = this.store.getAt(ix);
39415 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
39421 this.store.each(function(v) {
39423 // start at existing selection.
39424 if (cselitem.id == v.id) {
39430 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
39431 match = this.store.indexOf(v);
39436 if (match === false) {
39437 return true; // no more action?
39440 this.view.select(match);
39441 var sn = Roo.get(this.view.getSelectedNodes()[0])
39442 sn.scrollIntoView(sn.dom.parentNode, false);
39446 * @cfg {Boolean} grow
39450 * @cfg {Number} growMin
39454 * @cfg {Number} growMax
39462 * Copyright(c) 2010-2012, Roo J Solutions Limited
39469 * @class Roo.form.ComboBoxArray
39470 * @extends Roo.form.TextField
39471 * A facebook style adder... for lists of email / people / countries etc...
39472 * pick multiple items from a combo box, and shows each one.
39474 * Fred [x] Brian [x] [Pick another |v]
39477 * For this to work: it needs various extra information
39478 * - normal combo problay has
39480 * + displayField, valueField
39482 * For our purpose...
39485 * If we change from 'extends' to wrapping...
39492 * Create a new ComboBoxArray.
39493 * @param {Object} config Configuration options
39497 Roo.form.ComboBoxArray = function(config)
39500 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
39502 this.items = new Roo.util.MixedCollection(false);
39504 // construct the child combo...
39514 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
39517 * @cfg {Roo.form.Combo} combo The combo box that is wrapped
39522 // behavies liek a hiddne field
39523 inputType: 'hidden',
39525 * @cfg {Number} width The width of the box that displays the selected element
39532 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
39536 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
39538 hiddenName : false,
39541 // private the array of items that are displayed..
39543 // private - the hidden field el.
39545 // private - the filed el..
39548 //validateValue : function() { return true; }, // all values are ok!
39549 //onAddClick: function() { },
39551 onRender : function(ct, position)
39554 // create the standard hidden element
39555 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
39558 // give fake names to child combo;
39559 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
39560 this.combo.name = this.name? (this.name+'-subcombo') : this.name;
39562 this.combo = Roo.factory(this.combo, Roo.form);
39563 this.combo.onRender(ct, position);
39564 if (typeof(this.combo.width) != 'undefined') {
39565 this.combo.onResize(this.combo.width,0);
39568 this.combo.initEvents();
39570 // assigned so form know we need to do this..
39571 this.store = this.combo.store;
39572 this.valueField = this.combo.valueField;
39573 this.displayField = this.combo.displayField ;
39576 this.combo.wrap.addClass('x-cbarray-grp');
39578 var cbwrap = this.combo.wrap.createChild(
39579 {tag: 'div', cls: 'x-cbarray-cb'},
39584 this.hiddenEl = this.combo.wrap.createChild({
39585 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
39587 this.el = this.combo.wrap.createChild({
39588 tag: 'input', type:'hidden' , name: this.name, value : ''
39590 // this.el.dom.removeAttribute("name");
39593 this.outerWrap = this.combo.wrap;
39594 this.wrap = cbwrap;
39596 this.outerWrap.setWidth(this.width);
39597 this.outerWrap.dom.removeChild(this.el.dom);
39599 this.wrap.dom.appendChild(this.el.dom);
39600 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
39601 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
39603 this.combo.trigger.setStyle('position','relative');
39604 this.combo.trigger.setStyle('left', '0px');
39605 this.combo.trigger.setStyle('top', '2px');
39607 this.combo.el.setStyle('vertical-align', 'text-bottom');
39609 //this.trigger.setStyle('vertical-align', 'top');
39611 // this should use the code from combo really... on('add' ....)
39615 this.adder = this.outerWrap.createChild(
39616 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
39618 this.adder.on('click', function(e) {
39619 _t.fireEvent('adderclick', this, e);
39623 //this.adder.on('click', this.onAddClick, _t);
39626 this.combo.on('select', function(cb, rec, ix) {
39627 this.addItem(rec.data);
39630 cb.el.dom.value = '';
39631 //cb.lastData = rec.data;
39640 getName: function()
39642 // returns hidden if it's set..
39643 if (!this.rendered) {return ''};
39644 return this.hiddenName ? this.hiddenName : this.name;
39649 onResize: function(w, h){
39652 // not sure if this is needed..
39653 //this.combo.onResize(w,h);
39655 if(typeof w != 'number'){
39656 // we do not handle it!?!?
39659 var tw = this.combo.trigger.getWidth();
39660 tw += this.addicon ? this.addicon.getWidth() : 0;
39661 tw += this.editicon ? this.editicon.getWidth() : 0;
39663 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
39665 this.combo.trigger.setStyle('left', '0px');
39667 if(this.list && this.listWidth === undefined){
39668 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
39669 this.list.setWidth(lw);
39670 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
39677 addItem: function(rec)
39679 var valueField = this.combo.valueField;
39680 var displayField = this.combo.displayField;
39681 if (this.items.indexOfKey(rec[valueField]) > -1) {
39682 //console.log("GOT " + rec.data.id);
39686 var x = new Roo.form.ComboBoxArray.Item({
39687 //id : rec[this.idField],
39689 displayField : displayField ,
39690 tipField : displayField ,
39694 this.items.add(rec[valueField],x);
39695 // add it before the element..
39696 this.updateHiddenEl();
39697 x.render(this.outerWrap, this.wrap.dom);
39698 // add the image handler..
39701 updateHiddenEl : function()
39704 if (!this.hiddenEl) {
39708 var idField = this.combo.valueField;
39710 this.items.each(function(f) {
39711 ar.push(f.data[idField]);
39714 this.hiddenEl.dom.value = ar.join(',');
39720 //Roo.form.ComboBoxArray.superclass.reset.call(this);
39721 this.items.each(function(f) {
39724 this.el.dom.value = '';
39725 if (this.hiddenEl) {
39726 this.hiddenEl.dom.value = '';
39730 getValue: function()
39732 return this.hiddenEl ? this.hiddenEl.dom.value : '';
39734 setValue: function(v) // not a valid action - must use addItems..
39741 if (this.store.isLocal && (typeof(v) == 'string')) {
39742 // then we can use the store to find the values..
39743 // comma seperated at present.. this needs to allow JSON based encoding..
39744 this.hiddenEl.value = v;
39746 Roo.each(v.split(','), function(k) {
39747 Roo.log("CHECK " + this.valueField + ',' + k);
39748 var li = this.store.query(this.valueField, k);
39753 add[this.valueField] = k;
39754 add[this.displayField] = li.item(0).data[this.displayField];
39760 if (typeof(v) == 'object') {
39761 // then let's assume it's an array of objects..
39762 Roo.each(v, function(l) {
39770 setFromData: function(v)
39772 // this recieves an object, if setValues is called.
39774 this.el.dom.value = v[this.displayField];
39775 this.hiddenEl.dom.value = v[this.valueField];
39776 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
39779 var kv = v[this.valueField];
39780 var dv = v[this.displayField];
39781 kv = typeof(kv) != 'string' ? '' : kv;
39782 dv = typeof(dv) != 'string' ? '' : dv;
39785 var keys = kv.split(',');
39786 var display = dv.split(',');
39787 for (var i = 0 ; i < keys.length; i++) {
39790 add[this.valueField] = keys[i];
39791 add[this.displayField] = display[i];
39799 validateValue : function(value){
39800 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
39809 * @class Roo.form.ComboBoxArray.Item
39810 * @extends Roo.BoxComponent
39811 * A selected item in the list
39812 * Fred [x] Brian [x] [Pick another |v]
39815 * Create a new item.
39816 * @param {Object} config Configuration options
39819 Roo.form.ComboBoxArray.Item = function(config) {
39820 config.id = Roo.id();
39821 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
39824 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
39827 displayField : false,
39831 defaultAutoCreate : {
39833 cls: 'x-cbarray-item',
39840 src : Roo.BLANK_IMAGE_URL ,
39848 onRender : function(ct, position)
39850 Roo.form.Field.superclass.onRender.call(this, ct, position);
39853 var cfg = this.getAutoCreate();
39854 this.el = ct.createChild(cfg, position);
39857 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
39859 this.el.child('div').dom.innerHTML = this.cb.renderer ?
39860 this.cb.renderer(this.data) :
39861 String.format('{0}',this.data[this.displayField]);
39864 this.el.child('div').dom.setAttribute('qtip',
39865 String.format('{0}',this.data[this.tipField])
39868 this.el.child('img').on('click', this.remove, this);
39872 remove : function()
39875 this.cb.items.remove(this);
39876 this.el.child('img').un('click', this.remove, this);
39878 this.cb.updateHiddenEl();
39884 * Ext JS Library 1.1.1
39885 * Copyright(c) 2006-2007, Ext JS, LLC.
39887 * Originally Released Under LGPL - original licence link has changed is not relivant.
39890 * <script type="text/javascript">
39893 * @class Roo.form.Checkbox
39894 * @extends Roo.form.Field
39895 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
39897 * Creates a new Checkbox
39898 * @param {Object} config Configuration options
39900 Roo.form.Checkbox = function(config){
39901 Roo.form.Checkbox.superclass.constructor.call(this, config);
39905 * Fires when the checkbox is checked or unchecked.
39906 * @param {Roo.form.Checkbox} this This checkbox
39907 * @param {Boolean} checked The new checked value
39913 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
39915 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
39917 focusClass : undefined,
39919 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
39921 fieldClass: "x-form-field",
39923 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
39927 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
39928 * {tag: "input", type: "checkbox", autocomplete: "off"})
39930 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
39932 * @cfg {String} boxLabel The text that appears beside the checkbox
39936 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
39940 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
39942 valueOff: '0', // value when not checked..
39944 actionMode : 'viewEl',
39947 itemCls : 'x-menu-check-item x-form-item',
39948 groupClass : 'x-menu-group-item',
39949 inputType : 'hidden',
39952 inSetChecked: false, // check that we are not calling self...
39954 inputElement: false, // real input element?
39955 basedOn: false, // ????
39957 isFormField: true, // not sure where this is needed!!!!
39959 onResize : function(){
39960 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
39961 if(!this.boxLabel){
39962 this.el.alignTo(this.wrap, 'c-c');
39966 initEvents : function(){
39967 Roo.form.Checkbox.superclass.initEvents.call(this);
39968 this.el.on("click", this.onClick, this);
39969 this.el.on("change", this.onClick, this);
39973 getResizeEl : function(){
39977 getPositionEl : function(){
39982 onRender : function(ct, position){
39983 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
39985 if(this.inputValue !== undefined){
39986 this.el.dom.value = this.inputValue;
39989 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
39990 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
39991 var viewEl = this.wrap.createChild({
39992 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
39993 this.viewEl = viewEl;
39994 this.wrap.on('click', this.onClick, this);
39996 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
39997 this.el.on('propertychange', this.setFromHidden, this); //ie
40002 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
40003 // viewEl.on('click', this.onClick, this);
40005 //if(this.checked){
40006 this.setChecked(this.checked);
40008 //this.checked = this.el.dom;
40014 initValue : Roo.emptyFn,
40017 * Returns the checked state of the checkbox.
40018 * @return {Boolean} True if checked, else false
40020 getValue : function(){
40022 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
40024 return this.valueOff;
40029 onClick : function(){
40030 this.setChecked(!this.checked);
40032 //if(this.el.dom.checked != this.checked){
40033 // this.setValue(this.el.dom.checked);
40038 * Sets the checked state of the checkbox.
40039 * On is always based on a string comparison between inputValue and the param.
40040 * @param {Boolean/String} value - the value to set
40041 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
40043 setValue : function(v,suppressEvent){
40046 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
40047 //if(this.el && this.el.dom){
40048 // this.el.dom.checked = this.checked;
40049 // this.el.dom.defaultChecked = this.checked;
40051 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
40052 //this.fireEvent("check", this, this.checked);
40055 setChecked : function(state,suppressEvent)
40057 if (this.inSetChecked) {
40058 this.checked = state;
40064 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
40066 this.checked = state;
40067 if(suppressEvent !== true){
40068 this.fireEvent('check', this, state);
40070 this.inSetChecked = true;
40071 this.el.dom.value = state ? this.inputValue : this.valueOff;
40072 this.inSetChecked = false;
40075 // handle setting of hidden value by some other method!!?!?
40076 setFromHidden: function()
40081 //console.log("SET FROM HIDDEN");
40082 //alert('setFrom hidden');
40083 this.setValue(this.el.dom.value);
40086 onDestroy : function()
40089 Roo.get(this.viewEl).remove();
40092 Roo.form.Checkbox.superclass.onDestroy.call(this);
40097 * Ext JS Library 1.1.1
40098 * Copyright(c) 2006-2007, Ext JS, LLC.
40100 * Originally Released Under LGPL - original licence link has changed is not relivant.
40103 * <script type="text/javascript">
40107 * @class Roo.form.Radio
40108 * @extends Roo.form.Checkbox
40109 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
40110 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
40112 * Creates a new Radio
40113 * @param {Object} config Configuration options
40115 Roo.form.Radio = function(){
40116 Roo.form.Radio.superclass.constructor.apply(this, arguments);
40118 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
40119 inputType: 'radio',
40122 * If this radio is part of a group, it will return the selected value
40125 getGroupValue : function(){
40126 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
40130 onRender : function(ct, position){
40131 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
40133 if(this.inputValue !== undefined){
40134 this.el.dom.value = this.inputValue;
40137 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
40138 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
40139 //var viewEl = this.wrap.createChild({
40140 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
40141 //this.viewEl = viewEl;
40142 //this.wrap.on('click', this.onClick, this);
40144 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
40145 //this.el.on('propertychange', this.setFromHidden, this); //ie
40150 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
40151 // viewEl.on('click', this.onClick, this);
40154 this.el.dom.checked = 'checked' ;
40160 });//<script type="text/javascript">
40163 * Ext JS Library 1.1.1
40164 * Copyright(c) 2006-2007, Ext JS, LLC.
40165 * licensing@extjs.com
40167 * http://www.extjs.com/license
40173 * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
40174 * - IE ? - no idea how much works there.
40182 * @class Ext.form.HtmlEditor
40183 * @extends Ext.form.Field
40184 * Provides a lightweight HTML Editor component.
40186 * This has been tested on Fireforx / Chrome.. IE may not be so great..
40188 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
40189 * supported by this editor.</b><br/><br/>
40190 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
40191 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
40193 Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
40195 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
40199 * @cfg {String} createLinkText The default text for the create link prompt
40201 createLinkText : 'Please enter the URL for the link:',
40203 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
40205 defaultLinkValue : 'http:/'+'/',
40208 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
40213 * @cfg {Number} height (in pixels)
40217 * @cfg {Number} width (in pixels)
40222 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
40225 stylesheets: false,
40230 // private properties
40231 validationEvent : false,
40233 initialized : false,
40235 sourceEditMode : false,
40236 onFocus : Roo.emptyFn,
40238 hideMode:'offsets',
40240 defaultAutoCreate : { // modified by initCompnoent..
40242 style:"width:500px;height:300px;",
40243 autocomplete: "off"
40247 initComponent : function(){
40250 * @event initialize
40251 * Fires when the editor is fully initialized (including the iframe)
40252 * @param {HtmlEditor} this
40257 * Fires when the editor is first receives the focus. Any insertion must wait
40258 * until after this event.
40259 * @param {HtmlEditor} this
40263 * @event beforesync
40264 * Fires before the textarea is updated with content from the editor iframe. Return false
40265 * to cancel the sync.
40266 * @param {HtmlEditor} this
40267 * @param {String} html
40271 * @event beforepush
40272 * Fires before the iframe editor is updated with content from the textarea. Return false
40273 * to cancel the push.
40274 * @param {HtmlEditor} this
40275 * @param {String} html
40280 * Fires when the textarea is updated with content from the editor iframe.
40281 * @param {HtmlEditor} this
40282 * @param {String} html
40287 * Fires when the iframe editor is updated with content from the textarea.
40288 * @param {HtmlEditor} this
40289 * @param {String} html
40293 * @event editmodechange
40294 * Fires when the editor switches edit modes
40295 * @param {HtmlEditor} this
40296 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
40298 editmodechange: true,
40300 * @event editorevent
40301 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
40302 * @param {HtmlEditor} this
40306 this.defaultAutoCreate = {
40308 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
40309 autocomplete: "off"
40314 * Protected method that will not generally be called directly. It
40315 * is called when the editor creates its toolbar. Override this method if you need to
40316 * add custom toolbar buttons.
40317 * @param {HtmlEditor} editor
40319 createToolbar : function(editor){
40320 if (!editor.toolbars || !editor.toolbars.length) {
40321 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
40324 for (var i =0 ; i < editor.toolbars.length;i++) {
40325 editor.toolbars[i] = Roo.factory(
40326 typeof(editor.toolbars[i]) == 'string' ?
40327 { xtype: editor.toolbars[i]} : editor.toolbars[i],
40328 Roo.form.HtmlEditor);
40329 editor.toolbars[i].init(editor);
40336 * Protected method that will not generally be called directly. It
40337 * is called when the editor initializes the iframe with HTML contents. Override this method if you
40338 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
40340 getDocMarkup : function(){
40343 if (this.stylesheets === false) {
40345 Roo.get(document.head).select('style').each(function(node) {
40346 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
40349 Roo.get(document.head).select('link').each(function(node) {
40350 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
40353 } else if (!this.stylesheets.length) {
40355 st = '<style type="text/css">' +
40356 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
40359 Roo.each(this.stylesheets, function(s) {
40360 st += '<link rel="stylesheet" type="text/css" href="' + s +'" />'
40365 st += '<style type="text/css">' +
40366 'IMG { cursor: pointer } ' +
40370 return '<html><head>' + st +
40371 //<style type="text/css">' +
40372 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
40374 ' </head><body class="roo-htmleditor-body"></body></html>';
40378 onRender : function(ct, position)
40381 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
40382 this.el.dom.style.border = '0 none';
40383 this.el.dom.setAttribute('tabIndex', -1);
40384 this.el.addClass('x-hidden');
40385 if(Roo.isIE){ // fix IE 1px bogus margin
40386 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
40388 this.wrap = this.el.wrap({
40389 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
40392 if (this.resizable) {
40393 this.resizeEl = new Roo.Resizable(this.wrap, {
40397 minHeight : this.height,
40398 height: this.height,
40399 handles : this.resizable,
40402 resize : function(r, w, h) {
40403 _t.onResize(w,h); // -something
40410 this.frameId = Roo.id();
40412 this.createToolbar(this);
40416 var iframe = this.wrap.createChild({
40419 name: this.frameId,
40420 frameBorder : 'no',
40421 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
40425 // console.log(iframe);
40426 //this.wrap.dom.appendChild(iframe);
40428 this.iframe = iframe.dom;
40430 this.assignDocWin();
40432 this.doc.designMode = 'on';
40435 this.doc.write(this.getDocMarkup());
40439 var task = { // must defer to wait for browser to be ready
40441 //console.log("run task?" + this.doc.readyState);
40442 this.assignDocWin();
40443 if(this.doc.body || this.doc.readyState == 'complete'){
40445 this.doc.designMode="on";
40449 Roo.TaskMgr.stop(task);
40450 this.initEditor.defer(10, this);
40457 Roo.TaskMgr.start(task);
40460 this.setSize(this.wrap.getSize());
40462 if (this.resizeEl) {
40463 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
40464 // should trigger onReize..
40469 onResize : function(w, h)
40471 //Roo.log('resize: ' +w + ',' + h );
40472 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
40473 if(this.el && this.iframe){
40474 if(typeof w == 'number'){
40475 var aw = w - this.wrap.getFrameWidth('lr');
40476 this.el.setWidth(this.adjustWidth('textarea', aw));
40477 this.iframe.style.width = aw + 'px';
40479 if(typeof h == 'number'){
40481 for (var i =0; i < this.toolbars.length;i++) {
40482 // fixme - ask toolbars for heights?
40483 tbh += this.toolbars[i].tb.el.getHeight();
40484 if (this.toolbars[i].footer) {
40485 tbh += this.toolbars[i].footer.el.getHeight();
40492 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
40493 ah -= 5; // knock a few pixes off for look..
40494 this.el.setHeight(this.adjustWidth('textarea', ah));
40495 this.iframe.style.height = ah + 'px';
40497 (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
40504 * Toggles the editor between standard and source edit mode.
40505 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
40507 toggleSourceEdit : function(sourceEditMode){
40509 this.sourceEditMode = sourceEditMode === true;
40511 if(this.sourceEditMode){
40513 // Roo.log(this.syncValue());
40515 this.iframe.className = 'x-hidden';
40516 this.el.removeClass('x-hidden');
40517 this.el.dom.removeAttribute('tabIndex');
40521 // Roo.log(this.pushValue());
40523 this.iframe.className = '';
40524 this.el.addClass('x-hidden');
40525 this.el.dom.setAttribute('tabIndex', -1);
40528 this.setSize(this.wrap.getSize());
40529 this.fireEvent('editmodechange', this, this.sourceEditMode);
40532 // private used internally
40533 createLink : function(){
40534 var url = prompt(this.createLinkText, this.defaultLinkValue);
40535 if(url && url != 'http:/'+'/'){
40536 this.relayCmd('createlink', url);
40540 // private (for BoxComponent)
40541 adjustSize : Roo.BoxComponent.prototype.adjustSize,
40543 // private (for BoxComponent)
40544 getResizeEl : function(){
40548 // private (for BoxComponent)
40549 getPositionEl : function(){
40554 initEvents : function(){
40555 this.originalValue = this.getValue();
40559 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
40562 markInvalid : Roo.emptyFn,
40564 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
40567 clearInvalid : Roo.emptyFn,
40569 setValue : function(v){
40570 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
40575 * Protected method that will not generally be called directly. If you need/want
40576 * custom HTML cleanup, this is the method you should override.
40577 * @param {String} html The HTML to be cleaned
40578 * return {String} The cleaned HTML
40580 cleanHtml : function(html){
40581 html = String(html);
40582 if(html.length > 5){
40583 if(Roo.isSafari){ // strip safari nonsense
40584 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
40587 if(html == ' '){
40594 * Protected method that will not generally be called directly. Syncs the contents
40595 * of the editor iframe with the textarea.
40597 syncValue : function(){
40598 if(this.initialized){
40599 var bd = (this.doc.body || this.doc.documentElement);
40600 //this.cleanUpPaste(); -- this is done else where and causes havoc..
40601 var html = bd.innerHTML;
40603 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
40604 var m = bs.match(/text-align:(.*?);/i);
40606 html = '<div style="'+m[0]+'">' + html + '</div>';
40609 html = this.cleanHtml(html);
40610 // fix up the special chars.. normaly like back quotes in word...
40611 // however we do not want to do this with chinese..
40612 html = html.replace(/([\x80-\uffff])/g, function (a, b) {
40613 var cc = b.charCodeAt();
40615 (cc >= 0x4E00 && cc < 0xA000 ) ||
40616 (cc >= 0x3400 && cc < 0x4E00 ) ||
40617 (cc >= 0xf900 && cc < 0xfb00 )
40623 if(this.fireEvent('beforesync', this, html) !== false){
40624 this.el.dom.value = html;
40625 this.fireEvent('sync', this, html);
40631 * Protected method that will not generally be called directly. Pushes the value of the textarea
40632 * into the iframe editor.
40634 pushValue : function(){
40635 if(this.initialized){
40636 var v = this.el.dom.value;
40642 if(this.fireEvent('beforepush', this, v) !== false){
40643 var d = (this.doc.body || this.doc.documentElement);
40645 this.cleanUpPaste();
40646 this.el.dom.value = d.innerHTML;
40647 this.fireEvent('push', this, v);
40653 deferFocus : function(){
40654 this.focus.defer(10, this);
40658 focus : function(){
40659 if(this.win && !this.sourceEditMode){
40666 assignDocWin: function()
40668 var iframe = this.iframe;
40671 this.doc = iframe.contentWindow.document;
40672 this.win = iframe.contentWindow;
40674 if (!Roo.get(this.frameId)) {
40677 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
40678 this.win = Roo.get(this.frameId).dom.contentWindow;
40683 initEditor : function(){
40684 //console.log("INIT EDITOR");
40685 this.assignDocWin();
40689 this.doc.designMode="on";
40691 this.doc.write(this.getDocMarkup());
40694 var dbody = (this.doc.body || this.doc.documentElement);
40695 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
40696 // this copies styles from the containing element into thsi one..
40697 // not sure why we need all of this..
40698 var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
40699 ss['background-attachment'] = 'fixed'; // w3c
40700 dbody.bgProperties = 'fixed'; // ie
40701 Roo.DomHelper.applyStyles(dbody, ss);
40702 Roo.EventManager.on(this.doc, {
40703 //'mousedown': this.onEditorEvent,
40704 'mouseup': this.onEditorEvent,
40705 'dblclick': this.onEditorEvent,
40706 'click': this.onEditorEvent,
40707 'keyup': this.onEditorEvent,
40712 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
40714 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
40715 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
40717 this.initialized = true;
40719 this.fireEvent('initialize', this);
40724 onDestroy : function(){
40730 for (var i =0; i < this.toolbars.length;i++) {
40731 // fixme - ask toolbars for heights?
40732 this.toolbars[i].onDestroy();
40735 this.wrap.dom.innerHTML = '';
40736 this.wrap.remove();
40741 onFirstFocus : function(){
40743 this.assignDocWin();
40746 this.activated = true;
40747 for (var i =0; i < this.toolbars.length;i++) {
40748 this.toolbars[i].onFirstFocus();
40751 if(Roo.isGecko){ // prevent silly gecko errors
40753 var s = this.win.getSelection();
40754 if(!s.focusNode || s.focusNode.nodeType != 3){
40755 var r = s.getRangeAt(0);
40756 r.selectNodeContents((this.doc.body || this.doc.documentElement));
40761 this.execCmd('useCSS', true);
40762 this.execCmd('styleWithCSS', false);
40765 this.fireEvent('activate', this);
40769 adjustFont: function(btn){
40770 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
40771 //if(Roo.isSafari){ // safari
40774 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
40775 if(Roo.isSafari){ // safari
40776 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
40777 v = (v < 10) ? 10 : v;
40778 v = (v > 48) ? 48 : v;
40779 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
40784 v = Math.max(1, v+adjust);
40786 this.execCmd('FontSize', v );
40789 onEditorEvent : function(e){
40790 this.fireEvent('editorevent', this, e);
40791 // this.updateToolbar();
40792 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
40795 insertTag : function(tg)
40797 // could be a bit smarter... -> wrap the current selected tRoo..
40798 if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
40800 range = this.createRange(this.getSelection());
40801 var wrappingNode = this.doc.createElement(tg.toLowerCase());
40802 wrappingNode.appendChild(range.extractContents());
40803 range.insertNode(wrappingNode);
40810 this.execCmd("formatblock", tg);
40814 insertText : function(txt)
40818 var range = this.createRange();
40819 range.deleteContents();
40820 //alert(Sender.getAttribute('label'));
40822 range.insertNode(this.doc.createTextNode(txt));
40826 relayBtnCmd : function(btn){
40827 this.relayCmd(btn.cmd);
40831 * Executes a Midas editor command on the editor document and performs necessary focus and
40832 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
40833 * @param {String} cmd The Midas command
40834 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
40836 relayCmd : function(cmd, value){
40838 this.execCmd(cmd, value);
40839 this.fireEvent('editorevent', this);
40840 //this.updateToolbar();
40845 * Executes a Midas editor command directly on the editor document.
40846 * For visual commands, you should use {@link #relayCmd} instead.
40847 * <b>This should only be called after the editor is initialized.</b>
40848 * @param {String} cmd The Midas command
40849 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
40851 execCmd : function(cmd, value){
40852 this.doc.execCommand(cmd, false, value === undefined ? null : value);
40859 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
40861 * @param {String} text | dom node..
40863 insertAtCursor : function(text)
40868 if(!this.activated){
40874 var r = this.doc.selection.createRange();
40885 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
40889 // from jquery ui (MIT licenced)
40891 var win = this.win;
40893 if (win.getSelection && win.getSelection().getRangeAt) {
40894 range = win.getSelection().getRangeAt(0);
40895 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
40896 range.insertNode(node);
40897 } else if (win.document.selection && win.document.selection.createRange) {
40898 // no firefox support
40899 var txt = typeof(text) == 'string' ? text : text.outerHTML;
40900 win.document.selection.createRange().pasteHTML(txt);
40902 // no firefox support
40903 var txt = typeof(text) == 'string' ? text : text.outerHTML;
40904 this.execCmd('InsertHTML', txt);
40913 mozKeyPress : function(e){
40915 var c = e.getCharCode(), cmd;
40918 c = String.fromCharCode(c).toLowerCase();
40932 this.cleanUpPaste.defer(100, this);
40940 e.preventDefault();
40948 fixKeys : function(){ // load time branching for fastest keydown performance
40950 return function(e){
40951 var k = e.getKey(), r;
40954 r = this.doc.selection.createRange();
40957 r.pasteHTML('    ');
40964 r = this.doc.selection.createRange();
40966 var target = r.parentElement();
40967 if(!target || target.tagName.toLowerCase() != 'li'){
40969 r.pasteHTML('<br />');
40975 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
40976 this.cleanUpPaste.defer(100, this);
40982 }else if(Roo.isOpera){
40983 return function(e){
40984 var k = e.getKey();
40988 this.execCmd('InsertHTML','    ');
40991 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
40992 this.cleanUpPaste.defer(100, this);
40997 }else if(Roo.isSafari){
40998 return function(e){
40999 var k = e.getKey();
41003 this.execCmd('InsertText','\t');
41007 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41008 this.cleanUpPaste.defer(100, this);
41016 getAllAncestors: function()
41018 var p = this.getSelectedNode();
41021 a.push(p); // push blank onto stack..
41022 p = this.getParentElement();
41026 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
41030 a.push(this.doc.body);
41034 lastSelNode : false,
41037 getSelection : function()
41039 this.assignDocWin();
41040 return Roo.isIE ? this.doc.selection : this.win.getSelection();
41043 getSelectedNode: function()
41045 // this may only work on Gecko!!!
41047 // should we cache this!!!!
41052 var range = this.createRange(this.getSelection()).cloneRange();
41055 var parent = range.parentElement();
41057 var testRange = range.duplicate();
41058 testRange.moveToElementText(parent);
41059 if (testRange.inRange(range)) {
41062 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
41065 parent = parent.parentElement;
41070 // is ancestor a text element.
41071 var ac = range.commonAncestorContainer;
41072 if (ac.nodeType == 3) {
41073 ac = ac.parentNode;
41076 var ar = ac.childNodes;
41079 var other_nodes = [];
41080 var has_other_nodes = false;
41081 for (var i=0;i<ar.length;i++) {
41082 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
41085 // fullly contained node.
41087 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
41092 // probably selected..
41093 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
41094 other_nodes.push(ar[i]);
41098 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
41103 has_other_nodes = true;
41105 if (!nodes.length && other_nodes.length) {
41106 nodes= other_nodes;
41108 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
41114 createRange: function(sel)
41116 // this has strange effects when using with
41117 // top toolbar - not sure if it's a great idea.
41118 //this.editor.contentWindow.focus();
41119 if (typeof sel != "undefined") {
41121 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
41123 return this.doc.createRange();
41126 return this.doc.createRange();
41129 getParentElement: function()
41132 this.assignDocWin();
41133 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
41135 var range = this.createRange(sel);
41138 var p = range.commonAncestorContainer;
41139 while (p.nodeType == 3) { // text node
41150 * Range intersection.. the hard stuff...
41154 * [ -- selected range --- ]
41158 * if end is before start or hits it. fail.
41159 * if start is after end or hits it fail.
41161 * if either hits (but other is outside. - then it's not
41167 // @see http://www.thismuchiknow.co.uk/?p=64.
41168 rangeIntersectsNode : function(range, node)
41170 var nodeRange = node.ownerDocument.createRange();
41172 nodeRange.selectNode(node);
41174 nodeRange.selectNodeContents(node);
41177 var rangeStartRange = range.cloneRange();
41178 rangeStartRange.collapse(true);
41180 var rangeEndRange = range.cloneRange();
41181 rangeEndRange.collapse(false);
41183 var nodeStartRange = nodeRange.cloneRange();
41184 nodeStartRange.collapse(true);
41186 var nodeEndRange = nodeRange.cloneRange();
41187 nodeEndRange.collapse(false);
41189 return rangeStartRange.compareBoundaryPoints(
41190 Range.START_TO_START, nodeEndRange) == -1 &&
41191 rangeEndRange.compareBoundaryPoints(
41192 Range.START_TO_START, nodeStartRange) == 1;
41196 rangeCompareNode : function(range, node)
41198 var nodeRange = node.ownerDocument.createRange();
41200 nodeRange.selectNode(node);
41202 nodeRange.selectNodeContents(node);
41206 range.collapse(true);
41208 nodeRange.collapse(true);
41210 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
41211 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
41213 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
41215 var nodeIsBefore = ss == 1;
41216 var nodeIsAfter = ee == -1;
41218 if (nodeIsBefore && nodeIsAfter)
41220 if (!nodeIsBefore && nodeIsAfter)
41221 return 1; //right trailed.
41223 if (nodeIsBefore && !nodeIsAfter)
41224 return 2; // left trailed.
41229 // private? - in a new class?
41230 cleanUpPaste : function()
41232 // cleans up the whole document..
41233 Roo.log('cleanuppaste');
41234 this.cleanUpChildren(this.doc.body);
41235 var clean = this.cleanWordChars(this.doc.body.innerHTML);
41236 if (clean != this.doc.body.innerHTML) {
41237 this.doc.body.innerHTML = clean;
41242 cleanWordChars : function(input) {// change the chars to hex code
41243 var he = Roo.form.HtmlEditor;
41245 var output = input;
41246 Roo.each(he.swapCodes, function(sw) {
41247 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
41249 output = output.replace(swapper, sw[1]);
41256 cleanUpChildren : function (n)
41258 if (!n.childNodes.length) {
41261 for (var i = n.childNodes.length-1; i > -1 ; i--) {
41262 this.cleanUpChild(n.childNodes[i]);
41269 cleanUpChild : function (node)
41272 //console.log(node);
41273 if (node.nodeName == "#text") {
41274 // clean up silly Windows -- stuff?
41277 if (node.nodeName == "#comment") {
41278 node.parentNode.removeChild(node);
41279 // clean up silly Windows -- stuff?
41283 if (Roo.form.HtmlEditor.black.indexOf(node.tagName.toLowerCase()) > -1) {
41285 node.parentNode.removeChild(node);
41290 var remove_keep_children= Roo.form.HtmlEditor.remove.indexOf(node.tagName.toLowerCase()) > -1;
41292 // remove <a name=....> as rendering on yahoo mailer is borked with this.
41293 // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
41295 //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
41296 // remove_keep_children = true;
41299 if (remove_keep_children) {
41300 this.cleanUpChildren(node);
41301 // inserts everything just before this node...
41302 while (node.childNodes.length) {
41303 var cn = node.childNodes[0];
41304 node.removeChild(cn);
41305 node.parentNode.insertBefore(cn, node);
41307 node.parentNode.removeChild(node);
41311 if (!node.attributes || !node.attributes.length) {
41312 this.cleanUpChildren(node);
41316 function cleanAttr(n,v)
41319 if (v.match(/^\./) || v.match(/^\//)) {
41322 if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
41325 if (v.match(/^#/)) {
41328 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
41329 node.removeAttribute(n);
41333 function cleanStyle(n,v)
41335 if (v.match(/expression/)) { //XSS?? should we even bother..
41336 node.removeAttribute(n);
41339 var cwhite = typeof(ed.cwhite) == 'undefined' ? Roo.form.HtmlEditor.cwhite : ed.cwhite;
41340 var cblack = typeof(ed.cblack) == 'undefined' ? Roo.form.HtmlEditor.cblack : ed.cblack;
41343 var parts = v.split(/;/);
41346 Roo.each(parts, function(p) {
41347 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
41351 var l = p.split(':').shift().replace(/\s+/g,'');
41352 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
41355 if ( cblack.indexOf(l) > -1) {
41356 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
41357 //node.removeAttribute(n);
41361 // only allow 'c whitelisted system attributes'
41362 if ( cwhite.length && cwhite.indexOf(l) < 0) {
41363 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
41364 //node.removeAttribute(n);
41374 if (clean.length) {
41375 node.setAttribute(n, clean.join(';'));
41377 node.removeAttribute(n);
41383 for (var i = node.attributes.length-1; i > -1 ; i--) {
41384 var a = node.attributes[i];
41387 if (a.name.toLowerCase().substr(0,2)=='on') {
41388 node.removeAttribute(a.name);
41391 if (Roo.form.HtmlEditor.ablack.indexOf(a.name.toLowerCase()) > -1) {
41392 node.removeAttribute(a.name);
41395 if (Roo.form.HtmlEditor.aclean.indexOf(a.name.toLowerCase()) > -1) {
41396 cleanAttr(a.name,a.value); // fixme..
41399 if (a.name == 'style') {
41400 cleanStyle(a.name,a.value);
41403 /// clean up MS crap..
41404 // tecnically this should be a list of valid class'es..
41407 if (a.name == 'class') {
41408 if (a.value.match(/^Mso/)) {
41409 node.className = '';
41412 if (a.value.match(/body/)) {
41413 node.className = '';
41424 this.cleanUpChildren(node);
41430 // hide stuff that is not compatible
41444 * @event specialkey
41448 * @cfg {String} fieldClass @hide
41451 * @cfg {String} focusClass @hide
41454 * @cfg {String} autoCreate @hide
41457 * @cfg {String} inputType @hide
41460 * @cfg {String} invalidClass @hide
41463 * @cfg {String} invalidText @hide
41466 * @cfg {String} msgFx @hide
41469 * @cfg {String} validateOnBlur @hide
41473 Roo.form.HtmlEditor.white = [
41474 'area', 'br', 'img', 'input', 'hr', 'wbr',
41476 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
41477 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
41478 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
41479 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
41480 'table', 'ul', 'xmp',
41482 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
41485 'dir', 'menu', 'ol', 'ul', 'dl',
41491 Roo.form.HtmlEditor.black = [
41492 // 'embed', 'object', // enable - backend responsiblity to clean thiese
41494 'base', 'basefont', 'bgsound', 'blink', 'body',
41495 'frame', 'frameset', 'head', 'html', 'ilayer',
41496 'iframe', 'layer', 'link', 'meta', 'object',
41497 'script', 'style' ,'title', 'xml' // clean later..
41499 Roo.form.HtmlEditor.clean = [
41500 'script', 'style', 'title', 'xml'
41502 Roo.form.HtmlEditor.remove = [
41507 Roo.form.HtmlEditor.ablack = [
41511 Roo.form.HtmlEditor.aclean = [
41512 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
41516 Roo.form.HtmlEditor.pwhite= [
41517 'http', 'https', 'mailto'
41520 // white listed style attributes.
41521 Roo.form.HtmlEditor.cwhite= [
41522 // 'text-align', /// default is to allow most things..
41528 // black listed style attributes.
41529 Roo.form.HtmlEditor.cblack= [
41530 // 'font-size' -- this can be set by the project
41534 Roo.form.HtmlEditor.swapCodes =[
41545 // <script type="text/javascript">
41548 * Ext JS Library 1.1.1
41549 * Copyright(c) 2006-2007, Ext JS, LLC.
41555 * @class Roo.form.HtmlEditorToolbar1
41560 new Roo.form.HtmlEditor({
41563 new Roo.form.HtmlEditorToolbar1({
41564 disable : { fonts: 1 , format: 1, ..., ... , ...],
41570 * @cfg {Object} disable List of elements to disable..
41571 * @cfg {Array} btns List of additional buttons.
41575 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
41578 Roo.form.HtmlEditor.ToolbarStandard = function(config)
41581 Roo.apply(this, config);
41583 // default disabled, based on 'good practice'..
41584 this.disable = this.disable || {};
41585 Roo.applyIf(this.disable, {
41588 specialElements : true
41592 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
41593 // dont call parent... till later.
41596 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
41604 * @cfg {Object} disable List of toolbar elements to disable
41609 * @cfg {Array} fontFamilies An array of available font families
41627 // "á" , ?? a acute?
41632 "°" // , // degrees
41634 // "é" , // e ecute
41635 // "ú" , // u ecute?
41638 specialElements : [
41640 text: "Insert Table",
41643 ihtml : '<table><tr><td>Cell</td></tr></table>'
41647 text: "Insert Image",
41650 ihtml : '<img src="about:blank"/>'
41659 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
41660 "input:submit", "input:button", "select", "textarea", "label" ],
41663 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
41665 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
41669 * @cfg {String} defaultFont default font to use.
41671 defaultFont: 'tahoma',
41673 fontSelect : false,
41676 formatCombo : false,
41678 init : function(editor)
41680 this.editor = editor;
41683 var fid = editor.frameId;
41685 function btn(id, toggle, handler){
41686 var xid = fid + '-'+ id ;
41690 cls : 'x-btn-icon x-edit-'+id,
41691 enableToggle:toggle !== false,
41692 scope: editor, // was editor...
41693 handler:handler||editor.relayBtnCmd,
41694 clickEvent:'mousedown',
41695 tooltip: etb.buttonTips[id] || undefined, ///tips ???
41702 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
41704 // stop form submits
41705 tb.el.on('click', function(e){
41706 e.preventDefault(); // what does this do?
41709 if(!this.disable.font) { // && !Roo.isSafari){
41710 /* why no safari for fonts
41711 editor.fontSelect = tb.el.createChild({
41714 cls:'x-font-select',
41715 html: this.createFontOptions()
41718 editor.fontSelect.on('change', function(){
41719 var font = editor.fontSelect.dom.value;
41720 editor.relayCmd('fontname', font);
41721 editor.deferFocus();
41725 editor.fontSelect.dom,
41731 if(!this.disable.formats){
41732 this.formatCombo = new Roo.form.ComboBox({
41733 store: new Roo.data.SimpleStore({
41736 data : this.formats // from states.js
41740 //autoCreate : {tag: "div", size: "20"},
41741 displayField:'tag',
41745 triggerAction: 'all',
41746 emptyText:'Add tag',
41747 selectOnFocus:true,
41750 'select': function(c, r, i) {
41751 editor.insertTag(r.get('tag'));
41757 tb.addField(this.formatCombo);
41761 if(!this.disable.format){
41768 if(!this.disable.fontSize){
41773 btn('increasefontsize', false, editor.adjustFont),
41774 btn('decreasefontsize', false, editor.adjustFont)
41779 if(!this.disable.colors){
41782 id:editor.frameId +'-forecolor',
41783 cls:'x-btn-icon x-edit-forecolor',
41784 clickEvent:'mousedown',
41785 tooltip: this.buttonTips['forecolor'] || undefined,
41787 menu : new Roo.menu.ColorMenu({
41788 allowReselect: true,
41789 focus: Roo.emptyFn,
41792 selectHandler: function(cp, color){
41793 editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
41794 editor.deferFocus();
41797 clickEvent:'mousedown'
41800 id:editor.frameId +'backcolor',
41801 cls:'x-btn-icon x-edit-backcolor',
41802 clickEvent:'mousedown',
41803 tooltip: this.buttonTips['backcolor'] || undefined,
41805 menu : new Roo.menu.ColorMenu({
41806 focus: Roo.emptyFn,
41809 allowReselect: true,
41810 selectHandler: function(cp, color){
41812 editor.execCmd('useCSS', false);
41813 editor.execCmd('hilitecolor', color);
41814 editor.execCmd('useCSS', true);
41815 editor.deferFocus();
41817 editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
41818 Roo.isSafari || Roo.isIE ? '#'+color : color);
41819 editor.deferFocus();
41823 clickEvent:'mousedown'
41828 // now add all the items...
41831 if(!this.disable.alignments){
41834 btn('justifyleft'),
41835 btn('justifycenter'),
41836 btn('justifyright')
41840 //if(!Roo.isSafari){
41841 if(!this.disable.links){
41844 btn('createlink', false, editor.createLink) /// MOVE TO HERE?!!?!?!?!
41848 if(!this.disable.lists){
41851 btn('insertorderedlist'),
41852 btn('insertunorderedlist')
41855 if(!this.disable.sourceEdit){
41858 btn('sourceedit', true, function(btn){
41859 this.toggleSourceEdit(btn.pressed);
41866 // special menu.. - needs to be tidied up..
41867 if (!this.disable.special) {
41870 cls: 'x-edit-none',
41876 for (var i =0; i < this.specialChars.length; i++) {
41877 smenu.menu.items.push({
41879 html: this.specialChars[i],
41880 handler: function(a,b) {
41881 editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
41882 //editor.insertAtCursor(a.html);
41895 if (!this.disable.specialElements) {
41898 cls: 'x-edit-none',
41903 for (var i =0; i < this.specialElements.length; i++) {
41904 semenu.menu.items.push(
41906 handler: function(a,b) {
41907 editor.insertAtCursor(this.ihtml);
41909 }, this.specialElements[i])
41921 for(var i =0; i< this.btns.length;i++) {
41922 var b = Roo.factory(this.btns[i],Roo.form);
41923 b.cls = 'x-edit-none';
41932 // disable everything...
41934 this.tb.items.each(function(item){
41935 if(item.id != editor.frameId+ '-sourceedit'){
41939 this.rendered = true;
41941 // the all the btns;
41942 editor.on('editorevent', this.updateToolbar, this);
41943 // other toolbars need to implement this..
41944 //editor.on('editmodechange', this.updateToolbar, this);
41950 * Protected method that will not generally be called directly. It triggers
41951 * a toolbar update by reading the markup state of the current selection in the editor.
41953 updateToolbar: function(){
41955 if(!this.editor.activated){
41956 this.editor.onFirstFocus();
41960 var btns = this.tb.items.map,
41961 doc = this.editor.doc,
41962 frameId = this.editor.frameId;
41964 if(!this.disable.font && !Roo.isSafari){
41966 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
41967 if(name != this.fontSelect.dom.value){
41968 this.fontSelect.dom.value = name;
41972 if(!this.disable.format){
41973 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
41974 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
41975 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
41977 if(!this.disable.alignments){
41978 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
41979 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
41980 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
41982 if(!Roo.isSafari && !this.disable.lists){
41983 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
41984 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
41987 var ans = this.editor.getAllAncestors();
41988 if (this.formatCombo) {
41991 var store = this.formatCombo.store;
41992 this.formatCombo.setValue("");
41993 for (var i =0; i < ans.length;i++) {
41994 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
41996 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
42004 // hides menus... - so this cant be on a menu...
42005 Roo.menu.MenuMgr.hideAll();
42007 //this.editorsyncValue();
42011 createFontOptions : function(){
42012 var buf = [], fs = this.fontFamilies, ff, lc;
42016 for(var i = 0, len = fs.length; i< len; i++){
42018 lc = ff.toLowerCase();
42020 '<option value="',lc,'" style="font-family:',ff,';"',
42021 (this.defaultFont == lc ? ' selected="true">' : '>'),
42026 return buf.join('');
42029 toggleSourceEdit : function(sourceEditMode){
42030 if(sourceEditMode === undefined){
42031 sourceEditMode = !this.sourceEditMode;
42033 this.sourceEditMode = sourceEditMode === true;
42034 var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
42035 // just toggle the button?
42036 if(btn.pressed !== this.editor.sourceEditMode){
42037 btn.toggle(this.editor.sourceEditMode);
42041 if(this.sourceEditMode){
42042 this.tb.items.each(function(item){
42043 if(item.cmd != 'sourceedit'){
42049 if(this.initialized){
42050 this.tb.items.each(function(item){
42056 // tell the editor that it's been pressed..
42057 this.editor.toggleSourceEdit(sourceEditMode);
42061 * Object collection of toolbar tooltips for the buttons in the editor. The key
42062 * is the command id associated with that button and the value is a valid QuickTips object.
42067 title: 'Bold (Ctrl+B)',
42068 text: 'Make the selected text bold.',
42069 cls: 'x-html-editor-tip'
42072 title: 'Italic (Ctrl+I)',
42073 text: 'Make the selected text italic.',
42074 cls: 'x-html-editor-tip'
42082 title: 'Bold (Ctrl+B)',
42083 text: 'Make the selected text bold.',
42084 cls: 'x-html-editor-tip'
42087 title: 'Italic (Ctrl+I)',
42088 text: 'Make the selected text italic.',
42089 cls: 'x-html-editor-tip'
42092 title: 'Underline (Ctrl+U)',
42093 text: 'Underline the selected text.',
42094 cls: 'x-html-editor-tip'
42096 increasefontsize : {
42097 title: 'Grow Text',
42098 text: 'Increase the font size.',
42099 cls: 'x-html-editor-tip'
42101 decreasefontsize : {
42102 title: 'Shrink Text',
42103 text: 'Decrease the font size.',
42104 cls: 'x-html-editor-tip'
42107 title: 'Text Highlight Color',
42108 text: 'Change the background color of the selected text.',
42109 cls: 'x-html-editor-tip'
42112 title: 'Font Color',
42113 text: 'Change the color of the selected text.',
42114 cls: 'x-html-editor-tip'
42117 title: 'Align Text Left',
42118 text: 'Align text to the left.',
42119 cls: 'x-html-editor-tip'
42122 title: 'Center Text',
42123 text: 'Center text in the editor.',
42124 cls: 'x-html-editor-tip'
42127 title: 'Align Text Right',
42128 text: 'Align text to the right.',
42129 cls: 'x-html-editor-tip'
42131 insertunorderedlist : {
42132 title: 'Bullet List',
42133 text: 'Start a bulleted list.',
42134 cls: 'x-html-editor-tip'
42136 insertorderedlist : {
42137 title: 'Numbered List',
42138 text: 'Start a numbered list.',
42139 cls: 'x-html-editor-tip'
42142 title: 'Hyperlink',
42143 text: 'Make the selected text a hyperlink.',
42144 cls: 'x-html-editor-tip'
42147 title: 'Source Edit',
42148 text: 'Switch to source editing mode.',
42149 cls: 'x-html-editor-tip'
42153 onDestroy : function(){
42156 this.tb.items.each(function(item){
42158 item.menu.removeAll();
42160 item.menu.el.destroy();
42168 onFirstFocus: function() {
42169 this.tb.items.each(function(item){
42178 // <script type="text/javascript">
42181 * Ext JS Library 1.1.1
42182 * Copyright(c) 2006-2007, Ext JS, LLC.
42189 * @class Roo.form.HtmlEditor.ToolbarContext
42194 new Roo.form.HtmlEditor({
42197 { xtype: 'ToolbarStandard', styles : {} }
42198 { xtype: 'ToolbarContext', disable : {} }
42204 * @config : {Object} disable List of elements to disable.. (not done yet.)
42205 * @config : {Object} styles Map of styles available.
42209 Roo.form.HtmlEditor.ToolbarContext = function(config)
42212 Roo.apply(this, config);
42213 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
42214 // dont call parent... till later.
42215 this.styles = this.styles || {};
42220 Roo.form.HtmlEditor.ToolbarContext.types = {
42232 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
42294 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
42299 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
42309 style : 'fontFamily',
42310 displayField: 'display',
42311 optname : 'font-family',
42360 // should we really allow this??
42361 // should this just be
42372 style : 'fontFamily',
42373 displayField: 'display',
42374 optname : 'font-family',
42381 style : 'fontFamily',
42382 displayField: 'display',
42383 optname : 'font-family',
42390 style : 'fontFamily',
42391 displayField: 'display',
42392 optname : 'font-family',
42403 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
42404 Roo.form.HtmlEditor.ToolbarContext.stores = false;
42406 Roo.form.HtmlEditor.ToolbarContext.options = {
42408 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
42409 [ 'Courier New', 'Courier New'],
42410 [ 'Tahoma', 'Tahoma'],
42411 [ 'Times New Roman,serif', 'Times'],
42412 [ 'Verdana','Verdana' ]
42416 // fixme - these need to be configurable..
42419 Roo.form.HtmlEditor.ToolbarContext.types
42422 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
42430 * @cfg {Object} disable List of toolbar elements to disable
42435 * @cfg {Object} styles List of styles
42436 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
42438 * These must be defined in the page, so they get rendered correctly..
42449 init : function(editor)
42451 this.editor = editor;
42454 var fid = editor.frameId;
42456 function btn(id, toggle, handler){
42457 var xid = fid + '-'+ id ;
42461 cls : 'x-btn-icon x-edit-'+id,
42462 enableToggle:toggle !== false,
42463 scope: editor, // was editor...
42464 handler:handler||editor.relayBtnCmd,
42465 clickEvent:'mousedown',
42466 tooltip: etb.buttonTips[id] || undefined, ///tips ???
42470 // create a new element.
42471 var wdiv = editor.wrap.createChild({
42473 }, editor.wrap.dom.firstChild.nextSibling, true);
42475 // can we do this more than once??
42477 // stop form submits
42480 // disable everything...
42481 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
42482 this.toolbars = {};
42484 for (var i in ty) {
42486 this.toolbars[i] = this.buildToolbar(ty[i],i);
42488 this.tb = this.toolbars.BODY;
42490 this.buildFooter();
42491 this.footer.show();
42492 editor.on('hide', function( ) { this.footer.hide() }, this);
42493 editor.on('show', function( ) { this.footer.show() }, this);
42496 this.rendered = true;
42498 // the all the btns;
42499 editor.on('editorevent', this.updateToolbar, this);
42500 // other toolbars need to implement this..
42501 //editor.on('editmodechange', this.updateToolbar, this);
42507 * Protected method that will not generally be called directly. It triggers
42508 * a toolbar update by reading the markup state of the current selection in the editor.
42510 updateToolbar: function(editor,ev,sel){
42513 // capture mouse up - this is handy for selecting images..
42514 // perhaps should go somewhere else...
42515 if(!this.editor.activated){
42516 this.editor.onFirstFocus();
42520 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
42521 // selectNode - might want to handle IE?
42523 (ev.type == 'mouseup' || ev.type == 'click' ) &&
42524 ev.target && ev.target.tagName == 'IMG') {
42525 // they have click on an image...
42526 // let's see if we can change the selection...
42529 var nodeRange = sel.ownerDocument.createRange();
42531 nodeRange.selectNode(sel);
42533 nodeRange.selectNodeContents(sel);
42535 //nodeRange.collapse(true);
42536 var s = editor.win.getSelection();
42537 s.removeAllRanges();
42538 s.addRange(nodeRange);
42542 var updateFooter = sel ? false : true;
42545 var ans = this.editor.getAllAncestors();
42548 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
42551 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editor.doc.body;
42552 sel = sel ? sel : this.editor.doc.body;
42553 sel = sel.tagName.length ? sel : this.editor.doc.body;
42556 // pick a menu that exists..
42557 var tn = sel.tagName.toUpperCase();
42558 //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
42560 tn = sel.tagName.toUpperCase();
42562 var lastSel = this.tb.selectedNode
42564 this.tb.selectedNode = sel;
42566 // if current menu does not match..
42567 if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
42570 ///console.log("show: " + tn);
42571 this.tb = typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
42574 this.tb.items.first().el.innerHTML = tn + ': ';
42577 // update attributes
42578 if (this.tb.fields) {
42579 this.tb.fields.each(function(e) {
42581 e.setValue(sel.style[e.stylename]);
42584 e.setValue(sel.getAttribute(e.attrname));
42588 var hasStyles = false;
42589 for(var i in this.styles) {
42596 var st = this.tb.fields.item(0);
42598 st.store.removeAll();
42601 var cn = sel.className.split(/\s+/);
42604 if (this.styles['*']) {
42606 Roo.each(this.styles['*'], function(v) {
42607 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
42610 if (this.styles[tn]) {
42611 Roo.each(this.styles[tn], function(v) {
42612 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
42616 st.store.loadData(avs);
42620 // flag our selected Node.
42621 this.tb.selectedNode = sel;
42624 Roo.menu.MenuMgr.hideAll();
42628 if (!updateFooter) {
42629 //this.footDisp.dom.innerHTML = '';
42632 // update the footer
42636 this.footerEls = ans.reverse();
42637 Roo.each(this.footerEls, function(a,i) {
42638 if (!a) { return; }
42639 html += html.length ? ' > ' : '';
42641 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
42646 var sz = this.footDisp.up('td').getSize();
42647 this.footDisp.dom.style.width = (sz.width -10) + 'px';
42648 this.footDisp.dom.style.marginLeft = '5px';
42650 this.footDisp.dom.style.overflow = 'hidden';
42652 this.footDisp.dom.innerHTML = html;
42654 //this.editorsyncValue();
42661 onDestroy : function(){
42664 this.tb.items.each(function(item){
42666 item.menu.removeAll();
42668 item.menu.el.destroy();
42676 onFirstFocus: function() {
42677 // need to do this for all the toolbars..
42678 this.tb.items.each(function(item){
42682 buildToolbar: function(tlist, nm)
42684 var editor = this.editor;
42685 // create a new element.
42686 var wdiv = editor.wrap.createChild({
42688 }, editor.wrap.dom.firstChild.nextSibling, true);
42691 var tb = new Roo.Toolbar(wdiv);
42694 tb.add(nm+ ": ");
42697 for(var i in this.styles) {
42702 if (styles && styles.length) {
42704 // this needs a multi-select checkbox...
42705 tb.addField( new Roo.form.ComboBox({
42706 store: new Roo.data.SimpleStore({
42708 fields: ['val', 'selected'],
42711 name : '-roo-edit-className',
42712 attrname : 'className',
42713 displayField: 'val',
42717 triggerAction: 'all',
42718 emptyText:'Select Style',
42719 selectOnFocus:true,
42722 'select': function(c, r, i) {
42723 // initial support only for on class per el..
42724 tb.selectedNode.className = r ? r.get('val') : '';
42725 editor.syncValue();
42732 var tbc = Roo.form.HtmlEditor.ToolbarContext;
42733 var tbops = tbc.options;
42735 for (var i in tlist) {
42737 var item = tlist[i];
42738 tb.add(item.title + ": ");
42741 //optname == used so you can configure the options available..
42742 var opts = item.opts ? item.opts : false;
42743 if (item.optname) {
42744 opts = tbops[item.optname];
42749 // opts == pulldown..
42750 tb.addField( new Roo.form.ComboBox({
42751 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
42753 fields: ['val', 'display'],
42756 name : '-roo-edit-' + i,
42758 stylename : item.style ? item.style : false,
42759 displayField: item.displayField ? item.displayField : 'val',
42760 valueField : 'val',
42762 mode: typeof(tbc.stores[i]) != 'undefined' ? 'remote' : 'local',
42764 triggerAction: 'all',
42765 emptyText:'Select',
42766 selectOnFocus:true,
42767 width: item.width ? item.width : 130,
42769 'select': function(c, r, i) {
42771 tb.selectedNode.style[c.stylename] = r.get('val');
42774 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
42783 tb.addField( new Roo.form.TextField({
42786 //allowBlank:false,
42791 tb.addField( new Roo.form.TextField({
42792 name: '-roo-edit-' + i,
42799 'change' : function(f, nv, ov) {
42800 tb.selectedNode.setAttribute(f.attrname, nv);
42809 text: 'Remove Tag',
42812 click : function ()
42815 // undo does not work.
42817 var sn = tb.selectedNode;
42819 var pn = sn.parentNode;
42821 var stn = sn.childNodes[0];
42822 var en = sn.childNodes[sn.childNodes.length - 1 ];
42823 while (sn.childNodes.length) {
42824 var node = sn.childNodes[0];
42825 sn.removeChild(node);
42827 pn.insertBefore(node, sn);
42830 pn.removeChild(sn);
42831 var range = editor.createRange();
42833 range.setStart(stn,0);
42834 range.setEnd(en,0); //????
42835 //range.selectNode(sel);
42838 var selection = editor.getSelection();
42839 selection.removeAllRanges();
42840 selection.addRange(range);
42844 //_this.updateToolbar(null, null, pn);
42845 _this.updateToolbar(null, null, null);
42846 _this.footDisp.dom.innerHTML = '';
42856 tb.el.on('click', function(e){
42857 e.preventDefault(); // what does this do?
42859 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
42862 // dont need to disable them... as they will get hidden
42867 buildFooter : function()
42870 var fel = this.editor.wrap.createChild();
42871 this.footer = new Roo.Toolbar(fel);
42872 // toolbar has scrolly on left / right?
42873 var footDisp= new Roo.Toolbar.Fill();
42879 handler : function() {
42880 _t.footDisp.scrollTo('left',0,true)
42884 this.footer.add( footDisp );
42889 handler : function() {
42891 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
42895 var fel = Roo.get(footDisp.el);
42896 fel.addClass('x-editor-context');
42897 this.footDispWrap = fel;
42898 this.footDispWrap.overflow = 'hidden';
42900 this.footDisp = fel.createChild();
42901 this.footDispWrap.on('click', this.onContextClick, this)
42905 onContextClick : function (ev,dom)
42907 ev.preventDefault();
42908 var cn = dom.className;
42910 if (!cn.match(/x-ed-loc-/)) {
42913 var n = cn.split('-').pop();
42914 var ans = this.footerEls;
42918 var range = this.editor.createRange();
42920 range.selectNodeContents(sel);
42921 //range.selectNode(sel);
42924 var selection = this.editor.getSelection();
42925 selection.removeAllRanges();
42926 selection.addRange(range);
42930 this.updateToolbar(null, null, sel);
42947 * Ext JS Library 1.1.1
42948 * Copyright(c) 2006-2007, Ext JS, LLC.
42950 * Originally Released Under LGPL - original licence link has changed is not relivant.
42953 * <script type="text/javascript">
42957 * @class Roo.form.BasicForm
42958 * @extends Roo.util.Observable
42959 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
42961 * @param {String/HTMLElement/Roo.Element} el The form element or its id
42962 * @param {Object} config Configuration options
42964 Roo.form.BasicForm = function(el, config){
42965 this.allItems = [];
42966 this.childForms = [];
42967 Roo.apply(this, config);
42969 * The Roo.form.Field items in this form.
42970 * @type MixedCollection
42974 this.items = new Roo.util.MixedCollection(false, function(o){
42975 return o.id || (o.id = Roo.id());
42979 * @event beforeaction
42980 * Fires before any action is performed. Return false to cancel the action.
42981 * @param {Form} this
42982 * @param {Action} action The action to be performed
42984 beforeaction: true,
42986 * @event actionfailed
42987 * Fires when an action fails.
42988 * @param {Form} this
42989 * @param {Action} action The action that failed
42991 actionfailed : true,
42993 * @event actioncomplete
42994 * Fires when an action is completed.
42995 * @param {Form} this
42996 * @param {Action} action The action that completed
42998 actioncomplete : true
43003 Roo.form.BasicForm.superclass.constructor.call(this);
43006 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
43008 * @cfg {String} method
43009 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
43012 * @cfg {DataReader} reader
43013 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
43014 * This is optional as there is built-in support for processing JSON.
43017 * @cfg {DataReader} errorReader
43018 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
43019 * This is completely optional as there is built-in support for processing JSON.
43022 * @cfg {String} url
43023 * The URL to use for form actions if one isn't supplied in the action options.
43026 * @cfg {Boolean} fileUpload
43027 * Set to true if this form is a file upload.
43031 * @cfg {Object} baseParams
43032 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
43037 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
43042 activeAction : null,
43045 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
43046 * or setValues() data instead of when the form was first created.
43048 trackResetOnLoad : false,
43052 * childForms - used for multi-tab forms
43055 childForms : false,
43058 * allItems - full list of fields.
43064 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
43065 * element by passing it or its id or mask the form itself by passing in true.
43068 waitMsgTarget : false,
43071 initEl : function(el){
43072 this.el = Roo.get(el);
43073 this.id = this.el.id || Roo.id();
43074 this.el.on('submit', this.onSubmit, this);
43075 this.el.addClass('x-form');
43079 onSubmit : function(e){
43084 * Returns true if client-side validation on the form is successful.
43087 isValid : function(){
43089 this.items.each(function(f){
43098 * Returns true if any fields in this form have changed since their original load.
43101 isDirty : function(){
43103 this.items.each(function(f){
43113 * Performs a predefined action (submit or load) or custom actions you define on this form.
43114 * @param {String} actionName The name of the action type
43115 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
43116 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
43117 * accept other config options):
43119 Property Type Description
43120 ---------------- --------------- ----------------------------------------------------------------------------------
43121 url String The url for the action (defaults to the form's url)
43122 method String The form method to use (defaults to the form's method, or POST if not defined)
43123 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
43124 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
43125 validate the form on the client (defaults to false)
43127 * @return {BasicForm} this
43129 doAction : function(action, options){
43130 if(typeof action == 'string'){
43131 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
43133 if(this.fireEvent('beforeaction', this, action) !== false){
43134 this.beforeAction(action);
43135 action.run.defer(100, action);
43141 * Shortcut to do a submit action.
43142 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
43143 * @return {BasicForm} this
43145 submit : function(options){
43146 this.doAction('submit', options);
43151 * Shortcut to do a load action.
43152 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
43153 * @return {BasicForm} this
43155 load : function(options){
43156 this.doAction('load', options);
43161 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
43162 * @param {Record} record The record to edit
43163 * @return {BasicForm} this
43165 updateRecord : function(record){
43166 record.beginEdit();
43167 var fs = record.fields;
43168 fs.each(function(f){
43169 var field = this.findField(f.name);
43171 record.set(f.name, field.getValue());
43179 * Loads an Roo.data.Record into this form.
43180 * @param {Record} record The record to load
43181 * @return {BasicForm} this
43183 loadRecord : function(record){
43184 this.setValues(record.data);
43189 beforeAction : function(action){
43190 var o = action.options;
43193 if(this.waitMsgTarget === true){
43194 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
43195 }else if(this.waitMsgTarget){
43196 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
43197 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
43199 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
43205 afterAction : function(action, success){
43206 this.activeAction = null;
43207 var o = action.options;
43209 if(this.waitMsgTarget === true){
43211 }else if(this.waitMsgTarget){
43212 this.waitMsgTarget.unmask();
43214 Roo.MessageBox.updateProgress(1);
43215 Roo.MessageBox.hide();
43222 Roo.callback(o.success, o.scope, [this, action]);
43223 this.fireEvent('actioncomplete', this, action);
43227 // failure condition..
43228 // we have a scenario where updates need confirming.
43229 // eg. if a locking scenario exists..
43230 // we look for { errors : { needs_confirm : true }} in the response.
43232 (typeof(action.result) != 'undefined') &&
43233 (typeof(action.result.errors) != 'undefined') &&
43234 (typeof(action.result.errors.needs_confirm) != 'undefined')
43237 Roo.MessageBox.confirm(
43238 "Change requires confirmation",
43239 action.result.errorMsg,
43244 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
43254 Roo.callback(o.failure, o.scope, [this, action]);
43255 // show an error message if no failed handler is set..
43256 if (!this.hasListener('actionfailed')) {
43257 Roo.MessageBox.alert("Error",
43258 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
43259 action.result.errorMsg :
43260 "Saving Failed, please check your entries or try again"
43264 this.fireEvent('actionfailed', this, action);
43270 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
43271 * @param {String} id The value to search for
43274 findField : function(id){
43275 var field = this.items.get(id);
43277 this.items.each(function(f){
43278 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
43284 return field || null;
43288 * Add a secondary form to this one,
43289 * Used to provide tabbed forms. One form is primary, with hidden values
43290 * which mirror the elements from the other forms.
43292 * @param {Roo.form.Form} form to add.
43295 addForm : function(form)
43298 if (this.childForms.indexOf(form) > -1) {
43302 this.childForms.push(form);
43304 Roo.each(form.allItems, function (fe) {
43306 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
43307 if (this.findField(n)) { // already added..
43310 var add = new Roo.form.Hidden({
43313 add.render(this.el);
43320 * Mark fields in this form invalid in bulk.
43321 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
43322 * @return {BasicForm} this
43324 markInvalid : function(errors){
43325 if(errors instanceof Array){
43326 for(var i = 0, len = errors.length; i < len; i++){
43327 var fieldError = errors[i];
43328 var f = this.findField(fieldError.id);
43330 f.markInvalid(fieldError.msg);
43336 if(typeof errors[id] != 'function' && (field = this.findField(id))){
43337 field.markInvalid(errors[id]);
43341 Roo.each(this.childForms || [], function (f) {
43342 f.markInvalid(errors);
43349 * Set values for fields in this form in bulk.
43350 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
43351 * @return {BasicForm} this
43353 setValues : function(values){
43354 if(values instanceof Array){ // array of objects
43355 for(var i = 0, len = values.length; i < len; i++){
43357 var f = this.findField(v.id);
43359 f.setValue(v.value);
43360 if(this.trackResetOnLoad){
43361 f.originalValue = f.getValue();
43365 }else{ // object hash
43368 if(typeof values[id] != 'function' && (field = this.findField(id))){
43370 if (field.setFromData &&
43371 field.valueField &&
43372 field.displayField &&
43373 // combos' with local stores can
43374 // be queried via setValue()
43375 // to set their value..
43376 (field.store && !field.store.isLocal)
43380 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
43381 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
43382 field.setFromData(sd);
43385 field.setValue(values[id]);
43389 if(this.trackResetOnLoad){
43390 field.originalValue = field.getValue();
43396 Roo.each(this.childForms || [], function (f) {
43397 f.setValues(values);
43404 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
43405 * they are returned as an array.
43406 * @param {Boolean} asString
43409 getValues : function(asString){
43410 if (this.childForms) {
43411 // copy values from the child forms
43412 Roo.each(this.childForms, function (f) {
43413 this.setValues(f.getValues());
43419 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
43420 if(asString === true){
43423 return Roo.urlDecode(fs);
43427 * Returns the fields in this form as an object with key/value pairs.
43428 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
43431 getFieldValues : function(with_hidden)
43433 if (this.childForms) {
43434 // copy values from the child forms
43435 // should this call getFieldValues - probably not as we do not currently copy
43436 // hidden fields when we generate..
43437 Roo.each(this.childForms, function (f) {
43438 this.setValues(f.getValues());
43443 this.items.each(function(f){
43444 if (!f.getName()) {
43447 var v = f.getValue();
43448 if (f.inputType =='radio') {
43449 if (typeof(ret[f.getName()]) == 'undefined') {
43450 ret[f.getName()] = ''; // empty..
43453 if (!f.el.dom.checked) {
43457 v = f.el.dom.value;
43461 // not sure if this supported any more..
43462 if ((typeof(v) == 'object') && f.getRawValue) {
43463 v = f.getRawValue() ; // dates..
43465 // combo boxes where name != hiddenName...
43466 if (f.name != f.getName()) {
43467 ret[f.name] = f.getRawValue();
43469 ret[f.getName()] = v;
43476 * Clears all invalid messages in this form.
43477 * @return {BasicForm} this
43479 clearInvalid : function(){
43480 this.items.each(function(f){
43484 Roo.each(this.childForms || [], function (f) {
43493 * Resets this form.
43494 * @return {BasicForm} this
43496 reset : function(){
43497 this.items.each(function(f){
43501 Roo.each(this.childForms || [], function (f) {
43510 * Add Roo.form components to this form.
43511 * @param {Field} field1
43512 * @param {Field} field2 (optional)
43513 * @param {Field} etc (optional)
43514 * @return {BasicForm} this
43517 this.items.addAll(Array.prototype.slice.call(arguments, 0));
43523 * Removes a field from the items collection (does NOT remove its markup).
43524 * @param {Field} field
43525 * @return {BasicForm} this
43527 remove : function(field){
43528 this.items.remove(field);
43533 * Looks at the fields in this form, checks them for an id attribute,
43534 * and calls applyTo on the existing dom element with that id.
43535 * @return {BasicForm} this
43537 render : function(){
43538 this.items.each(function(f){
43539 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
43547 * Calls {@link Ext#apply} for all fields in this form with the passed object.
43548 * @param {Object} values
43549 * @return {BasicForm} this
43551 applyToFields : function(o){
43552 this.items.each(function(f){
43559 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
43560 * @param {Object} values
43561 * @return {BasicForm} this
43563 applyIfToFields : function(o){
43564 this.items.each(function(f){
43572 Roo.BasicForm = Roo.form.BasicForm;/*
43574 * Ext JS Library 1.1.1
43575 * Copyright(c) 2006-2007, Ext JS, LLC.
43577 * Originally Released Under LGPL - original licence link has changed is not relivant.
43580 * <script type="text/javascript">
43584 * @class Roo.form.Form
43585 * @extends Roo.form.BasicForm
43586 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
43588 * @param {Object} config Configuration options
43590 Roo.form.Form = function(config){
43592 if (config.items) {
43593 xitems = config.items;
43594 delete config.items;
43598 Roo.form.Form.superclass.constructor.call(this, null, config);
43599 this.url = this.url || this.action;
43601 this.root = new Roo.form.Layout(Roo.applyIf({
43605 this.active = this.root;
43607 * Array of all the buttons that have been added to this form via {@link addButton}
43611 this.allItems = [];
43614 * @event clientvalidation
43615 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
43616 * @param {Form} this
43617 * @param {Boolean} valid true if the form has passed client-side validation
43619 clientvalidation: true,
43622 * Fires when the form is rendered
43623 * @param {Roo.form.Form} form
43628 if (this.progressUrl) {
43629 // push a hidden field onto the list of fields..
43633 name : 'UPLOAD_IDENTIFIER'
43638 Roo.each(xitems, this.addxtype, this);
43644 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
43646 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
43649 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
43652 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
43654 buttonAlign:'center',
43657 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
43662 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
43663 * This property cascades to child containers if not set.
43668 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
43669 * fires a looping event with that state. This is required to bind buttons to the valid
43670 * state using the config value formBind:true on the button.
43672 monitorValid : false,
43675 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
43680 * @cfg {String} progressUrl - Url to return progress data
43683 progressUrl : false,
43686 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
43687 * fields are added and the column is closed. If no fields are passed the column remains open
43688 * until end() is called.
43689 * @param {Object} config The config to pass to the column
43690 * @param {Field} field1 (optional)
43691 * @param {Field} field2 (optional)
43692 * @param {Field} etc (optional)
43693 * @return Column The column container object
43695 column : function(c){
43696 var col = new Roo.form.Column(c);
43698 if(arguments.length > 1){ // duplicate code required because of Opera
43699 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
43706 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
43707 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
43708 * until end() is called.
43709 * @param {Object} config The config to pass to the fieldset
43710 * @param {Field} field1 (optional)
43711 * @param {Field} field2 (optional)
43712 * @param {Field} etc (optional)
43713 * @return FieldSet The fieldset container object
43715 fieldset : function(c){
43716 var fs = new Roo.form.FieldSet(c);
43718 if(arguments.length > 1){ // duplicate code required because of Opera
43719 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
43726 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
43727 * fields are added and the container is closed. If no fields are passed the container remains open
43728 * until end() is called.
43729 * @param {Object} config The config to pass to the Layout
43730 * @param {Field} field1 (optional)
43731 * @param {Field} field2 (optional)
43732 * @param {Field} etc (optional)
43733 * @return Layout The container object
43735 container : function(c){
43736 var l = new Roo.form.Layout(c);
43738 if(arguments.length > 1){ // duplicate code required because of Opera
43739 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
43746 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
43747 * @param {Object} container A Roo.form.Layout or subclass of Layout
43748 * @return {Form} this
43750 start : function(c){
43751 // cascade label info
43752 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
43753 this.active.stack.push(c);
43754 c.ownerCt = this.active;
43760 * Closes the current open container
43761 * @return {Form} this
43764 if(this.active == this.root){
43767 this.active = this.active.ownerCt;
43772 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
43773 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
43774 * as the label of the field.
43775 * @param {Field} field1
43776 * @param {Field} field2 (optional)
43777 * @param {Field} etc. (optional)
43778 * @return {Form} this
43781 this.active.stack.push.apply(this.active.stack, arguments);
43782 this.allItems.push.apply(this.allItems,arguments);
43784 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
43785 if(a[i].isFormField){
43790 Roo.form.Form.superclass.add.apply(this, r);
43800 * Find any element that has been added to a form, using it's ID or name
43801 * This can include framesets, columns etc. along with regular fields..
43802 * @param {String} id - id or name to find.
43804 * @return {Element} e - or false if nothing found.
43806 findbyId : function(id)
43812 Roo.each(this.allItems, function(f){
43813 if (f.id == id || f.name == id ){
43824 * Render this form into the passed container. This should only be called once!
43825 * @param {String/HTMLElement/Element} container The element this component should be rendered into
43826 * @return {Form} this
43828 render : function(ct)
43834 var o = this.autoCreate || {
43836 method : this.method || 'POST',
43837 id : this.id || Roo.id()
43839 this.initEl(ct.createChild(o));
43841 this.root.render(this.el);
43845 this.items.each(function(f){
43846 f.render('x-form-el-'+f.id);
43849 if(this.buttons.length > 0){
43850 // tables are required to maintain order and for correct IE layout
43851 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
43852 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
43853 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
43855 var tr = tb.getElementsByTagName('tr')[0];
43856 for(var i = 0, len = this.buttons.length; i < len; i++) {
43857 var b = this.buttons[i];
43858 var td = document.createElement('td');
43859 td.className = 'x-form-btn-td';
43860 b.render(tr.appendChild(td));
43863 if(this.monitorValid){ // initialize after render
43864 this.startMonitoring();
43866 this.fireEvent('rendered', this);
43871 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
43872 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
43873 * object or a valid Roo.DomHelper element config
43874 * @param {Function} handler The function called when the button is clicked
43875 * @param {Object} scope (optional) The scope of the handler function
43876 * @return {Roo.Button}
43878 addButton : function(config, handler, scope){
43882 minWidth: this.minButtonWidth,
43885 if(typeof config == "string"){
43888 Roo.apply(bc, config);
43890 var btn = new Roo.Button(null, bc);
43891 this.buttons.push(btn);
43896 * Adds a series of form elements (using the xtype property as the factory method.
43897 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
43898 * @param {Object} config
43901 addxtype : function()
43903 var ar = Array.prototype.slice.call(arguments, 0);
43905 for(var i = 0; i < ar.length; i++) {
43907 continue; // skip -- if this happends something invalid got sent, we
43908 // should ignore it, as basically that interface element will not show up
43909 // and that should be pretty obvious!!
43912 if (Roo.form[ar[i].xtype]) {
43914 var fe = Roo.factory(ar[i], Roo.form);
43920 fe.store.form = this;
43925 this.allItems.push(fe);
43926 if (fe.items && fe.addxtype) {
43927 fe.addxtype.apply(fe, fe.items);
43937 // console.log('adding ' + ar[i].xtype);
43939 if (ar[i].xtype == 'Button') {
43940 //console.log('adding button');
43941 //console.log(ar[i]);
43942 this.addButton(ar[i]);
43943 this.allItems.push(fe);
43947 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
43948 alert('end is not supported on xtype any more, use items');
43950 // //console.log('adding end');
43958 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
43959 * option "monitorValid"
43961 startMonitoring : function(){
43964 Roo.TaskMgr.start({
43965 run : this.bindHandler,
43966 interval : this.monitorPoll || 200,
43973 * Stops monitoring of the valid state of this form
43975 stopMonitoring : function(){
43976 this.bound = false;
43980 bindHandler : function(){
43982 return false; // stops binding
43985 this.items.each(function(f){
43986 if(!f.isValid(true)){
43991 for(var i = 0, len = this.buttons.length; i < len; i++){
43992 var btn = this.buttons[i];
43993 if(btn.formBind === true && btn.disabled === valid){
43994 btn.setDisabled(!valid);
43997 this.fireEvent('clientvalidation', this, valid);
44011 Roo.Form = Roo.form.Form;
44014 * Ext JS Library 1.1.1
44015 * Copyright(c) 2006-2007, Ext JS, LLC.
44017 * Originally Released Under LGPL - original licence link has changed is not relivant.
44020 * <script type="text/javascript">
44024 * @class Roo.form.Action
44025 * Internal Class used to handle form actions
44027 * @param {Roo.form.BasicForm} el The form element or its id
44028 * @param {Object} config Configuration options
44032 // define the action interface
44033 Roo.form.Action = function(form, options){
44035 this.options = options || {};
44038 * Client Validation Failed
44041 Roo.form.Action.CLIENT_INVALID = 'client';
44043 * Server Validation Failed
44046 Roo.form.Action.SERVER_INVALID = 'server';
44048 * Connect to Server Failed
44051 Roo.form.Action.CONNECT_FAILURE = 'connect';
44053 * Reading Data from Server Failed
44056 Roo.form.Action.LOAD_FAILURE = 'load';
44058 Roo.form.Action.prototype = {
44060 failureType : undefined,
44061 response : undefined,
44062 result : undefined,
44064 // interface method
44065 run : function(options){
44069 // interface method
44070 success : function(response){
44074 // interface method
44075 handleResponse : function(response){
44079 // default connection failure
44080 failure : function(response){
44082 this.response = response;
44083 this.failureType = Roo.form.Action.CONNECT_FAILURE;
44084 this.form.afterAction(this, false);
44087 processResponse : function(response){
44088 this.response = response;
44089 if(!response.responseText){
44092 this.result = this.handleResponse(response);
44093 return this.result;
44096 // utility functions used internally
44097 getUrl : function(appendParams){
44098 var url = this.options.url || this.form.url || this.form.el.dom.action;
44100 var p = this.getParams();
44102 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
44108 getMethod : function(){
44109 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
44112 getParams : function(){
44113 var bp = this.form.baseParams;
44114 var p = this.options.params;
44116 if(typeof p == "object"){
44117 p = Roo.urlEncode(Roo.applyIf(p, bp));
44118 }else if(typeof p == 'string' && bp){
44119 p += '&' + Roo.urlEncode(bp);
44122 p = Roo.urlEncode(bp);
44127 createCallback : function(){
44129 success: this.success,
44130 failure: this.failure,
44132 timeout: (this.form.timeout*1000),
44133 upload: this.form.fileUpload ? this.success : undefined
44138 Roo.form.Action.Submit = function(form, options){
44139 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
44142 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
44145 haveProgress : false,
44146 uploadComplete : false,
44148 // uploadProgress indicator.
44149 uploadProgress : function()
44151 if (!this.form.progressUrl) {
44155 if (!this.haveProgress) {
44156 Roo.MessageBox.progress("Uploading", "Uploading");
44158 if (this.uploadComplete) {
44159 Roo.MessageBox.hide();
44163 this.haveProgress = true;
44165 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
44167 var c = new Roo.data.Connection();
44169 url : this.form.progressUrl,
44174 success : function(req){
44175 //console.log(data);
44179 rdata = Roo.decode(req.responseText)
44181 Roo.log("Invalid data from server..");
44185 if (!rdata || !rdata.success) {
44187 Roo.MessageBox.alert(Roo.encode(rdata));
44190 var data = rdata.data;
44192 if (this.uploadComplete) {
44193 Roo.MessageBox.hide();
44198 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
44199 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
44202 this.uploadProgress.defer(2000,this);
44205 failure: function(data) {
44206 Roo.log('progress url failed ');
44217 // run get Values on the form, so it syncs any secondary forms.
44218 this.form.getValues();
44220 var o = this.options;
44221 var method = this.getMethod();
44222 var isPost = method == 'POST';
44223 if(o.clientValidation === false || this.form.isValid()){
44225 if (this.form.progressUrl) {
44226 this.form.findField('UPLOAD_IDENTIFIER').setValue(
44227 (new Date() * 1) + '' + Math.random());
44232 Roo.Ajax.request(Roo.apply(this.createCallback(), {
44233 form:this.form.el.dom,
44234 url:this.getUrl(!isPost),
44236 params:isPost ? this.getParams() : null,
44237 isUpload: this.form.fileUpload
44240 this.uploadProgress();
44242 }else if (o.clientValidation !== false){ // client validation failed
44243 this.failureType = Roo.form.Action.CLIENT_INVALID;
44244 this.form.afterAction(this, false);
44248 success : function(response)
44250 this.uploadComplete= true;
44251 if (this.haveProgress) {
44252 Roo.MessageBox.hide();
44256 var result = this.processResponse(response);
44257 if(result === true || result.success){
44258 this.form.afterAction(this, true);
44262 this.form.markInvalid(result.errors);
44263 this.failureType = Roo.form.Action.SERVER_INVALID;
44265 this.form.afterAction(this, false);
44267 failure : function(response)
44269 this.uploadComplete= true;
44270 if (this.haveProgress) {
44271 Roo.MessageBox.hide();
44274 this.response = response;
44275 this.failureType = Roo.form.Action.CONNECT_FAILURE;
44276 this.form.afterAction(this, false);
44279 handleResponse : function(response){
44280 if(this.form.errorReader){
44281 var rs = this.form.errorReader.read(response);
44284 for(var i = 0, len = rs.records.length; i < len; i++) {
44285 var r = rs.records[i];
44286 errors[i] = r.data;
44289 if(errors.length < 1){
44293 success : rs.success,
44299 ret = Roo.decode(response.responseText);
44303 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
44313 Roo.form.Action.Load = function(form, options){
44314 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
44315 this.reader = this.form.reader;
44318 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
44323 Roo.Ajax.request(Roo.apply(
44324 this.createCallback(), {
44325 method:this.getMethod(),
44326 url:this.getUrl(false),
44327 params:this.getParams()
44331 success : function(response){
44333 var result = this.processResponse(response);
44334 if(result === true || !result.success || !result.data){
44335 this.failureType = Roo.form.Action.LOAD_FAILURE;
44336 this.form.afterAction(this, false);
44339 this.form.clearInvalid();
44340 this.form.setValues(result.data);
44341 this.form.afterAction(this, true);
44344 handleResponse : function(response){
44345 if(this.form.reader){
44346 var rs = this.form.reader.read(response);
44347 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
44349 success : rs.success,
44353 return Roo.decode(response.responseText);
44357 Roo.form.Action.ACTION_TYPES = {
44358 'load' : Roo.form.Action.Load,
44359 'submit' : Roo.form.Action.Submit
44362 * Ext JS Library 1.1.1
44363 * Copyright(c) 2006-2007, Ext JS, LLC.
44365 * Originally Released Under LGPL - original licence link has changed is not relivant.
44368 * <script type="text/javascript">
44372 * @class Roo.form.Layout
44373 * @extends Roo.Component
44374 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
44376 * @param {Object} config Configuration options
44378 Roo.form.Layout = function(config){
44380 if (config.items) {
44381 xitems = config.items;
44382 delete config.items;
44384 Roo.form.Layout.superclass.constructor.call(this, config);
44386 Roo.each(xitems, this.addxtype, this);
44390 Roo.extend(Roo.form.Layout, Roo.Component, {
44392 * @cfg {String/Object} autoCreate
44393 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
44396 * @cfg {String/Object/Function} style
44397 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
44398 * a function which returns such a specification.
44401 * @cfg {String} labelAlign
44402 * Valid values are "left," "top" and "right" (defaults to "left")
44405 * @cfg {Number} labelWidth
44406 * Fixed width in pixels of all field labels (defaults to undefined)
44409 * @cfg {Boolean} clear
44410 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
44414 * @cfg {String} labelSeparator
44415 * The separator to use after field labels (defaults to ':')
44417 labelSeparator : ':',
44419 * @cfg {Boolean} hideLabels
44420 * True to suppress the display of field labels in this layout (defaults to false)
44422 hideLabels : false,
44425 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
44430 onRender : function(ct, position){
44431 if(this.el){ // from markup
44432 this.el = Roo.get(this.el);
44433 }else { // generate
44434 var cfg = this.getAutoCreate();
44435 this.el = ct.createChild(cfg, position);
44438 this.el.applyStyles(this.style);
44440 if(this.labelAlign){
44441 this.el.addClass('x-form-label-'+this.labelAlign);
44443 if(this.hideLabels){
44444 this.labelStyle = "display:none";
44445 this.elementStyle = "padding-left:0;";
44447 if(typeof this.labelWidth == 'number'){
44448 this.labelStyle = "width:"+this.labelWidth+"px;";
44449 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
44451 if(this.labelAlign == 'top'){
44452 this.labelStyle = "width:auto;";
44453 this.elementStyle = "padding-left:0;";
44456 var stack = this.stack;
44457 var slen = stack.length;
44459 if(!this.fieldTpl){
44460 var t = new Roo.Template(
44461 '<div class="x-form-item {5}">',
44462 '<label for="{0}" style="{2}">{1}{4}</label>',
44463 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
44465 '</div><div class="x-form-clear-left"></div>'
44467 t.disableFormats = true;
44469 Roo.form.Layout.prototype.fieldTpl = t;
44471 for(var i = 0; i < slen; i++) {
44472 if(stack[i].isFormField){
44473 this.renderField(stack[i]);
44475 this.renderComponent(stack[i]);
44480 this.el.createChild({cls:'x-form-clear'});
44485 renderField : function(f){
44486 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
44489 f.labelStyle||this.labelStyle||'', //2
44490 this.elementStyle||'', //3
44491 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
44492 f.itemCls||this.itemCls||'' //5
44493 ], true).getPrevSibling());
44497 renderComponent : function(c){
44498 c.render(c.isLayout ? this.el : this.el.createChild());
44501 * Adds a object form elements (using the xtype property as the factory method.)
44502 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
44503 * @param {Object} config
44505 addxtype : function(o)
44507 // create the lement.
44508 o.form = this.form;
44509 var fe = Roo.factory(o, Roo.form);
44510 this.form.allItems.push(fe);
44511 this.stack.push(fe);
44513 if (fe.isFormField) {
44514 this.form.items.add(fe);
44522 * @class Roo.form.Column
44523 * @extends Roo.form.Layout
44524 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
44526 * @param {Object} config Configuration options
44528 Roo.form.Column = function(config){
44529 Roo.form.Column.superclass.constructor.call(this, config);
44532 Roo.extend(Roo.form.Column, Roo.form.Layout, {
44534 * @cfg {Number/String} width
44535 * The fixed width of the column in pixels or CSS value (defaults to "auto")
44538 * @cfg {String/Object} autoCreate
44539 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
44543 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
44546 onRender : function(ct, position){
44547 Roo.form.Column.superclass.onRender.call(this, ct, position);
44549 this.el.setWidth(this.width);
44556 * @class Roo.form.Row
44557 * @extends Roo.form.Layout
44558 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
44560 * @param {Object} config Configuration options
44564 Roo.form.Row = function(config){
44565 Roo.form.Row.superclass.constructor.call(this, config);
44568 Roo.extend(Roo.form.Row, Roo.form.Layout, {
44570 * @cfg {Number/String} width
44571 * The fixed width of the column in pixels or CSS value (defaults to "auto")
44574 * @cfg {Number/String} height
44575 * The fixed height of the column in pixels or CSS value (defaults to "auto")
44577 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
44581 onRender : function(ct, position){
44582 //console.log('row render');
44584 var t = new Roo.Template(
44585 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
44586 '<label for="{0}" style="{2}">{1}{4}</label>',
44587 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
44591 t.disableFormats = true;
44593 Roo.form.Layout.prototype.rowTpl = t;
44595 this.fieldTpl = this.rowTpl;
44597 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
44598 var labelWidth = 100;
44600 if ((this.labelAlign != 'top')) {
44601 if (typeof this.labelWidth == 'number') {
44602 labelWidth = this.labelWidth
44604 this.padWidth = 20 + labelWidth;
44608 Roo.form.Column.superclass.onRender.call(this, ct, position);
44610 this.el.setWidth(this.width);
44613 this.el.setHeight(this.height);
44618 renderField : function(f){
44619 f.fieldEl = this.fieldTpl.append(this.el, [
44620 f.id, f.fieldLabel,
44621 f.labelStyle||this.labelStyle||'',
44622 this.elementStyle||'',
44623 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
44624 f.itemCls||this.itemCls||'',
44625 f.width ? f.width + this.padWidth : 160 + this.padWidth
44632 * @class Roo.form.FieldSet
44633 * @extends Roo.form.Layout
44634 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
44636 * @param {Object} config Configuration options
44638 Roo.form.FieldSet = function(config){
44639 Roo.form.FieldSet.superclass.constructor.call(this, config);
44642 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
44644 * @cfg {String} legend
44645 * The text to display as the legend for the FieldSet (defaults to '')
44648 * @cfg {String/Object} autoCreate
44649 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
44653 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
44656 onRender : function(ct, position){
44657 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
44659 this.setLegend(this.legend);
44664 setLegend : function(text){
44666 this.el.child('legend').update(text);
44671 * Ext JS Library 1.1.1
44672 * Copyright(c) 2006-2007, Ext JS, LLC.
44674 * Originally Released Under LGPL - original licence link has changed is not relivant.
44677 * <script type="text/javascript">
44680 * @class Roo.form.VTypes
44681 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
44684 Roo.form.VTypes = function(){
44685 // closure these in so they are only created once.
44686 var alpha = /^[a-zA-Z_]+$/;
44687 var alphanum = /^[a-zA-Z0-9_]+$/;
44688 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
44689 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
44691 // All these messages and functions are configurable
44694 * The function used to validate email addresses
44695 * @param {String} value The email address
44697 'email' : function(v){
44698 return email.test(v);
44701 * The error text to display when the email validation function returns false
44704 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
44706 * The keystroke filter mask to be applied on email input
44709 'emailMask' : /[a-z0-9_\.\-@]/i,
44712 * The function used to validate URLs
44713 * @param {String} value The URL
44715 'url' : function(v){
44716 return url.test(v);
44719 * The error text to display when the url validation function returns false
44722 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
44725 * The function used to validate alpha values
44726 * @param {String} value The value
44728 'alpha' : function(v){
44729 return alpha.test(v);
44732 * The error text to display when the alpha validation function returns false
44735 'alphaText' : 'This field should only contain letters and _',
44737 * The keystroke filter mask to be applied on alpha input
44740 'alphaMask' : /[a-z_]/i,
44743 * The function used to validate alphanumeric values
44744 * @param {String} value The value
44746 'alphanum' : function(v){
44747 return alphanum.test(v);
44750 * The error text to display when the alphanumeric validation function returns false
44753 'alphanumText' : 'This field should only contain letters, numbers and _',
44755 * The keystroke filter mask to be applied on alphanumeric input
44758 'alphanumMask' : /[a-z0-9_]/i
44760 }();//<script type="text/javascript">
44763 * @class Roo.form.FCKeditor
44764 * @extends Roo.form.TextArea
44765 * Wrapper around the FCKEditor http://www.fckeditor.net
44767 * Creates a new FCKeditor
44768 * @param {Object} config Configuration options
44770 Roo.form.FCKeditor = function(config){
44771 Roo.form.FCKeditor.superclass.constructor.call(this, config);
44774 * @event editorinit
44775 * Fired when the editor is initialized - you can add extra handlers here..
44776 * @param {FCKeditor} this
44777 * @param {Object} the FCK object.
44784 Roo.form.FCKeditor.editors = { };
44785 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
44787 //defaultAutoCreate : {
44788 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
44792 * @cfg {Object} fck options - see fck manual for details.
44797 * @cfg {Object} fck toolbar set (Basic or Default)
44799 toolbarSet : 'Basic',
44801 * @cfg {Object} fck BasePath
44803 basePath : '/fckeditor/',
44811 onRender : function(ct, position)
44814 this.defaultAutoCreate = {
44816 style:"width:300px;height:60px;",
44817 autocomplete: "off"
44820 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
44823 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
44824 if(this.preventScrollbars){
44825 this.el.setStyle("overflow", "hidden");
44827 this.el.setHeight(this.growMin);
44830 //console.log('onrender' + this.getId() );
44831 Roo.form.FCKeditor.editors[this.getId()] = this;
44834 this.replaceTextarea() ;
44838 getEditor : function() {
44839 return this.fckEditor;
44842 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
44843 * @param {Mixed} value The value to set
44847 setValue : function(value)
44849 //console.log('setValue: ' + value);
44851 if(typeof(value) == 'undefined') { // not sure why this is happending...
44854 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
44856 //if(!this.el || !this.getEditor()) {
44857 // this.value = value;
44858 //this.setValue.defer(100,this,[value]);
44862 if(!this.getEditor()) {
44866 this.getEditor().SetData(value);
44873 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
44874 * @return {Mixed} value The field value
44876 getValue : function()
44879 if (this.frame && this.frame.dom.style.display == 'none') {
44880 return Roo.form.FCKeditor.superclass.getValue.call(this);
44883 if(!this.el || !this.getEditor()) {
44885 // this.getValue.defer(100,this);
44890 var value=this.getEditor().GetData();
44891 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
44892 return Roo.form.FCKeditor.superclass.getValue.call(this);
44898 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
44899 * @return {Mixed} value The field value
44901 getRawValue : function()
44903 if (this.frame && this.frame.dom.style.display == 'none') {
44904 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
44907 if(!this.el || !this.getEditor()) {
44908 //this.getRawValue.defer(100,this);
44915 var value=this.getEditor().GetData();
44916 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
44917 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
44921 setSize : function(w,h) {
44925 //if (this.frame && this.frame.dom.style.display == 'none') {
44926 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
44929 //if(!this.el || !this.getEditor()) {
44930 // this.setSize.defer(100,this, [w,h]);
44936 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
44938 this.frame.dom.setAttribute('width', w);
44939 this.frame.dom.setAttribute('height', h);
44940 this.frame.setSize(w,h);
44944 toggleSourceEdit : function(value) {
44948 this.el.dom.style.display = value ? '' : 'none';
44949 this.frame.dom.style.display = value ? 'none' : '';
44954 focus: function(tag)
44956 if (this.frame.dom.style.display == 'none') {
44957 return Roo.form.FCKeditor.superclass.focus.call(this);
44959 if(!this.el || !this.getEditor()) {
44960 this.focus.defer(100,this, [tag]);
44967 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
44968 this.getEditor().Focus();
44970 if (!this.getEditor().Selection.GetSelection()) {
44971 this.focus.defer(100,this, [tag]);
44976 var r = this.getEditor().EditorDocument.createRange();
44977 r.setStart(tgs[0],0);
44978 r.setEnd(tgs[0],0);
44979 this.getEditor().Selection.GetSelection().removeAllRanges();
44980 this.getEditor().Selection.GetSelection().addRange(r);
44981 this.getEditor().Focus();
44988 replaceTextarea : function()
44990 if ( document.getElementById( this.getId() + '___Frame' ) )
44992 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
44994 // We must check the elements firstly using the Id and then the name.
44995 var oTextarea = document.getElementById( this.getId() );
44997 var colElementsByName = document.getElementsByName( this.getId() ) ;
44999 oTextarea.style.display = 'none' ;
45001 if ( oTextarea.tabIndex ) {
45002 this.TabIndex = oTextarea.tabIndex ;
45005 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
45006 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
45007 this.frame = Roo.get(this.getId() + '___Frame')
45010 _getConfigHtml : function()
45014 for ( var o in this.fckconfig ) {
45015 sConfig += sConfig.length > 0 ? '&' : '';
45016 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
45019 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
45023 _getIFrameHtml : function()
45025 var sFile = 'fckeditor.html' ;
45026 /* no idea what this is about..
45029 if ( (/fcksource=true/i).test( window.top.location.search ) )
45030 sFile = 'fckeditor.original.html' ;
45035 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
45036 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
45039 var html = '<iframe id="' + this.getId() +
45040 '___Frame" src="' + sLink +
45041 '" width="' + this.width +
45042 '" height="' + this.height + '"' +
45043 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
45044 ' frameborder="0" scrolling="no"></iframe>' ;
45049 _insertHtmlBefore : function( html, element )
45051 if ( element.insertAdjacentHTML ) {
45053 element.insertAdjacentHTML( 'beforeBegin', html ) ;
45055 var oRange = document.createRange() ;
45056 oRange.setStartBefore( element ) ;
45057 var oFragment = oRange.createContextualFragment( html );
45058 element.parentNode.insertBefore( oFragment, element ) ;
45071 //Roo.reg('fckeditor', Roo.form.FCKeditor);
45073 function FCKeditor_OnComplete(editorInstance){
45074 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
45075 f.fckEditor = editorInstance;
45076 //console.log("loaded");
45077 f.fireEvent('editorinit', f, editorInstance);
45097 //<script type="text/javascript">
45099 * @class Roo.form.GridField
45100 * @extends Roo.form.Field
45101 * Embed a grid (or editable grid into a form)
45104 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
45106 * xgrid.store = Roo.data.Store
45107 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
45108 * xgrid.store.reader = Roo.data.JsonReader
45112 * Creates a new GridField
45113 * @param {Object} config Configuration options
45115 Roo.form.GridField = function(config){
45116 Roo.form.GridField.superclass.constructor.call(this, config);
45120 Roo.extend(Roo.form.GridField, Roo.form.Field, {
45122 * @cfg {Number} width - used to restrict width of grid..
45126 * @cfg {Number} height - used to restrict height of grid..
45130 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
45136 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
45137 * {tag: "input", type: "checkbox", autocomplete: "off"})
45139 // defaultAutoCreate : { tag: 'div' },
45140 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
45142 * @cfg {String} addTitle Text to include for adding a title.
45146 onResize : function(){
45147 Roo.form.Field.superclass.onResize.apply(this, arguments);
45150 initEvents : function(){
45151 // Roo.form.Checkbox.superclass.initEvents.call(this);
45152 // has no events...
45157 getResizeEl : function(){
45161 getPositionEl : function(){
45166 onRender : function(ct, position){
45168 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
45169 var style = this.style;
45172 Roo.form.GridField.superclass.onRender.call(this, ct, position);
45173 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
45174 this.viewEl = this.wrap.createChild({ tag: 'div' });
45176 this.viewEl.applyStyles(style);
45179 this.viewEl.setWidth(this.width);
45182 this.viewEl.setHeight(this.height);
45184 //if(this.inputValue !== undefined){
45185 //this.setValue(this.value);
45188 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
45191 this.grid.render();
45192 this.grid.getDataSource().on('remove', this.refreshValue, this);
45193 this.grid.getDataSource().on('update', this.refreshValue, this);
45194 this.grid.on('afteredit', this.refreshValue, this);
45200 * Sets the value of the item.
45201 * @param {String} either an object or a string..
45203 setValue : function(v){
45205 v = v || []; // empty set..
45206 // this does not seem smart - it really only affects memoryproxy grids..
45207 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
45208 var ds = this.grid.getDataSource();
45209 // assumes a json reader..
45211 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
45212 ds.loadData( data);
45214 // clear selection so it does not get stale.
45215 if (this.grid.sm) {
45216 this.grid.sm.clearSelections();
45219 Roo.form.GridField.superclass.setValue.call(this, v);
45220 this.refreshValue();
45221 // should load data in the grid really....
45225 refreshValue: function() {
45227 this.grid.getDataSource().each(function(r) {
45230 this.el.dom.value = Roo.encode(val);
45238 * Ext JS Library 1.1.1
45239 * Copyright(c) 2006-2007, Ext JS, LLC.
45241 * Originally Released Under LGPL - original licence link has changed is not relivant.
45244 * <script type="text/javascript">
45247 * @class Roo.form.DisplayField
45248 * @extends Roo.form.Field
45249 * A generic Field to display non-editable data.
45251 * Creates a new Display Field item.
45252 * @param {Object} config Configuration options
45254 Roo.form.DisplayField = function(config){
45255 Roo.form.DisplayField.superclass.constructor.call(this, config);
45259 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
45260 inputType: 'hidden',
45266 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
45268 focusClass : undefined,
45270 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
45272 fieldClass: 'x-form-field',
45275 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
45277 valueRenderer: undefined,
45281 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
45282 * {tag: "input", type: "checkbox", autocomplete: "off"})
45285 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
45287 onResize : function(){
45288 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
45292 initEvents : function(){
45293 // Roo.form.Checkbox.superclass.initEvents.call(this);
45294 // has no events...
45299 getResizeEl : function(){
45303 getPositionEl : function(){
45308 onRender : function(ct, position){
45310 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
45311 //if(this.inputValue !== undefined){
45312 this.wrap = this.el.wrap();
45314 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
45316 if (this.bodyStyle) {
45317 this.viewEl.applyStyles(this.bodyStyle);
45319 //this.viewEl.setStyle('padding', '2px');
45321 this.setValue(this.value);
45326 initValue : Roo.emptyFn,
45331 onClick : function(){
45336 * Sets the checked state of the checkbox.
45337 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
45339 setValue : function(v){
45341 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
45342 // this might be called before we have a dom element..
45343 if (!this.viewEl) {
45346 this.viewEl.dom.innerHTML = html;
45347 Roo.form.DisplayField.superclass.setValue.call(this, v);
45357 * @class Roo.form.DayPicker
45358 * @extends Roo.form.Field
45359 * A Day picker show [M] [T] [W] ....
45361 * Creates a new Day Picker
45362 * @param {Object} config Configuration options
45364 Roo.form.DayPicker= function(config){
45365 Roo.form.DayPicker.superclass.constructor.call(this, config);
45369 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
45371 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
45373 focusClass : undefined,
45375 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
45377 fieldClass: "x-form-field",
45380 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
45381 * {tag: "input", type: "checkbox", autocomplete: "off"})
45383 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
45386 actionMode : 'viewEl',
45390 inputType : 'hidden',
45393 inputElement: false, // real input element?
45394 basedOn: false, // ????
45396 isFormField: true, // not sure where this is needed!!!!
45398 onResize : function(){
45399 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
45400 if(!this.boxLabel){
45401 this.el.alignTo(this.wrap, 'c-c');
45405 initEvents : function(){
45406 Roo.form.Checkbox.superclass.initEvents.call(this);
45407 this.el.on("click", this.onClick, this);
45408 this.el.on("change", this.onClick, this);
45412 getResizeEl : function(){
45416 getPositionEl : function(){
45422 onRender : function(ct, position){
45423 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
45425 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
45427 var r1 = '<table><tr>';
45428 var r2 = '<tr class="x-form-daypick-icons">';
45429 for (var i=0; i < 7; i++) {
45430 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
45431 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
45434 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
45435 viewEl.select('img').on('click', this.onClick, this);
45436 this.viewEl = viewEl;
45439 // this will not work on Chrome!!!
45440 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
45441 this.el.on('propertychange', this.setFromHidden, this); //ie
45449 initValue : Roo.emptyFn,
45452 * Returns the checked state of the checkbox.
45453 * @return {Boolean} True if checked, else false
45455 getValue : function(){
45456 return this.el.dom.value;
45461 onClick : function(e){
45462 //this.setChecked(!this.checked);
45463 Roo.get(e.target).toggleClass('x-menu-item-checked');
45464 this.refreshValue();
45465 //if(this.el.dom.checked != this.checked){
45466 // this.setValue(this.el.dom.checked);
45471 refreshValue : function()
45474 this.viewEl.select('img',true).each(function(e,i,n) {
45475 val += e.is(".x-menu-item-checked") ? String(n) : '';
45477 this.setValue(val, true);
45481 * Sets the checked state of the checkbox.
45482 * On is always based on a string comparison between inputValue and the param.
45483 * @param {Boolean/String} value - the value to set
45484 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
45486 setValue : function(v,suppressEvent){
45487 if (!this.el.dom) {
45490 var old = this.el.dom.value ;
45491 this.el.dom.value = v;
45492 if (suppressEvent) {
45496 // update display..
45497 this.viewEl.select('img',true).each(function(e,i,n) {
45499 var on = e.is(".x-menu-item-checked");
45500 var newv = v.indexOf(String(n)) > -1;
45502 e.toggleClass('x-menu-item-checked');
45508 this.fireEvent('change', this, v, old);
45513 // handle setting of hidden value by some other method!!?!?
45514 setFromHidden: function()
45519 //console.log("SET FROM HIDDEN");
45520 //alert('setFrom hidden');
45521 this.setValue(this.el.dom.value);
45524 onDestroy : function()
45527 Roo.get(this.viewEl).remove();
45530 Roo.form.DayPicker.superclass.onDestroy.call(this);
45534 * RooJS Library 1.1.1
45535 * Copyright(c) 2008-2011 Alan Knowles
45542 * @class Roo.form.ComboCheck
45543 * @extends Roo.form.ComboBox
45544 * A combobox for multiple select items.
45546 * FIXME - could do with a reset button..
45549 * Create a new ComboCheck
45550 * @param {Object} config Configuration options
45552 Roo.form.ComboCheck = function(config){
45553 Roo.form.ComboCheck.superclass.constructor.call(this, config);
45554 // should verify some data...
45556 // hiddenName = required..
45557 // displayField = required
45558 // valudField == required
45559 var req= [ 'hiddenName', 'displayField', 'valueField' ];
45561 Roo.each(req, function(e) {
45562 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
45563 throw "Roo.form.ComboCheck : missing value for: " + e;
45570 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
45575 selectedClass: 'x-menu-item-checked',
45578 onRender : function(ct, position){
45584 var cls = 'x-combo-list';
45587 this.tpl = new Roo.Template({
45588 html : '<div class="'+cls+'-item x-menu-check-item">' +
45589 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
45590 '<span>{' + this.displayField + '}</span>' +
45597 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
45598 this.view.singleSelect = false;
45599 this.view.multiSelect = true;
45600 this.view.toggleSelect = true;
45601 this.pageTb.add(new Roo.Toolbar.Fill(), {
45604 handler: function()
45611 onViewOver : function(e, t){
45617 onViewClick : function(doFocus,index){
45621 select: function () {
45622 //Roo.log("SELECT CALLED");
45625 selectByValue : function(xv, scrollIntoView){
45626 var ar = this.getValueArray();
45629 Roo.each(ar, function(v) {
45630 if(v === undefined || v === null){
45633 var r = this.findRecord(this.valueField, v);
45635 sels.push(this.store.indexOf(r))
45639 this.view.select(sels);
45645 onSelect : function(record, index){
45646 // Roo.log("onselect Called");
45647 // this is only called by the clear button now..
45648 this.view.clearSelections();
45649 this.setValue('[]');
45650 if (this.value != this.valueBefore) {
45651 this.fireEvent('change', this, this.value, this.valueBefore);
45652 this.valueBefore = this.value;
45655 getValueArray : function()
45660 //Roo.log(this.value);
45661 if (typeof(this.value) == 'undefined') {
45664 var ar = Roo.decode(this.value);
45665 return ar instanceof Array ? ar : []; //?? valid?
45668 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
45673 expand : function ()
45676 Roo.form.ComboCheck.superclass.expand.call(this);
45677 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
45678 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
45683 collapse : function(){
45684 Roo.form.ComboCheck.superclass.collapse.call(this);
45685 var sl = this.view.getSelectedIndexes();
45686 var st = this.store;
45690 Roo.each(sl, function(i) {
45692 nv.push(r.get(this.valueField));
45694 this.setValue(Roo.encode(nv));
45695 if (this.value != this.valueBefore) {
45697 this.fireEvent('change', this, this.value, this.valueBefore);
45698 this.valueBefore = this.value;
45703 setValue : function(v){
45707 var vals = this.getValueArray();
45709 Roo.each(vals, function(k) {
45710 var r = this.findRecord(this.valueField, k);
45712 tv.push(r.data[this.displayField]);
45713 }else if(this.valueNotFoundText !== undefined){
45714 tv.push( this.valueNotFoundText );
45719 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
45720 this.hiddenField.value = v;
45726 * Ext JS Library 1.1.1
45727 * Copyright(c) 2006-2007, Ext JS, LLC.
45729 * Originally Released Under LGPL - original licence link has changed is not relivant.
45732 * <script type="text/javascript">
45736 * @class Roo.form.Signature
45737 * @extends Roo.form.Field
45741 * @param {Object} config Configuration options
45744 Roo.form.Signature = function(config){
45745 Roo.form.Signature.superclass.constructor.call(this, config);
45747 this.addEvents({// not in used??
45750 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
45751 * @param {Roo.form.Signature} combo This combo box
45756 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
45757 * @param {Roo.form.ComboBox} combo This combo box
45758 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
45764 Roo.extend(Roo.form.Signature, Roo.form.Field, {
45766 * @cfg {Object} labels Label to use when rendering a form.
45770 * confirm : "Confirm"
45775 confirm : "Confirm"
45778 * @cfg {Number} width The signature panel width (defaults to 300)
45782 * @cfg {Number} height The signature panel height (defaults to 100)
45786 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
45788 allowBlank : false,
45791 // {Object} signPanel The signature SVG panel element (defaults to {})
45793 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
45794 isMouseDown : false,
45795 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
45796 isConfirmed : false,
45797 // {String} signatureTmp SVG mapping string (defaults to empty string)
45801 defaultAutoCreate : { // modified by initCompnoent..
45807 onRender : function(ct, position){
45809 Roo.form.Signature.superclass.onRender.call(this, ct, position);
45811 this.wrap = this.el.wrap({
45812 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
45815 this.createToolbar(this);
45816 this.signPanel = this.wrap.createChild({
45818 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
45822 this.svgID = Roo.id();
45823 this.svgEl = this.signPanel.createChild({
45824 xmlns : 'http://www.w3.org/2000/svg',
45826 id : this.svgID + "-svg",
45828 height: this.height,
45829 viewBox: '0 0 '+this.width+' '+this.height,
45833 id: this.svgID + "-svg-r",
45835 height: this.height,
45840 id: this.svgID + "-svg-l",
45842 y1: (this.height*0.8), // start set the line in 80% of height
45843 x2: this.width, // end
45844 y2: (this.height*0.8), // end set the line in 80% of height
45846 'stroke-width': "1",
45847 'stroke-dasharray': "3",
45848 'shape-rendering': "crispEdges",
45849 'pointer-events': "none"
45853 id: this.svgID + "-svg-p",
45855 'stroke-width': "3",
45857 'pointer-events': 'none'
45862 this.svgBox = this.svgEl.dom.getScreenCTM();
45864 createSVG : function(){
45865 var svg = this.signPanel;
45866 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
45869 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
45870 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
45871 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
45872 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
45873 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
45874 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
45875 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
45878 isTouchEvent : function(e){
45879 return e.type.match(/^touch/);
45881 getCoords : function (e) {
45882 var pt = this.svgEl.dom.createSVGPoint();
45885 if (this.isTouchEvent(e)) {
45886 pt.x = e.targetTouches[0].clientX
45887 pt.y = e.targetTouches[0].clientY;
45889 var a = this.svgEl.dom.getScreenCTM();
45890 var b = a.inverse();
45891 var mx = pt.matrixTransform(b);
45892 return mx.x + ',' + mx.y;
45894 //mouse event headler
45895 down : function (e) {
45896 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
45897 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
45899 this.isMouseDown = true;
45901 e.preventDefault();
45903 move : function (e) {
45904 if (this.isMouseDown) {
45905 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
45906 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
45909 e.preventDefault();
45911 up : function (e) {
45912 this.isMouseDown = false;
45913 var sp = this.signatureTmp.split(' ');
45916 if(!sp[sp.length-2].match(/^L/)){
45920 this.signatureTmp = sp.join(" ");
45923 if(this.getValue() != this.signatureTmp){
45924 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
45925 this.isConfirmed = false;
45927 e.preventDefault();
45931 * Protected method that will not generally be called directly. It
45932 * is called when the editor creates its toolbar. Override this method if you need to
45933 * add custom toolbar buttons.
45934 * @param {HtmlEditor} editor
45936 createToolbar : function(editor){
45937 function btn(id, toggle, handler){
45938 var xid = fid + '-'+ id ;
45942 cls : 'x-btn-icon x-edit-'+id,
45943 enableToggle:toggle !== false,
45944 scope: editor, // was editor...
45945 handler:handler||editor.relayBtnCmd,
45946 clickEvent:'mousedown',
45947 tooltip: etb.buttonTips[id] || undefined, ///tips ???
45953 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
45957 cls : ' x-signature-btn x-signature-'+id,
45958 scope: editor, // was editor...
45959 handler: this.reset,
45960 clickEvent:'mousedown',
45961 text: this.labels.clear
45968 cls : ' x-signature-btn x-signature-'+id,
45969 scope: editor, // was editor...
45970 handler: this.confirmHandler,
45971 clickEvent:'mousedown',
45972 text: this.labels.confirm
45979 * when user is clicked confirm then show this image.....
45981 * @return {String} Image Data URI
45983 getImageDataURI : function(){
45984 var svg = this.svgEl.dom.parentNode.innerHTML;
45985 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
45990 * @return {Boolean} this.isConfirmed
45992 getConfirmed : function(){
45993 return this.isConfirmed;
45997 * @return {Number} this.width
45999 getWidth : function(){
46004 * @return {Number} this.height
46006 getHeight : function(){
46007 return this.height;
46010 getSignature : function(){
46011 return this.signatureTmp;
46014 reset : function(){
46015 this.signatureTmp = '';
46016 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
46017 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
46018 this.isConfirmed = false;
46019 Roo.form.Signature.superclass.reset.call(this);
46021 setSignature : function(s){
46022 this.signatureTmp = s;
46023 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
46024 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
46026 this.isConfirmed = false;
46027 Roo.form.Signature.superclass.reset.call(this);
46030 // Roo.log(this.signPanel.dom.contentWindow.up())
46033 setConfirmed : function(){
46037 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
46040 confirmHandler : function(){
46041 if(!this.getSignature()){
46045 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
46046 this.setValue(this.getSignature());
46047 this.isConfirmed = true;
46049 this.fireEvent('confirm', this);
46052 // Subclasses should provide the validation implementation by overriding this
46053 validateValue : function(value){
46054 if(this.allowBlank){
46058 if(this.isConfirmed){
46065 * Ext JS Library 1.1.1
46066 * Copyright(c) 2006-2007, Ext JS, LLC.
46068 * Originally Released Under LGPL - original licence link has changed is not relivant.
46071 * <script type="text/javascript">
46076 * @class Roo.form.ComboBox
46077 * @extends Roo.form.TriggerField
46078 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
46080 * Create a new ComboBox.
46081 * @param {Object} config Configuration options
46083 Roo.form.Select = function(config){
46084 Roo.form.Select.superclass.constructor.call(this, config);
46088 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
46090 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
46093 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
46094 * rendering into an Roo.Editor, defaults to false)
46097 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
46098 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
46101 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
46104 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
46105 * the dropdown list (defaults to undefined, with no header element)
46109 * @cfg {String/Roo.Template} tpl The template to use to render the output
46113 defaultAutoCreate : {tag: "select" },
46115 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
46117 listWidth: undefined,
46119 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
46120 * mode = 'remote' or 'text' if mode = 'local')
46122 displayField: undefined,
46124 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
46125 * mode = 'remote' or 'value' if mode = 'local').
46126 * Note: use of a valueField requires the user make a selection
46127 * in order for a value to be mapped.
46129 valueField: undefined,
46133 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
46134 * field's data value (defaults to the underlying DOM element's name)
46136 hiddenName: undefined,
46138 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
46142 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
46144 selectedClass: 'x-combo-selected',
46146 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
46147 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
46148 * which displays a downward arrow icon).
46150 triggerClass : 'x-form-arrow-trigger',
46152 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
46156 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
46157 * anchor positions (defaults to 'tl-bl')
46159 listAlign: 'tl-bl?',
46161 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
46165 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
46166 * query specified by the allQuery config option (defaults to 'query')
46168 triggerAction: 'query',
46170 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
46171 * (defaults to 4, does not apply if editable = false)
46175 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
46176 * delay (typeAheadDelay) if it matches a known value (defaults to false)
46180 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
46181 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
46185 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
46186 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
46190 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
46191 * when editable = true (defaults to false)
46193 selectOnFocus:false,
46195 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
46197 queryParam: 'query',
46199 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
46200 * when mode = 'remote' (defaults to 'Loading...')
46202 loadingText: 'Loading...',
46204 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
46208 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
46212 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
46213 * traditional select (defaults to true)
46217 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
46221 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
46225 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
46226 * listWidth has a higher value)
46230 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
46231 * allow the user to set arbitrary text into the field (defaults to false)
46233 forceSelection:false,
46235 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
46236 * if typeAhead = true (defaults to 250)
46238 typeAheadDelay : 250,
46240 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
46241 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
46243 valueNotFoundText : undefined,
46246 * @cfg {String} defaultValue The value displayed after loading the store.
46251 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
46253 blockFocus : false,
46256 * @cfg {Boolean} disableClear Disable showing of clear button.
46258 disableClear : false,
46260 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
46262 alwaysQuery : false,
46268 // element that contains real text value.. (when hidden is used..)
46271 onRender : function(ct, position){
46272 Roo.form.Field.prototype.onRender.call(this, ct, position);
46275 this.store.on('beforeload', this.onBeforeLoad, this);
46276 this.store.on('load', this.onLoad, this);
46277 this.store.on('loadexception', this.onLoadException, this);
46278 this.store.load({});
46286 initEvents : function(){
46287 //Roo.form.ComboBox.superclass.initEvents.call(this);
46291 onDestroy : function(){
46294 this.store.un('beforeload', this.onBeforeLoad, this);
46295 this.store.un('load', this.onLoad, this);
46296 this.store.un('loadexception', this.onLoadException, this);
46298 //Roo.form.ComboBox.superclass.onDestroy.call(this);
46302 fireKey : function(e){
46303 if(e.isNavKeyPress() && !this.list.isVisible()){
46304 this.fireEvent("specialkey", this, e);
46309 onResize: function(w, h){
46317 * Allow or prevent the user from directly editing the field text. If false is passed,
46318 * the user will only be able to select from the items defined in the dropdown list. This method
46319 * is the runtime equivalent of setting the 'editable' config option at config time.
46320 * @param {Boolean} value True to allow the user to directly edit the field text
46322 setEditable : function(value){
46327 onBeforeLoad : function(){
46329 Roo.log("Select before load");
46332 this.innerList.update(this.loadingText ?
46333 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
46334 //this.restrictHeight();
46335 this.selectedIndex = -1;
46339 onLoad : function(){
46342 var dom = this.el.dom;
46343 dom.innerHTML = '';
46344 var od = dom.ownerDocument;
46346 if (this.emptyText) {
46347 var op = od.createElement('option');
46348 op.setAttribute('value', '');
46349 op.innerHTML = String.format('{0}', this.emptyText);
46350 dom.appendChild(op);
46352 if(this.store.getCount() > 0){
46354 var vf = this.valueField;
46355 var df = this.displayField;
46356 this.store.data.each(function(r) {
46357 // which colmsn to use... testing - cdoe / title..
46358 var op = od.createElement('option');
46359 op.setAttribute('value', r.data[vf]);
46360 op.innerHTML = String.format('{0}', r.data[df]);
46361 dom.appendChild(op);
46363 if (typeof(this.defaultValue != 'undefined')) {
46364 this.setValue(this.defaultValue);
46369 //this.onEmptyResults();
46374 onLoadException : function()
46376 dom.innerHTML = '';
46378 Roo.log("Select on load exception");
46382 Roo.log(this.store.reader.jsonData);
46383 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
46384 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
46390 onTypeAhead : function(){
46395 onSelect : function(record, index){
46396 Roo.log('on select?');
46398 if(this.fireEvent('beforeselect', this, record, index) !== false){
46399 this.setFromData(index > -1 ? record.data : false);
46401 this.fireEvent('select', this, record, index);
46406 * Returns the currently selected field value or empty string if no value is set.
46407 * @return {String} value The selected value
46409 getValue : function(){
46410 var dom = this.el.dom;
46411 this.value = dom.options[dom.selectedIndex].value;
46417 * Clears any text/value currently set in the field
46419 clearValue : function(){
46421 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
46426 * Sets the specified value into the field. If the value finds a match, the corresponding record text
46427 * will be displayed in the field. If the value does not match the data value of an existing item,
46428 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
46429 * Otherwise the field will be blank (although the value will still be set).
46430 * @param {String} value The value to match
46432 setValue : function(v){
46433 var d = this.el.dom;
46434 for (var i =0; i < d.options.length;i++) {
46435 if (v == d.options[i].value) {
46436 d.selectedIndex = i;
46444 * @property {Object} the last set data for the element
46449 * Sets the value of the field based on a object which is related to the record format for the store.
46450 * @param {Object} value the value to set as. or false on reset?
46452 setFromData : function(o){
46453 Roo.log('setfrom data?');
46459 reset : function(){
46463 findRecord : function(prop, value){
46468 if(this.store.getCount() > 0){
46469 this.store.each(function(r){
46470 if(r.data[prop] == value){
46480 getName: function()
46482 // returns hidden if it's set..
46483 if (!this.rendered) {return ''};
46484 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
46492 onEmptyResults : function(){
46493 Roo.log('empty results');
46498 * Returns true if the dropdown list is expanded, else false.
46500 isExpanded : function(){
46505 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
46506 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
46507 * @param {String} value The data value of the item to select
46508 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
46509 * selected item if it is not currently in view (defaults to true)
46510 * @return {Boolean} True if the value matched an item in the list, else false
46512 selectByValue : function(v, scrollIntoView){
46513 Roo.log('select By Value');
46516 if(v !== undefined && v !== null){
46517 var r = this.findRecord(this.valueField || this.displayField, v);
46519 this.select(this.store.indexOf(r), scrollIntoView);
46527 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
46528 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
46529 * @param {Number} index The zero-based index of the list item to select
46530 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
46531 * selected item if it is not currently in view (defaults to true)
46533 select : function(index, scrollIntoView){
46534 Roo.log('select ');
46537 this.selectedIndex = index;
46538 this.view.select(index);
46539 if(scrollIntoView !== false){
46540 var el = this.view.getNode(index);
46542 this.innerList.scrollChildIntoView(el, false);
46550 validateBlur : function(){
46557 initQuery : function(){
46558 this.doQuery(this.getRawValue());
46562 doForce : function(){
46563 if(this.el.dom.value.length > 0){
46564 this.el.dom.value =
46565 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
46571 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
46572 * query allowing the query action to be canceled if needed.
46573 * @param {String} query The SQL query to execute
46574 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
46575 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
46576 * saved in the current store (defaults to false)
46578 doQuery : function(q, forceAll){
46580 Roo.log('doQuery?');
46581 if(q === undefined || q === null){
46586 forceAll: forceAll,
46590 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
46594 forceAll = qe.forceAll;
46595 if(forceAll === true || (q.length >= this.minChars)){
46596 if(this.lastQuery != q || this.alwaysQuery){
46597 this.lastQuery = q;
46598 if(this.mode == 'local'){
46599 this.selectedIndex = -1;
46601 this.store.clearFilter();
46603 this.store.filter(this.displayField, q);
46607 this.store.baseParams[this.queryParam] = q;
46609 params: this.getParams(q)
46614 this.selectedIndex = -1;
46621 getParams : function(q){
46623 //p[this.queryParam] = q;
46626 p.limit = this.pageSize;
46632 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
46634 collapse : function(){
46639 collapseIf : function(e){
46644 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
46646 expand : function(){
46654 * @cfg {Boolean} grow
46658 * @cfg {Number} growMin
46662 * @cfg {Number} growMax
46670 setWidth : function()
46674 getResizeEl : function(){
46677 });//<script type="text/javasscript">
46681 * @class Roo.DDView
46682 * A DnD enabled version of Roo.View.
46683 * @param {Element/String} container The Element in which to create the View.
46684 * @param {String} tpl The template string used to create the markup for each element of the View
46685 * @param {Object} config The configuration properties. These include all the config options of
46686 * {@link Roo.View} plus some specific to this class.<br>
46688 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
46689 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
46691 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
46692 .x-view-drag-insert-above {
46693 border-top:1px dotted #3366cc;
46695 .x-view-drag-insert-below {
46696 border-bottom:1px dotted #3366cc;
46702 Roo.DDView = function(container, tpl, config) {
46703 Roo.DDView.superclass.constructor.apply(this, arguments);
46704 this.getEl().setStyle("outline", "0px none");
46705 this.getEl().unselectable();
46706 if (this.dragGroup) {
46707 this.setDraggable(this.dragGroup.split(","));
46709 if (this.dropGroup) {
46710 this.setDroppable(this.dropGroup.split(","));
46712 if (this.deletable) {
46713 this.setDeletable();
46715 this.isDirtyFlag = false;
46721 Roo.extend(Roo.DDView, Roo.View, {
46722 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
46723 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
46724 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
46725 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
46729 reset: Roo.emptyFn,
46731 clearInvalid: Roo.form.Field.prototype.clearInvalid,
46733 validate: function() {
46737 destroy: function() {
46738 this.purgeListeners();
46739 this.getEl.removeAllListeners();
46740 this.getEl().remove();
46741 if (this.dragZone) {
46742 if (this.dragZone.destroy) {
46743 this.dragZone.destroy();
46746 if (this.dropZone) {
46747 if (this.dropZone.destroy) {
46748 this.dropZone.destroy();
46753 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
46754 getName: function() {
46758 /** Loads the View from a JSON string representing the Records to put into the Store. */
46759 setValue: function(v) {
46761 throw "DDView.setValue(). DDView must be constructed with a valid Store";
46764 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
46765 this.store.proxy = new Roo.data.MemoryProxy(data);
46769 /** @return {String} a parenthesised list of the ids of the Records in the View. */
46770 getValue: function() {
46772 this.store.each(function(rec) {
46773 result += rec.id + ',';
46775 return result.substr(0, result.length - 1) + ')';
46778 getIds: function() {
46779 var i = 0, result = new Array(this.store.getCount());
46780 this.store.each(function(rec) {
46781 result[i++] = rec.id;
46786 isDirty: function() {
46787 return this.isDirtyFlag;
46791 * Part of the Roo.dd.DropZone interface. If no target node is found, the
46792 * whole Element becomes the target, and this causes the drop gesture to append.
46794 getTargetFromEvent : function(e) {
46795 var target = e.getTarget();
46796 while ((target !== null) && (target.parentNode != this.el.dom)) {
46797 target = target.parentNode;
46800 target = this.el.dom.lastChild || this.el.dom;
46806 * Create the drag data which consists of an object which has the property "ddel" as
46807 * the drag proxy element.
46809 getDragData : function(e) {
46810 var target = this.findItemFromChild(e.getTarget());
46812 this.handleSelection(e);
46813 var selNodes = this.getSelectedNodes();
46816 copy: this.copy || (this.allowCopy && e.ctrlKey),
46820 var selectedIndices = this.getSelectedIndexes();
46821 for (var i = 0; i < selectedIndices.length; i++) {
46822 dragData.records.push(this.store.getAt(selectedIndices[i]));
46824 if (selNodes.length == 1) {
46825 dragData.ddel = target.cloneNode(true); // the div element
46827 var div = document.createElement('div'); // create the multi element drag "ghost"
46828 div.className = 'multi-proxy';
46829 for (var i = 0, len = selNodes.length; i < len; i++) {
46830 div.appendChild(selNodes[i].cloneNode(true));
46832 dragData.ddel = div;
46834 //console.log(dragData)
46835 //console.log(dragData.ddel.innerHTML)
46838 //console.log('nodragData')
46842 /** Specify to which ddGroup items in this DDView may be dragged. */
46843 setDraggable: function(ddGroup) {
46844 if (ddGroup instanceof Array) {
46845 Roo.each(ddGroup, this.setDraggable, this);
46848 if (this.dragZone) {
46849 this.dragZone.addToGroup(ddGroup);
46851 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
46852 containerScroll: true,
46856 // Draggability implies selection. DragZone's mousedown selects the element.
46857 if (!this.multiSelect) { this.singleSelect = true; }
46859 // Wire the DragZone's handlers up to methods in *this*
46860 this.dragZone.getDragData = this.getDragData.createDelegate(this);
46864 /** Specify from which ddGroup this DDView accepts drops. */
46865 setDroppable: function(ddGroup) {
46866 if (ddGroup instanceof Array) {
46867 Roo.each(ddGroup, this.setDroppable, this);
46870 if (this.dropZone) {
46871 this.dropZone.addToGroup(ddGroup);
46873 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
46874 containerScroll: true,
46878 // Wire the DropZone's handlers up to methods in *this*
46879 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
46880 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
46881 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
46882 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
46883 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
46887 /** Decide whether to drop above or below a View node. */
46888 getDropPoint : function(e, n, dd){
46889 if (n == this.el.dom) { return "above"; }
46890 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
46891 var c = t + (b - t) / 2;
46892 var y = Roo.lib.Event.getPageY(e);
46900 onNodeEnter : function(n, dd, e, data){
46904 onNodeOver : function(n, dd, e, data){
46905 var pt = this.getDropPoint(e, n, dd);
46906 // set the insert point style on the target node
46907 var dragElClass = this.dropNotAllowed;
46910 if (pt == "above"){
46911 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
46912 targetElClass = "x-view-drag-insert-above";
46914 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
46915 targetElClass = "x-view-drag-insert-below";
46917 if (this.lastInsertClass != targetElClass){
46918 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
46919 this.lastInsertClass = targetElClass;
46922 return dragElClass;
46925 onNodeOut : function(n, dd, e, data){
46926 this.removeDropIndicators(n);
46929 onNodeDrop : function(n, dd, e, data){
46930 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
46933 var pt = this.getDropPoint(e, n, dd);
46934 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
46935 if (pt == "below") { insertAt++; }
46936 for (var i = 0; i < data.records.length; i++) {
46937 var r = data.records[i];
46938 var dup = this.store.getById(r.id);
46939 if (dup && (dd != this.dragZone)) {
46940 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
46943 this.store.insert(insertAt++, r.copy());
46945 data.source.isDirtyFlag = true;
46947 this.store.insert(insertAt++, r);
46949 this.isDirtyFlag = true;
46952 this.dragZone.cachedTarget = null;
46956 removeDropIndicators : function(n){
46958 Roo.fly(n).removeClass([
46959 "x-view-drag-insert-above",
46960 "x-view-drag-insert-below"]);
46961 this.lastInsertClass = "_noclass";
46966 * Utility method. Add a delete option to the DDView's context menu.
46967 * @param {String} imageUrl The URL of the "delete" icon image.
46969 setDeletable: function(imageUrl) {
46970 if (!this.singleSelect && !this.multiSelect) {
46971 this.singleSelect = true;
46973 var c = this.getContextMenu();
46974 this.contextMenu.on("itemclick", function(item) {
46977 this.remove(this.getSelectedIndexes());
46981 this.contextMenu.add({
46988 /** Return the context menu for this DDView. */
46989 getContextMenu: function() {
46990 if (!this.contextMenu) {
46991 // Create the View's context menu
46992 this.contextMenu = new Roo.menu.Menu({
46993 id: this.id + "-contextmenu"
46995 this.el.on("contextmenu", this.showContextMenu, this);
46997 return this.contextMenu;
47000 disableContextMenu: function() {
47001 if (this.contextMenu) {
47002 this.el.un("contextmenu", this.showContextMenu, this);
47006 showContextMenu: function(e, item) {
47007 item = this.findItemFromChild(e.getTarget());
47010 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
47011 this.contextMenu.showAt(e.getXY());
47016 * Remove {@link Roo.data.Record}s at the specified indices.
47017 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
47019 remove: function(selectedIndices) {
47020 selectedIndices = [].concat(selectedIndices);
47021 for (var i = 0; i < selectedIndices.length; i++) {
47022 var rec = this.store.getAt(selectedIndices[i]);
47023 this.store.remove(rec);
47028 * Double click fires the event, but also, if this is draggable, and there is only one other
47029 * related DropZone, it transfers the selected node.
47031 onDblClick : function(e){
47032 var item = this.findItemFromChild(e.getTarget());
47034 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
47037 if (this.dragGroup) {
47038 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
47039 while (targets.indexOf(this.dropZone) > -1) {
47040 targets.remove(this.dropZone);
47042 if (targets.length == 1) {
47043 this.dragZone.cachedTarget = null;
47044 var el = Roo.get(targets[0].getEl());
47045 var box = el.getBox(true);
47046 targets[0].onNodeDrop(el.dom, {
47048 xy: [box.x, box.y + box.height - 1]
47049 }, null, this.getDragData(e));
47055 handleSelection: function(e) {
47056 this.dragZone.cachedTarget = null;
47057 var item = this.findItemFromChild(e.getTarget());
47059 this.clearSelections(true);
47062 if (item && (this.multiSelect || this.singleSelect)){
47063 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
47064 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
47065 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
47066 this.unselect(item);
47068 this.select(item, this.multiSelect && e.ctrlKey);
47069 this.lastSelection = item;
47074 onItemClick : function(item, index, e){
47075 if(this.fireEvent("beforeclick", this, index, item, e) === false){
47081 unselect : function(nodeInfo, suppressEvent){
47082 var node = this.getNode(nodeInfo);
47083 if(node && this.isSelected(node)){
47084 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
47085 Roo.fly(node).removeClass(this.selectedClass);
47086 this.selections.remove(node);
47087 if(!suppressEvent){
47088 this.fireEvent("selectionchange", this, this.selections);
47096 * Ext JS Library 1.1.1
47097 * Copyright(c) 2006-2007, Ext JS, LLC.
47099 * Originally Released Under LGPL - original licence link has changed is not relivant.
47102 * <script type="text/javascript">
47106 * @class Roo.LayoutManager
47107 * @extends Roo.util.Observable
47108 * Base class for layout managers.
47110 Roo.LayoutManager = function(container, config){
47111 Roo.LayoutManager.superclass.constructor.call(this);
47112 this.el = Roo.get(container);
47113 // ie scrollbar fix
47114 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
47115 document.body.scroll = "no";
47116 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
47117 this.el.position('relative');
47119 this.id = this.el.id;
47120 this.el.addClass("x-layout-container");
47121 /** false to disable window resize monitoring @type Boolean */
47122 this.monitorWindowResize = true;
47127 * Fires when a layout is performed.
47128 * @param {Roo.LayoutManager} this
47132 * @event regionresized
47133 * Fires when the user resizes a region.
47134 * @param {Roo.LayoutRegion} region The resized region
47135 * @param {Number} newSize The new size (width for east/west, height for north/south)
47137 "regionresized" : true,
47139 * @event regioncollapsed
47140 * Fires when a region is collapsed.
47141 * @param {Roo.LayoutRegion} region The collapsed region
47143 "regioncollapsed" : true,
47145 * @event regionexpanded
47146 * Fires when a region is expanded.
47147 * @param {Roo.LayoutRegion} region The expanded region
47149 "regionexpanded" : true
47151 this.updating = false;
47152 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
47155 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
47157 * Returns true if this layout is currently being updated
47158 * @return {Boolean}
47160 isUpdating : function(){
47161 return this.updating;
47165 * Suspend the LayoutManager from doing auto-layouts while
47166 * making multiple add or remove calls
47168 beginUpdate : function(){
47169 this.updating = true;
47173 * Restore auto-layouts and optionally disable the manager from performing a layout
47174 * @param {Boolean} noLayout true to disable a layout update
47176 endUpdate : function(noLayout){
47177 this.updating = false;
47183 layout: function(){
47187 onRegionResized : function(region, newSize){
47188 this.fireEvent("regionresized", region, newSize);
47192 onRegionCollapsed : function(region){
47193 this.fireEvent("regioncollapsed", region);
47196 onRegionExpanded : function(region){
47197 this.fireEvent("regionexpanded", region);
47201 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
47202 * performs box-model adjustments.
47203 * @return {Object} The size as an object {width: (the width), height: (the height)}
47205 getViewSize : function(){
47207 if(this.el.dom != document.body){
47208 size = this.el.getSize();
47210 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
47212 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
47213 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
47218 * Returns the Element this layout is bound to.
47219 * @return {Roo.Element}
47221 getEl : function(){
47226 * Returns the specified region.
47227 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
47228 * @return {Roo.LayoutRegion}
47230 getRegion : function(target){
47231 return this.regions[target.toLowerCase()];
47234 onWindowResize : function(){
47235 if(this.monitorWindowResize){
47241 * Ext JS Library 1.1.1
47242 * Copyright(c) 2006-2007, Ext JS, LLC.
47244 * Originally Released Under LGPL - original licence link has changed is not relivant.
47247 * <script type="text/javascript">
47250 * @class Roo.BorderLayout
47251 * @extends Roo.LayoutManager
47252 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
47253 * please see: <br><br>
47254 * <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>
47255 * <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>
47258 var layout = new Roo.BorderLayout(document.body, {
47292 preferredTabWidth: 150
47297 var CP = Roo.ContentPanel;
47299 layout.beginUpdate();
47300 layout.add("north", new CP("north", "North"));
47301 layout.add("south", new CP("south", {title: "South", closable: true}));
47302 layout.add("west", new CP("west", {title: "West"}));
47303 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
47304 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
47305 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
47306 layout.getRegion("center").showPanel("center1");
47307 layout.endUpdate();
47310 <b>The container the layout is rendered into can be either the body element or any other element.
47311 If it is not the body element, the container needs to either be an absolute positioned element,
47312 or you will need to add "position:relative" to the css of the container. You will also need to specify
47313 the container size if it is not the body element.</b>
47316 * Create a new BorderLayout
47317 * @param {String/HTMLElement/Element} container The container this layout is bound to
47318 * @param {Object} config Configuration options
47320 Roo.BorderLayout = function(container, config){
47321 config = config || {};
47322 Roo.BorderLayout.superclass.constructor.call(this, container, config);
47323 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
47324 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
47325 var target = this.factory.validRegions[i];
47326 if(config[target]){
47327 this.addRegion(target, config[target]);
47332 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
47334 * Creates and adds a new region if it doesn't already exist.
47335 * @param {String} target The target region key (north, south, east, west or center).
47336 * @param {Object} config The regions config object
47337 * @return {BorderLayoutRegion} The new region
47339 addRegion : function(target, config){
47340 if(!this.regions[target]){
47341 var r = this.factory.create(target, this, config);
47342 this.bindRegion(target, r);
47344 return this.regions[target];
47348 bindRegion : function(name, r){
47349 this.regions[name] = r;
47350 r.on("visibilitychange", this.layout, this);
47351 r.on("paneladded", this.layout, this);
47352 r.on("panelremoved", this.layout, this);
47353 r.on("invalidated", this.layout, this);
47354 r.on("resized", this.onRegionResized, this);
47355 r.on("collapsed", this.onRegionCollapsed, this);
47356 r.on("expanded", this.onRegionExpanded, this);
47360 * Performs a layout update.
47362 layout : function(){
47363 if(this.updating) return;
47364 var size = this.getViewSize();
47365 var w = size.width;
47366 var h = size.height;
47371 //var x = 0, y = 0;
47373 var rs = this.regions;
47374 var north = rs["north"];
47375 var south = rs["south"];
47376 var west = rs["west"];
47377 var east = rs["east"];
47378 var center = rs["center"];
47379 //if(this.hideOnLayout){ // not supported anymore
47380 //c.el.setStyle("display", "none");
47382 if(north && north.isVisible()){
47383 var b = north.getBox();
47384 var m = north.getMargins();
47385 b.width = w - (m.left+m.right);
47388 centerY = b.height + b.y + m.bottom;
47389 centerH -= centerY;
47390 north.updateBox(this.safeBox(b));
47392 if(south && south.isVisible()){
47393 var b = south.getBox();
47394 var m = south.getMargins();
47395 b.width = w - (m.left+m.right);
47397 var totalHeight = (b.height + m.top + m.bottom);
47398 b.y = h - totalHeight + m.top;
47399 centerH -= totalHeight;
47400 south.updateBox(this.safeBox(b));
47402 if(west && west.isVisible()){
47403 var b = west.getBox();
47404 var m = west.getMargins();
47405 b.height = centerH - (m.top+m.bottom);
47407 b.y = centerY + m.top;
47408 var totalWidth = (b.width + m.left + m.right);
47409 centerX += totalWidth;
47410 centerW -= totalWidth;
47411 west.updateBox(this.safeBox(b));
47413 if(east && east.isVisible()){
47414 var b = east.getBox();
47415 var m = east.getMargins();
47416 b.height = centerH - (m.top+m.bottom);
47417 var totalWidth = (b.width + m.left + m.right);
47418 b.x = w - totalWidth + m.left;
47419 b.y = centerY + m.top;
47420 centerW -= totalWidth;
47421 east.updateBox(this.safeBox(b));
47424 var m = center.getMargins();
47426 x: centerX + m.left,
47427 y: centerY + m.top,
47428 width: centerW - (m.left+m.right),
47429 height: centerH - (m.top+m.bottom)
47431 //if(this.hideOnLayout){
47432 //center.el.setStyle("display", "block");
47434 center.updateBox(this.safeBox(centerBox));
47437 this.fireEvent("layout", this);
47441 safeBox : function(box){
47442 box.width = Math.max(0, box.width);
47443 box.height = Math.max(0, box.height);
47448 * Adds a ContentPanel (or subclass) to this layout.
47449 * @param {String} target The target region key (north, south, east, west or center).
47450 * @param {Roo.ContentPanel} panel The panel to add
47451 * @return {Roo.ContentPanel} The added panel
47453 add : function(target, panel){
47455 target = target.toLowerCase();
47456 return this.regions[target].add(panel);
47460 * Remove a ContentPanel (or subclass) to this layout.
47461 * @param {String} target The target region key (north, south, east, west or center).
47462 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
47463 * @return {Roo.ContentPanel} The removed panel
47465 remove : function(target, panel){
47466 target = target.toLowerCase();
47467 return this.regions[target].remove(panel);
47471 * Searches all regions for a panel with the specified id
47472 * @param {String} panelId
47473 * @return {Roo.ContentPanel} The panel or null if it wasn't found
47475 findPanel : function(panelId){
47476 var rs = this.regions;
47477 for(var target in rs){
47478 if(typeof rs[target] != "function"){
47479 var p = rs[target].getPanel(panelId);
47489 * Searches all regions for a panel with the specified id and activates (shows) it.
47490 * @param {String/ContentPanel} panelId The panels id or the panel itself
47491 * @return {Roo.ContentPanel} The shown panel or null
47493 showPanel : function(panelId) {
47494 var rs = this.regions;
47495 for(var target in rs){
47496 var r = rs[target];
47497 if(typeof r != "function"){
47498 if(r.hasPanel(panelId)){
47499 return r.showPanel(panelId);
47507 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
47508 * @param {Roo.state.Provider} provider (optional) An alternate state provider
47510 restoreState : function(provider){
47512 provider = Roo.state.Manager;
47514 var sm = new Roo.LayoutStateManager();
47515 sm.init(this, provider);
47519 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
47520 * object should contain properties for each region to add ContentPanels to, and each property's value should be
47521 * a valid ContentPanel config object. Example:
47523 // Create the main layout
47524 var layout = new Roo.BorderLayout('main-ct', {
47535 // Create and add multiple ContentPanels at once via configs
47538 id: 'source-files',
47540 title:'Ext Source Files',
47553 * @param {Object} regions An object containing ContentPanel configs by region name
47555 batchAdd : function(regions){
47556 this.beginUpdate();
47557 for(var rname in regions){
47558 var lr = this.regions[rname];
47560 this.addTypedPanels(lr, regions[rname]);
47567 addTypedPanels : function(lr, ps){
47568 if(typeof ps == 'string'){
47569 lr.add(new Roo.ContentPanel(ps));
47571 else if(ps instanceof Array){
47572 for(var i =0, len = ps.length; i < len; i++){
47573 this.addTypedPanels(lr, ps[i]);
47576 else if(!ps.events){ // raw config?
47578 delete ps.el; // prevent conflict
47579 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
47581 else { // panel object assumed!
47586 * Adds a xtype elements to the layout.
47590 xtype : 'ContentPanel',
47597 xtype : 'NestedLayoutPanel',
47603 items : [ ... list of content panels or nested layout panels.. ]
47607 * @param {Object} cfg Xtype definition of item to add.
47609 addxtype : function(cfg)
47611 // basically accepts a pannel...
47612 // can accept a layout region..!?!?
47613 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
47615 if (!cfg.xtype.match(/Panel$/)) {
47620 if (typeof(cfg.region) == 'undefined') {
47621 Roo.log("Failed to add Panel, region was not set");
47625 var region = cfg.region;
47631 xitems = cfg.items;
47638 case 'ContentPanel': // ContentPanel (el, cfg)
47639 case 'ScrollPanel': // ContentPanel (el, cfg)
47641 if(cfg.autoCreate) {
47642 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
47644 var el = this.el.createChild();
47645 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
47648 this.add(region, ret);
47652 case 'TreePanel': // our new panel!
47653 cfg.el = this.el.createChild();
47654 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
47655 this.add(region, ret);
47658 case 'NestedLayoutPanel':
47659 // create a new Layout (which is a Border Layout...
47660 var el = this.el.createChild();
47661 var clayout = cfg.layout;
47663 clayout.items = clayout.items || [];
47664 // replace this exitems with the clayout ones..
47665 xitems = clayout.items;
47668 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
47669 cfg.background = false;
47671 var layout = new Roo.BorderLayout(el, clayout);
47673 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
47674 //console.log('adding nested layout panel ' + cfg.toSource());
47675 this.add(region, ret);
47676 nb = {}; /// find first...
47681 // needs grid and region
47683 //var el = this.getRegion(region).el.createChild();
47684 var el = this.el.createChild();
47685 // create the grid first...
47687 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
47689 if (region == 'center' && this.active ) {
47690 cfg.background = false;
47692 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
47694 this.add(region, ret);
47695 if (cfg.background) {
47696 ret.on('activate', function(gp) {
47697 if (!gp.grid.rendered) {
47712 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
47714 // GridPanel (grid, cfg)
47717 this.beginUpdate();
47721 Roo.each(xitems, function(i) {
47722 region = nb && i.region ? i.region : false;
47724 var add = ret.addxtype(i);
47727 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
47728 if (!i.background) {
47729 abn[region] = nb[region] ;
47736 // make the last non-background panel active..
47737 //if (nb) { Roo.log(abn); }
47740 for(var r in abn) {
47741 region = this.getRegion(r);
47743 // tried using nb[r], but it does not work..
47745 region.showPanel(abn[r]);
47756 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
47757 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
47758 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
47759 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
47762 var CP = Roo.ContentPanel;
47764 var layout = Roo.BorderLayout.create({
47768 panels: [new CP("north", "North")]
47777 panels: [new CP("west", {title: "West"})]
47786 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
47795 panels: [new CP("south", {title: "South", closable: true})]
47802 preferredTabWidth: 150,
47804 new CP("center1", {title: "Close Me", closable: true}),
47805 new CP("center2", {title: "Center Panel", closable: false})
47810 layout.getRegion("center").showPanel("center1");
47815 Roo.BorderLayout.create = function(config, targetEl){
47816 var layout = new Roo.BorderLayout(targetEl || document.body, config);
47817 layout.beginUpdate();
47818 var regions = Roo.BorderLayout.RegionFactory.validRegions;
47819 for(var j = 0, jlen = regions.length; j < jlen; j++){
47820 var lr = regions[j];
47821 if(layout.regions[lr] && config[lr].panels){
47822 var r = layout.regions[lr];
47823 var ps = config[lr].panels;
47824 layout.addTypedPanels(r, ps);
47827 layout.endUpdate();
47832 Roo.BorderLayout.RegionFactory = {
47834 validRegions : ["north","south","east","west","center"],
47837 create : function(target, mgr, config){
47838 target = target.toLowerCase();
47839 if(config.lightweight || config.basic){
47840 return new Roo.BasicLayoutRegion(mgr, config, target);
47844 return new Roo.NorthLayoutRegion(mgr, config);
47846 return new Roo.SouthLayoutRegion(mgr, config);
47848 return new Roo.EastLayoutRegion(mgr, config);
47850 return new Roo.WestLayoutRegion(mgr, config);
47852 return new Roo.CenterLayoutRegion(mgr, config);
47854 throw 'Layout region "'+target+'" not supported.';
47858 * Ext JS Library 1.1.1
47859 * Copyright(c) 2006-2007, Ext JS, LLC.
47861 * Originally Released Under LGPL - original licence link has changed is not relivant.
47864 * <script type="text/javascript">
47868 * @class Roo.BasicLayoutRegion
47869 * @extends Roo.util.Observable
47870 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
47871 * and does not have a titlebar, tabs or any other features. All it does is size and position
47872 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
47874 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
47876 this.position = pos;
47879 * @scope Roo.BasicLayoutRegion
47883 * @event beforeremove
47884 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
47885 * @param {Roo.LayoutRegion} this
47886 * @param {Roo.ContentPanel} panel The panel
47887 * @param {Object} e The cancel event object
47889 "beforeremove" : true,
47891 * @event invalidated
47892 * Fires when the layout for this region is changed.
47893 * @param {Roo.LayoutRegion} this
47895 "invalidated" : true,
47897 * @event visibilitychange
47898 * Fires when this region is shown or hidden
47899 * @param {Roo.LayoutRegion} this
47900 * @param {Boolean} visibility true or false
47902 "visibilitychange" : true,
47904 * @event paneladded
47905 * Fires when a panel is added.
47906 * @param {Roo.LayoutRegion} this
47907 * @param {Roo.ContentPanel} panel The panel
47909 "paneladded" : true,
47911 * @event panelremoved
47912 * Fires when a panel is removed.
47913 * @param {Roo.LayoutRegion} this
47914 * @param {Roo.ContentPanel} panel The panel
47916 "panelremoved" : true,
47919 * Fires when this region is collapsed.
47920 * @param {Roo.LayoutRegion} this
47922 "collapsed" : true,
47925 * Fires when this region is expanded.
47926 * @param {Roo.LayoutRegion} this
47931 * Fires when this region is slid into view.
47932 * @param {Roo.LayoutRegion} this
47934 "slideshow" : true,
47937 * Fires when this region slides out of view.
47938 * @param {Roo.LayoutRegion} this
47940 "slidehide" : true,
47942 * @event panelactivated
47943 * Fires when a panel is activated.
47944 * @param {Roo.LayoutRegion} this
47945 * @param {Roo.ContentPanel} panel The activated panel
47947 "panelactivated" : true,
47950 * Fires when the user resizes this region.
47951 * @param {Roo.LayoutRegion} this
47952 * @param {Number} newSize The new size (width for east/west, height for north/south)
47956 /** A collection of panels in this region. @type Roo.util.MixedCollection */
47957 this.panels = new Roo.util.MixedCollection();
47958 this.panels.getKey = this.getPanelId.createDelegate(this);
47960 this.activePanel = null;
47961 // ensure listeners are added...
47963 if (config.listeners || config.events) {
47964 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
47965 listeners : config.listeners || {},
47966 events : config.events || {}
47970 if(skipConfig !== true){
47971 this.applyConfig(config);
47975 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
47976 getPanelId : function(p){
47980 applyConfig : function(config){
47981 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
47982 this.config = config;
47987 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
47988 * the width, for horizontal (north, south) the height.
47989 * @param {Number} newSize The new width or height
47991 resizeTo : function(newSize){
47992 var el = this.el ? this.el :
47993 (this.activePanel ? this.activePanel.getEl() : null);
47995 switch(this.position){
47998 el.setWidth(newSize);
47999 this.fireEvent("resized", this, newSize);
48003 el.setHeight(newSize);
48004 this.fireEvent("resized", this, newSize);
48010 getBox : function(){
48011 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
48014 getMargins : function(){
48015 return this.margins;
48018 updateBox : function(box){
48020 var el = this.activePanel.getEl();
48021 el.dom.style.left = box.x + "px";
48022 el.dom.style.top = box.y + "px";
48023 this.activePanel.setSize(box.width, box.height);
48027 * Returns the container element for this region.
48028 * @return {Roo.Element}
48030 getEl : function(){
48031 return this.activePanel;
48035 * Returns true if this region is currently visible.
48036 * @return {Boolean}
48038 isVisible : function(){
48039 return this.activePanel ? true : false;
48042 setActivePanel : function(panel){
48043 panel = this.getPanel(panel);
48044 if(this.activePanel && this.activePanel != panel){
48045 this.activePanel.setActiveState(false);
48046 this.activePanel.getEl().setLeftTop(-10000,-10000);
48048 this.activePanel = panel;
48049 panel.setActiveState(true);
48051 panel.setSize(this.box.width, this.box.height);
48053 this.fireEvent("panelactivated", this, panel);
48054 this.fireEvent("invalidated");
48058 * Show the specified panel.
48059 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
48060 * @return {Roo.ContentPanel} The shown panel or null
48062 showPanel : function(panel){
48063 if(panel = this.getPanel(panel)){
48064 this.setActivePanel(panel);
48070 * Get the active panel for this region.
48071 * @return {Roo.ContentPanel} The active panel or null
48073 getActivePanel : function(){
48074 return this.activePanel;
48078 * Add the passed ContentPanel(s)
48079 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
48080 * @return {Roo.ContentPanel} The panel added (if only one was added)
48082 add : function(panel){
48083 if(arguments.length > 1){
48084 for(var i = 0, len = arguments.length; i < len; i++) {
48085 this.add(arguments[i]);
48089 if(this.hasPanel(panel)){
48090 this.showPanel(panel);
48093 var el = panel.getEl();
48094 if(el.dom.parentNode != this.mgr.el.dom){
48095 this.mgr.el.dom.appendChild(el.dom);
48097 if(panel.setRegion){
48098 panel.setRegion(this);
48100 this.panels.add(panel);
48101 el.setStyle("position", "absolute");
48102 if(!panel.background){
48103 this.setActivePanel(panel);
48104 if(this.config.initialSize && this.panels.getCount()==1){
48105 this.resizeTo(this.config.initialSize);
48108 this.fireEvent("paneladded", this, panel);
48113 * Returns true if the panel is in this region.
48114 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
48115 * @return {Boolean}
48117 hasPanel : function(panel){
48118 if(typeof panel == "object"){ // must be panel obj
48119 panel = panel.getId();
48121 return this.getPanel(panel) ? true : false;
48125 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
48126 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
48127 * @param {Boolean} preservePanel Overrides the config preservePanel option
48128 * @return {Roo.ContentPanel} The panel that was removed
48130 remove : function(panel, preservePanel){
48131 panel = this.getPanel(panel);
48136 this.fireEvent("beforeremove", this, panel, e);
48137 if(e.cancel === true){
48140 var panelId = panel.getId();
48141 this.panels.removeKey(panelId);
48146 * Returns the panel specified or null if it's not in this region.
48147 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
48148 * @return {Roo.ContentPanel}
48150 getPanel : function(id){
48151 if(typeof id == "object"){ // must be panel obj
48154 return this.panels.get(id);
48158 * Returns this regions position (north/south/east/west/center).
48161 getPosition: function(){
48162 return this.position;
48166 * Ext JS Library 1.1.1
48167 * Copyright(c) 2006-2007, Ext JS, LLC.
48169 * Originally Released Under LGPL - original licence link has changed is not relivant.
48172 * <script type="text/javascript">
48176 * @class Roo.LayoutRegion
48177 * @extends Roo.BasicLayoutRegion
48178 * This class represents a region in a layout manager.
48179 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
48180 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
48181 * @cfg {Boolean} floatable False to disable floating (defaults to true)
48182 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
48183 * @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})
48184 * @cfg {String} tabPosition "top" or "bottom" (defaults to "bottom")
48185 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
48186 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
48187 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
48188 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
48189 * @cfg {String} title The title for the region (overrides panel titles)
48190 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
48191 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
48192 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
48193 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
48194 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
48195 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
48196 * the space available, similar to FireFox 1.5 tabs (defaults to false)
48197 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
48198 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
48199 * @cfg {Boolean} showPin True to show a pin button
48200 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
48201 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
48202 * @cfg {Boolean} disableTabTips True to disable tab tooltips
48203 * @cfg {Number} width For East/West panels
48204 * @cfg {Number} height For North/South panels
48205 * @cfg {Boolean} split To show the splitter
48206 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
48208 Roo.LayoutRegion = function(mgr, config, pos){
48209 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
48210 var dh = Roo.DomHelper;
48211 /** This region's container element
48212 * @type Roo.Element */
48213 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
48214 /** This region's title element
48215 * @type Roo.Element */
48217 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
48218 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
48219 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
48221 this.titleEl.enableDisplayMode();
48222 /** This region's title text element
48223 * @type HTMLElement */
48224 this.titleTextEl = this.titleEl.dom.firstChild;
48225 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
48226 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
48227 this.closeBtn.enableDisplayMode();
48228 this.closeBtn.on("click", this.closeClicked, this);
48229 this.closeBtn.hide();
48231 this.createBody(config);
48232 this.visible = true;
48233 this.collapsed = false;
48235 if(config.hideWhenEmpty){
48237 this.on("paneladded", this.validateVisibility, this);
48238 this.on("panelremoved", this.validateVisibility, this);
48240 this.applyConfig(config);
48243 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
48245 createBody : function(){
48246 /** This region's body element
48247 * @type Roo.Element */
48248 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
48251 applyConfig : function(c){
48252 if(c.collapsible && this.position != "center" && !this.collapsedEl){
48253 var dh = Roo.DomHelper;
48254 if(c.titlebar !== false){
48255 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
48256 this.collapseBtn.on("click", this.collapse, this);
48257 this.collapseBtn.enableDisplayMode();
48259 if(c.showPin === true || this.showPin){
48260 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
48261 this.stickBtn.enableDisplayMode();
48262 this.stickBtn.on("click", this.expand, this);
48263 this.stickBtn.hide();
48266 /** This region's collapsed element
48267 * @type Roo.Element */
48268 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
48269 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
48271 if(c.floatable !== false){
48272 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
48273 this.collapsedEl.on("click", this.collapseClick, this);
48276 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
48277 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
48278 id: "message", unselectable: "on", style:{"float":"left"}});
48279 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
48281 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
48282 this.expandBtn.on("click", this.expand, this);
48284 if(this.collapseBtn){
48285 this.collapseBtn.setVisible(c.collapsible == true);
48287 this.cmargins = c.cmargins || this.cmargins ||
48288 (this.position == "west" || this.position == "east" ?
48289 {top: 0, left: 2, right:2, bottom: 0} :
48290 {top: 2, left: 0, right:0, bottom: 2});
48291 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
48292 this.bottomTabs = c.tabPosition != "top";
48293 this.autoScroll = c.autoScroll || false;
48294 if(this.autoScroll){
48295 this.bodyEl.setStyle("overflow", "auto");
48297 this.bodyEl.setStyle("overflow", "hidden");
48299 //if(c.titlebar !== false){
48300 if((!c.titlebar && !c.title) || c.titlebar === false){
48301 this.titleEl.hide();
48303 this.titleEl.show();
48305 this.titleTextEl.innerHTML = c.title;
48309 this.duration = c.duration || .30;
48310 this.slideDuration = c.slideDuration || .45;
48313 this.collapse(true);
48320 * Returns true if this region is currently visible.
48321 * @return {Boolean}
48323 isVisible : function(){
48324 return this.visible;
48328 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
48329 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
48331 setCollapsedTitle : function(title){
48332 title = title || " ";
48333 if(this.collapsedTitleTextEl){
48334 this.collapsedTitleTextEl.innerHTML = title;
48338 getBox : function(){
48340 if(!this.collapsed){
48341 b = this.el.getBox(false, true);
48343 b = this.collapsedEl.getBox(false, true);
48348 getMargins : function(){
48349 return this.collapsed ? this.cmargins : this.margins;
48352 highlight : function(){
48353 this.el.addClass("x-layout-panel-dragover");
48356 unhighlight : function(){
48357 this.el.removeClass("x-layout-panel-dragover");
48360 updateBox : function(box){
48362 if(!this.collapsed){
48363 this.el.dom.style.left = box.x + "px";
48364 this.el.dom.style.top = box.y + "px";
48365 this.updateBody(box.width, box.height);
48367 this.collapsedEl.dom.style.left = box.x + "px";
48368 this.collapsedEl.dom.style.top = box.y + "px";
48369 this.collapsedEl.setSize(box.width, box.height);
48372 this.tabs.autoSizeTabs();
48376 updateBody : function(w, h){
48378 this.el.setWidth(w);
48379 w -= this.el.getBorderWidth("rl");
48380 if(this.config.adjustments){
48381 w += this.config.adjustments[0];
48385 this.el.setHeight(h);
48386 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
48387 h -= this.el.getBorderWidth("tb");
48388 if(this.config.adjustments){
48389 h += this.config.adjustments[1];
48391 this.bodyEl.setHeight(h);
48393 h = this.tabs.syncHeight(h);
48396 if(this.panelSize){
48397 w = w !== null ? w : this.panelSize.width;
48398 h = h !== null ? h : this.panelSize.height;
48400 if(this.activePanel){
48401 var el = this.activePanel.getEl();
48402 w = w !== null ? w : el.getWidth();
48403 h = h !== null ? h : el.getHeight();
48404 this.panelSize = {width: w, height: h};
48405 this.activePanel.setSize(w, h);
48407 if(Roo.isIE && this.tabs){
48408 this.tabs.el.repaint();
48413 * Returns the container element for this region.
48414 * @return {Roo.Element}
48416 getEl : function(){
48421 * Hides this region.
48424 if(!this.collapsed){
48425 this.el.dom.style.left = "-2000px";
48428 this.collapsedEl.dom.style.left = "-2000px";
48429 this.collapsedEl.hide();
48431 this.visible = false;
48432 this.fireEvent("visibilitychange", this, false);
48436 * Shows this region if it was previously hidden.
48439 if(!this.collapsed){
48442 this.collapsedEl.show();
48444 this.visible = true;
48445 this.fireEvent("visibilitychange", this, true);
48448 closeClicked : function(){
48449 if(this.activePanel){
48450 this.remove(this.activePanel);
48454 collapseClick : function(e){
48456 e.stopPropagation();
48459 e.stopPropagation();
48465 * Collapses this region.
48466 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
48468 collapse : function(skipAnim){
48469 if(this.collapsed) return;
48470 this.collapsed = true;
48472 this.split.el.hide();
48474 if(this.config.animate && skipAnim !== true){
48475 this.fireEvent("invalidated", this);
48476 this.animateCollapse();
48478 this.el.setLocation(-20000,-20000);
48480 this.collapsedEl.show();
48481 this.fireEvent("collapsed", this);
48482 this.fireEvent("invalidated", this);
48486 animateCollapse : function(){
48491 * Expands this region if it was previously collapsed.
48492 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
48493 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
48495 expand : function(e, skipAnim){
48496 if(e) e.stopPropagation();
48497 if(!this.collapsed || this.el.hasActiveFx()) return;
48499 this.afterSlideIn();
48502 this.collapsed = false;
48503 if(this.config.animate && skipAnim !== true){
48504 this.animateExpand();
48508 this.split.el.show();
48510 this.collapsedEl.setLocation(-2000,-2000);
48511 this.collapsedEl.hide();
48512 this.fireEvent("invalidated", this);
48513 this.fireEvent("expanded", this);
48517 animateExpand : function(){
48521 initTabs : function()
48523 this.bodyEl.setStyle("overflow", "hidden");
48524 var ts = new Roo.TabPanel(
48527 tabPosition: this.bottomTabs ? 'bottom' : 'top',
48528 disableTooltips: this.config.disableTabTips,
48529 toolbar : this.config.toolbar
48532 if(this.config.hideTabs){
48533 ts.stripWrap.setDisplayed(false);
48536 ts.resizeTabs = this.config.resizeTabs === true;
48537 ts.minTabWidth = this.config.minTabWidth || 40;
48538 ts.maxTabWidth = this.config.maxTabWidth || 250;
48539 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
48540 ts.monitorResize = false;
48541 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
48542 ts.bodyEl.addClass('x-layout-tabs-body');
48543 this.panels.each(this.initPanelAsTab, this);
48546 initPanelAsTab : function(panel){
48547 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
48548 this.config.closeOnTab && panel.isClosable());
48549 if(panel.tabTip !== undefined){
48550 ti.setTooltip(panel.tabTip);
48552 ti.on("activate", function(){
48553 this.setActivePanel(panel);
48555 if(this.config.closeOnTab){
48556 ti.on("beforeclose", function(t, e){
48558 this.remove(panel);
48564 updatePanelTitle : function(panel, title){
48565 if(this.activePanel == panel){
48566 this.updateTitle(title);
48569 var ti = this.tabs.getTab(panel.getEl().id);
48571 if(panel.tabTip !== undefined){
48572 ti.setTooltip(panel.tabTip);
48577 updateTitle : function(title){
48578 if(this.titleTextEl && !this.config.title){
48579 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
48583 setActivePanel : function(panel){
48584 panel = this.getPanel(panel);
48585 if(this.activePanel && this.activePanel != panel){
48586 this.activePanel.setActiveState(false);
48588 this.activePanel = panel;
48589 panel.setActiveState(true);
48590 if(this.panelSize){
48591 panel.setSize(this.panelSize.width, this.panelSize.height);
48594 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
48596 this.updateTitle(panel.getTitle());
48598 this.fireEvent("invalidated", this);
48600 this.fireEvent("panelactivated", this, panel);
48604 * Shows the specified panel.
48605 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
48606 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
48608 showPanel : function(panel){
48609 if(panel = this.getPanel(panel)){
48611 var tab = this.tabs.getTab(panel.getEl().id);
48612 if(tab.isHidden()){
48613 this.tabs.unhideTab(tab.id);
48617 this.setActivePanel(panel);
48624 * Get the active panel for this region.
48625 * @return {Roo.ContentPanel} The active panel or null
48627 getActivePanel : function(){
48628 return this.activePanel;
48631 validateVisibility : function(){
48632 if(this.panels.getCount() < 1){
48633 this.updateTitle(" ");
48634 this.closeBtn.hide();
48637 if(!this.isVisible()){
48644 * Adds the passed ContentPanel(s) to this region.
48645 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
48646 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
48648 add : function(panel){
48649 if(arguments.length > 1){
48650 for(var i = 0, len = arguments.length; i < len; i++) {
48651 this.add(arguments[i]);
48655 if(this.hasPanel(panel)){
48656 this.showPanel(panel);
48659 panel.setRegion(this);
48660 this.panels.add(panel);
48661 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
48662 this.bodyEl.dom.appendChild(panel.getEl().dom);
48663 if(panel.background !== true){
48664 this.setActivePanel(panel);
48666 this.fireEvent("paneladded", this, panel);
48672 this.initPanelAsTab(panel);
48674 if(panel.background !== true){
48675 this.tabs.activate(panel.getEl().id);
48677 this.fireEvent("paneladded", this, panel);
48682 * Hides the tab for the specified panel.
48683 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
48685 hidePanel : function(panel){
48686 if(this.tabs && (panel = this.getPanel(panel))){
48687 this.tabs.hideTab(panel.getEl().id);
48692 * Unhides the tab for a previously hidden panel.
48693 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
48695 unhidePanel : function(panel){
48696 if(this.tabs && (panel = this.getPanel(panel))){
48697 this.tabs.unhideTab(panel.getEl().id);
48701 clearPanels : function(){
48702 while(this.panels.getCount() > 0){
48703 this.remove(this.panels.first());
48708 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
48709 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
48710 * @param {Boolean} preservePanel Overrides the config preservePanel option
48711 * @return {Roo.ContentPanel} The panel that was removed
48713 remove : function(panel, preservePanel){
48714 panel = this.getPanel(panel);
48719 this.fireEvent("beforeremove", this, panel, e);
48720 if(e.cancel === true){
48723 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
48724 var panelId = panel.getId();
48725 this.panels.removeKey(panelId);
48727 document.body.appendChild(panel.getEl().dom);
48730 this.tabs.removeTab(panel.getEl().id);
48731 }else if (!preservePanel){
48732 this.bodyEl.dom.removeChild(panel.getEl().dom);
48734 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
48735 var p = this.panels.first();
48736 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
48737 tempEl.appendChild(p.getEl().dom);
48738 this.bodyEl.update("");
48739 this.bodyEl.dom.appendChild(p.getEl().dom);
48741 this.updateTitle(p.getTitle());
48743 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
48744 this.setActivePanel(p);
48746 panel.setRegion(null);
48747 if(this.activePanel == panel){
48748 this.activePanel = null;
48750 if(this.config.autoDestroy !== false && preservePanel !== true){
48751 try{panel.destroy();}catch(e){}
48753 this.fireEvent("panelremoved", this, panel);
48758 * Returns the TabPanel component used by this region
48759 * @return {Roo.TabPanel}
48761 getTabs : function(){
48765 createTool : function(parentEl, className){
48766 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
48767 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
48768 btn.addClassOnOver("x-layout-tools-button-over");
48773 * Ext JS Library 1.1.1
48774 * Copyright(c) 2006-2007, Ext JS, LLC.
48776 * Originally Released Under LGPL - original licence link has changed is not relivant.
48779 * <script type="text/javascript">
48785 * @class Roo.SplitLayoutRegion
48786 * @extends Roo.LayoutRegion
48787 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
48789 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
48790 this.cursor = cursor;
48791 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
48794 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
48795 splitTip : "Drag to resize.",
48796 collapsibleSplitTip : "Drag to resize. Double click to hide.",
48797 useSplitTips : false,
48799 applyConfig : function(config){
48800 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
48803 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
48804 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
48805 /** The SplitBar for this region
48806 * @type Roo.SplitBar */
48807 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
48808 this.split.on("moved", this.onSplitMove, this);
48809 this.split.useShim = config.useShim === true;
48810 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
48811 if(this.useSplitTips){
48812 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
48814 if(config.collapsible){
48815 this.split.el.on("dblclick", this.collapse, this);
48818 if(typeof config.minSize != "undefined"){
48819 this.split.minSize = config.minSize;
48821 if(typeof config.maxSize != "undefined"){
48822 this.split.maxSize = config.maxSize;
48824 if(config.hideWhenEmpty || config.hidden || config.collapsed){
48825 this.hideSplitter();
48830 getHMaxSize : function(){
48831 var cmax = this.config.maxSize || 10000;
48832 var center = this.mgr.getRegion("center");
48833 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
48836 getVMaxSize : function(){
48837 var cmax = this.config.maxSize || 10000;
48838 var center = this.mgr.getRegion("center");
48839 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
48842 onSplitMove : function(split, newSize){
48843 this.fireEvent("resized", this, newSize);
48847 * Returns the {@link Roo.SplitBar} for this region.
48848 * @return {Roo.SplitBar}
48850 getSplitBar : function(){
48855 this.hideSplitter();
48856 Roo.SplitLayoutRegion.superclass.hide.call(this);
48859 hideSplitter : function(){
48861 this.split.el.setLocation(-2000,-2000);
48862 this.split.el.hide();
48868 this.split.el.show();
48870 Roo.SplitLayoutRegion.superclass.show.call(this);
48873 beforeSlide: function(){
48874 if(Roo.isGecko){// firefox overflow auto bug workaround
48875 this.bodyEl.clip();
48876 if(this.tabs) this.tabs.bodyEl.clip();
48877 if(this.activePanel){
48878 this.activePanel.getEl().clip();
48880 if(this.activePanel.beforeSlide){
48881 this.activePanel.beforeSlide();
48887 afterSlide : function(){
48888 if(Roo.isGecko){// firefox overflow auto bug workaround
48889 this.bodyEl.unclip();
48890 if(this.tabs) this.tabs.bodyEl.unclip();
48891 if(this.activePanel){
48892 this.activePanel.getEl().unclip();
48893 if(this.activePanel.afterSlide){
48894 this.activePanel.afterSlide();
48900 initAutoHide : function(){
48901 if(this.autoHide !== false){
48902 if(!this.autoHideHd){
48903 var st = new Roo.util.DelayedTask(this.slideIn, this);
48904 this.autoHideHd = {
48905 "mouseout": function(e){
48906 if(!e.within(this.el, true)){
48910 "mouseover" : function(e){
48916 this.el.on(this.autoHideHd);
48920 clearAutoHide : function(){
48921 if(this.autoHide !== false){
48922 this.el.un("mouseout", this.autoHideHd.mouseout);
48923 this.el.un("mouseover", this.autoHideHd.mouseover);
48927 clearMonitor : function(){
48928 Roo.get(document).un("click", this.slideInIf, this);
48931 // these names are backwards but not changed for compat
48932 slideOut : function(){
48933 if(this.isSlid || this.el.hasActiveFx()){
48936 this.isSlid = true;
48937 if(this.collapseBtn){
48938 this.collapseBtn.hide();
48940 this.closeBtnState = this.closeBtn.getStyle('display');
48941 this.closeBtn.hide();
48943 this.stickBtn.show();
48946 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
48947 this.beforeSlide();
48948 this.el.setStyle("z-index", 10001);
48949 this.el.slideIn(this.getSlideAnchor(), {
48950 callback: function(){
48952 this.initAutoHide();
48953 Roo.get(document).on("click", this.slideInIf, this);
48954 this.fireEvent("slideshow", this);
48961 afterSlideIn : function(){
48962 this.clearAutoHide();
48963 this.isSlid = false;
48964 this.clearMonitor();
48965 this.el.setStyle("z-index", "");
48966 if(this.collapseBtn){
48967 this.collapseBtn.show();
48969 this.closeBtn.setStyle('display', this.closeBtnState);
48971 this.stickBtn.hide();
48973 this.fireEvent("slidehide", this);
48976 slideIn : function(cb){
48977 if(!this.isSlid || this.el.hasActiveFx()){
48981 this.isSlid = false;
48982 this.beforeSlide();
48983 this.el.slideOut(this.getSlideAnchor(), {
48984 callback: function(){
48985 this.el.setLeftTop(-10000, -10000);
48987 this.afterSlideIn();
48995 slideInIf : function(e){
48996 if(!e.within(this.el)){
49001 animateCollapse : function(){
49002 this.beforeSlide();
49003 this.el.setStyle("z-index", 20000);
49004 var anchor = this.getSlideAnchor();
49005 this.el.slideOut(anchor, {
49006 callback : function(){
49007 this.el.setStyle("z-index", "");
49008 this.collapsedEl.slideIn(anchor, {duration:.3});
49010 this.el.setLocation(-10000,-10000);
49012 this.fireEvent("collapsed", this);
49019 animateExpand : function(){
49020 this.beforeSlide();
49021 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
49022 this.el.setStyle("z-index", 20000);
49023 this.collapsedEl.hide({
49026 this.el.slideIn(this.getSlideAnchor(), {
49027 callback : function(){
49028 this.el.setStyle("z-index", "");
49031 this.split.el.show();
49033 this.fireEvent("invalidated", this);
49034 this.fireEvent("expanded", this);
49062 getAnchor : function(){
49063 return this.anchors[this.position];
49066 getCollapseAnchor : function(){
49067 return this.canchors[this.position];
49070 getSlideAnchor : function(){
49071 return this.sanchors[this.position];
49074 getAlignAdj : function(){
49075 var cm = this.cmargins;
49076 switch(this.position){
49092 getExpandAdj : function(){
49093 var c = this.collapsedEl, cm = this.cmargins;
49094 switch(this.position){
49096 return [-(cm.right+c.getWidth()+cm.left), 0];
49099 return [cm.right+c.getWidth()+cm.left, 0];
49102 return [0, -(cm.top+cm.bottom+c.getHeight())];
49105 return [0, cm.top+cm.bottom+c.getHeight()];
49111 * Ext JS Library 1.1.1
49112 * Copyright(c) 2006-2007, Ext JS, LLC.
49114 * Originally Released Under LGPL - original licence link has changed is not relivant.
49117 * <script type="text/javascript">
49120 * These classes are private internal classes
49122 Roo.CenterLayoutRegion = function(mgr, config){
49123 Roo.LayoutRegion.call(this, mgr, config, "center");
49124 this.visible = true;
49125 this.minWidth = config.minWidth || 20;
49126 this.minHeight = config.minHeight || 20;
49129 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
49131 // center panel can't be hidden
49135 // center panel can't be hidden
49138 getMinWidth: function(){
49139 return this.minWidth;
49142 getMinHeight: function(){
49143 return this.minHeight;
49148 Roo.NorthLayoutRegion = function(mgr, config){
49149 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
49151 this.split.placement = Roo.SplitBar.TOP;
49152 this.split.orientation = Roo.SplitBar.VERTICAL;
49153 this.split.el.addClass("x-layout-split-v");
49155 var size = config.initialSize || config.height;
49156 if(typeof size != "undefined"){
49157 this.el.setHeight(size);
49160 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
49161 orientation: Roo.SplitBar.VERTICAL,
49162 getBox : function(){
49163 if(this.collapsed){
49164 return this.collapsedEl.getBox();
49166 var box = this.el.getBox();
49168 box.height += this.split.el.getHeight();
49173 updateBox : function(box){
49174 if(this.split && !this.collapsed){
49175 box.height -= this.split.el.getHeight();
49176 this.split.el.setLeft(box.x);
49177 this.split.el.setTop(box.y+box.height);
49178 this.split.el.setWidth(box.width);
49180 if(this.collapsed){
49181 this.updateBody(box.width, null);
49183 Roo.LayoutRegion.prototype.updateBox.call(this, box);
49187 Roo.SouthLayoutRegion = function(mgr, config){
49188 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
49190 this.split.placement = Roo.SplitBar.BOTTOM;
49191 this.split.orientation = Roo.SplitBar.VERTICAL;
49192 this.split.el.addClass("x-layout-split-v");
49194 var size = config.initialSize || config.height;
49195 if(typeof size != "undefined"){
49196 this.el.setHeight(size);
49199 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
49200 orientation: Roo.SplitBar.VERTICAL,
49201 getBox : function(){
49202 if(this.collapsed){
49203 return this.collapsedEl.getBox();
49205 var box = this.el.getBox();
49207 var sh = this.split.el.getHeight();
49214 updateBox : function(box){
49215 if(this.split && !this.collapsed){
49216 var sh = this.split.el.getHeight();
49219 this.split.el.setLeft(box.x);
49220 this.split.el.setTop(box.y-sh);
49221 this.split.el.setWidth(box.width);
49223 if(this.collapsed){
49224 this.updateBody(box.width, null);
49226 Roo.LayoutRegion.prototype.updateBox.call(this, box);
49230 Roo.EastLayoutRegion = function(mgr, config){
49231 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
49233 this.split.placement = Roo.SplitBar.RIGHT;
49234 this.split.orientation = Roo.SplitBar.HORIZONTAL;
49235 this.split.el.addClass("x-layout-split-h");
49237 var size = config.initialSize || config.width;
49238 if(typeof size != "undefined"){
49239 this.el.setWidth(size);
49242 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
49243 orientation: Roo.SplitBar.HORIZONTAL,
49244 getBox : function(){
49245 if(this.collapsed){
49246 return this.collapsedEl.getBox();
49248 var box = this.el.getBox();
49250 var sw = this.split.el.getWidth();
49257 updateBox : function(box){
49258 if(this.split && !this.collapsed){
49259 var sw = this.split.el.getWidth();
49261 this.split.el.setLeft(box.x);
49262 this.split.el.setTop(box.y);
49263 this.split.el.setHeight(box.height);
49266 if(this.collapsed){
49267 this.updateBody(null, box.height);
49269 Roo.LayoutRegion.prototype.updateBox.call(this, box);
49273 Roo.WestLayoutRegion = function(mgr, config){
49274 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
49276 this.split.placement = Roo.SplitBar.LEFT;
49277 this.split.orientation = Roo.SplitBar.HORIZONTAL;
49278 this.split.el.addClass("x-layout-split-h");
49280 var size = config.initialSize || config.width;
49281 if(typeof size != "undefined"){
49282 this.el.setWidth(size);
49285 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
49286 orientation: Roo.SplitBar.HORIZONTAL,
49287 getBox : function(){
49288 if(this.collapsed){
49289 return this.collapsedEl.getBox();
49291 var box = this.el.getBox();
49293 box.width += this.split.el.getWidth();
49298 updateBox : function(box){
49299 if(this.split && !this.collapsed){
49300 var sw = this.split.el.getWidth();
49302 this.split.el.setLeft(box.x+box.width);
49303 this.split.el.setTop(box.y);
49304 this.split.el.setHeight(box.height);
49306 if(this.collapsed){
49307 this.updateBody(null, box.height);
49309 Roo.LayoutRegion.prototype.updateBox.call(this, box);
49314 * Ext JS Library 1.1.1
49315 * Copyright(c) 2006-2007, Ext JS, LLC.
49317 * Originally Released Under LGPL - original licence link has changed is not relivant.
49320 * <script type="text/javascript">
49325 * Private internal class for reading and applying state
49327 Roo.LayoutStateManager = function(layout){
49328 // default empty state
49337 Roo.LayoutStateManager.prototype = {
49338 init : function(layout, provider){
49339 this.provider = provider;
49340 var state = provider.get(layout.id+"-layout-state");
49342 var wasUpdating = layout.isUpdating();
49344 layout.beginUpdate();
49346 for(var key in state){
49347 if(typeof state[key] != "function"){
49348 var rstate = state[key];
49349 var r = layout.getRegion(key);
49352 r.resizeTo(rstate.size);
49354 if(rstate.collapsed == true){
49357 r.expand(null, true);
49363 layout.endUpdate();
49365 this.state = state;
49367 this.layout = layout;
49368 layout.on("regionresized", this.onRegionResized, this);
49369 layout.on("regioncollapsed", this.onRegionCollapsed, this);
49370 layout.on("regionexpanded", this.onRegionExpanded, this);
49373 storeState : function(){
49374 this.provider.set(this.layout.id+"-layout-state", this.state);
49377 onRegionResized : function(region, newSize){
49378 this.state[region.getPosition()].size = newSize;
49382 onRegionCollapsed : function(region){
49383 this.state[region.getPosition()].collapsed = true;
49387 onRegionExpanded : function(region){
49388 this.state[region.getPosition()].collapsed = false;
49393 * Ext JS Library 1.1.1
49394 * Copyright(c) 2006-2007, Ext JS, LLC.
49396 * Originally Released Under LGPL - original licence link has changed is not relivant.
49399 * <script type="text/javascript">
49402 * @class Roo.ContentPanel
49403 * @extends Roo.util.Observable
49404 * A basic ContentPanel element.
49405 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
49406 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
49407 * @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
49408 * @cfg {Boolean} closable True if the panel can be closed/removed
49409 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
49410 * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
49411 * @cfg {Toolbar} toolbar A toolbar for this panel
49412 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
49413 * @cfg {String} title The title for this panel
49414 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
49415 * @cfg {String} url Calls {@link #setUrl} with this value
49416 * @cfg {String} region (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
49417 * @cfg {String/Object} params When used with {@link #url}, calls {@link #setUrl} with this value
49418 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
49419 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
49422 * Create a new ContentPanel.
49423 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
49424 * @param {String/Object} config A string to set only the title or a config object
49425 * @param {String} content (optional) Set the HTML content for this panel
49426 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
49428 Roo.ContentPanel = function(el, config, content){
49432 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
49436 if (config && config.parentLayout) {
49437 el = config.parentLayout.el.createChild();
49440 if(el.autoCreate){ // xtype is available if this is called from factory
49444 this.el = Roo.get(el);
49445 if(!this.el && config && config.autoCreate){
49446 if(typeof config.autoCreate == "object"){
49447 if(!config.autoCreate.id){
49448 config.autoCreate.id = config.id||el;
49450 this.el = Roo.DomHelper.append(document.body,
49451 config.autoCreate, true);
49453 this.el = Roo.DomHelper.append(document.body,
49454 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
49457 this.closable = false;
49458 this.loaded = false;
49459 this.active = false;
49460 if(typeof config == "string"){
49461 this.title = config;
49463 Roo.apply(this, config);
49466 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
49467 this.wrapEl = this.el.wrap();
49468 this.toolbar.container = this.el.insertSibling(false, 'before');
49469 this.toolbar = new Roo.Toolbar(this.toolbar);
49472 // xtype created footer. - not sure if will work as we normally have to render first..
49473 if (this.footer && !this.footer.el && this.footer.xtype) {
49474 if (!this.wrapEl) {
49475 this.wrapEl = this.el.wrap();
49478 this.footer.container = this.wrapEl.createChild();
49480 this.footer = Roo.factory(this.footer, Roo);
49485 this.resizeEl = Roo.get(this.resizeEl, true);
49487 this.resizeEl = this.el;
49489 // handle view.xtype
49497 * Fires when this panel is activated.
49498 * @param {Roo.ContentPanel} this
49502 * @event deactivate
49503 * Fires when this panel is activated.
49504 * @param {Roo.ContentPanel} this
49506 "deactivate" : true,
49510 * Fires when this panel is resized if fitToFrame is true.
49511 * @param {Roo.ContentPanel} this
49512 * @param {Number} width The width after any component adjustments
49513 * @param {Number} height The height after any component adjustments
49519 * Fires when this tab is created
49520 * @param {Roo.ContentPanel} this
49531 if(this.autoScroll){
49532 this.resizeEl.setStyle("overflow", "auto");
49534 // fix randome scrolling
49535 this.el.on('scroll', function() {
49536 Roo.log('fix random scolling');
49537 this.scrollTo('top',0);
49540 content = content || this.content;
49542 this.setContent(content);
49544 if(config && config.url){
49545 this.setUrl(this.url, this.params, this.loadOnce);
49550 Roo.ContentPanel.superclass.constructor.call(this);
49552 if (this.view && typeof(this.view.xtype) != 'undefined') {
49553 this.view.el = this.el.appendChild(document.createElement("div"));
49554 this.view = Roo.factory(this.view);
49555 this.view.render && this.view.render(false, '');
49559 this.fireEvent('render', this);
49562 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
49564 setRegion : function(region){
49565 this.region = region;
49567 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
49569 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
49574 * Returns the toolbar for this Panel if one was configured.
49575 * @return {Roo.Toolbar}
49577 getToolbar : function(){
49578 return this.toolbar;
49581 setActiveState : function(active){
49582 this.active = active;
49584 this.fireEvent("deactivate", this);
49586 this.fireEvent("activate", this);
49590 * Updates this panel's element
49591 * @param {String} content The new content
49592 * @param {Boolean} loadScripts (optional) true to look for and process scripts
49594 setContent : function(content, loadScripts){
49595 this.el.update(content, loadScripts);
49598 ignoreResize : function(w, h){
49599 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
49602 this.lastSize = {width: w, height: h};
49607 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
49608 * @return {Roo.UpdateManager} The UpdateManager
49610 getUpdateManager : function(){
49611 return this.el.getUpdateManager();
49614 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
49615 * @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:
49618 url: "your-url.php",
49619 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
49620 callback: yourFunction,
49621 scope: yourObject, //(optional scope)
49624 text: "Loading...",
49629 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
49630 * 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.
49631 * @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}
49632 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
49633 * @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.
49634 * @return {Roo.ContentPanel} this
49637 var um = this.el.getUpdateManager();
49638 um.update.apply(um, arguments);
49644 * 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.
49645 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
49646 * @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)
49647 * @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)
49648 * @return {Roo.UpdateManager} The UpdateManager
49650 setUrl : function(url, params, loadOnce){
49651 if(this.refreshDelegate){
49652 this.removeListener("activate", this.refreshDelegate);
49654 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
49655 this.on("activate", this.refreshDelegate);
49656 return this.el.getUpdateManager();
49659 _handleRefresh : function(url, params, loadOnce){
49660 if(!loadOnce || !this.loaded){
49661 var updater = this.el.getUpdateManager();
49662 updater.update(url, params, this._setLoaded.createDelegate(this));
49666 _setLoaded : function(){
49667 this.loaded = true;
49671 * Returns this panel's id
49674 getId : function(){
49679 * Returns this panel's element - used by regiosn to add.
49680 * @return {Roo.Element}
49682 getEl : function(){
49683 return this.wrapEl || this.el;
49686 adjustForComponents : function(width, height)
49688 //Roo.log('adjustForComponents ');
49689 if(this.resizeEl != this.el){
49690 width -= this.el.getFrameWidth('lr');
49691 height -= this.el.getFrameWidth('tb');
49694 var te = this.toolbar.getEl();
49695 height -= te.getHeight();
49696 te.setWidth(width);
49699 var te = this.footer.getEl();
49700 Roo.log("footer:" + te.getHeight());
49702 height -= te.getHeight();
49703 te.setWidth(width);
49707 if(this.adjustments){
49708 width += this.adjustments[0];
49709 height += this.adjustments[1];
49711 return {"width": width, "height": height};
49714 setSize : function(width, height){
49715 if(this.fitToFrame && !this.ignoreResize(width, height)){
49716 if(this.fitContainer && this.resizeEl != this.el){
49717 this.el.setSize(width, height);
49719 var size = this.adjustForComponents(width, height);
49720 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
49721 this.fireEvent('resize', this, size.width, size.height);
49726 * Returns this panel's title
49729 getTitle : function(){
49734 * Set this panel's title
49735 * @param {String} title
49737 setTitle : function(title){
49738 this.title = title;
49740 this.region.updatePanelTitle(this, title);
49745 * Returns true is this panel was configured to be closable
49746 * @return {Boolean}
49748 isClosable : function(){
49749 return this.closable;
49752 beforeSlide : function(){
49754 this.resizeEl.clip();
49757 afterSlide : function(){
49759 this.resizeEl.unclip();
49763 * Force a content refresh from the URL specified in the {@link #setUrl} method.
49764 * Will fail silently if the {@link #setUrl} method has not been called.
49765 * This does not activate the panel, just updates its content.
49767 refresh : function(){
49768 if(this.refreshDelegate){
49769 this.loaded = false;
49770 this.refreshDelegate();
49775 * Destroys this panel
49777 destroy : function(){
49778 this.el.removeAllListeners();
49779 var tempEl = document.createElement("span");
49780 tempEl.appendChild(this.el.dom);
49781 tempEl.innerHTML = "";
49787 * form - if the content panel contains a form - this is a reference to it.
49788 * @type {Roo.form.Form}
49792 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
49793 * This contains a reference to it.
49799 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
49809 * @param {Object} cfg Xtype definition of item to add.
49812 addxtype : function(cfg) {
49814 if (cfg.xtype.match(/^Form$/)) {
49817 //if (this.footer) {
49818 // el = this.footer.container.insertSibling(false, 'before');
49820 el = this.el.createChild();
49823 this.form = new Roo.form.Form(cfg);
49826 if ( this.form.allItems.length) this.form.render(el.dom);
49829 // should only have one of theses..
49830 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
49831 // views.. should not be just added - used named prop 'view''
49833 cfg.el = this.el.appendChild(document.createElement("div"));
49836 var ret = new Roo.factory(cfg);
49838 ret.render && ret.render(false, ''); // render blank..
49847 * @class Roo.GridPanel
49848 * @extends Roo.ContentPanel
49850 * Create a new GridPanel.
49851 * @param {Roo.grid.Grid} grid The grid for this panel
49852 * @param {String/Object} config A string to set only the panel's title, or a config object
49854 Roo.GridPanel = function(grid, config){
49857 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
49858 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
49860 this.wrapper.dom.appendChild(grid.getGridEl().dom);
49862 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
49865 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
49867 // xtype created footer. - not sure if will work as we normally have to render first..
49868 if (this.footer && !this.footer.el && this.footer.xtype) {
49870 this.footer.container = this.grid.getView().getFooterPanel(true);
49871 this.footer.dataSource = this.grid.dataSource;
49872 this.footer = Roo.factory(this.footer, Roo);
49876 grid.monitorWindowResize = false; // turn off autosizing
49877 grid.autoHeight = false;
49878 grid.autoWidth = false;
49880 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
49883 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
49884 getId : function(){
49885 return this.grid.id;
49889 * Returns the grid for this panel
49890 * @return {Roo.grid.Grid}
49892 getGrid : function(){
49896 setSize : function(width, height){
49897 if(!this.ignoreResize(width, height)){
49898 var grid = this.grid;
49899 var size = this.adjustForComponents(width, height);
49900 grid.getGridEl().setSize(size.width, size.height);
49905 beforeSlide : function(){
49906 this.grid.getView().scroller.clip();
49909 afterSlide : function(){
49910 this.grid.getView().scroller.unclip();
49913 destroy : function(){
49914 this.grid.destroy();
49916 Roo.GridPanel.superclass.destroy.call(this);
49922 * @class Roo.NestedLayoutPanel
49923 * @extends Roo.ContentPanel
49925 * Create a new NestedLayoutPanel.
49928 * @param {Roo.BorderLayout} layout The layout for this panel
49929 * @param {String/Object} config A string to set only the title or a config object
49931 Roo.NestedLayoutPanel = function(layout, config)
49933 // construct with only one argument..
49934 /* FIXME - implement nicer consturctors
49935 if (layout.layout) {
49937 layout = config.layout;
49938 delete config.layout;
49940 if (layout.xtype && !layout.getEl) {
49941 // then layout needs constructing..
49942 layout = Roo.factory(layout, Roo);
49947 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
49949 layout.monitorWindowResize = false; // turn off autosizing
49950 this.layout = layout;
49951 this.layout.getEl().addClass("x-layout-nested-layout");
49958 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
49960 setSize : function(width, height){
49961 if(!this.ignoreResize(width, height)){
49962 var size = this.adjustForComponents(width, height);
49963 var el = this.layout.getEl();
49964 el.setSize(size.width, size.height);
49965 var touch = el.dom.offsetWidth;
49966 this.layout.layout();
49967 // ie requires a double layout on the first pass
49968 if(Roo.isIE && !this.initialized){
49969 this.initialized = true;
49970 this.layout.layout();
49975 // activate all subpanels if not currently active..
49977 setActiveState : function(active){
49978 this.active = active;
49980 this.fireEvent("deactivate", this);
49984 this.fireEvent("activate", this);
49985 // not sure if this should happen before or after..
49986 if (!this.layout) {
49987 return; // should not happen..
49990 for (var r in this.layout.regions) {
49991 reg = this.layout.getRegion(r);
49992 if (reg.getActivePanel()) {
49993 //reg.showPanel(reg.getActivePanel()); // force it to activate..
49994 reg.setActivePanel(reg.getActivePanel());
49997 if (!reg.panels.length) {
50000 reg.showPanel(reg.getPanel(0));
50009 * Returns the nested BorderLayout for this panel
50010 * @return {Roo.BorderLayout}
50012 getLayout : function(){
50013 return this.layout;
50017 * Adds a xtype elements to the layout of the nested panel
50021 xtype : 'ContentPanel',
50028 xtype : 'NestedLayoutPanel',
50034 items : [ ... list of content panels or nested layout panels.. ]
50038 * @param {Object} cfg Xtype definition of item to add.
50040 addxtype : function(cfg) {
50041 return this.layout.addxtype(cfg);
50046 Roo.ScrollPanel = function(el, config, content){
50047 config = config || {};
50048 config.fitToFrame = true;
50049 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
50051 this.el.dom.style.overflow = "hidden";
50052 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
50053 this.el.removeClass("x-layout-inactive-content");
50054 this.el.on("mousewheel", this.onWheel, this);
50056 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
50057 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
50058 up.unselectable(); down.unselectable();
50059 up.on("click", this.scrollUp, this);
50060 down.on("click", this.scrollDown, this);
50061 up.addClassOnOver("x-scroller-btn-over");
50062 down.addClassOnOver("x-scroller-btn-over");
50063 up.addClassOnClick("x-scroller-btn-click");
50064 down.addClassOnClick("x-scroller-btn-click");
50065 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
50067 this.resizeEl = this.el;
50068 this.el = wrap; this.up = up; this.down = down;
50071 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
50073 wheelIncrement : 5,
50074 scrollUp : function(){
50075 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
50078 scrollDown : function(){
50079 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
50082 afterScroll : function(){
50083 var el = this.resizeEl;
50084 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
50085 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
50086 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
50089 setSize : function(){
50090 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
50091 this.afterScroll();
50094 onWheel : function(e){
50095 var d = e.getWheelDelta();
50096 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
50097 this.afterScroll();
50101 setContent : function(content, loadScripts){
50102 this.resizeEl.update(content, loadScripts);
50116 * @class Roo.TreePanel
50117 * @extends Roo.ContentPanel
50119 * Create a new TreePanel. - defaults to fit/scoll contents.
50120 * @param {String/Object} config A string to set only the panel's title, or a config object
50121 * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
50123 Roo.TreePanel = function(config){
50124 var el = config.el;
50125 var tree = config.tree;
50126 delete config.tree;
50127 delete config.el; // hopefull!
50129 // wrapper for IE7 strict & safari scroll issue
50131 var treeEl = el.createChild();
50132 config.resizeEl = treeEl;
50136 Roo.TreePanel.superclass.constructor.call(this, el, config);
50139 this.tree = new Roo.tree.TreePanel(treeEl , tree);
50140 //console.log(tree);
50141 this.on('activate', function()
50143 if (this.tree.rendered) {
50146 //console.log('render tree');
50147 this.tree.render();
50149 // this should not be needed.. - it's actually the 'el' that resizes?
50150 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
50152 //this.on('resize', function (cp, w, h) {
50153 // this.tree.innerCt.setWidth(w);
50154 // this.tree.innerCt.setHeight(h);
50155 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
50162 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
50179 * Ext JS Library 1.1.1
50180 * Copyright(c) 2006-2007, Ext JS, LLC.
50182 * Originally Released Under LGPL - original licence link has changed is not relivant.
50185 * <script type="text/javascript">
50190 * @class Roo.ReaderLayout
50191 * @extends Roo.BorderLayout
50192 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
50193 * center region containing two nested regions (a top one for a list view and one for item preview below),
50194 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
50195 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
50196 * expedites the setup of the overall layout and regions for this common application style.
50199 var reader = new Roo.ReaderLayout();
50200 var CP = Roo.ContentPanel; // shortcut for adding
50202 reader.beginUpdate();
50203 reader.add("north", new CP("north", "North"));
50204 reader.add("west", new CP("west", {title: "West"}));
50205 reader.add("east", new CP("east", {title: "East"}));
50207 reader.regions.listView.add(new CP("listView", "List"));
50208 reader.regions.preview.add(new CP("preview", "Preview"));
50209 reader.endUpdate();
50212 * Create a new ReaderLayout
50213 * @param {Object} config Configuration options
50214 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
50215 * document.body if omitted)
50217 Roo.ReaderLayout = function(config, renderTo){
50218 var c = config || {size:{}};
50219 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
50220 north: c.north !== false ? Roo.apply({
50224 }, c.north) : false,
50225 west: c.west !== false ? Roo.apply({
50233 margins:{left:5,right:0,bottom:5,top:5},
50234 cmargins:{left:5,right:5,bottom:5,top:5}
50235 }, c.west) : false,
50236 east: c.east !== false ? Roo.apply({
50244 margins:{left:0,right:5,bottom:5,top:5},
50245 cmargins:{left:5,right:5,bottom:5,top:5}
50246 }, c.east) : false,
50247 center: Roo.apply({
50248 tabPosition: 'top',
50252 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
50256 this.el.addClass('x-reader');
50258 this.beginUpdate();
50260 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
50261 south: c.preview !== false ? Roo.apply({
50268 cmargins:{top:5,left:0, right:0, bottom:0}
50269 }, c.preview) : false,
50270 center: Roo.apply({
50276 this.add('center', new Roo.NestedLayoutPanel(inner,
50277 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
50281 this.regions.preview = inner.getRegion('south');
50282 this.regions.listView = inner.getRegion('center');
50285 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
50287 * Ext JS Library 1.1.1
50288 * Copyright(c) 2006-2007, Ext JS, LLC.
50290 * Originally Released Under LGPL - original licence link has changed is not relivant.
50293 * <script type="text/javascript">
50297 * @class Roo.grid.Grid
50298 * @extends Roo.util.Observable
50299 * This class represents the primary interface of a component based grid control.
50300 * <br><br>Usage:<pre><code>
50301 var grid = new Roo.grid.Grid("my-container-id", {
50304 selModel: mySelectionModel,
50305 autoSizeColumns: true,
50306 monitorWindowResize: false,
50307 trackMouseOver: true
50312 * <b>Common Problems:</b><br/>
50313 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
50314 * element will correct this<br/>
50315 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
50316 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
50317 * are unpredictable.<br/>
50318 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
50319 * grid to calculate dimensions/offsets.<br/>
50321 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
50322 * The container MUST have some type of size defined for the grid to fill. The container will be
50323 * automatically set to position relative if it isn't already.
50324 * @param {Object} config A config object that sets properties on this grid.
50326 Roo.grid.Grid = function(container, config){
50327 // initialize the container
50328 this.container = Roo.get(container);
50329 this.container.update("");
50330 this.container.setStyle("overflow", "hidden");
50331 this.container.addClass('x-grid-container');
50333 this.id = this.container.id;
50335 Roo.apply(this, config);
50336 // check and correct shorthanded configs
50338 this.dataSource = this.ds;
50342 this.colModel = this.cm;
50346 this.selModel = this.sm;
50350 if (this.selModel) {
50351 this.selModel = Roo.factory(this.selModel, Roo.grid);
50352 this.sm = this.selModel;
50353 this.sm.xmodule = this.xmodule || false;
50355 if (typeof(this.colModel.config) == 'undefined') {
50356 this.colModel = new Roo.grid.ColumnModel(this.colModel);
50357 this.cm = this.colModel;
50358 this.cm.xmodule = this.xmodule || false;
50360 if (this.dataSource) {
50361 this.dataSource= Roo.factory(this.dataSource, Roo.data);
50362 this.ds = this.dataSource;
50363 this.ds.xmodule = this.xmodule || false;
50370 this.container.setWidth(this.width);
50374 this.container.setHeight(this.height);
50381 * The raw click event for the entire grid.
50382 * @param {Roo.EventObject} e
50387 * The raw dblclick event for the entire grid.
50388 * @param {Roo.EventObject} e
50392 * @event contextmenu
50393 * The raw contextmenu event for the entire grid.
50394 * @param {Roo.EventObject} e
50396 "contextmenu" : true,
50399 * The raw mousedown event for the entire grid.
50400 * @param {Roo.EventObject} e
50402 "mousedown" : true,
50405 * The raw mouseup event for the entire grid.
50406 * @param {Roo.EventObject} e
50411 * The raw mouseover event for the entire grid.
50412 * @param {Roo.EventObject} e
50414 "mouseover" : true,
50417 * The raw mouseout event for the entire grid.
50418 * @param {Roo.EventObject} e
50423 * The raw keypress event for the entire grid.
50424 * @param {Roo.EventObject} e
50429 * The raw keydown event for the entire grid.
50430 * @param {Roo.EventObject} e
50438 * Fires when a cell is clicked
50439 * @param {Grid} this
50440 * @param {Number} rowIndex
50441 * @param {Number} columnIndex
50442 * @param {Roo.EventObject} e
50444 "cellclick" : true,
50446 * @event celldblclick
50447 * Fires when a cell is double clicked
50448 * @param {Grid} this
50449 * @param {Number} rowIndex
50450 * @param {Number} columnIndex
50451 * @param {Roo.EventObject} e
50453 "celldblclick" : true,
50456 * Fires when a row is clicked
50457 * @param {Grid} this
50458 * @param {Number} rowIndex
50459 * @param {Roo.EventObject} e
50463 * @event rowdblclick
50464 * Fires when a row is double clicked
50465 * @param {Grid} this
50466 * @param {Number} rowIndex
50467 * @param {Roo.EventObject} e
50469 "rowdblclick" : true,
50471 * @event headerclick
50472 * Fires when a header is clicked
50473 * @param {Grid} this
50474 * @param {Number} columnIndex
50475 * @param {Roo.EventObject} e
50477 "headerclick" : true,
50479 * @event headerdblclick
50480 * Fires when a header cell is double clicked
50481 * @param {Grid} this
50482 * @param {Number} columnIndex
50483 * @param {Roo.EventObject} e
50485 "headerdblclick" : true,
50487 * @event rowcontextmenu
50488 * Fires when a row is right clicked
50489 * @param {Grid} this
50490 * @param {Number} rowIndex
50491 * @param {Roo.EventObject} e
50493 "rowcontextmenu" : true,
50495 * @event cellcontextmenu
50496 * Fires when a cell is right clicked
50497 * @param {Grid} this
50498 * @param {Number} rowIndex
50499 * @param {Number} cellIndex
50500 * @param {Roo.EventObject} e
50502 "cellcontextmenu" : true,
50504 * @event headercontextmenu
50505 * Fires when a header is right clicked
50506 * @param {Grid} this
50507 * @param {Number} columnIndex
50508 * @param {Roo.EventObject} e
50510 "headercontextmenu" : true,
50512 * @event bodyscroll
50513 * Fires when the body element is scrolled
50514 * @param {Number} scrollLeft
50515 * @param {Number} scrollTop
50517 "bodyscroll" : true,
50519 * @event columnresize
50520 * Fires when the user resizes a column
50521 * @param {Number} columnIndex
50522 * @param {Number} newSize
50524 "columnresize" : true,
50526 * @event columnmove
50527 * Fires when the user moves a column
50528 * @param {Number} oldIndex
50529 * @param {Number} newIndex
50531 "columnmove" : true,
50534 * Fires when row(s) start being dragged
50535 * @param {Grid} this
50536 * @param {Roo.GridDD} dd The drag drop object
50537 * @param {event} e The raw browser event
50539 "startdrag" : true,
50542 * Fires when a drag operation is complete
50543 * @param {Grid} this
50544 * @param {Roo.GridDD} dd The drag drop object
50545 * @param {event} e The raw browser event
50550 * Fires when dragged row(s) are dropped on a valid DD target
50551 * @param {Grid} this
50552 * @param {Roo.GridDD} dd The drag drop object
50553 * @param {String} targetId The target drag drop object
50554 * @param {event} e The raw browser event
50559 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
50560 * @param {Grid} this
50561 * @param {Roo.GridDD} dd The drag drop object
50562 * @param {String} targetId The target drag drop object
50563 * @param {event} e The raw browser event
50568 * Fires when the dragged row(s) first cross another DD target while being dragged
50569 * @param {Grid} this
50570 * @param {Roo.GridDD} dd The drag drop object
50571 * @param {String} targetId The target drag drop object
50572 * @param {event} e The raw browser event
50574 "dragenter" : true,
50577 * Fires when the dragged row(s) leave another DD target while being dragged
50578 * @param {Grid} this
50579 * @param {Roo.GridDD} dd The drag drop object
50580 * @param {String} targetId The target drag drop object
50581 * @param {event} e The raw browser event
50586 * Fires when a row is rendered, so you can change add a style to it.
50587 * @param {GridView} gridview The grid view
50588 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
50594 * Fires when the grid is rendered
50595 * @param {Grid} grid
50600 Roo.grid.Grid.superclass.constructor.call(this);
50602 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
50605 * @cfg {String} ddGroup - drag drop group.
50609 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
50611 minColumnWidth : 25,
50614 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
50615 * <b>on initial render.</b> It is more efficient to explicitly size the columns
50616 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
50618 autoSizeColumns : false,
50621 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
50623 autoSizeHeaders : true,
50626 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
50628 monitorWindowResize : true,
50631 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
50632 * rows measured to get a columns size. Default is 0 (all rows).
50634 maxRowsToMeasure : 0,
50637 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
50639 trackMouseOver : true,
50642 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
50646 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
50648 enableDragDrop : false,
50651 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
50653 enableColumnMove : true,
50656 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
50658 enableColumnHide : true,
50661 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
50663 enableRowHeightSync : false,
50666 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
50671 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
50673 autoHeight : false,
50676 * @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.
50678 autoExpandColumn : false,
50681 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
50684 autoExpandMin : 50,
50687 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
50689 autoExpandMax : 1000,
50692 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
50697 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
50701 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
50711 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
50712 * of a fixed width. Default is false.
50715 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
50718 * Called once after all setup has been completed and the grid is ready to be rendered.
50719 * @return {Roo.grid.Grid} this
50721 render : function()
50723 var c = this.container;
50724 // try to detect autoHeight/width mode
50725 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
50726 this.autoHeight = true;
50728 var view = this.getView();
50731 c.on("click", this.onClick, this);
50732 c.on("dblclick", this.onDblClick, this);
50733 c.on("contextmenu", this.onContextMenu, this);
50734 c.on("keydown", this.onKeyDown, this);
50736 c.on("touchstart", this.onTouchStart, this);
50739 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
50741 this.getSelectionModel().init(this);
50746 this.loadMask = new Roo.LoadMask(this.container,
50747 Roo.apply({store:this.dataSource}, this.loadMask));
50751 if (this.toolbar && this.toolbar.xtype) {
50752 this.toolbar.container = this.getView().getHeaderPanel(true);
50753 this.toolbar = new Roo.Toolbar(this.toolbar);
50755 if (this.footer && this.footer.xtype) {
50756 this.footer.dataSource = this.getDataSource();
50757 this.footer.container = this.getView().getFooterPanel(true);
50758 this.footer = Roo.factory(this.footer, Roo);
50760 if (this.dropTarget && this.dropTarget.xtype) {
50761 delete this.dropTarget.xtype;
50762 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
50766 this.rendered = true;
50767 this.fireEvent('render', this);
50772 * Reconfigures the grid to use a different Store and Column Model.
50773 * The View will be bound to the new objects and refreshed.
50774 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
50775 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
50777 reconfigure : function(dataSource, colModel){
50779 this.loadMask.destroy();
50780 this.loadMask = new Roo.LoadMask(this.container,
50781 Roo.apply({store:dataSource}, this.loadMask));
50783 this.view.bind(dataSource, colModel);
50784 this.dataSource = dataSource;
50785 this.colModel = colModel;
50786 this.view.refresh(true);
50790 onKeyDown : function(e){
50791 this.fireEvent("keydown", e);
50795 * Destroy this grid.
50796 * @param {Boolean} removeEl True to remove the element
50798 destroy : function(removeEl, keepListeners){
50800 this.loadMask.destroy();
50802 var c = this.container;
50803 c.removeAllListeners();
50804 this.view.destroy();
50805 this.colModel.purgeListeners();
50806 if(!keepListeners){
50807 this.purgeListeners();
50810 if(removeEl === true){
50816 processEvent : function(name, e){
50817 // does this fire select???
50818 Roo.log('grid:processEvent ' + name);
50820 if (name != 'touchstart' ) {
50821 this.fireEvent(name, e);
50824 var t = e.getTarget();
50826 var header = v.findHeaderIndex(t);
50827 if(header !== false){
50828 this.fireEvent("header" + (name == 'touchstart' ? 'click' : name), this, header, e);
50830 var row = v.findRowIndex(t);
50831 var cell = v.findCellIndex(t);
50832 if (name == 'touchstart') {
50833 // first touch is always a click.
50834 // hopefull this happens after selection is updated.?
50837 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
50838 var cs = this.selModel.getSelectedCell();
50839 if (row == cs[0] && cell == cs[1]){
50843 if (typeof(this.selModel.getSelections) != 'undefined') {
50844 var cs = this.selModel.getSelections();
50845 var ds = this.dataSource;
50846 if (cs.length == 1 && ds.getAt(row) == cs[0]){
50857 this.fireEvent("row" + name, this, row, e);
50858 if(cell !== false){
50859 this.fireEvent("cell" + name, this, row, cell, e);
50866 onClick : function(e){
50867 this.processEvent("click", e);
50870 onTouchStart : function(e){
50871 this.processEvent("touchstart", e);
50875 onContextMenu : function(e, t){
50876 this.processEvent("contextmenu", e);
50880 onDblClick : function(e){
50881 this.processEvent("dblclick", e);
50885 walkCells : function(row, col, step, fn, scope){
50886 var cm = this.colModel, clen = cm.getColumnCount();
50887 var ds = this.dataSource, rlen = ds.getCount(), first = true;
50899 if(fn.call(scope || this, row, col, cm) === true){
50917 if(fn.call(scope || this, row, col, cm) === true){
50929 getSelections : function(){
50930 return this.selModel.getSelections();
50934 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
50935 * but if manual update is required this method will initiate it.
50937 autoSize : function(){
50939 this.view.layout();
50940 if(this.view.adjustForScroll){
50941 this.view.adjustForScroll();
50947 * Returns the grid's underlying element.
50948 * @return {Element} The element
50950 getGridEl : function(){
50951 return this.container;
50954 // private for compatibility, overridden by editor grid
50955 stopEditing : function(){},
50958 * Returns the grid's SelectionModel.
50959 * @return {SelectionModel}
50961 getSelectionModel : function(){
50962 if(!this.selModel){
50963 this.selModel = new Roo.grid.RowSelectionModel();
50965 return this.selModel;
50969 * Returns the grid's DataSource.
50970 * @return {DataSource}
50972 getDataSource : function(){
50973 return this.dataSource;
50977 * Returns the grid's ColumnModel.
50978 * @return {ColumnModel}
50980 getColumnModel : function(){
50981 return this.colModel;
50985 * Returns the grid's GridView object.
50986 * @return {GridView}
50988 getView : function(){
50990 this.view = new Roo.grid.GridView(this.viewConfig);
50995 * Called to get grid's drag proxy text, by default returns this.ddText.
50998 getDragDropText : function(){
50999 var count = this.selModel.getCount();
51000 return String.format(this.ddText, count, count == 1 ? '' : 's');
51004 * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
51005 * %0 is replaced with the number of selected rows.
51008 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
51010 * Ext JS Library 1.1.1
51011 * Copyright(c) 2006-2007, Ext JS, LLC.
51013 * Originally Released Under LGPL - original licence link has changed is not relivant.
51016 * <script type="text/javascript">
51019 Roo.grid.AbstractGridView = function(){
51023 "beforerowremoved" : true,
51024 "beforerowsinserted" : true,
51025 "beforerefresh" : true,
51026 "rowremoved" : true,
51027 "rowsinserted" : true,
51028 "rowupdated" : true,
51031 Roo.grid.AbstractGridView.superclass.constructor.call(this);
51034 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
51035 rowClass : "x-grid-row",
51036 cellClass : "x-grid-cell",
51037 tdClass : "x-grid-td",
51038 hdClass : "x-grid-hd",
51039 splitClass : "x-grid-hd-split",
51041 init: function(grid){
51043 var cid = this.grid.getGridEl().id;
51044 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
51045 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
51046 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
51047 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
51050 getColumnRenderers : function(){
51051 var renderers = [];
51052 var cm = this.grid.colModel;
51053 var colCount = cm.getColumnCount();
51054 for(var i = 0; i < colCount; i++){
51055 renderers[i] = cm.getRenderer(i);
51060 getColumnIds : function(){
51062 var cm = this.grid.colModel;
51063 var colCount = cm.getColumnCount();
51064 for(var i = 0; i < colCount; i++){
51065 ids[i] = cm.getColumnId(i);
51070 getDataIndexes : function(){
51071 if(!this.indexMap){
51072 this.indexMap = this.buildIndexMap();
51074 return this.indexMap.colToData;
51077 getColumnIndexByDataIndex : function(dataIndex){
51078 if(!this.indexMap){
51079 this.indexMap = this.buildIndexMap();
51081 return this.indexMap.dataToCol[dataIndex];
51085 * Set a css style for a column dynamically.
51086 * @param {Number} colIndex The index of the column
51087 * @param {String} name The css property name
51088 * @param {String} value The css value
51090 setCSSStyle : function(colIndex, name, value){
51091 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
51092 Roo.util.CSS.updateRule(selector, name, value);
51095 generateRules : function(cm){
51096 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
51097 Roo.util.CSS.removeStyleSheet(rulesId);
51098 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
51099 var cid = cm.getColumnId(i);
51100 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
51101 this.tdSelector, cid, " {\n}\n",
51102 this.hdSelector, cid, " {\n}\n",
51103 this.splitSelector, cid, " {\n}\n");
51105 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
51109 * Ext JS Library 1.1.1
51110 * Copyright(c) 2006-2007, Ext JS, LLC.
51112 * Originally Released Under LGPL - original licence link has changed is not relivant.
51115 * <script type="text/javascript">
51119 // This is a support class used internally by the Grid components
51120 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
51122 this.view = grid.getView();
51123 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
51124 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
51126 this.setHandleElId(Roo.id(hd));
51127 this.setOuterHandleElId(Roo.id(hd2));
51129 this.scroll = false;
51131 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
51133 getDragData : function(e){
51134 var t = Roo.lib.Event.getTarget(e);
51135 var h = this.view.findHeaderCell(t);
51137 return {ddel: h.firstChild, header:h};
51142 onInitDrag : function(e){
51143 this.view.headersDisabled = true;
51144 var clone = this.dragData.ddel.cloneNode(true);
51145 clone.id = Roo.id();
51146 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
51147 this.proxy.update(clone);
51151 afterValidDrop : function(){
51153 setTimeout(function(){
51154 v.headersDisabled = false;
51158 afterInvalidDrop : function(){
51160 setTimeout(function(){
51161 v.headersDisabled = false;
51167 * Ext JS Library 1.1.1
51168 * Copyright(c) 2006-2007, Ext JS, LLC.
51170 * Originally Released Under LGPL - original licence link has changed is not relivant.
51173 * <script type="text/javascript">
51176 // This is a support class used internally by the Grid components
51177 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
51179 this.view = grid.getView();
51180 // split the proxies so they don't interfere with mouse events
51181 this.proxyTop = Roo.DomHelper.append(document.body, {
51182 cls:"col-move-top", html:" "
51184 this.proxyBottom = Roo.DomHelper.append(document.body, {
51185 cls:"col-move-bottom", html:" "
51187 this.proxyTop.hide = this.proxyBottom.hide = function(){
51188 this.setLeftTop(-100,-100);
51189 this.setStyle("visibility", "hidden");
51191 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
51192 // temporarily disabled
51193 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
51194 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
51196 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
51197 proxyOffsets : [-4, -9],
51198 fly: Roo.Element.fly,
51200 getTargetFromEvent : function(e){
51201 var t = Roo.lib.Event.getTarget(e);
51202 var cindex = this.view.findCellIndex(t);
51203 if(cindex !== false){
51204 return this.view.getHeaderCell(cindex);
51209 nextVisible : function(h){
51210 var v = this.view, cm = this.grid.colModel;
51213 if(!cm.isHidden(v.getCellIndex(h))){
51221 prevVisible : function(h){
51222 var v = this.view, cm = this.grid.colModel;
51225 if(!cm.isHidden(v.getCellIndex(h))){
51233 positionIndicator : function(h, n, e){
51234 var x = Roo.lib.Event.getPageX(e);
51235 var r = Roo.lib.Dom.getRegion(n.firstChild);
51236 var px, pt, py = r.top + this.proxyOffsets[1];
51237 if((r.right - x) <= (r.right-r.left)/2){
51238 px = r.right+this.view.borderWidth;
51244 var oldIndex = this.view.getCellIndex(h);
51245 var newIndex = this.view.getCellIndex(n);
51247 if(this.grid.colModel.isFixed(newIndex)){
51251 var locked = this.grid.colModel.isLocked(newIndex);
51256 if(oldIndex < newIndex){
51259 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
51262 px += this.proxyOffsets[0];
51263 this.proxyTop.setLeftTop(px, py);
51264 this.proxyTop.show();
51265 if(!this.bottomOffset){
51266 this.bottomOffset = this.view.mainHd.getHeight();
51268 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
51269 this.proxyBottom.show();
51273 onNodeEnter : function(n, dd, e, data){
51274 if(data.header != n){
51275 this.positionIndicator(data.header, n, e);
51279 onNodeOver : function(n, dd, e, data){
51280 var result = false;
51281 if(data.header != n){
51282 result = this.positionIndicator(data.header, n, e);
51285 this.proxyTop.hide();
51286 this.proxyBottom.hide();
51288 return result ? this.dropAllowed : this.dropNotAllowed;
51291 onNodeOut : function(n, dd, e, data){
51292 this.proxyTop.hide();
51293 this.proxyBottom.hide();
51296 onNodeDrop : function(n, dd, e, data){
51297 var h = data.header;
51299 var cm = this.grid.colModel;
51300 var x = Roo.lib.Event.getPageX(e);
51301 var r = Roo.lib.Dom.getRegion(n.firstChild);
51302 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
51303 var oldIndex = this.view.getCellIndex(h);
51304 var newIndex = this.view.getCellIndex(n);
51305 var locked = cm.isLocked(newIndex);
51309 if(oldIndex < newIndex){
51312 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
51315 cm.setLocked(oldIndex, locked, true);
51316 cm.moveColumn(oldIndex, newIndex);
51317 this.grid.fireEvent("columnmove", oldIndex, newIndex);
51325 * Ext JS Library 1.1.1
51326 * Copyright(c) 2006-2007, Ext JS, LLC.
51328 * Originally Released Under LGPL - original licence link has changed is not relivant.
51331 * <script type="text/javascript">
51335 * @class Roo.grid.GridView
51336 * @extends Roo.util.Observable
51339 * @param {Object} config
51341 Roo.grid.GridView = function(config){
51342 Roo.grid.GridView.superclass.constructor.call(this);
51345 Roo.apply(this, config);
51348 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
51350 unselectable : 'unselectable="on"',
51351 unselectableCls : 'x-unselectable',
51354 rowClass : "x-grid-row",
51356 cellClass : "x-grid-col",
51358 tdClass : "x-grid-td",
51360 hdClass : "x-grid-hd",
51362 splitClass : "x-grid-split",
51364 sortClasses : ["sort-asc", "sort-desc"],
51366 enableMoveAnim : false,
51370 dh : Roo.DomHelper,
51372 fly : Roo.Element.fly,
51374 css : Roo.util.CSS,
51380 scrollIncrement : 22,
51382 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
51384 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
51386 bind : function(ds, cm){
51388 this.ds.un("load", this.onLoad, this);
51389 this.ds.un("datachanged", this.onDataChange, this);
51390 this.ds.un("add", this.onAdd, this);
51391 this.ds.un("remove", this.onRemove, this);
51392 this.ds.un("update", this.onUpdate, this);
51393 this.ds.un("clear", this.onClear, this);
51396 ds.on("load", this.onLoad, this);
51397 ds.on("datachanged", this.onDataChange, this);
51398 ds.on("add", this.onAdd, this);
51399 ds.on("remove", this.onRemove, this);
51400 ds.on("update", this.onUpdate, this);
51401 ds.on("clear", this.onClear, this);
51406 this.cm.un("widthchange", this.onColWidthChange, this);
51407 this.cm.un("headerchange", this.onHeaderChange, this);
51408 this.cm.un("hiddenchange", this.onHiddenChange, this);
51409 this.cm.un("columnmoved", this.onColumnMove, this);
51410 this.cm.un("columnlockchange", this.onColumnLock, this);
51413 this.generateRules(cm);
51414 cm.on("widthchange", this.onColWidthChange, this);
51415 cm.on("headerchange", this.onHeaderChange, this);
51416 cm.on("hiddenchange", this.onHiddenChange, this);
51417 cm.on("columnmoved", this.onColumnMove, this);
51418 cm.on("columnlockchange", this.onColumnLock, this);
51423 init: function(grid){
51424 Roo.grid.GridView.superclass.init.call(this, grid);
51426 this.bind(grid.dataSource, grid.colModel);
51428 grid.on("headerclick", this.handleHeaderClick, this);
51430 if(grid.trackMouseOver){
51431 grid.on("mouseover", this.onRowOver, this);
51432 grid.on("mouseout", this.onRowOut, this);
51434 grid.cancelTextSelection = function(){};
51435 this.gridId = grid.id;
51437 var tpls = this.templates || {};
51440 tpls.master = new Roo.Template(
51441 '<div class="x-grid" hidefocus="true">',
51442 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
51443 '<div class="x-grid-topbar"></div>',
51444 '<div class="x-grid-scroller"><div></div></div>',
51445 '<div class="x-grid-locked">',
51446 '<div class="x-grid-header">{lockedHeader}</div>',
51447 '<div class="x-grid-body">{lockedBody}</div>',
51449 '<div class="x-grid-viewport">',
51450 '<div class="x-grid-header">{header}</div>',
51451 '<div class="x-grid-body">{body}</div>',
51453 '<div class="x-grid-bottombar"></div>',
51455 '<div class="x-grid-resize-proxy"> </div>',
51458 tpls.master.disableformats = true;
51462 tpls.header = new Roo.Template(
51463 '<table border="0" cellspacing="0" cellpadding="0">',
51464 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
51467 tpls.header.disableformats = true;
51469 tpls.header.compile();
51472 tpls.hcell = new Roo.Template(
51473 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
51474 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
51477 tpls.hcell.disableFormats = true;
51479 tpls.hcell.compile();
51482 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
51483 this.unselectableCls + '" ' + this.unselectable +'> </div>');
51484 tpls.hsplit.disableFormats = true;
51486 tpls.hsplit.compile();
51489 tpls.body = new Roo.Template(
51490 '<table border="0" cellspacing="0" cellpadding="0">',
51491 "<tbody>{rows}</tbody>",
51494 tpls.body.disableFormats = true;
51496 tpls.body.compile();
51499 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
51500 tpls.row.disableFormats = true;
51502 tpls.row.compile();
51505 tpls.cell = new Roo.Template(
51506 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
51507 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
51508 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
51511 tpls.cell.disableFormats = true;
51513 tpls.cell.compile();
51515 this.templates = tpls;
51518 // remap these for backwards compat
51519 onColWidthChange : function(){
51520 this.updateColumns.apply(this, arguments);
51522 onHeaderChange : function(){
51523 this.updateHeaders.apply(this, arguments);
51525 onHiddenChange : function(){
51526 this.handleHiddenChange.apply(this, arguments);
51528 onColumnMove : function(){
51529 this.handleColumnMove.apply(this, arguments);
51531 onColumnLock : function(){
51532 this.handleLockChange.apply(this, arguments);
51535 onDataChange : function(){
51537 this.updateHeaderSortState();
51540 onClear : function(){
51544 onUpdate : function(ds, record){
51545 this.refreshRow(record);
51548 refreshRow : function(record){
51549 var ds = this.ds, index;
51550 if(typeof record == 'number'){
51552 record = ds.getAt(index);
51554 index = ds.indexOf(record);
51556 this.insertRows(ds, index, index, true);
51557 this.onRemove(ds, record, index+1, true);
51558 this.syncRowHeights(index, index);
51560 this.fireEvent("rowupdated", this, index, record);
51563 onAdd : function(ds, records, index){
51564 this.insertRows(ds, index, index + (records.length-1));
51567 onRemove : function(ds, record, index, isUpdate){
51568 if(isUpdate !== true){
51569 this.fireEvent("beforerowremoved", this, index, record);
51571 var bt = this.getBodyTable(), lt = this.getLockedTable();
51572 if(bt.rows[index]){
51573 bt.firstChild.removeChild(bt.rows[index]);
51575 if(lt.rows[index]){
51576 lt.firstChild.removeChild(lt.rows[index]);
51578 if(isUpdate !== true){
51579 this.stripeRows(index);
51580 this.syncRowHeights(index, index);
51582 this.fireEvent("rowremoved", this, index, record);
51586 onLoad : function(){
51587 this.scrollToTop();
51591 * Scrolls the grid to the top
51593 scrollToTop : function(){
51595 this.scroller.dom.scrollTop = 0;
51601 * Gets a panel in the header of the grid that can be used for toolbars etc.
51602 * After modifying the contents of this panel a call to grid.autoSize() may be
51603 * required to register any changes in size.
51604 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
51605 * @return Roo.Element
51607 getHeaderPanel : function(doShow){
51609 this.headerPanel.show();
51611 return this.headerPanel;
51615 * Gets a panel in the footer of the grid that can be used for toolbars etc.
51616 * After modifying the contents of this panel a call to grid.autoSize() may be
51617 * required to register any changes in size.
51618 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
51619 * @return Roo.Element
51621 getFooterPanel : function(doShow){
51623 this.footerPanel.show();
51625 return this.footerPanel;
51628 initElements : function(){
51629 var E = Roo.Element;
51630 var el = this.grid.getGridEl().dom.firstChild;
51631 var cs = el.childNodes;
51633 this.el = new E(el);
51635 this.focusEl = new E(el.firstChild);
51636 this.focusEl.swallowEvent("click", true);
51638 this.headerPanel = new E(cs[1]);
51639 this.headerPanel.enableDisplayMode("block");
51641 this.scroller = new E(cs[2]);
51642 this.scrollSizer = new E(this.scroller.dom.firstChild);
51644 this.lockedWrap = new E(cs[3]);
51645 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
51646 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
51648 this.mainWrap = new E(cs[4]);
51649 this.mainHd = new E(this.mainWrap.dom.firstChild);
51650 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
51652 this.footerPanel = new E(cs[5]);
51653 this.footerPanel.enableDisplayMode("block");
51655 this.resizeProxy = new E(cs[6]);
51657 this.headerSelector = String.format(
51658 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
51659 this.lockedHd.id, this.mainHd.id
51662 this.splitterSelector = String.format(
51663 '#{0} div.x-grid-split, #{1} div.x-grid-split',
51664 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
51667 idToCssName : function(s)
51669 return s.replace(/[^a-z0-9]+/ig, '-');
51672 getHeaderCell : function(index){
51673 return Roo.DomQuery.select(this.headerSelector)[index];
51676 getHeaderCellMeasure : function(index){
51677 return this.getHeaderCell(index).firstChild;
51680 getHeaderCellText : function(index){
51681 return this.getHeaderCell(index).firstChild.firstChild;
51684 getLockedTable : function(){
51685 return this.lockedBody.dom.firstChild;
51688 getBodyTable : function(){
51689 return this.mainBody.dom.firstChild;
51692 getLockedRow : function(index){
51693 return this.getLockedTable().rows[index];
51696 getRow : function(index){
51697 return this.getBodyTable().rows[index];
51700 getRowComposite : function(index){
51702 this.rowEl = new Roo.CompositeElementLite();
51704 var els = [], lrow, mrow;
51705 if(lrow = this.getLockedRow(index)){
51708 if(mrow = this.getRow(index)){
51711 this.rowEl.elements = els;
51715 * Gets the 'td' of the cell
51717 * @param {Integer} rowIndex row to select
51718 * @param {Integer} colIndex column to select
51722 getCell : function(rowIndex, colIndex){
51723 var locked = this.cm.getLockedCount();
51725 if(colIndex < locked){
51726 source = this.lockedBody.dom.firstChild;
51728 source = this.mainBody.dom.firstChild;
51729 colIndex -= locked;
51731 return source.rows[rowIndex].childNodes[colIndex];
51734 getCellText : function(rowIndex, colIndex){
51735 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
51738 getCellBox : function(cell){
51739 var b = this.fly(cell).getBox();
51740 if(Roo.isOpera){ // opera fails to report the Y
51741 b.y = cell.offsetTop + this.mainBody.getY();
51746 getCellIndex : function(cell){
51747 var id = String(cell.className).match(this.cellRE);
51749 return parseInt(id[1], 10);
51754 findHeaderIndex : function(n){
51755 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
51756 return r ? this.getCellIndex(r) : false;
51759 findHeaderCell : function(n){
51760 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
51761 return r ? r : false;
51764 findRowIndex : function(n){
51768 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
51769 return r ? r.rowIndex : false;
51772 findCellIndex : function(node){
51773 var stop = this.el.dom;
51774 while(node && node != stop){
51775 if(this.findRE.test(node.className)){
51776 return this.getCellIndex(node);
51778 node = node.parentNode;
51783 getColumnId : function(index){
51784 return this.cm.getColumnId(index);
51787 getSplitters : function()
51789 if(this.splitterSelector){
51790 return Roo.DomQuery.select(this.splitterSelector);
51796 getSplitter : function(index){
51797 return this.getSplitters()[index];
51800 onRowOver : function(e, t){
51802 if((row = this.findRowIndex(t)) !== false){
51803 this.getRowComposite(row).addClass("x-grid-row-over");
51807 onRowOut : function(e, t){
51809 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
51810 this.getRowComposite(row).removeClass("x-grid-row-over");
51814 renderHeaders : function(){
51816 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
51817 var cb = [], lb = [], sb = [], lsb = [], p = {};
51818 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
51819 p.cellId = "x-grid-hd-0-" + i;
51820 p.splitId = "x-grid-csplit-0-" + i;
51821 p.id = cm.getColumnId(i);
51822 p.title = cm.getColumnTooltip(i) || "";
51823 p.value = cm.getColumnHeader(i) || "";
51824 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
51825 if(!cm.isLocked(i)){
51826 cb[cb.length] = ct.apply(p);
51827 sb[sb.length] = st.apply(p);
51829 lb[lb.length] = ct.apply(p);
51830 lsb[lsb.length] = st.apply(p);
51833 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
51834 ht.apply({cells: cb.join(""), splits:sb.join("")})];
51837 updateHeaders : function(){
51838 var html = this.renderHeaders();
51839 this.lockedHd.update(html[0]);
51840 this.mainHd.update(html[1]);
51844 * Focuses the specified row.
51845 * @param {Number} row The row index
51847 focusRow : function(row)
51849 //Roo.log('GridView.focusRow');
51850 var x = this.scroller.dom.scrollLeft;
51851 this.focusCell(row, 0, false);
51852 this.scroller.dom.scrollLeft = x;
51856 * Focuses the specified cell.
51857 * @param {Number} row The row index
51858 * @param {Number} col The column index
51859 * @param {Boolean} hscroll false to disable horizontal scrolling
51861 focusCell : function(row, col, hscroll)
51863 //Roo.log('GridView.focusCell');
51864 var el = this.ensureVisible(row, col, hscroll);
51865 this.focusEl.alignTo(el, "tl-tl");
51867 this.focusEl.focus();
51869 this.focusEl.focus.defer(1, this.focusEl);
51874 * Scrolls the specified cell into view
51875 * @param {Number} row The row index
51876 * @param {Number} col The column index
51877 * @param {Boolean} hscroll false to disable horizontal scrolling
51879 ensureVisible : function(row, col, hscroll)
51881 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
51882 //return null; //disable for testing.
51883 if(typeof row != "number"){
51884 row = row.rowIndex;
51886 if(row < 0 && row >= this.ds.getCount()){
51889 col = (col !== undefined ? col : 0);
51890 var cm = this.grid.colModel;
51891 while(cm.isHidden(col)){
51895 var el = this.getCell(row, col);
51899 var c = this.scroller.dom;
51901 var ctop = parseInt(el.offsetTop, 10);
51902 var cleft = parseInt(el.offsetLeft, 10);
51903 var cbot = ctop + el.offsetHeight;
51904 var cright = cleft + el.offsetWidth;
51906 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
51907 var stop = parseInt(c.scrollTop, 10);
51908 var sleft = parseInt(c.scrollLeft, 10);
51909 var sbot = stop + ch;
51910 var sright = sleft + c.clientWidth;
51912 Roo.log('GridView.ensureVisible:' +
51914 ' c.clientHeight:' + c.clientHeight +
51915 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
51923 c.scrollTop = ctop;
51924 //Roo.log("set scrolltop to ctop DISABLE?");
51925 }else if(cbot > sbot){
51926 //Roo.log("set scrolltop to cbot-ch");
51927 c.scrollTop = cbot-ch;
51930 if(hscroll !== false){
51932 c.scrollLeft = cleft;
51933 }else if(cright > sright){
51934 c.scrollLeft = cright-c.clientWidth;
51941 updateColumns : function(){
51942 this.grid.stopEditing();
51943 var cm = this.grid.colModel, colIds = this.getColumnIds();
51944 //var totalWidth = cm.getTotalWidth();
51946 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
51947 //if(cm.isHidden(i)) continue;
51948 var w = cm.getColumnWidth(i);
51949 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
51950 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
51952 this.updateSplitters();
51955 generateRules : function(cm){
51956 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
51957 Roo.util.CSS.removeStyleSheet(rulesId);
51958 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
51959 var cid = cm.getColumnId(i);
51961 if(cm.config[i].align){
51962 align = 'text-align:'+cm.config[i].align+';';
51965 if(cm.isHidden(i)){
51966 hidden = 'display:none;';
51968 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
51970 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
51971 this.hdSelector, cid, " {\n", align, width, "}\n",
51972 this.tdSelector, cid, " {\n",hidden,"\n}\n",
51973 this.splitSelector, cid, " {\n", hidden , "\n}\n");
51975 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
51978 updateSplitters : function(){
51979 var cm = this.cm, s = this.getSplitters();
51980 if(s){ // splitters not created yet
51981 var pos = 0, locked = true;
51982 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
51983 if(cm.isHidden(i)) continue;
51984 var w = cm.getColumnWidth(i); // make sure it's a number
51985 if(!cm.isLocked(i) && locked){
51990 s[i].style.left = (pos-this.splitOffset) + "px";
51995 handleHiddenChange : function(colModel, colIndex, hidden){
51997 this.hideColumn(colIndex);
51999 this.unhideColumn(colIndex);
52003 hideColumn : function(colIndex){
52004 var cid = this.getColumnId(colIndex);
52005 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
52006 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
52008 this.updateHeaders();
52010 this.updateSplitters();
52014 unhideColumn : function(colIndex){
52015 var cid = this.getColumnId(colIndex);
52016 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
52017 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
52020 this.updateHeaders();
52022 this.updateSplitters();
52026 insertRows : function(dm, firstRow, lastRow, isUpdate){
52027 if(firstRow == 0 && lastRow == dm.getCount()-1){
52031 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
52033 var s = this.getScrollState();
52034 var markup = this.renderRows(firstRow, lastRow);
52035 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
52036 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
52037 this.restoreScroll(s);
52039 this.fireEvent("rowsinserted", this, firstRow, lastRow);
52040 this.syncRowHeights(firstRow, lastRow);
52041 this.stripeRows(firstRow);
52047 bufferRows : function(markup, target, index){
52048 var before = null, trows = target.rows, tbody = target.tBodies[0];
52049 if(index < trows.length){
52050 before = trows[index];
52052 var b = document.createElement("div");
52053 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
52054 var rows = b.firstChild.rows;
52055 for(var i = 0, len = rows.length; i < len; i++){
52057 tbody.insertBefore(rows[0], before);
52059 tbody.appendChild(rows[0]);
52066 deleteRows : function(dm, firstRow, lastRow){
52067 if(dm.getRowCount()<1){
52068 this.fireEvent("beforerefresh", this);
52069 this.mainBody.update("");
52070 this.lockedBody.update("");
52071 this.fireEvent("refresh", this);
52073 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
52074 var bt = this.getBodyTable();
52075 var tbody = bt.firstChild;
52076 var rows = bt.rows;
52077 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
52078 tbody.removeChild(rows[firstRow]);
52080 this.stripeRows(firstRow);
52081 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
52085 updateRows : function(dataSource, firstRow, lastRow){
52086 var s = this.getScrollState();
52088 this.restoreScroll(s);
52091 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
52095 this.updateHeaderSortState();
52098 getScrollState : function(){
52100 var sb = this.scroller.dom;
52101 return {left: sb.scrollLeft, top: sb.scrollTop};
52104 stripeRows : function(startRow){
52105 if(!this.grid.stripeRows || this.ds.getCount() < 1){
52108 startRow = startRow || 0;
52109 var rows = this.getBodyTable().rows;
52110 var lrows = this.getLockedTable().rows;
52111 var cls = ' x-grid-row-alt ';
52112 for(var i = startRow, len = rows.length; i < len; i++){
52113 var row = rows[i], lrow = lrows[i];
52114 var isAlt = ((i+1) % 2 == 0);
52115 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
52116 if(isAlt == hasAlt){
52120 row.className += " x-grid-row-alt";
52122 row.className = row.className.replace("x-grid-row-alt", "");
52125 lrow.className = row.className;
52130 restoreScroll : function(state){
52131 //Roo.log('GridView.restoreScroll');
52132 var sb = this.scroller.dom;
52133 sb.scrollLeft = state.left;
52134 sb.scrollTop = state.top;
52138 syncScroll : function(){
52139 //Roo.log('GridView.syncScroll');
52140 var sb = this.scroller.dom;
52141 var sh = this.mainHd.dom;
52142 var bs = this.mainBody.dom;
52143 var lv = this.lockedBody.dom;
52144 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
52145 lv.scrollTop = bs.scrollTop = sb.scrollTop;
52148 handleScroll : function(e){
52150 var sb = this.scroller.dom;
52151 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
52155 handleWheel : function(e){
52156 var d = e.getWheelDelta();
52157 this.scroller.dom.scrollTop -= d*22;
52158 // set this here to prevent jumpy scrolling on large tables
52159 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
52163 renderRows : function(startRow, endRow){
52164 // pull in all the crap needed to render rows
52165 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
52166 var colCount = cm.getColumnCount();
52168 if(ds.getCount() < 1){
52172 // build a map for all the columns
52174 for(var i = 0; i < colCount; i++){
52175 var name = cm.getDataIndex(i);
52177 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
52178 renderer : cm.getRenderer(i),
52179 id : cm.getColumnId(i),
52180 locked : cm.isLocked(i)
52184 startRow = startRow || 0;
52185 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
52187 // records to render
52188 var rs = ds.getRange(startRow, endRow);
52190 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
52193 // As much as I hate to duplicate code, this was branched because FireFox really hates
52194 // [].join("") on strings. The performance difference was substantial enough to
52195 // branch this function
52196 doRender : Roo.isGecko ?
52197 function(cs, rs, ds, startRow, colCount, stripe){
52198 var ts = this.templates, ct = ts.cell, rt = ts.row;
52200 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
52202 var hasListener = this.grid.hasListener('rowclass');
52204 for(var j = 0, len = rs.length; j < len; j++){
52205 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
52206 for(var i = 0; i < colCount; i++){
52208 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
52210 p.css = p.attr = "";
52211 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
52212 if(p.value == undefined || p.value === "") p.value = " ";
52213 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
52214 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
52216 var markup = ct.apply(p);
52224 if(stripe && ((rowIndex+1) % 2 == 0)){
52225 alt.push("x-grid-row-alt")
52228 alt.push( " x-grid-dirty-row");
52231 if(this.getRowClass){
52232 alt.push(this.getRowClass(r, rowIndex));
52238 rowIndex : rowIndex,
52241 this.grid.fireEvent('rowclass', this, rowcfg);
52242 alt.push(rowcfg.rowClass);
52244 rp.alt = alt.join(" ");
52245 lbuf+= rt.apply(rp);
52247 buf+= rt.apply(rp);
52249 return [lbuf, buf];
52251 function(cs, rs, ds, startRow, colCount, stripe){
52252 var ts = this.templates, ct = ts.cell, rt = ts.row;
52254 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
52255 var hasListener = this.grid.hasListener('rowclass');
52258 for(var j = 0, len = rs.length; j < len; j++){
52259 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
52260 for(var i = 0; i < colCount; i++){
52262 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
52264 p.css = p.attr = "";
52265 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
52266 if(p.value == undefined || p.value === "") p.value = " ";
52267 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
52268 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
52271 var markup = ct.apply(p);
52273 cb[cb.length] = markup;
52275 lcb[lcb.length] = markup;
52279 if(stripe && ((rowIndex+1) % 2 == 0)){
52280 alt.push( "x-grid-row-alt");
52283 alt.push(" x-grid-dirty-row");
52286 if(this.getRowClass){
52287 alt.push( this.getRowClass(r, rowIndex));
52293 rowIndex : rowIndex,
52296 this.grid.fireEvent('rowclass', this, rowcfg);
52297 alt.push(rowcfg.rowClass);
52299 rp.alt = alt.join(" ");
52300 rp.cells = lcb.join("");
52301 lbuf[lbuf.length] = rt.apply(rp);
52302 rp.cells = cb.join("");
52303 buf[buf.length] = rt.apply(rp);
52305 return [lbuf.join(""), buf.join("")];
52308 renderBody : function(){
52309 var markup = this.renderRows();
52310 var bt = this.templates.body;
52311 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
52315 * Refreshes the grid
52316 * @param {Boolean} headersToo
52318 refresh : function(headersToo){
52319 this.fireEvent("beforerefresh", this);
52320 this.grid.stopEditing();
52321 var result = this.renderBody();
52322 this.lockedBody.update(result[0]);
52323 this.mainBody.update(result[1]);
52324 if(headersToo === true){
52325 this.updateHeaders();
52326 this.updateColumns();
52327 this.updateSplitters();
52328 this.updateHeaderSortState();
52330 this.syncRowHeights();
52332 this.fireEvent("refresh", this);
52335 handleColumnMove : function(cm, oldIndex, newIndex){
52336 this.indexMap = null;
52337 var s = this.getScrollState();
52338 this.refresh(true);
52339 this.restoreScroll(s);
52340 this.afterMove(newIndex);
52343 afterMove : function(colIndex){
52344 if(this.enableMoveAnim && Roo.enableFx){
52345 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
52347 // if multisort - fix sortOrder, and reload..
52348 if (this.grid.dataSource.multiSort) {
52349 // the we can call sort again..
52350 var dm = this.grid.dataSource;
52351 var cm = this.grid.colModel;
52353 for(var i = 0; i < cm.config.length; i++ ) {
52355 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
52356 continue; // dont' bother, it's not in sort list or being set.
52359 so.push(cm.config[i].dataIndex);
52362 dm.load(dm.lastOptions);
52369 updateCell : function(dm, rowIndex, dataIndex){
52370 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
52371 if(typeof colIndex == "undefined"){ // not present in grid
52374 var cm = this.grid.colModel;
52375 var cell = this.getCell(rowIndex, colIndex);
52376 var cellText = this.getCellText(rowIndex, colIndex);
52379 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
52380 id : cm.getColumnId(colIndex),
52381 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
52383 var renderer = cm.getRenderer(colIndex);
52384 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
52385 if(typeof val == "undefined" || val === "") val = " ";
52386 cellText.innerHTML = val;
52387 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
52388 this.syncRowHeights(rowIndex, rowIndex);
52391 calcColumnWidth : function(colIndex, maxRowsToMeasure){
52393 if(this.grid.autoSizeHeaders){
52394 var h = this.getHeaderCellMeasure(colIndex);
52395 maxWidth = Math.max(maxWidth, h.scrollWidth);
52398 if(this.cm.isLocked(colIndex)){
52399 tb = this.getLockedTable();
52402 tb = this.getBodyTable();
52403 index = colIndex - this.cm.getLockedCount();
52406 var rows = tb.rows;
52407 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
52408 for(var i = 0; i < stopIndex; i++){
52409 var cell = rows[i].childNodes[index].firstChild;
52410 maxWidth = Math.max(maxWidth, cell.scrollWidth);
52413 return maxWidth + /*margin for error in IE*/ 5;
52416 * Autofit a column to its content.
52417 * @param {Number} colIndex
52418 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
52420 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
52421 if(this.cm.isHidden(colIndex)){
52422 return; // can't calc a hidden column
52425 var cid = this.cm.getColumnId(colIndex);
52426 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
52427 if(this.grid.autoSizeHeaders){
52428 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
52431 var newWidth = this.calcColumnWidth(colIndex);
52432 this.cm.setColumnWidth(colIndex,
52433 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
52434 if(!suppressEvent){
52435 this.grid.fireEvent("columnresize", colIndex, newWidth);
52440 * Autofits all columns to their content and then expands to fit any extra space in the grid
52442 autoSizeColumns : function(){
52443 var cm = this.grid.colModel;
52444 var colCount = cm.getColumnCount();
52445 for(var i = 0; i < colCount; i++){
52446 this.autoSizeColumn(i, true, true);
52448 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
52451 this.updateColumns();
52457 * Autofits all columns to the grid's width proportionate with their current size
52458 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
52460 fitColumns : function(reserveScrollSpace){
52461 var cm = this.grid.colModel;
52462 var colCount = cm.getColumnCount();
52466 for (i = 0; i < colCount; i++){
52467 if(!cm.isHidden(i) && !cm.isFixed(i)){
52468 w = cm.getColumnWidth(i);
52474 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
52475 if(reserveScrollSpace){
52478 var frac = (avail - cm.getTotalWidth())/width;
52479 while (cols.length){
52482 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
52484 this.updateColumns();
52488 onRowSelect : function(rowIndex){
52489 var row = this.getRowComposite(rowIndex);
52490 row.addClass("x-grid-row-selected");
52493 onRowDeselect : function(rowIndex){
52494 var row = this.getRowComposite(rowIndex);
52495 row.removeClass("x-grid-row-selected");
52498 onCellSelect : function(row, col){
52499 var cell = this.getCell(row, col);
52501 Roo.fly(cell).addClass("x-grid-cell-selected");
52505 onCellDeselect : function(row, col){
52506 var cell = this.getCell(row, col);
52508 Roo.fly(cell).removeClass("x-grid-cell-selected");
52512 updateHeaderSortState : function(){
52514 // sort state can be single { field: xxx, direction : yyy}
52515 // or { xxx=>ASC , yyy : DESC ..... }
52518 if (!this.ds.multiSort) {
52519 var state = this.ds.getSortState();
52523 mstate[state.field] = state.direction;
52524 // FIXME... - this is not used here.. but might be elsewhere..
52525 this.sortState = state;
52528 mstate = this.ds.sortToggle;
52530 //remove existing sort classes..
52532 var sc = this.sortClasses;
52533 var hds = this.el.select(this.headerSelector).removeClass(sc);
52535 for(var f in mstate) {
52537 var sortColumn = this.cm.findColumnIndex(f);
52539 if(sortColumn != -1){
52540 var sortDir = mstate[f];
52541 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
52550 handleHeaderClick : function(g, index){
52551 if(this.headersDisabled){
52554 var dm = g.dataSource, cm = g.colModel;
52555 if(!cm.isSortable(index)){
52560 if (dm.multiSort) {
52561 // update the sortOrder
52563 for(var i = 0; i < cm.config.length; i++ ) {
52565 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
52566 continue; // dont' bother, it's not in sort list or being set.
52569 so.push(cm.config[i].dataIndex);
52575 dm.sort(cm.getDataIndex(index));
52579 destroy : function(){
52581 this.colMenu.removeAll();
52582 Roo.menu.MenuMgr.unregister(this.colMenu);
52583 this.colMenu.getEl().remove();
52584 delete this.colMenu;
52587 this.hmenu.removeAll();
52588 Roo.menu.MenuMgr.unregister(this.hmenu);
52589 this.hmenu.getEl().remove();
52592 if(this.grid.enableColumnMove){
52593 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
52595 for(var dd in dds){
52596 if(!dds[dd].config.isTarget && dds[dd].dragElId){
52597 var elid = dds[dd].dragElId;
52599 Roo.get(elid).remove();
52600 } else if(dds[dd].config.isTarget){
52601 dds[dd].proxyTop.remove();
52602 dds[dd].proxyBottom.remove();
52605 if(Roo.dd.DDM.locationCache[dd]){
52606 delete Roo.dd.DDM.locationCache[dd];
52609 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
52612 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
52613 this.bind(null, null);
52614 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
52617 handleLockChange : function(){
52618 this.refresh(true);
52621 onDenyColumnLock : function(){
52625 onDenyColumnHide : function(){
52629 handleHdMenuClick : function(item){
52630 var index = this.hdCtxIndex;
52631 var cm = this.cm, ds = this.ds;
52634 ds.sort(cm.getDataIndex(index), "ASC");
52637 ds.sort(cm.getDataIndex(index), "DESC");
52640 var lc = cm.getLockedCount();
52641 if(cm.getColumnCount(true) <= lc+1){
52642 this.onDenyColumnLock();
52646 cm.setLocked(index, true, true);
52647 cm.moveColumn(index, lc);
52648 this.grid.fireEvent("columnmove", index, lc);
52650 cm.setLocked(index, true);
52654 var lc = cm.getLockedCount();
52655 if((lc-1) != index){
52656 cm.setLocked(index, false, true);
52657 cm.moveColumn(index, lc-1);
52658 this.grid.fireEvent("columnmove", index, lc-1);
52660 cm.setLocked(index, false);
52664 index = cm.getIndexById(item.id.substr(4));
52666 if(item.checked && cm.getColumnCount(true) <= 1){
52667 this.onDenyColumnHide();
52670 cm.setHidden(index, item.checked);
52676 beforeColMenuShow : function(){
52677 var cm = this.cm, colCount = cm.getColumnCount();
52678 this.colMenu.removeAll();
52679 for(var i = 0; i < colCount; i++){
52680 this.colMenu.add(new Roo.menu.CheckItem({
52681 id: "col-"+cm.getColumnId(i),
52682 text: cm.getColumnHeader(i),
52683 checked: !cm.isHidden(i),
52689 handleHdCtx : function(g, index, e){
52691 var hd = this.getHeaderCell(index);
52692 this.hdCtxIndex = index;
52693 var ms = this.hmenu.items, cm = this.cm;
52694 ms.get("asc").setDisabled(!cm.isSortable(index));
52695 ms.get("desc").setDisabled(!cm.isSortable(index));
52696 if(this.grid.enableColLock !== false){
52697 ms.get("lock").setDisabled(cm.isLocked(index));
52698 ms.get("unlock").setDisabled(!cm.isLocked(index));
52700 this.hmenu.show(hd, "tl-bl");
52703 handleHdOver : function(e){
52704 var hd = this.findHeaderCell(e.getTarget());
52705 if(hd && !this.headersDisabled){
52706 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
52707 this.fly(hd).addClass("x-grid-hd-over");
52712 handleHdOut : function(e){
52713 var hd = this.findHeaderCell(e.getTarget());
52715 this.fly(hd).removeClass("x-grid-hd-over");
52719 handleSplitDblClick : function(e, t){
52720 var i = this.getCellIndex(t);
52721 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
52722 this.autoSizeColumn(i, true);
52727 render : function(){
52730 var colCount = cm.getColumnCount();
52732 if(this.grid.monitorWindowResize === true){
52733 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
52735 var header = this.renderHeaders();
52736 var body = this.templates.body.apply({rows:""});
52737 var html = this.templates.master.apply({
52740 lockedHeader: header[0],
52744 //this.updateColumns();
52746 this.grid.getGridEl().dom.innerHTML = html;
52748 this.initElements();
52750 // a kludge to fix the random scolling effect in webkit
52751 this.el.on("scroll", function() {
52752 this.el.dom.scrollTop=0; // hopefully not recursive..
52755 this.scroller.on("scroll", this.handleScroll, this);
52756 this.lockedBody.on("mousewheel", this.handleWheel, this);
52757 this.mainBody.on("mousewheel", this.handleWheel, this);
52759 this.mainHd.on("mouseover", this.handleHdOver, this);
52760 this.mainHd.on("mouseout", this.handleHdOut, this);
52761 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
52762 {delegate: "."+this.splitClass});
52764 this.lockedHd.on("mouseover", this.handleHdOver, this);
52765 this.lockedHd.on("mouseout", this.handleHdOut, this);
52766 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
52767 {delegate: "."+this.splitClass});
52769 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
52770 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
52773 this.updateSplitters();
52775 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
52776 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
52777 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
52780 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
52781 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
52783 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
52784 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
52786 if(this.grid.enableColLock !== false){
52787 this.hmenu.add('-',
52788 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
52789 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
52792 if(this.grid.enableColumnHide !== false){
52794 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
52795 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
52796 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
52798 this.hmenu.add('-',
52799 {id:"columns", text: this.columnsText, menu: this.colMenu}
52802 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
52804 this.grid.on("headercontextmenu", this.handleHdCtx, this);
52807 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
52808 this.dd = new Roo.grid.GridDragZone(this.grid, {
52809 ddGroup : this.grid.ddGroup || 'GridDD'
52815 for(var i = 0; i < colCount; i++){
52816 if(cm.isHidden(i)){
52817 this.hideColumn(i);
52819 if(cm.config[i].align){
52820 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
52821 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
52825 this.updateHeaderSortState();
52827 this.beforeInitialResize();
52830 // two part rendering gives faster view to the user
52831 this.renderPhase2.defer(1, this);
52834 renderPhase2 : function(){
52835 // render the rows now
52837 if(this.grid.autoSizeColumns){
52838 this.autoSizeColumns();
52842 beforeInitialResize : function(){
52846 onColumnSplitterMoved : function(i, w){
52847 this.userResized = true;
52848 var cm = this.grid.colModel;
52849 cm.setColumnWidth(i, w, true);
52850 var cid = cm.getColumnId(i);
52851 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
52852 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
52853 this.updateSplitters();
52855 this.grid.fireEvent("columnresize", i, w);
52858 syncRowHeights : function(startIndex, endIndex){
52859 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
52860 startIndex = startIndex || 0;
52861 var mrows = this.getBodyTable().rows;
52862 var lrows = this.getLockedTable().rows;
52863 var len = mrows.length-1;
52864 endIndex = Math.min(endIndex || len, len);
52865 for(var i = startIndex; i <= endIndex; i++){
52866 var m = mrows[i], l = lrows[i];
52867 var h = Math.max(m.offsetHeight, l.offsetHeight);
52868 m.style.height = l.style.height = h + "px";
52873 layout : function(initialRender, is2ndPass){
52875 var auto = g.autoHeight;
52876 var scrollOffset = 16;
52877 var c = g.getGridEl(), cm = this.cm,
52878 expandCol = g.autoExpandColumn,
52880 //c.beginMeasure();
52882 if(!c.dom.offsetWidth){ // display:none?
52884 this.lockedWrap.show();
52885 this.mainWrap.show();
52890 var hasLock = this.cm.isLocked(0);
52892 var tbh = this.headerPanel.getHeight();
52893 var bbh = this.footerPanel.getHeight();
52896 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
52897 var newHeight = ch + c.getBorderWidth("tb");
52899 newHeight = Math.min(g.maxHeight, newHeight);
52901 c.setHeight(newHeight);
52905 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
52908 var s = this.scroller;
52910 var csize = c.getSize(true);
52912 this.el.setSize(csize.width, csize.height);
52914 this.headerPanel.setWidth(csize.width);
52915 this.footerPanel.setWidth(csize.width);
52917 var hdHeight = this.mainHd.getHeight();
52918 var vw = csize.width;
52919 var vh = csize.height - (tbh + bbh);
52923 var bt = this.getBodyTable();
52924 var ltWidth = hasLock ?
52925 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
52927 var scrollHeight = bt.offsetHeight;
52928 var scrollWidth = ltWidth + bt.offsetWidth;
52929 var vscroll = false, hscroll = false;
52931 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
52933 var lw = this.lockedWrap, mw = this.mainWrap;
52934 var lb = this.lockedBody, mb = this.mainBody;
52936 setTimeout(function(){
52937 var t = s.dom.offsetTop;
52938 var w = s.dom.clientWidth,
52939 h = s.dom.clientHeight;
52942 lw.setSize(ltWidth, h);
52944 mw.setLeftTop(ltWidth, t);
52945 mw.setSize(w-ltWidth, h);
52947 lb.setHeight(h-hdHeight);
52948 mb.setHeight(h-hdHeight);
52950 if(is2ndPass !== true && !gv.userResized && expandCol){
52951 // high speed resize without full column calculation
52953 var ci = cm.getIndexById(expandCol);
52955 ci = cm.findColumnIndex(expandCol);
52957 ci = Math.max(0, ci); // make sure it's got at least the first col.
52958 var expandId = cm.getColumnId(ci);
52959 var tw = cm.getTotalWidth(false);
52960 var currentWidth = cm.getColumnWidth(ci);
52961 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
52962 if(currentWidth != cw){
52963 cm.setColumnWidth(ci, cw, true);
52964 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
52965 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
52966 gv.updateSplitters();
52967 gv.layout(false, true);
52979 onWindowResize : function(){
52980 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
52986 appendFooter : function(parentEl){
52990 sortAscText : "Sort Ascending",
52991 sortDescText : "Sort Descending",
52992 lockText : "Lock Column",
52993 unlockText : "Unlock Column",
52994 columnsText : "Columns"
52998 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
52999 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
53000 this.proxy.el.addClass('x-grid3-col-dd');
53003 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
53004 handleMouseDown : function(e){
53008 callHandleMouseDown : function(e){
53009 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
53014 * Ext JS Library 1.1.1
53015 * Copyright(c) 2006-2007, Ext JS, LLC.
53017 * Originally Released Under LGPL - original licence link has changed is not relivant.
53020 * <script type="text/javascript">
53024 // This is a support class used internally by the Grid components
53025 Roo.grid.SplitDragZone = function(grid, hd, hd2){
53027 this.view = grid.getView();
53028 this.proxy = this.view.resizeProxy;
53029 Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
53030 "gridSplitters" + this.grid.getGridEl().id, {
53031 dragElId : Roo.id(this.proxy.dom), resizeFrame:false
53033 this.setHandleElId(Roo.id(hd));
53034 this.setOuterHandleElId(Roo.id(hd2));
53035 this.scroll = false;
53037 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
53038 fly: Roo.Element.fly,
53040 b4StartDrag : function(x, y){
53041 this.view.headersDisabled = true;
53042 this.proxy.setHeight(this.view.mainWrap.getHeight());
53043 var w = this.cm.getColumnWidth(this.cellIndex);
53044 var minw = Math.max(w-this.grid.minColumnWidth, 0);
53045 this.resetConstraints();
53046 this.setXConstraint(minw, 1000);
53047 this.setYConstraint(0, 0);
53048 this.minX = x - minw;
53049 this.maxX = x + 1000;
53051 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
53055 handleMouseDown : function(e){
53056 ev = Roo.EventObject.setEvent(e);
53057 var t = this.fly(ev.getTarget());
53058 if(t.hasClass("x-grid-split")){
53059 this.cellIndex = this.view.getCellIndex(t.dom);
53060 this.split = t.dom;
53061 this.cm = this.grid.colModel;
53062 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
53063 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
53068 endDrag : function(e){
53069 this.view.headersDisabled = false;
53070 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
53071 var diff = endX - this.startPos;
53072 this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
53075 autoOffset : function(){
53076 this.setDelta(0,0);
53080 * Ext JS Library 1.1.1
53081 * Copyright(c) 2006-2007, Ext JS, LLC.
53083 * Originally Released Under LGPL - original licence link has changed is not relivant.
53086 * <script type="text/javascript">
53090 // This is a support class used internally by the Grid components
53091 Roo.grid.GridDragZone = function(grid, config){
53092 this.view = grid.getView();
53093 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
53094 if(this.view.lockedBody){
53095 this.setHandleElId(Roo.id(this.view.mainBody.dom));
53096 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
53098 this.scroll = false;
53100 this.ddel = document.createElement('div');
53101 this.ddel.className = 'x-grid-dd-wrap';
53104 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
53105 ddGroup : "GridDD",
53107 getDragData : function(e){
53108 var t = Roo.lib.Event.getTarget(e);
53109 var rowIndex = this.view.findRowIndex(t);
53110 var sm = this.grid.selModel;
53112 //Roo.log(rowIndex);
53114 if (sm.getSelectedCell) {
53115 // cell selection..
53116 if (!sm.getSelectedCell()) {
53119 if (rowIndex != sm.getSelectedCell()[0]) {
53125 if(rowIndex !== false){
53130 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
53132 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
53135 if (e.hasModifier()){
53136 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
53139 Roo.log("getDragData");
53144 rowIndex: rowIndex,
53145 selections:sm.getSelections ? sm.getSelections() : (
53146 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
53153 onInitDrag : function(e){
53154 var data = this.dragData;
53155 this.ddel.innerHTML = this.grid.getDragDropText();
53156 this.proxy.update(this.ddel);
53157 // fire start drag?
53160 afterRepair : function(){
53161 this.dragging = false;
53164 getRepairXY : function(e, data){
53168 onEndDrag : function(data, e){
53172 onValidDrop : function(dd, e, id){
53177 beforeInvalidDrop : function(e, id){
53182 * Ext JS Library 1.1.1
53183 * Copyright(c) 2006-2007, Ext JS, LLC.
53185 * Originally Released Under LGPL - original licence link has changed is not relivant.
53188 * <script type="text/javascript">
53193 * @class Roo.grid.ColumnModel
53194 * @extends Roo.util.Observable
53195 * This is the default implementation of a ColumnModel used by the Grid. It defines
53196 * the columns in the grid.
53199 var colModel = new Roo.grid.ColumnModel([
53200 {header: "Ticker", width: 60, sortable: true, locked: true},
53201 {header: "Company Name", width: 150, sortable: true},
53202 {header: "Market Cap.", width: 100, sortable: true},
53203 {header: "$ Sales", width: 100, sortable: true, renderer: money},
53204 {header: "Employees", width: 100, sortable: true, resizable: false}
53209 * The config options listed for this class are options which may appear in each
53210 * individual column definition.
53211 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
53213 * @param {Object} config An Array of column config objects. See this class's
53214 * config objects for details.
53216 Roo.grid.ColumnModel = function(config){
53218 * The config passed into the constructor
53220 this.config = config;
53223 // if no id, create one
53224 // if the column does not have a dataIndex mapping,
53225 // map it to the order it is in the config
53226 for(var i = 0, len = config.length; i < len; i++){
53228 if(typeof c.dataIndex == "undefined"){
53231 if(typeof c.renderer == "string"){
53232 c.renderer = Roo.util.Format[c.renderer];
53234 if(typeof c.id == "undefined"){
53237 if(c.editor && c.editor.xtype){
53238 c.editor = Roo.factory(c.editor, Roo.grid);
53240 if(c.editor && c.editor.isFormField){
53241 c.editor = new Roo.grid.GridEditor(c.editor);
53243 this.lookup[c.id] = c;
53247 * The width of columns which have no width specified (defaults to 100)
53250 this.defaultWidth = 100;
53253 * Default sortable of columns which have no sortable specified (defaults to false)
53256 this.defaultSortable = false;
53260 * @event widthchange
53261 * Fires when the width of a column changes.
53262 * @param {ColumnModel} this
53263 * @param {Number} columnIndex The column index
53264 * @param {Number} newWidth The new width
53266 "widthchange": true,
53268 * @event headerchange
53269 * Fires when the text of a header changes.
53270 * @param {ColumnModel} this
53271 * @param {Number} columnIndex The column index
53272 * @param {Number} newText The new header text
53274 "headerchange": true,
53276 * @event hiddenchange
53277 * Fires when a column is hidden or "unhidden".
53278 * @param {ColumnModel} this
53279 * @param {Number} columnIndex The column index
53280 * @param {Boolean} hidden true if hidden, false otherwise
53282 "hiddenchange": true,
53284 * @event columnmoved
53285 * Fires when a column is moved.
53286 * @param {ColumnModel} this
53287 * @param {Number} oldIndex
53288 * @param {Number} newIndex
53290 "columnmoved" : true,
53292 * @event columlockchange
53293 * Fires when a column's locked state is changed
53294 * @param {ColumnModel} this
53295 * @param {Number} colIndex
53296 * @param {Boolean} locked true if locked
53298 "columnlockchange" : true
53300 Roo.grid.ColumnModel.superclass.constructor.call(this);
53302 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
53304 * @cfg {String} header The header text to display in the Grid view.
53307 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
53308 * {@link Roo.data.Record} definition from which to draw the column's value. If not
53309 * specified, the column's index is used as an index into the Record's data Array.
53312 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
53313 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
53316 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
53317 * Defaults to the value of the {@link #defaultSortable} property.
53318 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
53321 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
53324 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
53327 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
53330 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
53333 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
53334 * given the cell's data value. See {@link #setRenderer}. If not specified, the
53335 * default renderer uses the raw data value.
53338 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
53341 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
53345 * Returns the id of the column at the specified index.
53346 * @param {Number} index The column index
53347 * @return {String} the id
53349 getColumnId : function(index){
53350 return this.config[index].id;
53354 * Returns the column for a specified id.
53355 * @param {String} id The column id
53356 * @return {Object} the column
53358 getColumnById : function(id){
53359 return this.lookup[id];
53364 * Returns the column for a specified dataIndex.
53365 * @param {String} dataIndex The column dataIndex
53366 * @return {Object|Boolean} the column or false if not found
53368 getColumnByDataIndex: function(dataIndex){
53369 var index = this.findColumnIndex(dataIndex);
53370 return index > -1 ? this.config[index] : false;
53374 * Returns the index for a specified column id.
53375 * @param {String} id The column id
53376 * @return {Number} the index, or -1 if not found
53378 getIndexById : function(id){
53379 for(var i = 0, len = this.config.length; i < len; i++){
53380 if(this.config[i].id == id){
53388 * Returns the index for a specified column dataIndex.
53389 * @param {String} dataIndex The column dataIndex
53390 * @return {Number} the index, or -1 if not found
53393 findColumnIndex : function(dataIndex){
53394 for(var i = 0, len = this.config.length; i < len; i++){
53395 if(this.config[i].dataIndex == dataIndex){
53403 moveColumn : function(oldIndex, newIndex){
53404 var c = this.config[oldIndex];
53405 this.config.splice(oldIndex, 1);
53406 this.config.splice(newIndex, 0, c);
53407 this.dataMap = null;
53408 this.fireEvent("columnmoved", this, oldIndex, newIndex);
53411 isLocked : function(colIndex){
53412 return this.config[colIndex].locked === true;
53415 setLocked : function(colIndex, value, suppressEvent){
53416 if(this.isLocked(colIndex) == value){
53419 this.config[colIndex].locked = value;
53420 if(!suppressEvent){
53421 this.fireEvent("columnlockchange", this, colIndex, value);
53425 getTotalLockedWidth : function(){
53426 var totalWidth = 0;
53427 for(var i = 0; i < this.config.length; i++){
53428 if(this.isLocked(i) && !this.isHidden(i)){
53429 this.totalWidth += this.getColumnWidth(i);
53435 getLockedCount : function(){
53436 for(var i = 0, len = this.config.length; i < len; i++){
53437 if(!this.isLocked(i)){
53444 * Returns the number of columns.
53447 getColumnCount : function(visibleOnly){
53448 if(visibleOnly === true){
53450 for(var i = 0, len = this.config.length; i < len; i++){
53451 if(!this.isHidden(i)){
53457 return this.config.length;
53461 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
53462 * @param {Function} fn
53463 * @param {Object} scope (optional)
53464 * @return {Array} result
53466 getColumnsBy : function(fn, scope){
53468 for(var i = 0, len = this.config.length; i < len; i++){
53469 var c = this.config[i];
53470 if(fn.call(scope||this, c, i) === true){
53478 * Returns true if the specified column is sortable.
53479 * @param {Number} col The column index
53480 * @return {Boolean}
53482 isSortable : function(col){
53483 if(typeof this.config[col].sortable == "undefined"){
53484 return this.defaultSortable;
53486 return this.config[col].sortable;
53490 * Returns the rendering (formatting) function defined for the column.
53491 * @param {Number} col The column index.
53492 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
53494 getRenderer : function(col){
53495 if(!this.config[col].renderer){
53496 return Roo.grid.ColumnModel.defaultRenderer;
53498 return this.config[col].renderer;
53502 * Sets the rendering (formatting) function for a column.
53503 * @param {Number} col The column index
53504 * @param {Function} fn The function to use to process the cell's raw data
53505 * to return HTML markup for the grid view. The render function is called with
53506 * the following parameters:<ul>
53507 * <li>Data value.</li>
53508 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
53509 * <li>css A CSS style string to apply to the table cell.</li>
53510 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
53511 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
53512 * <li>Row index</li>
53513 * <li>Column index</li>
53514 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
53516 setRenderer : function(col, fn){
53517 this.config[col].renderer = fn;
53521 * Returns the width for the specified column.
53522 * @param {Number} col The column index
53525 getColumnWidth : function(col){
53526 return this.config[col].width * 1 || this.defaultWidth;
53530 * Sets the width for a column.
53531 * @param {Number} col The column index
53532 * @param {Number} width The new width
53534 setColumnWidth : function(col, width, suppressEvent){
53535 this.config[col].width = width;
53536 this.totalWidth = null;
53537 if(!suppressEvent){
53538 this.fireEvent("widthchange", this, col, width);
53543 * Returns the total width of all columns.
53544 * @param {Boolean} includeHidden True to include hidden column widths
53547 getTotalWidth : function(includeHidden){
53548 if(!this.totalWidth){
53549 this.totalWidth = 0;
53550 for(var i = 0, len = this.config.length; i < len; i++){
53551 if(includeHidden || !this.isHidden(i)){
53552 this.totalWidth += this.getColumnWidth(i);
53556 return this.totalWidth;
53560 * Returns the header for the specified column.
53561 * @param {Number} col The column index
53564 getColumnHeader : function(col){
53565 return this.config[col].header;
53569 * Sets the header for a column.
53570 * @param {Number} col The column index
53571 * @param {String} header The new header
53573 setColumnHeader : function(col, header){
53574 this.config[col].header = header;
53575 this.fireEvent("headerchange", this, col, header);
53579 * Returns the tooltip for the specified column.
53580 * @param {Number} col The column index
53583 getColumnTooltip : function(col){
53584 return this.config[col].tooltip;
53587 * Sets the tooltip for a column.
53588 * @param {Number} col The column index
53589 * @param {String} tooltip The new tooltip
53591 setColumnTooltip : function(col, tooltip){
53592 this.config[col].tooltip = tooltip;
53596 * Returns the dataIndex for the specified column.
53597 * @param {Number} col The column index
53600 getDataIndex : function(col){
53601 return this.config[col].dataIndex;
53605 * Sets the dataIndex for a column.
53606 * @param {Number} col The column index
53607 * @param {Number} dataIndex The new dataIndex
53609 setDataIndex : function(col, dataIndex){
53610 this.config[col].dataIndex = dataIndex;
53616 * Returns true if the cell is editable.
53617 * @param {Number} colIndex The column index
53618 * @param {Number} rowIndex The row index
53619 * @return {Boolean}
53621 isCellEditable : function(colIndex, rowIndex){
53622 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
53626 * Returns the editor defined for the cell/column.
53627 * return false or null to disable editing.
53628 * @param {Number} colIndex The column index
53629 * @param {Number} rowIndex The row index
53632 getCellEditor : function(colIndex, rowIndex){
53633 return this.config[colIndex].editor;
53637 * Sets if a column is editable.
53638 * @param {Number} col The column index
53639 * @param {Boolean} editable True if the column is editable
53641 setEditable : function(col, editable){
53642 this.config[col].editable = editable;
53647 * Returns true if the column is hidden.
53648 * @param {Number} colIndex The column index
53649 * @return {Boolean}
53651 isHidden : function(colIndex){
53652 return this.config[colIndex].hidden;
53657 * Returns true if the column width cannot be changed
53659 isFixed : function(colIndex){
53660 return this.config[colIndex].fixed;
53664 * Returns true if the column can be resized
53665 * @return {Boolean}
53667 isResizable : function(colIndex){
53668 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
53671 * Sets if a column is hidden.
53672 * @param {Number} colIndex The column index
53673 * @param {Boolean} hidden True if the column is hidden
53675 setHidden : function(colIndex, hidden){
53676 this.config[colIndex].hidden = hidden;
53677 this.totalWidth = null;
53678 this.fireEvent("hiddenchange", this, colIndex, hidden);
53682 * Sets the editor for a column.
53683 * @param {Number} col The column index
53684 * @param {Object} editor The editor object
53686 setEditor : function(col, editor){
53687 this.config[col].editor = editor;
53691 Roo.grid.ColumnModel.defaultRenderer = function(value){
53692 if(typeof value == "string" && value.length < 1){
53698 // Alias for backwards compatibility
53699 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
53702 * Ext JS Library 1.1.1
53703 * Copyright(c) 2006-2007, Ext JS, LLC.
53705 * Originally Released Under LGPL - original licence link has changed is not relivant.
53708 * <script type="text/javascript">
53712 * @class Roo.grid.AbstractSelectionModel
53713 * @extends Roo.util.Observable
53714 * Abstract base class for grid SelectionModels. It provides the interface that should be
53715 * implemented by descendant classes. This class should not be directly instantiated.
53718 Roo.grid.AbstractSelectionModel = function(){
53719 this.locked = false;
53720 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
53723 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
53724 /** @ignore Called by the grid automatically. Do not call directly. */
53725 init : function(grid){
53731 * Locks the selections.
53734 this.locked = true;
53738 * Unlocks the selections.
53740 unlock : function(){
53741 this.locked = false;
53745 * Returns true if the selections are locked.
53746 * @return {Boolean}
53748 isLocked : function(){
53749 return this.locked;
53753 * Ext JS Library 1.1.1
53754 * Copyright(c) 2006-2007, Ext JS, LLC.
53756 * Originally Released Under LGPL - original licence link has changed is not relivant.
53759 * <script type="text/javascript">
53762 * @extends Roo.grid.AbstractSelectionModel
53763 * @class Roo.grid.RowSelectionModel
53764 * The default SelectionModel used by {@link Roo.grid.Grid}.
53765 * It supports multiple selections and keyboard selection/navigation.
53767 * @param {Object} config
53769 Roo.grid.RowSelectionModel = function(config){
53770 Roo.apply(this, config);
53771 this.selections = new Roo.util.MixedCollection(false, function(o){
53776 this.lastActive = false;
53780 * @event selectionchange
53781 * Fires when the selection changes
53782 * @param {SelectionModel} this
53784 "selectionchange" : true,
53786 * @event afterselectionchange
53787 * Fires after the selection changes (eg. by key press or clicking)
53788 * @param {SelectionModel} this
53790 "afterselectionchange" : true,
53792 * @event beforerowselect
53793 * Fires when a row is selected being selected, return false to cancel.
53794 * @param {SelectionModel} this
53795 * @param {Number} rowIndex The selected index
53796 * @param {Boolean} keepExisting False if other selections will be cleared
53798 "beforerowselect" : true,
53801 * Fires when a row is selected.
53802 * @param {SelectionModel} this
53803 * @param {Number} rowIndex The selected index
53804 * @param {Roo.data.Record} r The record
53806 "rowselect" : true,
53808 * @event rowdeselect
53809 * Fires when a row is deselected.
53810 * @param {SelectionModel} this
53811 * @param {Number} rowIndex The selected index
53813 "rowdeselect" : true
53815 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
53816 this.locked = false;
53819 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
53821 * @cfg {Boolean} singleSelect
53822 * True to allow selection of only one row at a time (defaults to false)
53824 singleSelect : false,
53827 initEvents : function(){
53829 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
53830 this.grid.on("mousedown", this.handleMouseDown, this);
53831 }else{ // allow click to work like normal
53832 this.grid.on("rowclick", this.handleDragableRowClick, this);
53835 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
53836 "up" : function(e){
53838 this.selectPrevious(e.shiftKey);
53839 }else if(this.last !== false && this.lastActive !== false){
53840 var last = this.last;
53841 this.selectRange(this.last, this.lastActive-1);
53842 this.grid.getView().focusRow(this.lastActive);
53843 if(last !== false){
53847 this.selectFirstRow();
53849 this.fireEvent("afterselectionchange", this);
53851 "down" : function(e){
53853 this.selectNext(e.shiftKey);
53854 }else if(this.last !== false && this.lastActive !== false){
53855 var last = this.last;
53856 this.selectRange(this.last, this.lastActive+1);
53857 this.grid.getView().focusRow(this.lastActive);
53858 if(last !== false){
53862 this.selectFirstRow();
53864 this.fireEvent("afterselectionchange", this);
53869 var view = this.grid.view;
53870 view.on("refresh", this.onRefresh, this);
53871 view.on("rowupdated", this.onRowUpdated, this);
53872 view.on("rowremoved", this.onRemove, this);
53876 onRefresh : function(){
53877 var ds = this.grid.dataSource, i, v = this.grid.view;
53878 var s = this.selections;
53879 s.each(function(r){
53880 if((i = ds.indexOfId(r.id)) != -1){
53889 onRemove : function(v, index, r){
53890 this.selections.remove(r);
53894 onRowUpdated : function(v, index, r){
53895 if(this.isSelected(r)){
53896 v.onRowSelect(index);
53902 * @param {Array} records The records to select
53903 * @param {Boolean} keepExisting (optional) True to keep existing selections
53905 selectRecords : function(records, keepExisting){
53907 this.clearSelections();
53909 var ds = this.grid.dataSource;
53910 for(var i = 0, len = records.length; i < len; i++){
53911 this.selectRow(ds.indexOf(records[i]), true);
53916 * Gets the number of selected rows.
53919 getCount : function(){
53920 return this.selections.length;
53924 * Selects the first row in the grid.
53926 selectFirstRow : function(){
53931 * Select the last row.
53932 * @param {Boolean} keepExisting (optional) True to keep existing selections
53934 selectLastRow : function(keepExisting){
53935 this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
53939 * Selects the row immediately following the last selected row.
53940 * @param {Boolean} keepExisting (optional) True to keep existing selections
53942 selectNext : function(keepExisting){
53943 if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
53944 this.selectRow(this.last+1, keepExisting);
53945 this.grid.getView().focusRow(this.last);
53950 * Selects the row that precedes the last selected row.
53951 * @param {Boolean} keepExisting (optional) True to keep existing selections
53953 selectPrevious : function(keepExisting){
53955 this.selectRow(this.last-1, keepExisting);
53956 this.grid.getView().focusRow(this.last);
53961 * Returns the selected records
53962 * @return {Array} Array of selected records
53964 getSelections : function(){
53965 return [].concat(this.selections.items);
53969 * Returns the first selected record.
53972 getSelected : function(){
53973 return this.selections.itemAt(0);
53978 * Clears all selections.
53980 clearSelections : function(fast){
53981 if(this.locked) return;
53983 var ds = this.grid.dataSource;
53984 var s = this.selections;
53985 s.each(function(r){
53986 this.deselectRow(ds.indexOfId(r.id));
53990 this.selections.clear();
53997 * Selects all rows.
53999 selectAll : function(){
54000 if(this.locked) return;
54001 this.selections.clear();
54002 for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
54003 this.selectRow(i, true);
54008 * Returns True if there is a selection.
54009 * @return {Boolean}
54011 hasSelection : function(){
54012 return this.selections.length > 0;
54016 * Returns True if the specified row is selected.
54017 * @param {Number/Record} record The record or index of the record to check
54018 * @return {Boolean}
54020 isSelected : function(index){
54021 var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
54022 return (r && this.selections.key(r.id) ? true : false);
54026 * Returns True if the specified record id is selected.
54027 * @param {String} id The id of record to check
54028 * @return {Boolean}
54030 isIdSelected : function(id){
54031 return (this.selections.key(id) ? true : false);
54035 handleMouseDown : function(e, t){
54036 var view = this.grid.getView(), rowIndex;
54037 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
54040 if(e.shiftKey && this.last !== false){
54041 var last = this.last;
54042 this.selectRange(last, rowIndex, e.ctrlKey);
54043 this.last = last; // reset the last
54044 view.focusRow(rowIndex);
54046 var isSelected = this.isSelected(rowIndex);
54047 if(e.button !== 0 && isSelected){
54048 view.focusRow(rowIndex);
54049 }else if(e.ctrlKey && isSelected){
54050 this.deselectRow(rowIndex);
54051 }else if(!isSelected){
54052 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
54053 view.focusRow(rowIndex);
54056 this.fireEvent("afterselectionchange", this);
54059 handleDragableRowClick : function(grid, rowIndex, e)
54061 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
54062 this.selectRow(rowIndex, false);
54063 grid.view.focusRow(rowIndex);
54064 this.fireEvent("afterselectionchange", this);
54069 * Selects multiple rows.
54070 * @param {Array} rows Array of the indexes of the row to select
54071 * @param {Boolean} keepExisting (optional) True to keep existing selections
54073 selectRows : function(rows, keepExisting){
54075 this.clearSelections();
54077 for(var i = 0, len = rows.length; i < len; i++){
54078 this.selectRow(rows[i], true);
54083 * Selects a range of rows. All rows in between startRow and endRow are also selected.
54084 * @param {Number} startRow The index of the first row in the range
54085 * @param {Number} endRow The index of the last row in the range
54086 * @param {Boolean} keepExisting (optional) True to retain existing selections
54088 selectRange : function(startRow, endRow, keepExisting){
54089 if(this.locked) return;
54091 this.clearSelections();
54093 if(startRow <= endRow){
54094 for(var i = startRow; i <= endRow; i++){
54095 this.selectRow(i, true);
54098 for(var i = startRow; i >= endRow; i--){
54099 this.selectRow(i, true);
54105 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
54106 * @param {Number} startRow The index of the first row in the range
54107 * @param {Number} endRow The index of the last row in the range
54109 deselectRange : function(startRow, endRow, preventViewNotify){
54110 if(this.locked) return;
54111 for(var i = startRow; i <= endRow; i++){
54112 this.deselectRow(i, preventViewNotify);
54118 * @param {Number} row The index of the row to select
54119 * @param {Boolean} keepExisting (optional) True to keep existing selections
54121 selectRow : function(index, keepExisting, preventViewNotify){
54122 if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
54123 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
54124 if(!keepExisting || this.singleSelect){
54125 this.clearSelections();
54127 var r = this.grid.dataSource.getAt(index);
54128 this.selections.add(r);
54129 this.last = this.lastActive = index;
54130 if(!preventViewNotify){
54131 this.grid.getView().onRowSelect(index);
54133 this.fireEvent("rowselect", this, index, r);
54134 this.fireEvent("selectionchange", this);
54140 * @param {Number} row The index of the row to deselect
54142 deselectRow : function(index, preventViewNotify){
54143 if(this.locked) return;
54144 if(this.last == index){
54147 if(this.lastActive == index){
54148 this.lastActive = false;
54150 var r = this.grid.dataSource.getAt(index);
54151 this.selections.remove(r);
54152 if(!preventViewNotify){
54153 this.grid.getView().onRowDeselect(index);
54155 this.fireEvent("rowdeselect", this, index);
54156 this.fireEvent("selectionchange", this);
54160 restoreLast : function(){
54162 this.last = this._last;
54167 acceptsNav : function(row, col, cm){
54168 return !cm.isHidden(col) && cm.isCellEditable(col, row);
54172 onEditorKey : function(field, e){
54173 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
54178 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
54180 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
54182 }else if(k == e.ENTER && !e.ctrlKey){
54186 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
54188 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
54190 }else if(k == e.ESC){
54194 g.startEditing(newCell[0], newCell[1]);
54199 * Ext JS Library 1.1.1
54200 * Copyright(c) 2006-2007, Ext JS, LLC.
54202 * Originally Released Under LGPL - original licence link has changed is not relivant.
54205 * <script type="text/javascript">
54208 * @class Roo.grid.CellSelectionModel
54209 * @extends Roo.grid.AbstractSelectionModel
54210 * This class provides the basic implementation for cell selection in a grid.
54212 * @param {Object} config The object containing the configuration of this model.
54213 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
54215 Roo.grid.CellSelectionModel = function(config){
54216 Roo.apply(this, config);
54218 this.selection = null;
54222 * @event beforerowselect
54223 * Fires before a cell is selected.
54224 * @param {SelectionModel} this
54225 * @param {Number} rowIndex The selected row index
54226 * @param {Number} colIndex The selected cell index
54228 "beforecellselect" : true,
54230 * @event cellselect
54231 * Fires when a cell is selected.
54232 * @param {SelectionModel} this
54233 * @param {Number} rowIndex The selected row index
54234 * @param {Number} colIndex The selected cell index
54236 "cellselect" : true,
54238 * @event selectionchange
54239 * Fires when the active selection changes.
54240 * @param {SelectionModel} this
54241 * @param {Object} selection null for no selection or an object (o) with two properties
54243 <li>o.record: the record object for the row the selection is in</li>
54244 <li>o.cell: An array of [rowIndex, columnIndex]</li>
54247 "selectionchange" : true,
54250 * Fires when the tab (or enter) was pressed on the last editable cell
54251 * You can use this to trigger add new row.
54252 * @param {SelectionModel} this
54256 * @event beforeeditnext
54257 * Fires before the next editable sell is made active
54258 * You can use this to skip to another cell or fire the tabend
54259 * if you set cell to false
54260 * @param {Object} eventdata object : { cell : [ row, col ] }
54262 "beforeeditnext" : true
54264 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
54267 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
54269 enter_is_tab: false,
54272 initEvents : function(){
54273 this.grid.on("mousedown", this.handleMouseDown, this);
54274 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
54275 var view = this.grid.view;
54276 view.on("refresh", this.onViewChange, this);
54277 view.on("rowupdated", this.onRowUpdated, this);
54278 view.on("beforerowremoved", this.clearSelections, this);
54279 view.on("beforerowsinserted", this.clearSelections, this);
54280 if(this.grid.isEditor){
54281 this.grid.on("beforeedit", this.beforeEdit, this);
54286 beforeEdit : function(e){
54287 this.select(e.row, e.column, false, true, e.record);
54291 onRowUpdated : function(v, index, r){
54292 if(this.selection && this.selection.record == r){
54293 v.onCellSelect(index, this.selection.cell[1]);
54298 onViewChange : function(){
54299 this.clearSelections(true);
54303 * Returns the currently selected cell,.
54304 * @return {Array} The selected cell (row, column) or null if none selected.
54306 getSelectedCell : function(){
54307 return this.selection ? this.selection.cell : null;
54311 * Clears all selections.
54312 * @param {Boolean} true to prevent the gridview from being notified about the change.
54314 clearSelections : function(preventNotify){
54315 var s = this.selection;
54317 if(preventNotify !== true){
54318 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
54320 this.selection = null;
54321 this.fireEvent("selectionchange", this, null);
54326 * Returns true if there is a selection.
54327 * @return {Boolean}
54329 hasSelection : function(){
54330 return this.selection ? true : false;
54334 handleMouseDown : function(e, t){
54335 var v = this.grid.getView();
54336 if(this.isLocked()){
54339 var row = v.findRowIndex(t);
54340 var cell = v.findCellIndex(t);
54341 if(row !== false && cell !== false){
54342 this.select(row, cell);
54348 * @param {Number} rowIndex
54349 * @param {Number} collIndex
54351 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
54352 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
54353 this.clearSelections();
54354 r = r || this.grid.dataSource.getAt(rowIndex);
54357 cell : [rowIndex, colIndex]
54359 if(!preventViewNotify){
54360 var v = this.grid.getView();
54361 v.onCellSelect(rowIndex, colIndex);
54362 if(preventFocus !== true){
54363 v.focusCell(rowIndex, colIndex);
54366 this.fireEvent("cellselect", this, rowIndex, colIndex);
54367 this.fireEvent("selectionchange", this, this.selection);
54372 isSelectable : function(rowIndex, colIndex, cm){
54373 return !cm.isHidden(colIndex);
54377 handleKeyDown : function(e){
54378 //Roo.log('Cell Sel Model handleKeyDown');
54379 if(!e.isNavKeyPress()){
54382 var g = this.grid, s = this.selection;
54385 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
54387 this.select(cell[0], cell[1]);
54392 var walk = function(row, col, step){
54393 return g.walkCells(row, col, step, sm.isSelectable, sm);
54395 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
54402 // handled by onEditorKey
54403 if (g.isEditor && g.editing) {
54407 newCell = walk(r, c-1, -1);
54409 newCell = walk(r, c+1, 1);
54414 newCell = walk(r+1, c, 1);
54418 newCell = walk(r-1, c, -1);
54422 newCell = walk(r, c+1, 1);
54426 newCell = walk(r, c-1, -1);
54431 if(g.isEditor && !g.editing){
54432 g.startEditing(r, c);
54441 this.select(newCell[0], newCell[1]);
54447 acceptsNav : function(row, col, cm){
54448 return !cm.isHidden(col) && cm.isCellEditable(col, row);
54452 * @param {Number} field (not used) - as it's normally used as a listener
54453 * @param {Number} e - event - fake it by using
54455 * var e = Roo.EventObjectImpl.prototype;
54456 * e.keyCode = e.TAB
54460 onEditorKey : function(field, e){
54462 var k = e.getKey(),
54465 ed = g.activeEditor,
54467 ///Roo.log('onEditorKey' + k);
54470 if (this.enter_is_tab && k == e.ENTER) {
54476 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
54478 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
54484 } else if(k == e.ENTER && !e.ctrlKey){
54487 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
54489 } else if(k == e.ESC){
54494 var ecall = { cell : newCell, forward : forward };
54495 this.fireEvent('beforeeditnext', ecall );
54496 newCell = ecall.cell;
54497 forward = ecall.forward;
54501 //Roo.log('next cell after edit');
54502 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
54503 } else if (forward) {
54504 // tabbed past last
54505 this.fireEvent.defer(100, this, ['tabend',this]);
54510 * Ext JS Library 1.1.1
54511 * Copyright(c) 2006-2007, Ext JS, LLC.
54513 * Originally Released Under LGPL - original licence link has changed is not relivant.
54516 * <script type="text/javascript">
54520 * @class Roo.grid.EditorGrid
54521 * @extends Roo.grid.Grid
54522 * Class for creating and editable grid.
54523 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
54524 * The container MUST have some type of size defined for the grid to fill. The container will be
54525 * automatically set to position relative if it isn't already.
54526 * @param {Object} dataSource The data model to bind to
54527 * @param {Object} colModel The column model with info about this grid's columns
54529 Roo.grid.EditorGrid = function(container, config){
54530 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
54531 this.getGridEl().addClass("xedit-grid");
54533 if(!this.selModel){
54534 this.selModel = new Roo.grid.CellSelectionModel();
54537 this.activeEditor = null;
54541 * @event beforeedit
54542 * Fires before cell editing is triggered. The edit event object has the following properties <br />
54543 * <ul style="padding:5px;padding-left:16px;">
54544 * <li>grid - This grid</li>
54545 * <li>record - The record being edited</li>
54546 * <li>field - The field name being edited</li>
54547 * <li>value - The value for the field being edited.</li>
54548 * <li>row - The grid row index</li>
54549 * <li>column - The grid column index</li>
54550 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
54552 * @param {Object} e An edit event (see above for description)
54554 "beforeedit" : true,
54557 * Fires after a cell is edited. <br />
54558 * <ul style="padding:5px;padding-left:16px;">
54559 * <li>grid - This grid</li>
54560 * <li>record - The record being edited</li>
54561 * <li>field - The field name being edited</li>
54562 * <li>value - The value being set</li>
54563 * <li>originalValue - The original value for the field, before the edit.</li>
54564 * <li>row - The grid row index</li>
54565 * <li>column - The grid column index</li>
54567 * @param {Object} e An edit event (see above for description)
54569 "afteredit" : true,
54571 * @event validateedit
54572 * Fires after a cell is edited, but before the value is set in the record.
54573 * You can use this to modify the value being set in the field, Return false
54574 * to cancel the change. The edit event object has the following properties <br />
54575 * <ul style="padding:5px;padding-left:16px;">
54576 * <li>editor - This editor</li>
54577 * <li>grid - This grid</li>
54578 * <li>record - The record being edited</li>
54579 * <li>field - The field name being edited</li>
54580 * <li>value - The value being set</li>
54581 * <li>originalValue - The original value for the field, before the edit.</li>
54582 * <li>row - The grid row index</li>
54583 * <li>column - The grid column index</li>
54584 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
54586 * @param {Object} e An edit event (see above for description)
54588 "validateedit" : true
54590 this.on("bodyscroll", this.stopEditing, this);
54591 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
54594 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
54596 * @cfg {Number} clicksToEdit
54597 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
54604 trackMouseOver: false, // causes very odd FF errors
54606 onCellDblClick : function(g, row, col){
54607 this.startEditing(row, col);
54610 onEditComplete : function(ed, value, startValue){
54611 this.editing = false;
54612 this.activeEditor = null;
54613 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
54615 var field = this.colModel.getDataIndex(ed.col);
54620 originalValue: startValue,
54627 var cell = Roo.get(this.view.getCell(ed.row,ed.col))
54630 if(String(value) !== String(startValue)){
54632 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
54633 r.set(field, e.value);
54634 // if we are dealing with a combo box..
54635 // then we also set the 'name' colum to be the displayField
54636 if (ed.field.displayField && ed.field.name) {
54637 r.set(ed.field.name, ed.field.el.dom.value);
54640 delete e.cancel; //?? why!!!
54641 this.fireEvent("afteredit", e);
54644 this.fireEvent("afteredit", e); // always fire it!
54646 this.view.focusCell(ed.row, ed.col);
54650 * Starts editing the specified for the specified row/column
54651 * @param {Number} rowIndex
54652 * @param {Number} colIndex
54654 startEditing : function(row, col){
54655 this.stopEditing();
54656 if(this.colModel.isCellEditable(col, row)){
54657 this.view.ensureVisible(row, col, true);
54659 var r = this.dataSource.getAt(row);
54660 var field = this.colModel.getDataIndex(col);
54661 var cell = Roo.get(this.view.getCell(row,col));
54666 value: r.data[field],
54671 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
54672 this.editing = true;
54673 var ed = this.colModel.getCellEditor(col, row);
54679 ed.render(ed.parentEl || document.body);
54685 (function(){ // complex but required for focus issues in safari, ie and opera
54689 ed.on("complete", this.onEditComplete, this, {single: true});
54690 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
54691 this.activeEditor = ed;
54692 var v = r.data[field];
54693 ed.startEdit(this.view.getCell(row, col), v);
54694 // combo's with 'displayField and name set
54695 if (ed.field.displayField && ed.field.name) {
54696 ed.field.el.dom.value = r.data[ed.field.name];
54700 }).defer(50, this);
54706 * Stops any active editing
54708 stopEditing : function(){
54709 if(this.activeEditor){
54710 this.activeEditor.completeEdit();
54712 this.activeEditor = null;
54716 * Called to get grid's drag proxy text, by default returns this.ddText.
54719 getDragDropText : function(){
54720 var count = this.selModel.getSelectedCell() ? 1 : 0;
54721 return String.format(this.ddText, count, count == 1 ? '' : 's');
54726 * Ext JS Library 1.1.1
54727 * Copyright(c) 2006-2007, Ext JS, LLC.
54729 * Originally Released Under LGPL - original licence link has changed is not relivant.
54732 * <script type="text/javascript">
54735 // private - not really -- you end up using it !
54736 // This is a support class used internally by the Grid components
54739 * @class Roo.grid.GridEditor
54740 * @extends Roo.Editor
54741 * Class for creating and editable grid elements.
54742 * @param {Object} config any settings (must include field)
54744 Roo.grid.GridEditor = function(field, config){
54745 if (!config && field.field) {
54747 field = Roo.factory(config.field, Roo.form);
54749 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
54750 field.monitorTab = false;
54753 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
54756 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
54759 alignment: "tl-tl",
54762 cls: "x-small-editor x-grid-editor",
54767 * Ext JS Library 1.1.1
54768 * Copyright(c) 2006-2007, Ext JS, LLC.
54770 * Originally Released Under LGPL - original licence link has changed is not relivant.
54773 * <script type="text/javascript">
54778 Roo.grid.PropertyRecord = Roo.data.Record.create([
54779 {name:'name',type:'string'}, 'value'
54783 Roo.grid.PropertyStore = function(grid, source){
54785 this.store = new Roo.data.Store({
54786 recordType : Roo.grid.PropertyRecord
54788 this.store.on('update', this.onUpdate, this);
54790 this.setSource(source);
54792 Roo.grid.PropertyStore.superclass.constructor.call(this);
54797 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
54798 setSource : function(o){
54800 this.store.removeAll();
54803 if(this.isEditableValue(o[k])){
54804 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
54807 this.store.loadRecords({records: data}, {}, true);
54810 onUpdate : function(ds, record, type){
54811 if(type == Roo.data.Record.EDIT){
54812 var v = record.data['value'];
54813 var oldValue = record.modified['value'];
54814 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
54815 this.source[record.id] = v;
54817 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
54824 getProperty : function(row){
54825 return this.store.getAt(row);
54828 isEditableValue: function(val){
54829 if(val && val instanceof Date){
54831 }else if(typeof val == 'object' || typeof val == 'function'){
54837 setValue : function(prop, value){
54838 this.source[prop] = value;
54839 this.store.getById(prop).set('value', value);
54842 getSource : function(){
54843 return this.source;
54847 Roo.grid.PropertyColumnModel = function(grid, store){
54850 g.PropertyColumnModel.superclass.constructor.call(this, [
54851 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
54852 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
54854 this.store = store;
54855 this.bselect = Roo.DomHelper.append(document.body, {
54856 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
54857 {tag: 'option', value: 'true', html: 'true'},
54858 {tag: 'option', value: 'false', html: 'false'}
54861 Roo.id(this.bselect);
54864 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
54865 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
54866 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
54867 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
54868 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
54870 this.renderCellDelegate = this.renderCell.createDelegate(this);
54871 this.renderPropDelegate = this.renderProp.createDelegate(this);
54874 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
54878 valueText : 'Value',
54880 dateFormat : 'm/j/Y',
54883 renderDate : function(dateVal){
54884 return dateVal.dateFormat(this.dateFormat);
54887 renderBool : function(bVal){
54888 return bVal ? 'true' : 'false';
54891 isCellEditable : function(colIndex, rowIndex){
54892 return colIndex == 1;
54895 getRenderer : function(col){
54897 this.renderCellDelegate : this.renderPropDelegate;
54900 renderProp : function(v){
54901 return this.getPropertyName(v);
54904 renderCell : function(val){
54906 if(val instanceof Date){
54907 rv = this.renderDate(val);
54908 }else if(typeof val == 'boolean'){
54909 rv = this.renderBool(val);
54911 return Roo.util.Format.htmlEncode(rv);
54914 getPropertyName : function(name){
54915 var pn = this.grid.propertyNames;
54916 return pn && pn[name] ? pn[name] : name;
54919 getCellEditor : function(colIndex, rowIndex){
54920 var p = this.store.getProperty(rowIndex);
54921 var n = p.data['name'], val = p.data['value'];
54923 if(typeof(this.grid.customEditors[n]) == 'string'){
54924 return this.editors[this.grid.customEditors[n]];
54926 if(typeof(this.grid.customEditors[n]) != 'undefined'){
54927 return this.grid.customEditors[n];
54929 if(val instanceof Date){
54930 return this.editors['date'];
54931 }else if(typeof val == 'number'){
54932 return this.editors['number'];
54933 }else if(typeof val == 'boolean'){
54934 return this.editors['boolean'];
54936 return this.editors['string'];
54942 * @class Roo.grid.PropertyGrid
54943 * @extends Roo.grid.EditorGrid
54944 * This class represents the interface of a component based property grid control.
54945 * <br><br>Usage:<pre><code>
54946 var grid = new Roo.grid.PropertyGrid("my-container-id", {
54954 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
54955 * The container MUST have some type of size defined for the grid to fill. The container will be
54956 * automatically set to position relative if it isn't already.
54957 * @param {Object} config A config object that sets properties on this grid.
54959 Roo.grid.PropertyGrid = function(container, config){
54960 config = config || {};
54961 var store = new Roo.grid.PropertyStore(this);
54962 this.store = store;
54963 var cm = new Roo.grid.PropertyColumnModel(this, store);
54964 store.store.sort('name', 'ASC');
54965 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
54968 enableColLock:false,
54969 enableColumnMove:false,
54971 trackMouseOver: false,
54974 this.getGridEl().addClass('x-props-grid');
54975 this.lastEditRow = null;
54976 this.on('columnresize', this.onColumnResize, this);
54979 * @event beforepropertychange
54980 * Fires before a property changes (return false to stop?)
54981 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
54982 * @param {String} id Record Id
54983 * @param {String} newval New Value
54984 * @param {String} oldval Old Value
54986 "beforepropertychange": true,
54988 * @event propertychange
54989 * Fires after a property changes
54990 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
54991 * @param {String} id Record Id
54992 * @param {String} newval New Value
54993 * @param {String} oldval Old Value
54995 "propertychange": true
54997 this.customEditors = this.customEditors || {};
54999 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
55002 * @cfg {Object} customEditors map of colnames=> custom editors.
55003 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
55004 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
55005 * false disables editing of the field.
55009 * @cfg {Object} propertyNames map of property Names to their displayed value
55012 render : function(){
55013 Roo.grid.PropertyGrid.superclass.render.call(this);
55014 this.autoSize.defer(100, this);
55017 autoSize : function(){
55018 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
55020 this.view.fitColumns();
55024 onColumnResize : function(){
55025 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
55029 * Sets the data for the Grid
55030 * accepts a Key => Value object of all the elements avaiable.
55031 * @param {Object} data to appear in grid.
55033 setSource : function(source){
55034 this.store.setSource(source);
55038 * Gets all the data from the grid.
55039 * @return {Object} data data stored in grid
55041 getSource : function(){
55042 return this.store.getSource();
55046 * Ext JS Library 1.1.1
55047 * Copyright(c) 2006-2007, Ext JS, LLC.
55049 * Originally Released Under LGPL - original licence link has changed is not relivant.
55052 * <script type="text/javascript">
55056 * @class Roo.LoadMask
55057 * A simple utility class for generically masking elements while loading data. If the element being masked has
55058 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
55059 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
55060 * element's UpdateManager load indicator and will be destroyed after the initial load.
55062 * Create a new LoadMask
55063 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
55064 * @param {Object} config The config object
55066 Roo.LoadMask = function(el, config){
55067 this.el = Roo.get(el);
55068 Roo.apply(this, config);
55070 this.store.on('beforeload', this.onBeforeLoad, this);
55071 this.store.on('load', this.onLoad, this);
55072 this.store.on('loadexception', this.onLoadException, this);
55073 this.removeMask = false;
55075 var um = this.el.getUpdateManager();
55076 um.showLoadIndicator = false; // disable the default indicator
55077 um.on('beforeupdate', this.onBeforeLoad, this);
55078 um.on('update', this.onLoad, this);
55079 um.on('failure', this.onLoad, this);
55080 this.removeMask = true;
55084 Roo.LoadMask.prototype = {
55086 * @cfg {Boolean} removeMask
55087 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
55088 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
55091 * @cfg {String} msg
55092 * The text to display in a centered loading message box (defaults to 'Loading...')
55094 msg : 'Loading...',
55096 * @cfg {String} msgCls
55097 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
55099 msgCls : 'x-mask-loading',
55102 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
55108 * Disables the mask to prevent it from being displayed
55110 disable : function(){
55111 this.disabled = true;
55115 * Enables the mask so that it can be displayed
55117 enable : function(){
55118 this.disabled = false;
55121 onLoadException : function()
55123 Roo.log(arguments);
55125 if (typeof(arguments[3]) != 'undefined') {
55126 Roo.MessageBox.alert("Error loading",arguments[3]);
55130 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
55131 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
55140 this.el.unmask(this.removeMask);
55143 onLoad : function()
55145 this.el.unmask(this.removeMask);
55149 onBeforeLoad : function(){
55150 if(!this.disabled){
55151 this.el.mask(this.msg, this.msgCls);
55156 destroy : function(){
55158 this.store.un('beforeload', this.onBeforeLoad, this);
55159 this.store.un('load', this.onLoad, this);
55160 this.store.un('loadexception', this.onLoadException, this);
55162 var um = this.el.getUpdateManager();
55163 um.un('beforeupdate', this.onBeforeLoad, this);
55164 um.un('update', this.onLoad, this);
55165 um.un('failure', this.onLoad, this);
55170 * Ext JS Library 1.1.1
55171 * Copyright(c) 2006-2007, Ext JS, LLC.
55173 * Originally Released Under LGPL - original licence link has changed is not relivant.
55176 * <script type="text/javascript">
55181 * @class Roo.XTemplate
55182 * @extends Roo.Template
55183 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
55185 var t = new Roo.XTemplate(
55186 '<select name="{name}">',
55187 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
55191 // then append, applying the master template values
55194 * Supported features:
55199 {a_variable} - output encoded.
55200 {a_variable.format:("Y-m-d")} - call a method on the variable
55201 {a_variable:raw} - unencoded output
55202 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
55203 {a_variable:this.method_on_template(...)} - call a method on the template object.
55208 <tpl for="a_variable or condition.."></tpl>
55209 <tpl if="a_variable or condition"></tpl>
55210 <tpl exec="some javascript"></tpl>
55211 <tpl name="named_template"></tpl> (experimental)
55213 <tpl for="."></tpl> - just iterate the property..
55214 <tpl for=".."></tpl> - iterates with the parent (probably the template)
55218 Roo.XTemplate = function()
55220 Roo.XTemplate.superclass.constructor.apply(this, arguments);
55227 Roo.extend(Roo.XTemplate, Roo.Template, {
55230 * The various sub templates
55235 * basic tag replacing syntax
55238 * // you can fake an object call by doing this
55242 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
55245 * compile the template
55247 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
55250 compile: function()
55254 s = ['<tpl>', s, '</tpl>'].join('');
55256 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
55257 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
55258 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
55259 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
55260 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
55265 while(true == !!(m = s.match(re))){
55266 var forMatch = m[0].match(nameRe),
55267 ifMatch = m[0].match(ifRe),
55268 execMatch = m[0].match(execRe),
55269 namedMatch = m[0].match(namedRe),
55274 name = forMatch && forMatch[1] ? forMatch[1] : '';
55277 // if - puts fn into test..
55278 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
55280 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
55285 // exec - calls a function... returns empty if true is returned.
55286 exp = execMatch && execMatch[1] ? execMatch[1] : null;
55288 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
55296 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
55297 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
55298 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
55301 var uid = namedMatch ? namedMatch[1] : id;
55305 id: namedMatch ? namedMatch[1] : id,
55312 s = s.replace(m[0], '');
55314 s = s.replace(m[0], '{xtpl'+ id + '}');
55319 for(var i = tpls.length-1; i >= 0; --i){
55320 this.compileTpl(tpls[i]);
55321 this.tpls[tpls[i].id] = tpls[i];
55323 this.master = tpls[tpls.length-1];
55327 * same as applyTemplate, except it's done to one of the subTemplates
55328 * when using named templates, you can do:
55330 * var str = pl.applySubTemplate('your-name', values);
55333 * @param {Number} id of the template
55334 * @param {Object} values to apply to template
55335 * @param {Object} parent (normaly the instance of this object)
55337 applySubTemplate : function(id, values, parent)
55341 var t = this.tpls[id];
55345 if(t.test && !t.test.call(this, values, parent)){
55349 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
55350 Roo.log(e.toString());
55356 if(t.exec && t.exec.call(this, values, parent)){
55360 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
55361 Roo.log(e.toString());
55366 var vs = t.target ? t.target.call(this, values, parent) : values;
55367 parent = t.target ? values : parent;
55368 if(t.target && vs instanceof Array){
55370 for(var i = 0, len = vs.length; i < len; i++){
55371 buf[buf.length] = t.compiled.call(this, vs[i], parent);
55373 return buf.join('');
55375 return t.compiled.call(this, vs, parent);
55377 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
55378 Roo.log(e.toString());
55379 Roo.log(t.compiled);
55384 compileTpl : function(tpl)
55386 var fm = Roo.util.Format;
55387 var useF = this.disableFormats !== true;
55388 var sep = Roo.isGecko ? "+" : ",";
55389 var undef = function(str) {
55390 Roo.log("Property not found :" + str);
55394 var fn = function(m, name, format, args)
55396 //Roo.log(arguments);
55397 args = args ? args.replace(/\\'/g,"'") : args;
55398 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
55399 if (typeof(format) == 'undefined') {
55400 format= 'htmlEncode';
55402 if (format == 'raw' ) {
55406 if(name.substr(0, 4) == 'xtpl'){
55407 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
55410 // build an array of options to determine if value is undefined..
55412 // basically get 'xxxx.yyyy' then do
55413 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
55414 // (function () { Roo.log("Property not found"); return ''; })() :
55419 Roo.each(name.split('.'), function(st) {
55420 lookfor += (lookfor.length ? '.': '') + st;
55421 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
55424 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
55427 if(format && useF){
55429 args = args ? ',' + args : "";
55431 if(format.substr(0, 5) != "this."){
55432 format = "fm." + format + '(';
55434 format = 'this.call("'+ format.substr(5) + '", ';
55438 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
55442 // called with xxyx.yuu:(test,test)
55444 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
55446 // raw.. - :raw modifier..
55447 return "'"+ sep + udef_st + name + ")"+sep+"'";
55451 // branched to use + in gecko and [].join() in others
55453 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
55454 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
55457 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
55458 body.push(tpl.body.replace(/(\r\n|\n)/g,
55459 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
55460 body.push("'].join('');};};");
55461 body = body.join('');
55464 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
55466 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
55472 applyTemplate : function(values){
55473 return this.master.compiled.call(this, values, {});
55474 //var s = this.subs;
55477 apply : function(){
55478 return this.applyTemplate.apply(this, arguments);
55483 Roo.XTemplate.from = function(el){
55484 el = Roo.getDom(el);
55485 return new Roo.XTemplate(el.value || el.innerHTML);
55487 * Original code for Roojs - LGPL
55488 * <script type="text/javascript">
55492 * @class Roo.XComponent
55493 * A delayed Element creator...
55494 * Or a way to group chunks of interface together.
55496 * Mypart.xyx = new Roo.XComponent({
55498 parent : 'Mypart.xyz', // empty == document.element.!!
55502 disabled : function() {}
55504 tree : function() { // return an tree of xtype declared components
55508 xtype : 'NestedLayoutPanel',
55515 * It can be used to build a big heiracy, with parent etc.
55516 * or you can just use this to render a single compoent to a dom element
55517 * MYPART.render(Roo.Element | String(id) | dom_element )
55519 * @extends Roo.util.Observable
55521 * @param cfg {Object} configuration of component
55524 Roo.XComponent = function(cfg) {
55525 Roo.apply(this, cfg);
55529 * Fires when this the componnt is built
55530 * @param {Roo.XComponent} c the component
55535 this.region = this.region || 'center'; // default..
55536 Roo.XComponent.register(this);
55537 this.modules = false;
55538 this.el = false; // where the layout goes..
55542 Roo.extend(Roo.XComponent, Roo.util.Observable, {
55545 * The created element (with Roo.factory())
55546 * @type {Roo.Layout}
55552 * for BC - use el in new code
55553 * @type {Roo.Layout}
55559 * for BC - use el in new code
55560 * @type {Roo.Layout}
55565 * @cfg {Function|boolean} disabled
55566 * If this module is disabled by some rule, return true from the funtion
55571 * @cfg {String} parent
55572 * Name of parent element which it get xtype added to..
55577 * @cfg {String} order
55578 * Used to set the order in which elements are created (usefull for multiple tabs)
55583 * @cfg {String} name
55584 * String to display while loading.
55588 * @cfg {String} region
55589 * Region to render component to (defaults to center)
55594 * @cfg {Array} items
55595 * A single item array - the first element is the root of the tree..
55596 * It's done this way to stay compatible with the Xtype system...
55602 * The method that retuns the tree of parts that make up this compoennt
55609 * render element to dom or tree
55610 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
55613 render : function(el)
55617 var hp = this.parent ? 1 : 0;
55619 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
55620 // if parent is a '#.....' string, then let's use that..
55621 var ename = this.parent.substr(1)
55622 this.parent = false;
55623 el = Roo.get(ename);
55625 Roo.log("Warning - element can not be found :#" + ename );
55631 if (!this.parent) {
55633 el = el ? Roo.get(el) : false;
55635 // it's a top level one..
55637 el : new Roo.BorderLayout(el || document.body, {
55643 tabPosition: 'top',
55644 //resizeTabs: true,
55645 alwaysShowTabs: el && hp? false : true,
55646 hideTabs: el || !hp ? true : false,
55653 if (!this.parent.el) {
55654 // probably an old style ctor, which has been disabled.
55658 // The 'tree' method is '_tree now'
55660 var tree = this._tree ? this._tree() : this.tree();
55661 tree.region = tree.region || this.region;
55662 this.el = this.parent.el.addxtype(tree);
55663 this.fireEvent('built', this);
55665 this.panel = this.el;
55666 this.layout = this.panel.layout;
55667 this.parentLayout = this.parent.layout || false;
55673 Roo.apply(Roo.XComponent, {
55675 * @property hideProgress
55676 * true to disable the building progress bar.. usefull on single page renders.
55679 hideProgress : false,
55681 * @property buildCompleted
55682 * True when the builder has completed building the interface.
55685 buildCompleted : false,
55688 * @property topModule
55689 * the upper most module - uses document.element as it's constructor.
55696 * @property modules
55697 * array of modules to be created by registration system.
55698 * @type {Array} of Roo.XComponent
55703 * @property elmodules
55704 * array of modules to be created by which use #ID
55705 * @type {Array} of Roo.XComponent
55712 * Register components to be built later.
55714 * This solves the following issues
55715 * - Building is not done on page load, but after an authentication process has occured.
55716 * - Interface elements are registered on page load
55717 * - Parent Interface elements may not be loaded before child, so this handles that..
55724 module : 'Pman.Tab.projectMgr',
55726 parent : 'Pman.layout',
55727 disabled : false, // or use a function..
55730 * * @param {Object} details about module
55732 register : function(obj) {
55734 Roo.XComponent.event.fireEvent('register', obj);
55735 switch(typeof(obj.disabled) ) {
55741 if ( obj.disabled() ) {
55747 if (obj.disabled) {
55753 this.modules.push(obj);
55757 * convert a string to an object..
55758 * eg. 'AAA.BBB' -> finds AAA.BBB
55762 toObject : function(str)
55764 if (!str || typeof(str) == 'object') {
55767 if (str.substring(0,1) == '#') {
55771 var ar = str.split('.');
55776 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
55778 throw "Module not found : " + str;
55782 throw "Module not found : " + str;
55784 Roo.each(ar, function(e) {
55785 if (typeof(o[e]) == 'undefined') {
55786 throw "Module not found : " + str;
55797 * move modules into their correct place in the tree..
55800 preBuild : function ()
55803 Roo.each(this.modules , function (obj)
55805 Roo.XComponent.event.fireEvent('beforebuild', obj);
55807 var opar = obj.parent;
55809 obj.parent = this.toObject(opar);
55811 Roo.log("parent:toObject failed: " + e.toString());
55816 Roo.debug && Roo.log("GOT top level module");
55817 Roo.debug && Roo.log(obj);
55818 obj.modules = new Roo.util.MixedCollection(false,
55819 function(o) { return o.order + '' }
55821 this.topModule = obj;
55824 // parent is a string (usually a dom element name..)
55825 if (typeof(obj.parent) == 'string') {
55826 this.elmodules.push(obj);
55829 if (obj.parent.constructor != Roo.XComponent) {
55830 Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
55832 if (!obj.parent.modules) {
55833 obj.parent.modules = new Roo.util.MixedCollection(false,
55834 function(o) { return o.order + '' }
55837 if (obj.parent.disabled) {
55838 obj.disabled = true;
55840 obj.parent.modules.add(obj);
55845 * make a list of modules to build.
55846 * @return {Array} list of modules.
55849 buildOrder : function()
55852 var cmp = function(a,b) {
55853 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
55855 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
55856 throw "No top level modules to build";
55859 // make a flat list in order of modules to build.
55860 var mods = this.topModule ? [ this.topModule ] : [];
55863 // elmodules (is a list of DOM based modules )
55864 Roo.each(this.elmodules, function(e) {
55866 if (!this.topModule &&
55867 typeof(e.parent) == 'string' &&
55868 e.parent.substring(0,1) == '#' &&
55869 Roo.get(e.parent.substr(1))
55872 _this.topModule = e;
55878 // add modules to their parents..
55879 var addMod = function(m) {
55880 Roo.debug && Roo.log("build Order: add: " + m.name);
55883 if (m.modules && !m.disabled) {
55884 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
55885 m.modules.keySort('ASC', cmp );
55886 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
55888 m.modules.each(addMod);
55890 Roo.debug && Roo.log("build Order: no child modules");
55892 // not sure if this is used any more..
55894 m.finalize.name = m.name + " (clean up) ";
55895 mods.push(m.finalize);
55899 if (this.topModule && this.topModule.modules) {
55900 this.topModule.modules.keySort('ASC', cmp );
55901 this.topModule.modules.each(addMod);
55907 * Build the registered modules.
55908 * @param {Object} parent element.
55909 * @param {Function} optional method to call after module has been added.
55917 var mods = this.buildOrder();
55919 //this.allmods = mods;
55920 //Roo.debug && Roo.log(mods);
55922 if (!mods.length) { // should not happen
55923 throw "NO modules!!!";
55927 var msg = "Building Interface...";
55928 // flash it up as modal - so we store the mask!?
55929 if (!this.hideProgress) {
55930 Roo.MessageBox.show({ title: 'loading' });
55931 Roo.MessageBox.show({
55932 title: "Please wait...",
55941 var total = mods.length;
55944 var progressRun = function() {
55945 if (!mods.length) {
55946 Roo.debug && Roo.log('hide?');
55947 if (!this.hideProgress) {
55948 Roo.MessageBox.hide();
55950 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
55956 var m = mods.shift();
55959 Roo.debug && Roo.log(m);
55960 // not sure if this is supported any more.. - modules that are are just function
55961 if (typeof(m) == 'function') {
55963 return progressRun.defer(10, _this);
55967 msg = "Building Interface " + (total - mods.length) +
55969 (m.name ? (' - ' + m.name) : '');
55970 Roo.debug && Roo.log(msg);
55971 if (!this.hideProgress) {
55972 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
55976 // is the module disabled?
55977 var disabled = (typeof(m.disabled) == 'function') ?
55978 m.disabled.call(m.module.disabled) : m.disabled;
55982 return progressRun(); // we do not update the display!
55990 // it's 10 on top level, and 1 on others??? why...
55991 return progressRun.defer(10, _this);
55994 progressRun.defer(1, _this);
56008 * wrapper for event.on - aliased later..
56009 * Typically use to register a event handler for register:
56011 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
56020 Roo.XComponent.event = new Roo.util.Observable({
56024 * Fires when an Component is registered,
56025 * set the disable property on the Component to stop registration.
56026 * @param {Roo.XComponent} c the component being registerd.
56031 * @event beforebuild
56032 * Fires before each Component is built
56033 * can be used to apply permissions.
56034 * @param {Roo.XComponent} c the component being registerd.
56037 'beforebuild' : true,
56039 * @event buildcomplete
56040 * Fires on the top level element when all elements have been built
56041 * @param {Roo.XComponent} the top level component.
56043 'buildcomplete' : true
56048 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);