4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
17 window["undefined"] = window["undefined"];
21 * Roo core utilities and functions.
26 * Copies all the properties of config to obj.
27 * @param {Object} obj The receiver of the properties
28 * @param {Object} config The source of the properties
29 * @param {Object} defaults A different object that will also be applied for default values
30 * @return {Object} returns obj
35 Roo.apply = function(o, c, defaults){
37 // no "this" reference for friendly out of scope calls
38 Roo.apply(o, defaults);
40 if(o && c && typeof c == 'object'){
51 var ua = navigator.userAgent.toLowerCase();
53 var isStrict = document.compatMode == "CSS1Compat",
54 isOpera = ua.indexOf("opera") > -1,
55 isSafari = (/webkit|khtml/).test(ua),
56 isFirefox = ua.indexOf("firefox") > -1,
57 isIE = ua.indexOf("msie") > -1,
58 isIE7 = ua.indexOf("msie 7") > -1,
59 isIE11 = /trident.*rv\:11\./.test(ua),
60 isGecko = !isSafari && ua.indexOf("gecko") > -1,
61 isBorderBox = isIE && !isStrict,
62 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
63 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
64 isLinux = (ua.indexOf("linux") != -1),
65 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
66 isIOS = /iphone|ipad/.test(ua),
67 isTouch = (function() {
69 document.createEvent("TouchEvent");
76 // remove css image flicker
79 document.execCommand("BackgroundImageCache", false, true);
85 * True if the browser is in strict mode
90 * True if the page is running over SSL
95 * True when the document is fully initialized and ready for action
100 * Turn on debugging output (currently only the factory uses this)
107 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
110 enableGarbageCollector : true,
113 * True to automatically purge event listeners after uncaching an element (defaults to false).
114 * Note: this only happens if enableGarbageCollector is true.
117 enableListenerCollection:false,
120 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
121 * the IE insecure content warning (defaults to javascript:false).
124 SSL_SECURE_URL : "javascript:false",
127 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
128 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
131 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
133 emptyFn : function(){},
136 * Copies all the properties of config to obj if they don't already exist.
137 * @param {Object} obj The receiver of the properties
138 * @param {Object} config The source of the properties
139 * @return {Object} returns obj
141 applyIf : function(o, c){
144 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
151 * Applies event listeners to elements by selectors when the document is ready.
152 * The event name is specified with an @ suffix.
155 // add a listener for click on all anchors in element with id foo
156 '#foo a@click' : function(e, t){
160 // add the same listener to multiple selectors (separated by comma BEFORE the @)
161 '#foo a, #bar span.some-class@mouseover' : function(){
166 * @param {Object} obj The list of behaviors to apply
168 addBehaviors : function(o){
170 Roo.onReady(function(){
175 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
177 var parts = b.split('@');
178 if(parts[1]){ // for Object prototype breakers
181 cache[s] = Roo.select(s);
183 cache[s].on(parts[1], o[b]);
190 * Generates unique ids. If the element already has an id, it is unchanged
191 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
192 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
193 * @return {String} The generated Id.
195 id : function(el, prefix){
196 prefix = prefix || "roo-gen";
198 var id = prefix + (++idSeed);
199 return el ? (el.id ? el.id : (el.id = id)) : id;
204 * Extends one class with another class and optionally overrides members with the passed literal. This class
205 * also adds the function "override()" to the class that can be used to override
206 * members on an instance.
207 * @param {Object} subclass The class inheriting the functionality
208 * @param {Object} superclass The class being extended
209 * @param {Object} overrides (optional) A literal with members
214 var io = function(o){
219 return function(sb, sp, overrides){
220 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
223 sb = function(){sp.apply(this, arguments);};
225 var F = function(){}, sbp, spp = sp.prototype;
227 sbp = sb.prototype = new F();
231 if(spp.constructor == Object.prototype.constructor){
236 sb.override = function(o){
240 Roo.override(sb, overrides);
246 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
248 Roo.override(MyClass, {
249 newMethod1: function(){
252 newMethod2: function(foo){
257 * @param {Object} origclass The class to override
258 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
259 * containing one or more methods.
262 override : function(origclass, overrides){
264 var p = origclass.prototype;
265 for(var method in overrides){
266 p[method] = overrides[method];
271 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
273 Roo.namespace('Company', 'Company.data');
274 Company.Widget = function() { ... }
275 Company.data.CustomStore = function(config) { ... }
277 * @param {String} namespace1
278 * @param {String} namespace2
279 * @param {String} etc
282 namespace : function(){
283 var a=arguments, o=null, i, j, d, rt;
284 for (i=0; i<a.length; ++i) {
288 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
289 for (j=1; j<d.length; ++j) {
290 o[d[j]]=o[d[j]] || {};
296 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
298 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
299 Roo.factory(conf, Roo.data);
301 * @param {String} classname
302 * @param {String} namespace (optional)
306 factory : function(c, ns)
308 // no xtype, no ns or c.xns - or forced off by c.xns
309 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
312 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
313 if (c.constructor == ns[c.xtype]) {// already created...
317 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
318 var ret = new ns[c.xtype](c);
322 c.xns = false; // prevent recursion..
326 * Logs to console if it can.
328 * @param {String|Object} string
333 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
340 * 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.
344 urlEncode : function(o){
350 var ov = o[key], k = Roo.encodeURIComponent(key);
351 var type = typeof ov;
352 if(type == 'undefined'){
354 }else if(type != "function" && type != "object"){
355 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
356 }else if(ov instanceof Array){
358 for(var i = 0, len = ov.length; i < len; i++) {
359 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
370 * Safe version of encodeURIComponent
371 * @param {String} data
375 encodeURIComponent : function (data)
378 return encodeURIComponent(data);
379 } catch(e) {} // should be an uri encode error.
381 if (data == '' || data == null){
384 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
385 function nibble_to_hex(nibble){
386 var chars = '0123456789ABCDEF';
387 return chars.charAt(nibble);
389 data = data.toString();
391 for(var i=0; i<data.length; i++){
392 var c = data.charCodeAt(i);
393 var bs = new Array();
396 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
397 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
398 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
399 bs[3] = 0x80 | (c & 0x3F);
400 }else if (c > 0x800){
402 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
403 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
404 bs[2] = 0x80 | (c & 0x3F);
407 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
408 bs[1] = 0x80 | (c & 0x3F);
413 for(var j=0; j<bs.length; j++){
415 var hex = nibble_to_hex((b & 0xF0) >>> 4)
416 + nibble_to_hex(b &0x0F);
425 * 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]}.
426 * @param {String} string
427 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
428 * @return {Object} A literal with members
430 urlDecode : function(string, overwrite){
431 if(!string || !string.length){
435 var pairs = string.split('&');
436 var pair, name, value;
437 for(var i = 0, len = pairs.length; i < len; i++){
438 pair = pairs[i].split('=');
439 name = decodeURIComponent(pair[0]);
440 value = decodeURIComponent(pair[1]);
441 if(overwrite !== true){
442 if(typeof obj[name] == "undefined"){
444 }else if(typeof obj[name] == "string"){
445 obj[name] = [obj[name]];
446 obj[name].push(value);
448 obj[name].push(value);
458 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
459 * passed array is not really an array, your function is called once with it.
460 * The supplied function is called with (Object item, Number index, Array allItems).
461 * @param {Array/NodeList/Mixed} array
462 * @param {Function} fn
463 * @param {Object} scope
465 each : function(array, fn, scope){
466 if(typeof array.length == "undefined" || typeof array == "string"){
469 for(var i = 0, len = array.length; i < len; i++){
470 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
475 combine : function(){
476 var as = arguments, l = as.length, r = [];
477 for(var i = 0; i < l; i++){
479 if(a instanceof Array){
481 }else if(a.length !== undefined && !a.substr){
482 r = r.concat(Array.prototype.slice.call(a, 0));
491 * Escapes the passed string for use in a regular expression
492 * @param {String} str
495 escapeRe : function(s) {
496 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
500 callback : function(cb, scope, args, delay){
501 if(typeof cb == "function"){
503 cb.defer(delay, scope, args || []);
505 cb.apply(scope, args || []);
511 * Return the dom node for the passed string (id), dom node, or Roo.Element
512 * @param {String/HTMLElement/Roo.Element} el
513 * @return HTMLElement
515 getDom : function(el){
519 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
523 * Shorthand for {@link Roo.ComponentMgr#get}
525 * @return Roo.Component
527 getCmp : function(id){
528 return Roo.ComponentMgr.get(id);
531 num : function(v, defaultValue){
532 if(typeof v != 'number'){
538 destroy : function(){
539 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
543 as.removeAllListeners();
547 if(typeof as.purgeListeners == 'function'){
550 if(typeof as.destroy == 'function'){
557 // inpired by a similar function in mootools library
559 * Returns the type of object that is passed in. If the object passed in is null or undefined it
560 * return false otherwise it returns one of the following values:<ul>
561 * <li><b>string</b>: If the object passed is a string</li>
562 * <li><b>number</b>: If the object passed is a number</li>
563 * <li><b>boolean</b>: If the object passed is a boolean value</li>
564 * <li><b>function</b>: If the object passed is a function reference</li>
565 * <li><b>object</b>: If the object passed is an object</li>
566 * <li><b>array</b>: If the object passed is an array</li>
567 * <li><b>regexp</b>: If the object passed is a regular expression</li>
568 * <li><b>element</b>: If the object passed is a DOM Element</li>
569 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
570 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
571 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
572 * @param {Mixed} object
576 if(o === undefined || o === null){
583 if(t == 'object' && o.nodeName) {
585 case 1: return 'element';
586 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
589 if(t == 'object' || t == 'function') {
590 switch(o.constructor) {
591 case Array: return 'array';
592 case RegExp: return 'regexp';
594 if(typeof o.length == 'number' && typeof o.item == 'function') {
602 * Returns true if the passed value is null, undefined or an empty string (optional).
603 * @param {Mixed} value The value to test
604 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
607 isEmpty : function(v, allowBlank){
608 return v === null || v === undefined || (!allowBlank ? v === '' : false);
616 isFirefox : isFirefox,
626 isBorderBox : isBorderBox,
628 isWindows : isWindows,
639 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
640 * you may want to set this to true.
643 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
648 * Selects a single element as a Roo Element
649 * This is about as close as you can get to jQuery's $('do crazy stuff')
650 * @param {String} selector The selector/xpath query
651 * @param {Node} root (optional) The start of the query (defaults to document).
652 * @return {Roo.Element}
654 selectNode : function(selector, root)
656 var node = Roo.DomQuery.selectNode(selector,root);
657 return node ? Roo.get(node) : new Roo.Element(false);
665 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
666 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
669 "Roo.bootstrap.dash");
672 * Ext JS Library 1.1.1
673 * Copyright(c) 2006-2007, Ext JS, LLC.
675 * Originally Released Under LGPL - original licence link has changed is not relivant.
678 * <script type="text/javascript">
682 // wrappedn so fnCleanup is not in global scope...
684 function fnCleanUp() {
685 var p = Function.prototype;
686 delete p.createSequence;
688 delete p.createDelegate;
689 delete p.createCallback;
690 delete p.createInterceptor;
692 window.detachEvent("onunload", fnCleanUp);
694 window.attachEvent("onunload", fnCleanUp);
701 * These functions are available on every Function object (any JavaScript function).
703 Roo.apply(Function.prototype, {
705 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
706 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
707 * Will create a function that is bound to those 2 args.
708 * @return {Function} The new function
710 createCallback : function(/*args...*/){
711 // make args available, in function below
712 var args = arguments;
715 return method.apply(window, args);
720 * Creates a delegate (callback) that sets the scope to obj.
721 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
722 * Will create a function that is automatically scoped to this.
723 * @param {Object} obj (optional) The object for which the scope is set
724 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
725 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
726 * if a number the args are inserted at the specified position
727 * @return {Function} The new function
729 createDelegate : function(obj, args, appendArgs){
732 var callArgs = args || arguments;
733 if(appendArgs === true){
734 callArgs = Array.prototype.slice.call(arguments, 0);
735 callArgs = callArgs.concat(args);
736 }else if(typeof appendArgs == "number"){
737 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
738 var applyArgs = [appendArgs, 0].concat(args); // create method call params
739 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
741 return method.apply(obj || window, callArgs);
746 * Calls this function after the number of millseconds specified.
747 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
748 * @param {Object} obj (optional) The object for which the scope is set
749 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
750 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
751 * if a number the args are inserted at the specified position
752 * @return {Number} The timeout id that can be used with clearTimeout
754 defer : function(millis, obj, args, appendArgs){
755 var fn = this.createDelegate(obj, args, appendArgs);
757 return setTimeout(fn, millis);
763 * Create a combined function call sequence of the original function + the passed function.
764 * The resulting function returns the results of the original function.
765 * The passed fcn is called with the parameters of the original function
766 * @param {Function} fcn The function to sequence
767 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
768 * @return {Function} The new function
770 createSequence : function(fcn, scope){
771 if(typeof fcn != "function"){
776 var retval = method.apply(this || window, arguments);
777 fcn.apply(scope || this || window, arguments);
783 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
784 * The resulting function returns the results of the original function.
785 * The passed fcn is called with the parameters of the original function.
787 * @param {Function} fcn The function to call before the original
788 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
789 * @return {Function} The new function
791 createInterceptor : function(fcn, scope){
792 if(typeof fcn != "function"){
799 if(fcn.apply(scope || this || window, arguments) === false){
802 return method.apply(this || window, arguments);
808 * Ext JS Library 1.1.1
809 * Copyright(c) 2006-2007, Ext JS, LLC.
811 * Originally Released Under LGPL - original licence link has changed is not relivant.
814 * <script type="text/javascript">
817 Roo.applyIf(String, {
822 * Escapes the passed string for ' and \
823 * @param {String} string The string to escape
824 * @return {String} The escaped string
827 escape : function(string) {
828 return string.replace(/('|\\)/g, "\\$1");
832 * Pads the left side of a string with a specified character. This is especially useful
833 * for normalizing number and date strings. Example usage:
835 var s = String.leftPad('123', 5, '0');
836 // s now contains the string: '00123'
838 * @param {String} string The original string
839 * @param {Number} size The total length of the output string
840 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
841 * @return {String} The padded string
844 leftPad : function (val, size, ch) {
845 var result = new String(val);
846 if(ch === null || ch === undefined || ch === '') {
849 while (result.length < size) {
850 result = ch + result;
856 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
857 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
859 var cls = 'my-class', text = 'Some text';
860 var s = String.format('<div class="{0}">{1}</div>', cls, text);
861 // s now contains the string: '<div class="my-class">Some text</div>'
863 * @param {String} string The tokenized string to be formatted
864 * @param {String} value1 The value to replace token {0}
865 * @param {String} value2 Etc...
866 * @return {String} The formatted string
869 format : function(format){
870 var args = Array.prototype.slice.call(arguments, 1);
871 return format.replace(/\{(\d+)\}/g, function(m, i){
872 return Roo.util.Format.htmlEncode(args[i]);
878 * Utility function that allows you to easily switch a string between two alternating values. The passed value
879 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
880 * they are already different, the first value passed in is returned. Note that this method returns the new value
881 * but does not change the current string.
883 // alternate sort directions
884 sort = sort.toggle('ASC', 'DESC');
886 // instead of conditional logic:
887 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
889 * @param {String} value The value to compare to the current string
890 * @param {String} other The new value to use if the string already equals the first value passed in
891 * @return {String} The new value
894 String.prototype.toggle = function(value, other){
895 return this == value ? other : value;
898 * Ext JS Library 1.1.1
899 * Copyright(c) 2006-2007, Ext JS, LLC.
901 * Originally Released Under LGPL - original licence link has changed is not relivant.
904 * <script type="text/javascript">
910 Roo.applyIf(Number.prototype, {
912 * Checks whether or not the current number is within a desired range. If the number is already within the
913 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
914 * exceeded. Note that this method returns the constrained value but does not change the current number.
915 * @param {Number} min The minimum number in the range
916 * @param {Number} max The maximum number in the range
917 * @return {Number} The constrained value if outside the range, otherwise the current value
919 constrain : function(min, max){
920 return Math.min(Math.max(this, min), max);
924 * Ext JS Library 1.1.1
925 * Copyright(c) 2006-2007, Ext JS, LLC.
927 * Originally Released Under LGPL - original licence link has changed is not relivant.
930 * <script type="text/javascript">
935 Roo.applyIf(Array.prototype, {
938 * Checks whether or not the specified object exists in the array.
939 * @param {Object} o The object to check for
940 * @return {Number} The index of o in the array (or -1 if it is not found)
942 indexOf : function(o){
943 for (var i = 0, len = this.length; i < len; i++){
944 if(this[i] == o) return i;
950 * Removes the specified object from the array. If the object is not found nothing happens.
951 * @param {Object} o The object to remove
953 remove : function(o){
954 var index = this.indexOf(o);
956 this.splice(index, 1);
960 * Map (JS 1.6 compatibility)
961 * @param {Function} function to call
965 var len = this.length >>> 0;
966 if (typeof fun != "function")
967 throw new TypeError();
969 var res = new Array(len);
970 var thisp = arguments[1];
971 for (var i = 0; i < len; i++)
974 res[i] = fun.call(thisp, this[i], i, this);
985 * Ext JS Library 1.1.1
986 * Copyright(c) 2006-2007, Ext JS, LLC.
988 * Originally Released Under LGPL - original licence link has changed is not relivant.
991 * <script type="text/javascript">
997 * The date parsing and format syntax is a subset of
998 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
999 * supported will provide results equivalent to their PHP versions.
1001 * Following is the list of all currently supported formats:
1004 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1006 Format Output Description
1007 ------ ---------- --------------------------------------------------------------
1008 d 10 Day of the month, 2 digits with leading zeros
1009 D Wed A textual representation of a day, three letters
1010 j 10 Day of the month without leading zeros
1011 l Wednesday A full textual representation of the day of the week
1012 S th English ordinal day of month suffix, 2 chars (use with j)
1013 w 3 Numeric representation of the day of the week
1014 z 9 The julian date, or day of the year (0-365)
1015 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1016 F January A full textual representation of the month
1017 m 01 Numeric representation of a month, with leading zeros
1018 M Jan Month name abbreviation, three letters
1019 n 1 Numeric representation of a month, without leading zeros
1020 t 31 Number of days in the given month
1021 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1022 Y 2007 A full numeric representation of a year, 4 digits
1023 y 07 A two digit representation of a year
1024 a pm Lowercase Ante meridiem and Post meridiem
1025 A PM Uppercase Ante meridiem and Post meridiem
1026 g 3 12-hour format of an hour without leading zeros
1027 G 15 24-hour format of an hour without leading zeros
1028 h 03 12-hour format of an hour with leading zeros
1029 H 15 24-hour format of an hour with leading zeros
1030 i 05 Minutes with leading zeros
1031 s 01 Seconds, with leading zeros
1032 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1033 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1034 T CST Timezone setting of the machine running the code
1035 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1038 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1040 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1041 document.write(dt.format('Y-m-d')); //2007-01-10
1042 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1043 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
1046 * Here are some standard date/time patterns that you might find helpful. They
1047 * are not part of the source of Date.js, but to use them you can simply copy this
1048 * block of code into any script that is included after Date.js and they will also become
1049 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1052 ISO8601Long:"Y-m-d H:i:s",
1053 ISO8601Short:"Y-m-d",
1055 LongDate: "l, F d, Y",
1056 FullDateTime: "l, F d, Y g:i:s A",
1059 LongTime: "g:i:s A",
1060 SortableDateTime: "Y-m-d\\TH:i:s",
1061 UniversalSortableDateTime: "Y-m-d H:i:sO",
1068 var dt = new Date();
1069 document.write(dt.format(Date.patterns.ShortDate));
1074 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1075 * They generate precompiled functions from date formats instead of parsing and
1076 * processing the pattern every time you format a date. These functions are available
1077 * on every Date object (any javascript function).
1079 * The original article and download are here:
1080 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1087 Returns the number of milliseconds between this date and date
1088 @param {Date} date (optional) Defaults to now
1089 @return {Number} The diff in milliseconds
1090 @member Date getElapsed
1092 Date.prototype.getElapsed = function(date) {
1093 return Math.abs((date || new Date()).getTime()-this.getTime());
1095 // was in date file..
1099 Date.parseFunctions = {count:0};
1101 Date.parseRegexes = [];
1103 Date.formatFunctions = {count:0};
1106 Date.prototype.dateFormat = function(format) {
1107 if (Date.formatFunctions[format] == null) {
1108 Date.createNewFormat(format);
1110 var func = Date.formatFunctions[format];
1111 return this[func]();
1116 * Formats a date given the supplied format string
1117 * @param {String} format The format string
1118 * @return {String} The formatted date
1121 Date.prototype.format = Date.prototype.dateFormat;
1124 Date.createNewFormat = function(format) {
1125 var funcName = "format" + Date.formatFunctions.count++;
1126 Date.formatFunctions[format] = funcName;
1127 var code = "Date.prototype." + funcName + " = function(){return ";
1128 var special = false;
1130 for (var i = 0; i < format.length; ++i) {
1131 ch = format.charAt(i);
1132 if (!special && ch == "\\") {
1137 code += "'" + String.escape(ch) + "' + ";
1140 code += Date.getFormatCode(ch);
1143 /** eval:var:zzzzzzzzzzzzz */
1144 eval(code.substring(0, code.length - 3) + ";}");
1148 Date.getFormatCode = function(character) {
1149 switch (character) {
1151 return "String.leftPad(this.getDate(), 2, '0') + ";
1153 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1155 return "this.getDate() + ";
1157 return "Date.dayNames[this.getDay()] + ";
1159 return "this.getSuffix() + ";
1161 return "this.getDay() + ";
1163 return "this.getDayOfYear() + ";
1165 return "this.getWeekOfYear() + ";
1167 return "Date.monthNames[this.getMonth()] + ";
1169 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1171 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1173 return "(this.getMonth() + 1) + ";
1175 return "this.getDaysInMonth() + ";
1177 return "(this.isLeapYear() ? 1 : 0) + ";
1179 return "this.getFullYear() + ";
1181 return "('' + this.getFullYear()).substring(2, 4) + ";
1183 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1185 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1187 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1189 return "this.getHours() + ";
1191 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1193 return "String.leftPad(this.getHours(), 2, '0') + ";
1195 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1197 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1199 return "this.getGMTOffset() + ";
1201 return "this.getGMTColonOffset() + ";
1203 return "this.getTimezone() + ";
1205 return "(this.getTimezoneOffset() * -60) + ";
1207 return "'" + String.escape(character) + "' + ";
1212 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1213 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1214 * the date format that is not specified will default to the current date value for that part. Time parts can also
1215 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1216 * string or the parse operation will fail.
1219 //dt = Fri May 25 2007 (current date)
1220 var dt = new Date();
1222 //dt = Thu May 25 2006 (today's month/day in 2006)
1223 dt = Date.parseDate("2006", "Y");
1225 //dt = Sun Jan 15 2006 (all date parts specified)
1226 dt = Date.parseDate("2006-1-15", "Y-m-d");
1228 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1229 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1231 * @param {String} input The unparsed date as a string
1232 * @param {String} format The format the date is in
1233 * @return {Date} The parsed date
1236 Date.parseDate = function(input, format) {
1237 if (Date.parseFunctions[format] == null) {
1238 Date.createParser(format);
1240 var func = Date.parseFunctions[format];
1241 return Date[func](input);
1247 Date.createParser = function(format) {
1248 var funcName = "parse" + Date.parseFunctions.count++;
1249 var regexNum = Date.parseRegexes.length;
1250 var currentGroup = 1;
1251 Date.parseFunctions[format] = funcName;
1253 var code = "Date." + funcName + " = function(input){\n"
1254 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1255 + "var d = new Date();\n"
1256 + "y = d.getFullYear();\n"
1257 + "m = d.getMonth();\n"
1258 + "d = d.getDate();\n"
1259 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1260 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1261 + "if (results && results.length > 0) {";
1264 var special = false;
1266 for (var i = 0; i < format.length; ++i) {
1267 ch = format.charAt(i);
1268 if (!special && ch == "\\") {
1273 regex += String.escape(ch);
1276 var obj = Date.formatCodeToRegex(ch, currentGroup);
1277 currentGroup += obj.g;
1279 if (obj.g && obj.c) {
1285 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1286 + "{v = new Date(y, m, d, h, i, s);}\n"
1287 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1288 + "{v = new Date(y, m, d, h, i);}\n"
1289 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1290 + "{v = new Date(y, m, d, h);}\n"
1291 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1292 + "{v = new Date(y, m, d);}\n"
1293 + "else if (y >= 0 && m >= 0)\n"
1294 + "{v = new Date(y, m);}\n"
1295 + "else if (y >= 0)\n"
1296 + "{v = new Date(y);}\n"
1297 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1298 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1299 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1302 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1303 /** eval:var:zzzzzzzzzzzzz */
1308 Date.formatCodeToRegex = function(character, currentGroup) {
1309 switch (character) {
1313 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1316 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1317 s:"(\\d{1,2})"}; // day of month without leading zeroes
1320 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1321 s:"(\\d{2})"}; // day of month with leading zeroes
1325 s:"(?:" + Date.dayNames.join("|") + ")"};
1329 s:"(?:st|nd|rd|th)"};
1344 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1345 s:"(" + Date.monthNames.join("|") + ")"};
1348 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1349 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1352 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1353 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1356 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1357 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1368 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1372 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1373 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1377 c:"if (results[" + currentGroup + "] == 'am') {\n"
1378 + "if (h == 12) { h = 0; }\n"
1379 + "} else { if (h < 12) { h += 12; }}",
1383 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1384 + "if (h == 12) { h = 0; }\n"
1385 + "} else { if (h < 12) { h += 12; }}",
1390 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1391 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1395 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1396 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1399 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1403 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1408 "o = results[", currentGroup, "];\n",
1409 "var sn = o.substring(0,1);\n", // get + / - sign
1410 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1411 "var mn = o.substring(3,5) % 60;\n", // get minutes
1412 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1413 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1415 s:"([+\-]\\d{2,4})"};
1421 "o = results[", currentGroup, "];\n",
1422 "var sn = o.substring(0,1);\n",
1423 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1424 "var mn = o.substring(4,6) % 60;\n",
1425 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1426 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1432 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1435 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1436 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1437 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1441 s:String.escape(character)};
1446 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1447 * @return {String} The abbreviated timezone name (e.g. 'CST')
1449 Date.prototype.getTimezone = function() {
1450 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1454 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1455 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1457 Date.prototype.getGMTOffset = function() {
1458 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1459 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1460 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1464 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1465 * @return {String} 2-characters representing hours and 2-characters representing minutes
1466 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1468 Date.prototype.getGMTColonOffset = function() {
1469 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1470 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1472 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1476 * Get the numeric day number of the year, adjusted for leap year.
1477 * @return {Number} 0 through 364 (365 in leap years)
1479 Date.prototype.getDayOfYear = function() {
1481 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1482 for (var i = 0; i < this.getMonth(); ++i) {
1483 num += Date.daysInMonth[i];
1485 return num + this.getDate() - 1;
1489 * Get the string representation of the numeric week number of the year
1490 * (equivalent to the format specifier 'W').
1491 * @return {String} '00' through '52'
1493 Date.prototype.getWeekOfYear = function() {
1494 // Skip to Thursday of this week
1495 var now = this.getDayOfYear() + (4 - this.getDay());
1496 // Find the first Thursday of the year
1497 var jan1 = new Date(this.getFullYear(), 0, 1);
1498 var then = (7 - jan1.getDay() + 4);
1499 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1503 * Whether or not the current date is in a leap year.
1504 * @return {Boolean} True if the current date is in a leap year, else false
1506 Date.prototype.isLeapYear = function() {
1507 var year = this.getFullYear();
1508 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1512 * Get the first day of the current month, adjusted for leap year. The returned value
1513 * is the numeric day index within the week (0-6) which can be used in conjunction with
1514 * the {@link #monthNames} array to retrieve the textual day name.
1517 var dt = new Date('1/10/2007');
1518 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1520 * @return {Number} The day number (0-6)
1522 Date.prototype.getFirstDayOfMonth = function() {
1523 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1524 return (day < 0) ? (day + 7) : day;
1528 * Get the last day of the current month, adjusted for leap year. The returned value
1529 * is the numeric day index within the week (0-6) which can be used in conjunction with
1530 * the {@link #monthNames} array to retrieve the textual day name.
1533 var dt = new Date('1/10/2007');
1534 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1536 * @return {Number} The day number (0-6)
1538 Date.prototype.getLastDayOfMonth = function() {
1539 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1540 return (day < 0) ? (day + 7) : day;
1545 * Get the first date of this date's month
1548 Date.prototype.getFirstDateOfMonth = function() {
1549 return new Date(this.getFullYear(), this.getMonth(), 1);
1553 * Get the last date of this date's month
1556 Date.prototype.getLastDateOfMonth = function() {
1557 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1560 * Get the number of days in the current month, adjusted for leap year.
1561 * @return {Number} The number of days in the month
1563 Date.prototype.getDaysInMonth = function() {
1564 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1565 return Date.daysInMonth[this.getMonth()];
1569 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1570 * @return {String} 'st, 'nd', 'rd' or 'th'
1572 Date.prototype.getSuffix = function() {
1573 switch (this.getDate()) {
1590 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1593 * An array of textual month names.
1594 * Override these values for international dates, for example...
1595 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1614 * An array of textual day names.
1615 * Override these values for international dates, for example...
1616 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1632 Date.monthNumbers = {
1647 * Creates and returns a new Date instance with the exact same date value as the called instance.
1648 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1649 * variable will also be changed. When the intention is to create a new variable that will not
1650 * modify the original instance, you should create a clone.
1652 * Example of correctly cloning a date:
1655 var orig = new Date('10/1/2006');
1658 document.write(orig); //returns 'Thu Oct 05 2006'!
1661 var orig = new Date('10/1/2006');
1662 var copy = orig.clone();
1664 document.write(orig); //returns 'Thu Oct 01 2006'
1666 * @return {Date} The new Date instance
1668 Date.prototype.clone = function() {
1669 return new Date(this.getTime());
1673 * Clears any time information from this date
1674 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1675 @return {Date} this or the clone
1677 Date.prototype.clearTime = function(clone){
1679 return this.clone().clearTime();
1684 this.setMilliseconds(0);
1689 // safari setMonth is broken
1691 Date.brokenSetMonth = Date.prototype.setMonth;
1692 Date.prototype.setMonth = function(num){
1694 var n = Math.ceil(-num);
1695 var back_year = Math.ceil(n/12);
1696 var month = (n % 12) ? 12 - n % 12 : 0 ;
1697 this.setFullYear(this.getFullYear() - back_year);
1698 return Date.brokenSetMonth.call(this, month);
1700 return Date.brokenSetMonth.apply(this, arguments);
1705 /** Date interval constant
1709 /** Date interval constant
1713 /** Date interval constant
1717 /** Date interval constant
1721 /** Date interval constant
1725 /** Date interval constant
1729 /** Date interval constant
1735 * Provides a convenient method of performing basic date arithmetic. This method
1736 * does not modify the Date instance being called - it creates and returns
1737 * a new Date instance containing the resulting date value.
1742 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1743 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1745 //Negative values will subtract correctly:
1746 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1747 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1749 //You can even chain several calls together in one line!
1750 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1751 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1754 * @param {String} interval A valid date interval enum value
1755 * @param {Number} value The amount to add to the current date
1756 * @return {Date} The new Date instance
1758 Date.prototype.add = function(interval, value){
1759 var d = this.clone();
1760 if (!interval || value === 0) return d;
1761 switch(interval.toLowerCase()){
1763 d.setMilliseconds(this.getMilliseconds() + value);
1766 d.setSeconds(this.getSeconds() + value);
1769 d.setMinutes(this.getMinutes() + value);
1772 d.setHours(this.getHours() + value);
1775 d.setDate(this.getDate() + value);
1778 var day = this.getDate();
1780 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1783 d.setMonth(this.getMonth() + value);
1786 d.setFullYear(this.getFullYear() + value);
1793 * Ext JS Library 1.1.1
1794 * Copyright(c) 2006-2007, Ext JS, LLC.
1796 * Originally Released Under LGPL - original licence link has changed is not relivant.
1799 * <script type="text/javascript">
1803 * @class Roo.lib.Dom
1806 * Dom utils (from YIU afaik)
1811 * Get the view width
1812 * @param {Boolean} full True will get the full document, otherwise it's the view width
1813 * @return {Number} The width
1816 getViewWidth : function(full) {
1817 return full ? this.getDocumentWidth() : this.getViewportWidth();
1820 * Get the view height
1821 * @param {Boolean} full True will get the full document, otherwise it's the view height
1822 * @return {Number} The height
1824 getViewHeight : function(full) {
1825 return full ? this.getDocumentHeight() : this.getViewportHeight();
1828 getDocumentHeight: function() {
1829 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1830 return Math.max(scrollHeight, this.getViewportHeight());
1833 getDocumentWidth: function() {
1834 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1835 return Math.max(scrollWidth, this.getViewportWidth());
1838 getViewportHeight: function() {
1839 var height = self.innerHeight;
1840 var mode = document.compatMode;
1842 if ((mode || Roo.isIE) && !Roo.isOpera) {
1843 height = (mode == "CSS1Compat") ?
1844 document.documentElement.clientHeight :
1845 document.body.clientHeight;
1851 getViewportWidth: function() {
1852 var width = self.innerWidth;
1853 var mode = document.compatMode;
1855 if (mode || Roo.isIE) {
1856 width = (mode == "CSS1Compat") ?
1857 document.documentElement.clientWidth :
1858 document.body.clientWidth;
1863 isAncestor : function(p, c) {
1870 if (p.contains && !Roo.isSafari) {
1871 return p.contains(c);
1872 } else if (p.compareDocumentPosition) {
1873 return !!(p.compareDocumentPosition(c) & 16);
1875 var parent = c.parentNode;
1880 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1883 parent = parent.parentNode;
1889 getRegion : function(el) {
1890 return Roo.lib.Region.getRegion(el);
1893 getY : function(el) {
1894 return this.getXY(el)[1];
1897 getX : function(el) {
1898 return this.getXY(el)[0];
1901 getXY : function(el) {
1902 var p, pe, b, scroll, bd = document.body;
1903 el = Roo.getDom(el);
1904 var fly = Roo.lib.AnimBase.fly;
1905 if (el.getBoundingClientRect) {
1906 b = el.getBoundingClientRect();
1907 scroll = fly(document).getScroll();
1908 return [b.left + scroll.left, b.top + scroll.top];
1914 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1921 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1928 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1929 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1936 if (p != el && pe.getStyle('overflow') != 'visible') {
1944 if (Roo.isSafari && hasAbsolute) {
1949 if (Roo.isGecko && !hasAbsolute) {
1951 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1952 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1956 while (p && p != bd) {
1957 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1969 setXY : function(el, xy) {
1970 el = Roo.fly(el, '_setXY');
1972 var pts = el.translatePoints(xy);
1973 if (xy[0] !== false) {
1974 el.dom.style.left = pts.left + "px";
1976 if (xy[1] !== false) {
1977 el.dom.style.top = pts.top + "px";
1981 setX : function(el, x) {
1982 this.setXY(el, [x, false]);
1985 setY : function(el, y) {
1986 this.setXY(el, [false, y]);
1990 * Portions of this file are based on pieces of Yahoo User Interface Library
1991 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1992 * YUI licensed under the BSD License:
1993 * http://developer.yahoo.net/yui/license.txt
1994 * <script type="text/javascript">
1998 Roo.lib.Event = function() {
1999 var loadComplete = false;
2001 var unloadListeners = [];
2003 var onAvailStack = [];
2005 var lastError = null;
2018 startInterval: function() {
2019 if (!this._interval) {
2021 var callback = function() {
2022 self._tryPreloadAttach();
2024 this._interval = setInterval(callback, this.POLL_INTERVAL);
2029 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2030 onAvailStack.push({ id: p_id,
2033 override: p_override,
2034 checkReady: false });
2036 retryCount = this.POLL_RETRYS;
2037 this.startInterval();
2041 addListener: function(el, eventName, fn) {
2042 el = Roo.getDom(el);
2047 if ("unload" == eventName) {
2048 unloadListeners[unloadListeners.length] =
2049 [el, eventName, fn];
2053 var wrappedFn = function(e) {
2054 return fn(Roo.lib.Event.getEvent(e));
2057 var li = [el, eventName, fn, wrappedFn];
2059 var index = listeners.length;
2060 listeners[index] = li;
2062 this.doAdd(el, eventName, wrappedFn, false);
2068 removeListener: function(el, eventName, fn) {
2071 el = Roo.getDom(el);
2074 return this.purgeElement(el, false, eventName);
2078 if ("unload" == eventName) {
2080 for (i = 0,len = unloadListeners.length; i < len; i++) {
2081 var li = unloadListeners[i];
2084 li[1] == eventName &&
2086 unloadListeners.splice(i, 1);
2094 var cacheItem = null;
2097 var index = arguments[3];
2099 if ("undefined" == typeof index) {
2100 index = this._getCacheIndex(el, eventName, fn);
2104 cacheItem = listeners[index];
2107 if (!el || !cacheItem) {
2111 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2113 delete listeners[index][this.WFN];
2114 delete listeners[index][this.FN];
2115 listeners.splice(index, 1);
2122 getTarget: function(ev, resolveTextNode) {
2123 ev = ev.browserEvent || ev;
2124 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2125 var t = ev.target || ev.srcElement;
2126 return this.resolveTextNode(t);
2130 resolveTextNode: function(node) {
2131 if (Roo.isSafari && node && 3 == node.nodeType) {
2132 return node.parentNode;
2139 getPageX: function(ev) {
2140 ev = ev.browserEvent || ev;
2141 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2143 if (!x && 0 !== x) {
2144 x = ev.clientX || 0;
2147 x += this.getScroll()[1];
2155 getPageY: function(ev) {
2156 ev = ev.browserEvent || ev;
2157 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2159 if (!y && 0 !== y) {
2160 y = ev.clientY || 0;
2163 y += this.getScroll()[0];
2172 getXY: function(ev) {
2173 ev = ev.browserEvent || ev;
2174 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2175 return [this.getPageX(ev), this.getPageY(ev)];
2179 getRelatedTarget: function(ev) {
2180 ev = ev.browserEvent || ev;
2181 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2182 var t = ev.relatedTarget;
2184 if (ev.type == "mouseout") {
2186 } else if (ev.type == "mouseover") {
2191 return this.resolveTextNode(t);
2195 getTime: function(ev) {
2196 ev = ev.browserEvent || ev;
2197 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2199 var t = new Date().getTime();
2203 this.lastError = ex;
2212 stopEvent: function(ev) {
2213 this.stopPropagation(ev);
2214 this.preventDefault(ev);
2218 stopPropagation: function(ev) {
2219 ev = ev.browserEvent || ev;
2220 if (ev.stopPropagation) {
2221 ev.stopPropagation();
2223 ev.cancelBubble = true;
2228 preventDefault: function(ev) {
2229 ev = ev.browserEvent || ev;
2230 if(ev.preventDefault) {
2231 ev.preventDefault();
2233 ev.returnValue = false;
2238 getEvent: function(e) {
2239 var ev = e || window.event;
2241 var c = this.getEvent.caller;
2243 ev = c.arguments[0];
2244 if (ev && Event == ev.constructor) {
2254 getCharCode: function(ev) {
2255 ev = ev.browserEvent || ev;
2256 return ev.charCode || ev.keyCode || 0;
2260 _getCacheIndex: function(el, eventName, fn) {
2261 for (var i = 0,len = listeners.length; i < len; ++i) {
2262 var li = listeners[i];
2264 li[this.FN] == fn &&
2265 li[this.EL] == el &&
2266 li[this.TYPE] == eventName) {
2278 getEl: function(id) {
2279 return document.getElementById(id);
2283 clearCache: function() {
2287 _load: function(e) {
2288 loadComplete = true;
2289 var EU = Roo.lib.Event;
2293 EU.doRemove(window, "load", EU._load);
2298 _tryPreloadAttach: function() {
2307 var tryAgain = !loadComplete;
2309 tryAgain = (retryCount > 0);
2314 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2315 var item = onAvailStack[i];
2317 var el = this.getEl(item.id);
2320 if (!item.checkReady ||
2323 (document && document.body)) {
2326 if (item.override) {
2327 if (item.override === true) {
2330 scope = item.override;
2333 item.fn.call(scope, item.obj);
2334 onAvailStack[i] = null;
2337 notAvail.push(item);
2342 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2346 this.startInterval();
2348 clearInterval(this._interval);
2349 this._interval = null;
2352 this.locked = false;
2359 purgeElement: function(el, recurse, eventName) {
2360 var elListeners = this.getListeners(el, eventName);
2362 for (var i = 0,len = elListeners.length; i < len; ++i) {
2363 var l = elListeners[i];
2364 this.removeListener(el, l.type, l.fn);
2368 if (recurse && el && el.childNodes) {
2369 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2370 this.purgeElement(el.childNodes[i], recurse, eventName);
2376 getListeners: function(el, eventName) {
2377 var results = [], searchLists;
2379 searchLists = [listeners, unloadListeners];
2380 } else if (eventName == "unload") {
2381 searchLists = [unloadListeners];
2383 searchLists = [listeners];
2386 for (var j = 0; j < searchLists.length; ++j) {
2387 var searchList = searchLists[j];
2388 if (searchList && searchList.length > 0) {
2389 for (var i = 0,len = searchList.length; i < len; ++i) {
2390 var l = searchList[i];
2391 if (l && l[this.EL] === el &&
2392 (!eventName || eventName === l[this.TYPE])) {
2397 adjust: l[this.ADJ_SCOPE],
2405 return (results.length) ? results : null;
2409 _unload: function(e) {
2411 var EU = Roo.lib.Event, i, j, l, len, index;
2413 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2414 l = unloadListeners[i];
2417 if (l[EU.ADJ_SCOPE]) {
2418 if (l[EU.ADJ_SCOPE] === true) {
2421 scope = l[EU.ADJ_SCOPE];
2424 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2425 unloadListeners[i] = null;
2431 unloadListeners = null;
2433 if (listeners && listeners.length > 0) {
2434 j = listeners.length;
2437 l = listeners[index];
2439 EU.removeListener(l[EU.EL], l[EU.TYPE],
2449 EU.doRemove(window, "unload", EU._unload);
2454 getScroll: function() {
2455 var dd = document.documentElement, db = document.body;
2456 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2457 return [dd.scrollTop, dd.scrollLeft];
2459 return [db.scrollTop, db.scrollLeft];
2466 doAdd: function () {
2467 if (window.addEventListener) {
2468 return function(el, eventName, fn, capture) {
2469 el.addEventListener(eventName, fn, (capture));
2471 } else if (window.attachEvent) {
2472 return function(el, eventName, fn, capture) {
2473 el.attachEvent("on" + eventName, fn);
2482 doRemove: function() {
2483 if (window.removeEventListener) {
2484 return function (el, eventName, fn, capture) {
2485 el.removeEventListener(eventName, fn, (capture));
2487 } else if (window.detachEvent) {
2488 return function (el, eventName, fn) {
2489 el.detachEvent("on" + eventName, fn);
2501 var E = Roo.lib.Event;
2502 E.on = E.addListener;
2503 E.un = E.removeListener;
2505 if (document && document.body) {
2508 E.doAdd(window, "load", E._load);
2510 E.doAdd(window, "unload", E._unload);
2511 E._tryPreloadAttach();
2515 * Portions of this file are based on pieces of Yahoo User Interface Library
2516 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2517 * YUI licensed under the BSD License:
2518 * http://developer.yahoo.net/yui/license.txt
2519 * <script type="text/javascript">
2525 * @class Roo.lib.Ajax
2532 request : function(method, uri, cb, data, options) {
2534 var hs = options.headers;
2537 if(hs.hasOwnProperty(h)){
2538 this.initHeader(h, hs[h], false);
2542 if(options.xmlData){
2543 this.initHeader('Content-Type', 'text/xml', false);
2545 data = options.xmlData;
2549 return this.asyncRequest(method, uri, cb, data);
2552 serializeForm : function(form) {
2553 if(typeof form == 'string') {
2554 form = (document.getElementById(form) || document.forms[form]);
2557 var el, name, val, disabled, data = '', hasSubmit = false;
2558 for (var i = 0; i < form.elements.length; i++) {
2559 el = form.elements[i];
2560 disabled = form.elements[i].disabled;
2561 name = form.elements[i].name;
2562 val = form.elements[i].value;
2564 if (!disabled && name){
2568 case 'select-multiple':
2569 for (var j = 0; j < el.options.length; j++) {
2570 if (el.options[j].selected) {
2572 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2575 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2583 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2596 if(hasSubmit == false) {
2597 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2602 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2607 data = data.substr(0, data.length - 1);
2615 useDefaultHeader:true,
2617 defaultPostHeader:'application/x-www-form-urlencoded',
2619 useDefaultXhrHeader:true,
2621 defaultXhrHeader:'XMLHttpRequest',
2623 hasDefaultHeaders:true,
2635 setProgId:function(id)
2637 this.activeX.unshift(id);
2640 setDefaultPostHeader:function(b)
2642 this.useDefaultHeader = b;
2645 setDefaultXhrHeader:function(b)
2647 this.useDefaultXhrHeader = b;
2650 setPollingInterval:function(i)
2652 if (typeof i == 'number' && isFinite(i)) {
2653 this.pollInterval = i;
2657 createXhrObject:function(transactionId)
2663 http = new XMLHttpRequest();
2665 obj = { conn:http, tId:transactionId };
2669 for (var i = 0; i < this.activeX.length; ++i) {
2673 http = new ActiveXObject(this.activeX[i]);
2675 obj = { conn:http, tId:transactionId };
2688 getConnectionObject:function()
2691 var tId = this.transactionId;
2695 o = this.createXhrObject(tId);
2697 this.transactionId++;
2708 asyncRequest:function(method, uri, callback, postData)
2710 var o = this.getConnectionObject();
2716 o.conn.open(method, uri, true);
2718 if (this.useDefaultXhrHeader) {
2719 if (!this.defaultHeaders['X-Requested-With']) {
2720 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2724 if(postData && this.useDefaultHeader){
2725 this.initHeader('Content-Type', this.defaultPostHeader);
2728 if (this.hasDefaultHeaders || this.hasHeaders) {
2732 this.handleReadyState(o, callback);
2733 o.conn.send(postData || null);
2739 handleReadyState:function(o, callback)
2743 if (callback && callback.timeout) {
2745 this.timeout[o.tId] = window.setTimeout(function() {
2746 oConn.abort(o, callback, true);
2747 }, callback.timeout);
2750 this.poll[o.tId] = window.setInterval(
2752 if (o.conn && o.conn.readyState == 4) {
2753 window.clearInterval(oConn.poll[o.tId]);
2754 delete oConn.poll[o.tId];
2756 if(callback && callback.timeout) {
2757 window.clearTimeout(oConn.timeout[o.tId]);
2758 delete oConn.timeout[o.tId];
2761 oConn.handleTransactionResponse(o, callback);
2764 , this.pollInterval);
2767 handleTransactionResponse:function(o, callback, isAbort)
2771 this.releaseObject(o);
2775 var httpStatus, responseObject;
2779 if (o.conn.status !== undefined && o.conn.status != 0) {
2780 httpStatus = o.conn.status;
2792 if (httpStatus >= 200 && httpStatus < 300) {
2793 responseObject = this.createResponseObject(o, callback.argument);
2794 if (callback.success) {
2795 if (!callback.scope) {
2796 callback.success(responseObject);
2801 callback.success.apply(callback.scope, [responseObject]);
2806 switch (httpStatus) {
2814 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2815 if (callback.failure) {
2816 if (!callback.scope) {
2817 callback.failure(responseObject);
2820 callback.failure.apply(callback.scope, [responseObject]);
2825 responseObject = this.createResponseObject(o, callback.argument);
2826 if (callback.failure) {
2827 if (!callback.scope) {
2828 callback.failure(responseObject);
2831 callback.failure.apply(callback.scope, [responseObject]);
2837 this.releaseObject(o);
2838 responseObject = null;
2841 createResponseObject:function(o, callbackArg)
2848 var headerStr = o.conn.getAllResponseHeaders();
2849 var header = headerStr.split('\n');
2850 for (var i = 0; i < header.length; i++) {
2851 var delimitPos = header[i].indexOf(':');
2852 if (delimitPos != -1) {
2853 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2861 obj.status = o.conn.status;
2862 obj.statusText = o.conn.statusText;
2863 obj.getResponseHeader = headerObj;
2864 obj.getAllResponseHeaders = headerStr;
2865 obj.responseText = o.conn.responseText;
2866 obj.responseXML = o.conn.responseXML;
2868 if (typeof callbackArg !== undefined) {
2869 obj.argument = callbackArg;
2875 createExceptionObject:function(tId, callbackArg, isAbort)
2878 var COMM_ERROR = 'communication failure';
2879 var ABORT_CODE = -1;
2880 var ABORT_ERROR = 'transaction aborted';
2886 obj.status = ABORT_CODE;
2887 obj.statusText = ABORT_ERROR;
2890 obj.status = COMM_CODE;
2891 obj.statusText = COMM_ERROR;
2895 obj.argument = callbackArg;
2901 initHeader:function(label, value, isDefault)
2903 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2905 if (headerObj[label] === undefined) {
2906 headerObj[label] = value;
2911 headerObj[label] = value + "," + headerObj[label];
2915 this.hasDefaultHeaders = true;
2918 this.hasHeaders = true;
2923 setHeader:function(o)
2925 if (this.hasDefaultHeaders) {
2926 for (var prop in this.defaultHeaders) {
2927 if (this.defaultHeaders.hasOwnProperty(prop)) {
2928 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2933 if (this.hasHeaders) {
2934 for (var prop in this.headers) {
2935 if (this.headers.hasOwnProperty(prop)) {
2936 o.conn.setRequestHeader(prop, this.headers[prop]);
2940 this.hasHeaders = false;
2944 resetDefaultHeaders:function() {
2945 delete this.defaultHeaders;
2946 this.defaultHeaders = {};
2947 this.hasDefaultHeaders = false;
2950 abort:function(o, callback, isTimeout)
2952 if(this.isCallInProgress(o)) {
2954 window.clearInterval(this.poll[o.tId]);
2955 delete this.poll[o.tId];
2957 delete this.timeout[o.tId];
2960 this.handleTransactionResponse(o, callback, true);
2970 isCallInProgress:function(o)
2973 return o.conn.readyState != 4 && o.conn.readyState != 0;
2982 releaseObject:function(o)
2991 'MSXML2.XMLHTTP.3.0',
2999 * Portions of this file are based on pieces of Yahoo User Interface Library
3000 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3001 * YUI licensed under the BSD License:
3002 * http://developer.yahoo.net/yui/license.txt
3003 * <script type="text/javascript">
3007 Roo.lib.Region = function(t, r, b, l) {
3017 Roo.lib.Region.prototype = {
3018 contains : function(region) {
3019 return ( region.left >= this.left &&
3020 region.right <= this.right &&
3021 region.top >= this.top &&
3022 region.bottom <= this.bottom );
3026 getArea : function() {
3027 return ( (this.bottom - this.top) * (this.right - this.left) );
3030 intersect : function(region) {
3031 var t = Math.max(this.top, region.top);
3032 var r = Math.min(this.right, region.right);
3033 var b = Math.min(this.bottom, region.bottom);
3034 var l = Math.max(this.left, region.left);
3036 if (b >= t && r >= l) {
3037 return new Roo.lib.Region(t, r, b, l);
3042 union : function(region) {
3043 var t = Math.min(this.top, region.top);
3044 var r = Math.max(this.right, region.right);
3045 var b = Math.max(this.bottom, region.bottom);
3046 var l = Math.min(this.left, region.left);
3048 return new Roo.lib.Region(t, r, b, l);
3051 adjust : function(t, l, b, r) {
3060 Roo.lib.Region.getRegion = function(el) {
3061 var p = Roo.lib.Dom.getXY(el);
3064 var r = p[0] + el.offsetWidth;
3065 var b = p[1] + el.offsetHeight;
3068 return new Roo.lib.Region(t, r, b, l);
3071 * Portions of this file are based on pieces of Yahoo User Interface Library
3072 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3073 * YUI licensed under the BSD License:
3074 * http://developer.yahoo.net/yui/license.txt
3075 * <script type="text/javascript">
3078 //@@dep Roo.lib.Region
3081 Roo.lib.Point = function(x, y) {
3082 if (x instanceof Array) {
3086 this.x = this.right = this.left = this[0] = x;
3087 this.y = this.top = this.bottom = this[1] = y;
3090 Roo.lib.Point.prototype = new Roo.lib.Region();
3092 * Portions of this file are based on pieces of Yahoo User Interface Library
3093 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3094 * YUI licensed under the BSD License:
3095 * http://developer.yahoo.net/yui/license.txt
3096 * <script type="text/javascript">
3103 scroll : function(el, args, duration, easing, cb, scope) {
3104 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3107 motion : function(el, args, duration, easing, cb, scope) {
3108 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3111 color : function(el, args, duration, easing, cb, scope) {
3112 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3115 run : function(el, args, duration, easing, cb, scope, type) {
3116 type = type || Roo.lib.AnimBase;
3117 if (typeof easing == "string") {
3118 easing = Roo.lib.Easing[easing];
3120 var anim = new type(el, args, duration, easing);
3121 anim.animateX(function() {
3122 Roo.callback(cb, scope);
3128 * Portions of this file are based on pieces of Yahoo User Interface Library
3129 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3130 * YUI licensed under the BSD License:
3131 * http://developer.yahoo.net/yui/license.txt
3132 * <script type="text/javascript">
3140 if (!libFlyweight) {
3141 libFlyweight = new Roo.Element.Flyweight();
3143 libFlyweight.dom = el;
3144 return libFlyweight;
3147 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3151 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3153 this.init(el, attributes, duration, method);
3157 Roo.lib.AnimBase.fly = fly;
3161 Roo.lib.AnimBase.prototype = {
3163 toString: function() {
3164 var el = this.getEl();
3165 var id = el.id || el.tagName;
3166 return ("Anim " + id);
3170 noNegatives: /width|height|opacity|padding/i,
3171 offsetAttribute: /^((width|height)|(top|left))$/,
3172 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3173 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3177 doMethod: function(attr, start, end) {
3178 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3182 setAttribute: function(attr, val, unit) {
3183 if (this.patterns.noNegatives.test(attr)) {
3184 val = (val > 0) ? val : 0;
3187 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3191 getAttribute: function(attr) {
3192 var el = this.getEl();
3193 var val = fly(el).getStyle(attr);
3195 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3196 return parseFloat(val);
3199 var a = this.patterns.offsetAttribute.exec(attr) || [];
3200 var pos = !!( a[3] );
3201 var box = !!( a[2] );
3204 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3205 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3214 getDefaultUnit: function(attr) {
3215 if (this.patterns.defaultUnit.test(attr)) {
3222 animateX : function(callback, scope) {
3223 var f = function() {
3224 this.onComplete.removeListener(f);
3225 if (typeof callback == "function") {
3226 callback.call(scope || this, this);
3229 this.onComplete.addListener(f, this);
3234 setRuntimeAttribute: function(attr) {
3237 var attributes = this.attributes;
3239 this.runtimeAttributes[attr] = {};
3241 var isset = function(prop) {
3242 return (typeof prop !== 'undefined');
3245 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3249 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3252 if (isset(attributes[attr]['to'])) {
3253 end = attributes[attr]['to'];
3254 } else if (isset(attributes[attr]['by'])) {
3255 if (start.constructor == Array) {
3257 for (var i = 0, len = start.length; i < len; ++i) {
3258 end[i] = start[i] + attributes[attr]['by'][i];
3261 end = start + attributes[attr]['by'];
3265 this.runtimeAttributes[attr].start = start;
3266 this.runtimeAttributes[attr].end = end;
3269 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3273 init: function(el, attributes, duration, method) {
3275 var isAnimated = false;
3278 var startTime = null;
3281 var actualFrames = 0;
3284 el = Roo.getDom(el);
3287 this.attributes = attributes || {};
3290 this.duration = duration || 1;
3293 this.method = method || Roo.lib.Easing.easeNone;
3296 this.useSeconds = true;
3299 this.currentFrame = 0;
3302 this.totalFrames = Roo.lib.AnimMgr.fps;
3305 this.getEl = function() {
3310 this.isAnimated = function() {
3315 this.getStartTime = function() {
3319 this.runtimeAttributes = {};
3322 this.animate = function() {
3323 if (this.isAnimated()) {
3327 this.currentFrame = 0;
3329 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3331 Roo.lib.AnimMgr.registerElement(this);
3335 this.stop = function(finish) {
3337 this.currentFrame = this.totalFrames;
3338 this._onTween.fire();
3340 Roo.lib.AnimMgr.stop(this);
3343 var onStart = function() {
3344 this.onStart.fire();
3346 this.runtimeAttributes = {};
3347 for (var attr in this.attributes) {
3348 this.setRuntimeAttribute(attr);
3353 startTime = new Date();
3357 var onTween = function() {
3359 duration: new Date() - this.getStartTime(),
3360 currentFrame: this.currentFrame
3363 data.toString = function() {
3365 'duration: ' + data.duration +
3366 ', currentFrame: ' + data.currentFrame
3370 this.onTween.fire(data);
3372 var runtimeAttributes = this.runtimeAttributes;
3374 for (var attr in runtimeAttributes) {
3375 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3381 var onComplete = function() {
3382 var actual_duration = (new Date() - startTime) / 1000 ;
3385 duration: actual_duration,
3386 frames: actualFrames,
3387 fps: actualFrames / actual_duration
3390 data.toString = function() {
3392 'duration: ' + data.duration +
3393 ', frames: ' + data.frames +
3394 ', fps: ' + data.fps
3400 this.onComplete.fire(data);
3404 this._onStart = new Roo.util.Event(this);
3405 this.onStart = new Roo.util.Event(this);
3406 this.onTween = new Roo.util.Event(this);
3407 this._onTween = new Roo.util.Event(this);
3408 this.onComplete = new Roo.util.Event(this);
3409 this._onComplete = new Roo.util.Event(this);
3410 this._onStart.addListener(onStart);
3411 this._onTween.addListener(onTween);
3412 this._onComplete.addListener(onComplete);
3417 * Portions of this file are based on pieces of Yahoo User Interface Library
3418 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3419 * YUI licensed under the BSD License:
3420 * http://developer.yahoo.net/yui/license.txt
3421 * <script type="text/javascript">
3425 Roo.lib.AnimMgr = new function() {
3442 this.registerElement = function(tween) {
3443 queue[queue.length] = tween;
3445 tween._onStart.fire();
3450 this.unRegister = function(tween, index) {
3451 tween._onComplete.fire();
3452 index = index || getIndex(tween);
3454 queue.splice(index, 1);
3458 if (tweenCount <= 0) {
3464 this.start = function() {
3465 if (thread === null) {
3466 thread = setInterval(this.run, this.delay);
3471 this.stop = function(tween) {
3473 clearInterval(thread);
3475 for (var i = 0, len = queue.length; i < len; ++i) {
3476 if (queue[0].isAnimated()) {
3477 this.unRegister(queue[0], 0);
3486 this.unRegister(tween);
3491 this.run = function() {
3492 for (var i = 0, len = queue.length; i < len; ++i) {
3493 var tween = queue[i];
3494 if (!tween || !tween.isAnimated()) {
3498 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3500 tween.currentFrame += 1;
3502 if (tween.useSeconds) {
3503 correctFrame(tween);
3505 tween._onTween.fire();
3508 Roo.lib.AnimMgr.stop(tween, i);
3513 var getIndex = function(anim) {
3514 for (var i = 0, len = queue.length; i < len; ++i) {
3515 if (queue[i] == anim) {
3523 var correctFrame = function(tween) {
3524 var frames = tween.totalFrames;
3525 var frame = tween.currentFrame;
3526 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3527 var elapsed = (new Date() - tween.getStartTime());
3530 if (elapsed < tween.duration * 1000) {
3531 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3533 tweak = frames - (frame + 1);
3535 if (tweak > 0 && isFinite(tweak)) {
3536 if (tween.currentFrame + tweak >= frames) {
3537 tweak = frames - (frame + 1);
3540 tween.currentFrame += tweak;
3546 * Portions of this file are based on pieces of Yahoo User Interface Library
3547 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3548 * YUI licensed under the BSD License:
3549 * http://developer.yahoo.net/yui/license.txt
3550 * <script type="text/javascript">
3553 Roo.lib.Bezier = new function() {
3555 this.getPosition = function(points, t) {
3556 var n = points.length;
3559 for (var i = 0; i < n; ++i) {
3560 tmp[i] = [points[i][0], points[i][1]];
3563 for (var j = 1; j < n; ++j) {
3564 for (i = 0; i < n - j; ++i) {
3565 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3566 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3570 return [ tmp[0][0], tmp[0][1] ];
3574 * Portions of this file are based on pieces of Yahoo User Interface Library
3575 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3576 * YUI licensed under the BSD License:
3577 * http://developer.yahoo.net/yui/license.txt
3578 * <script type="text/javascript">
3583 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3584 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3587 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3589 var fly = Roo.lib.AnimBase.fly;
3591 var superclass = Y.ColorAnim.superclass;
3592 var proto = Y.ColorAnim.prototype;
3594 proto.toString = function() {
3595 var el = this.getEl();
3596 var id = el.id || el.tagName;
3597 return ("ColorAnim " + id);
3600 proto.patterns.color = /color$/i;
3601 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3602 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3603 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3604 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3607 proto.parseColor = function(s) {
3608 if (s.length == 3) {
3612 var c = this.patterns.hex.exec(s);
3613 if (c && c.length == 4) {
3614 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3617 c = this.patterns.rgb.exec(s);
3618 if (c && c.length == 4) {
3619 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3622 c = this.patterns.hex3.exec(s);
3623 if (c && c.length == 4) {
3624 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3629 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3630 proto.getAttribute = function(attr) {
3631 var el = this.getEl();
3632 if (this.patterns.color.test(attr)) {
3633 var val = fly(el).getStyle(attr);
3635 if (this.patterns.transparent.test(val)) {
3636 var parent = el.parentNode;
3637 val = fly(parent).getStyle(attr);
3639 while (parent && this.patterns.transparent.test(val)) {
3640 parent = parent.parentNode;
3641 val = fly(parent).getStyle(attr);
3642 if (parent.tagName.toUpperCase() == 'HTML') {
3648 val = superclass.getAttribute.call(this, attr);
3653 proto.getAttribute = function(attr) {
3654 var el = this.getEl();
3655 if (this.patterns.color.test(attr)) {
3656 var val = fly(el).getStyle(attr);
3658 if (this.patterns.transparent.test(val)) {
3659 var parent = el.parentNode;
3660 val = fly(parent).getStyle(attr);
3662 while (parent && this.patterns.transparent.test(val)) {
3663 parent = parent.parentNode;
3664 val = fly(parent).getStyle(attr);
3665 if (parent.tagName.toUpperCase() == 'HTML') {
3671 val = superclass.getAttribute.call(this, attr);
3677 proto.doMethod = function(attr, start, end) {
3680 if (this.patterns.color.test(attr)) {
3682 for (var i = 0, len = start.length; i < len; ++i) {
3683 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3686 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3689 val = superclass.doMethod.call(this, attr, start, end);
3695 proto.setRuntimeAttribute = function(attr) {
3696 superclass.setRuntimeAttribute.call(this, attr);
3698 if (this.patterns.color.test(attr)) {
3699 var attributes = this.attributes;
3700 var start = this.parseColor(this.runtimeAttributes[attr].start);
3701 var end = this.parseColor(this.runtimeAttributes[attr].end);
3703 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3704 end = this.parseColor(attributes[attr].by);
3706 for (var i = 0, len = start.length; i < len; ++i) {
3707 end[i] = start[i] + end[i];
3711 this.runtimeAttributes[attr].start = start;
3712 this.runtimeAttributes[attr].end = end;
3718 * Portions of this file are based on pieces of Yahoo User Interface Library
3719 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3720 * YUI licensed under the BSD License:
3721 * http://developer.yahoo.net/yui/license.txt
3722 * <script type="text/javascript">
3728 easeNone: function (t, b, c, d) {
3729 return c * t / d + b;
3733 easeIn: function (t, b, c, d) {
3734 return c * (t /= d) * t + b;
3738 easeOut: function (t, b, c, d) {
3739 return -c * (t /= d) * (t - 2) + b;
3743 easeBoth: function (t, b, c, d) {
3744 if ((t /= d / 2) < 1) {
3745 return c / 2 * t * t + b;
3748 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3752 easeInStrong: function (t, b, c, d) {
3753 return c * (t /= d) * t * t * t + b;
3757 easeOutStrong: function (t, b, c, d) {
3758 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3762 easeBothStrong: function (t, b, c, d) {
3763 if ((t /= d / 2) < 1) {
3764 return c / 2 * t * t * t * t + b;
3767 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3772 elasticIn: function (t, b, c, d, a, p) {
3776 if ((t /= d) == 1) {
3783 if (!a || a < Math.abs(c)) {
3788 var s = p / (2 * Math.PI) * Math.asin(c / a);
3791 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3795 elasticOut: function (t, b, c, d, a, p) {
3799 if ((t /= d) == 1) {
3806 if (!a || a < Math.abs(c)) {
3811 var s = p / (2 * Math.PI) * Math.asin(c / a);
3814 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3818 elasticBoth: function (t, b, c, d, a, p) {
3823 if ((t /= d / 2) == 2) {
3831 if (!a || a < Math.abs(c)) {
3836 var s = p / (2 * Math.PI) * Math.asin(c / a);
3840 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3841 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3843 return a * Math.pow(2, -10 * (t -= 1)) *
3844 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3849 backIn: function (t, b, c, d, s) {
3850 if (typeof s == 'undefined') {
3853 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3857 backOut: function (t, b, c, d, s) {
3858 if (typeof s == 'undefined') {
3861 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3865 backBoth: function (t, b, c, d, s) {
3866 if (typeof s == 'undefined') {
3870 if ((t /= d / 2 ) < 1) {
3871 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3873 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3877 bounceIn: function (t, b, c, d) {
3878 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3882 bounceOut: function (t, b, c, d) {
3883 if ((t /= d) < (1 / 2.75)) {
3884 return c * (7.5625 * t * t) + b;
3885 } else if (t < (2 / 2.75)) {
3886 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3887 } else if (t < (2.5 / 2.75)) {
3888 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3890 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3894 bounceBoth: function (t, b, c, d) {
3896 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3898 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3901 * Portions of this file are based on pieces of Yahoo User Interface Library
3902 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3903 * YUI licensed under the BSD License:
3904 * http://developer.yahoo.net/yui/license.txt
3905 * <script type="text/javascript">
3909 Roo.lib.Motion = function(el, attributes, duration, method) {
3911 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3915 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3919 var superclass = Y.Motion.superclass;
3920 var proto = Y.Motion.prototype;
3922 proto.toString = function() {
3923 var el = this.getEl();
3924 var id = el.id || el.tagName;
3925 return ("Motion " + id);
3928 proto.patterns.points = /^points$/i;
3930 proto.setAttribute = function(attr, val, unit) {
3931 if (this.patterns.points.test(attr)) {
3932 unit = unit || 'px';
3933 superclass.setAttribute.call(this, 'left', val[0], unit);
3934 superclass.setAttribute.call(this, 'top', val[1], unit);
3936 superclass.setAttribute.call(this, attr, val, unit);
3940 proto.getAttribute = function(attr) {
3941 if (this.patterns.points.test(attr)) {
3943 superclass.getAttribute.call(this, 'left'),
3944 superclass.getAttribute.call(this, 'top')
3947 val = superclass.getAttribute.call(this, attr);
3953 proto.doMethod = function(attr, start, end) {
3956 if (this.patterns.points.test(attr)) {
3957 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3958 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3960 val = superclass.doMethod.call(this, attr, start, end);
3965 proto.setRuntimeAttribute = function(attr) {
3966 if (this.patterns.points.test(attr)) {
3967 var el = this.getEl();
3968 var attributes = this.attributes;
3970 var control = attributes['points']['control'] || [];
3974 if (control.length > 0 && !(control[0] instanceof Array)) {
3975 control = [control];
3978 for (i = 0,len = control.length; i < len; ++i) {
3979 tmp[i] = control[i];
3984 Roo.fly(el).position();
3986 if (isset(attributes['points']['from'])) {
3987 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3990 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3993 start = this.getAttribute('points');
3996 if (isset(attributes['points']['to'])) {
3997 end = translateValues.call(this, attributes['points']['to'], start);
3999 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4000 for (i = 0,len = control.length; i < len; ++i) {
4001 control[i] = translateValues.call(this, control[i], start);
4005 } else if (isset(attributes['points']['by'])) {
4006 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4008 for (i = 0,len = control.length; i < len; ++i) {
4009 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4013 this.runtimeAttributes[attr] = [start];
4015 if (control.length > 0) {
4016 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4019 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4022 superclass.setRuntimeAttribute.call(this, attr);
4026 var translateValues = function(val, start) {
4027 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4028 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4033 var isset = function(prop) {
4034 return (typeof prop !== 'undefined');
4038 * Portions of this file are based on pieces of Yahoo User Interface Library
4039 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4040 * YUI licensed under the BSD License:
4041 * http://developer.yahoo.net/yui/license.txt
4042 * <script type="text/javascript">
4046 Roo.lib.Scroll = function(el, attributes, duration, method) {
4048 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4052 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4056 var superclass = Y.Scroll.superclass;
4057 var proto = Y.Scroll.prototype;
4059 proto.toString = function() {
4060 var el = this.getEl();
4061 var id = el.id || el.tagName;
4062 return ("Scroll " + id);
4065 proto.doMethod = function(attr, start, end) {
4068 if (attr == 'scroll') {
4070 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4071 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4075 val = superclass.doMethod.call(this, attr, start, end);
4080 proto.getAttribute = function(attr) {
4082 var el = this.getEl();
4084 if (attr == 'scroll') {
4085 val = [ el.scrollLeft, el.scrollTop ];
4087 val = superclass.getAttribute.call(this, attr);
4093 proto.setAttribute = function(attr, val, unit) {
4094 var el = this.getEl();
4096 if (attr == 'scroll') {
4097 el.scrollLeft = val[0];
4098 el.scrollTop = val[1];
4100 superclass.setAttribute.call(this, attr, val, unit);
4106 * Ext JS Library 1.1.1
4107 * Copyright(c) 2006-2007, Ext JS, LLC.
4109 * Originally Released Under LGPL - original licence link has changed is not relivant.
4112 * <script type="text/javascript">
4116 // nasty IE9 hack - what a pile of crap that is..
4118 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4119 Range.prototype.createContextualFragment = function (html) {
4120 var doc = window.document;
4121 var container = doc.createElement("div");
4122 container.innerHTML = html;
4123 var frag = doc.createDocumentFragment(), n;
4124 while ((n = container.firstChild)) {
4125 frag.appendChild(n);
4132 * @class Roo.DomHelper
4133 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4134 * 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>.
4137 Roo.DomHelper = function(){
4138 var tempTableEl = null;
4139 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4140 var tableRe = /^table|tbody|tr|td$/i;
4142 // build as innerHTML where available
4144 var createHtml = function(o){
4145 if(typeof o == 'string'){
4154 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4155 if(attr == "style"){
4157 if(typeof s == "function"){
4160 if(typeof s == "string"){
4161 b += ' style="' + s + '"';
4162 }else if(typeof s == "object"){
4165 if(typeof s[key] != "function"){
4166 b += key + ":" + s[key] + ";";
4173 b += ' class="' + o["cls"] + '"';
4174 }else if(attr == "htmlFor"){
4175 b += ' for="' + o["htmlFor"] + '"';
4177 b += " " + attr + '="' + o[attr] + '"';
4181 if(emptyTags.test(o.tag)){
4185 var cn = o.children || o.cn;
4187 //http://bugs.kde.org/show_bug.cgi?id=71506
4188 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4189 for(var i = 0, len = cn.length; i < len; i++) {
4190 b += createHtml(cn[i], b);
4193 b += createHtml(cn, b);
4199 b += "</" + o.tag + ">";
4206 var createDom = function(o, parentNode){
4208 // defininition craeted..
4210 if (o.ns && o.ns != 'html') {
4212 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4213 xmlns[o.ns] = o.xmlns;
4216 if (typeof(xmlns[o.ns]) == 'undefined') {
4217 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4223 if (typeof(o) == 'string') {
4224 return parentNode.appendChild(document.createTextNode(o));
4226 o.tag = o.tag || div;
4227 if (o.ns && Roo.isIE) {
4229 o.tag = o.ns + ':' + o.tag;
4232 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4233 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4236 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4237 attr == "style" || typeof o[attr] == "function") continue;
4239 if(attr=="cls" && Roo.isIE){
4240 el.className = o["cls"];
4242 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4243 else el[attr] = o[attr];
4246 Roo.DomHelper.applyStyles(el, o.style);
4247 var cn = o.children || o.cn;
4249 //http://bugs.kde.org/show_bug.cgi?id=71506
4250 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4251 for(var i = 0, len = cn.length; i < len; i++) {
4252 createDom(cn[i], el);
4259 el.innerHTML = o.html;
4262 parentNode.appendChild(el);
4267 var ieTable = function(depth, s, h, e){
4268 tempTableEl.innerHTML = [s, h, e].join('');
4269 var i = -1, el = tempTableEl;
4276 // kill repeat to save bytes
4280 tbe = '</tbody>'+te,
4286 * Nasty code for IE's broken table implementation
4288 var insertIntoTable = function(tag, where, el, html){
4290 tempTableEl = document.createElement('div');
4295 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4298 if(where == 'beforebegin'){
4302 before = el.nextSibling;
4305 node = ieTable(4, trs, html, tre);
4307 else if(tag == 'tr'){
4308 if(where == 'beforebegin'){
4311 node = ieTable(3, tbs, html, tbe);
4312 } else if(where == 'afterend'){
4313 before = el.nextSibling;
4315 node = ieTable(3, tbs, html, tbe);
4316 } else{ // INTO a TR
4317 if(where == 'afterbegin'){
4318 before = el.firstChild;
4320 node = ieTable(4, trs, html, tre);
4322 } else if(tag == 'tbody'){
4323 if(where == 'beforebegin'){
4326 node = ieTable(2, ts, html, te);
4327 } else if(where == 'afterend'){
4328 before = el.nextSibling;
4330 node = ieTable(2, ts, html, te);
4332 if(where == 'afterbegin'){
4333 before = el.firstChild;
4335 node = ieTable(3, tbs, html, tbe);
4338 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4341 if(where == 'afterbegin'){
4342 before = el.firstChild;
4344 node = ieTable(2, ts, html, te);
4346 el.insertBefore(node, before);
4351 /** True to force the use of DOM instead of html fragments @type Boolean */
4355 * Returns the markup for the passed Element(s) config
4356 * @param {Object} o The Dom object spec (and children)
4359 markup : function(o){
4360 return createHtml(o);
4364 * Applies a style specification to an element
4365 * @param {String/HTMLElement} el The element to apply styles to
4366 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4367 * a function which returns such a specification.
4369 applyStyles : function(el, styles){
4372 if(typeof styles == "string"){
4373 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4375 while ((matches = re.exec(styles)) != null){
4376 el.setStyle(matches[1], matches[2]);
4378 }else if (typeof styles == "object"){
4379 for (var style in styles){
4380 el.setStyle(style, styles[style]);
4382 }else if (typeof styles == "function"){
4383 Roo.DomHelper.applyStyles(el, styles.call());
4389 * Inserts an HTML fragment into the Dom
4390 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4391 * @param {HTMLElement} el The context element
4392 * @param {String} html The HTML fragmenet
4393 * @return {HTMLElement} The new node
4395 insertHtml : function(where, el, html){
4396 where = where.toLowerCase();
4397 if(el.insertAdjacentHTML){
4398 if(tableRe.test(el.tagName)){
4400 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4406 el.insertAdjacentHTML('BeforeBegin', html);
4407 return el.previousSibling;
4409 el.insertAdjacentHTML('AfterBegin', html);
4410 return el.firstChild;
4412 el.insertAdjacentHTML('BeforeEnd', html);
4413 return el.lastChild;
4415 el.insertAdjacentHTML('AfterEnd', html);
4416 return el.nextSibling;
4418 throw 'Illegal insertion point -> "' + where + '"';
4420 var range = el.ownerDocument.createRange();
4424 range.setStartBefore(el);
4425 frag = range.createContextualFragment(html);
4426 el.parentNode.insertBefore(frag, el);
4427 return el.previousSibling;
4430 range.setStartBefore(el.firstChild);
4431 frag = range.createContextualFragment(html);
4432 el.insertBefore(frag, el.firstChild);
4433 return el.firstChild;
4435 el.innerHTML = html;
4436 return el.firstChild;
4440 range.setStartAfter(el.lastChild);
4441 frag = range.createContextualFragment(html);
4442 el.appendChild(frag);
4443 return el.lastChild;
4445 el.innerHTML = html;
4446 return el.lastChild;
4449 range.setStartAfter(el);
4450 frag = range.createContextualFragment(html);
4451 el.parentNode.insertBefore(frag, el.nextSibling);
4452 return el.nextSibling;
4454 throw 'Illegal insertion point -> "' + where + '"';
4458 * Creates new Dom element(s) and inserts them before el
4459 * @param {String/HTMLElement/Element} el The context element
4460 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4461 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4462 * @return {HTMLElement/Roo.Element} The new node
4464 insertBefore : function(el, o, returnElement){
4465 return this.doInsert(el, o, returnElement, "beforeBegin");
4469 * Creates new Dom element(s) and inserts them after el
4470 * @param {String/HTMLElement/Element} el The context element
4471 * @param {Object} o The Dom object spec (and children)
4472 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4473 * @return {HTMLElement/Roo.Element} The new node
4475 insertAfter : function(el, o, returnElement){
4476 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4480 * Creates new Dom element(s) and inserts them as the first child of el
4481 * @param {String/HTMLElement/Element} el The context element
4482 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4483 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4484 * @return {HTMLElement/Roo.Element} The new node
4486 insertFirst : function(el, o, returnElement){
4487 return this.doInsert(el, o, returnElement, "afterBegin");
4491 doInsert : function(el, o, returnElement, pos, sibling){
4492 el = Roo.getDom(el);
4494 if(this.useDom || o.ns){
4495 newNode = createDom(o, null);
4496 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4498 var html = createHtml(o);
4499 newNode = this.insertHtml(pos, el, html);
4501 return returnElement ? Roo.get(newNode, true) : newNode;
4505 * Creates new Dom element(s) and appends them to el
4506 * @param {String/HTMLElement/Element} el The context element
4507 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4508 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4509 * @return {HTMLElement/Roo.Element} The new node
4511 append : function(el, o, returnElement){
4512 el = Roo.getDom(el);
4514 if(this.useDom || o.ns){
4515 newNode = createDom(o, null);
4516 el.appendChild(newNode);
4518 var html = createHtml(o);
4519 newNode = this.insertHtml("beforeEnd", el, html);
4521 return returnElement ? Roo.get(newNode, true) : newNode;
4525 * Creates new Dom element(s) and overwrites the contents of el with them
4526 * @param {String/HTMLElement/Element} el The context element
4527 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4528 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4529 * @return {HTMLElement/Roo.Element} The new node
4531 overwrite : function(el, o, returnElement){
4532 el = Roo.getDom(el);
4535 while (el.childNodes.length) {
4536 el.removeChild(el.firstChild);
4540 el.innerHTML = createHtml(o);
4543 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4547 * Creates a new Roo.DomHelper.Template from the Dom object spec
4548 * @param {Object} o The Dom object spec (and children)
4549 * @return {Roo.DomHelper.Template} The new template
4551 createTemplate : function(o){
4552 var html = createHtml(o);
4553 return new Roo.Template(html);
4559 * Ext JS Library 1.1.1
4560 * Copyright(c) 2006-2007, Ext JS, LLC.
4562 * Originally Released Under LGPL - original licence link has changed is not relivant.
4565 * <script type="text/javascript">
4569 * @class Roo.Template
4570 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4571 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4574 var t = new Roo.Template({
4575 html : '<div name="{id}">' +
4576 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4578 myformat: function (value, allValues) {
4579 return 'XX' + value;
4582 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4584 * For more information see this blog post with examples:
4585 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4586 - Create Elements using DOM, HTML fragments and Templates</a>.
4588 * @param {Object} cfg - Configuration object.
4590 Roo.Template = function(cfg){
4592 if(cfg instanceof Array){
4594 }else if(arguments.length > 1){
4595 cfg = Array.prototype.join.call(arguments, "");
4599 if (typeof(cfg) == 'object') {
4610 Roo.Template.prototype = {
4613 * @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..
4614 * it should be fixed so that template is observable...
4618 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4622 * Returns an HTML fragment of this template with the specified values applied.
4623 * @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'})
4624 * @return {String} The HTML fragment
4626 applyTemplate : function(values){
4630 return this.compiled(values);
4632 var useF = this.disableFormats !== true;
4633 var fm = Roo.util.Format, tpl = this;
4634 var fn = function(m, name, format, args){
4636 if(format.substr(0, 5) == "this."){
4637 return tpl.call(format.substr(5), values[name], values);
4640 // quoted values are required for strings in compiled templates,
4641 // but for non compiled we need to strip them
4642 // quoted reversed for jsmin
4643 var re = /^\s*['"](.*)["']\s*$/;
4644 args = args.split(',');
4645 for(var i = 0, len = args.length; i < len; i++){
4646 args[i] = args[i].replace(re, "$1");
4648 args = [values[name]].concat(args);
4650 args = [values[name]];
4652 return fm[format].apply(fm, args);
4655 return values[name] !== undefined ? values[name] : "";
4658 return this.html.replace(this.re, fn);
4676 this.loading = true;
4677 this.compiled = false;
4679 var cx = new Roo.data.Connection();
4683 success : function (response) {
4685 _t.html = response.responseText;
4689 failure : function(response) {
4690 Roo.log("Template failed to load from " + _t.url);
4697 * Sets the HTML used as the template and optionally compiles it.
4698 * @param {String} html
4699 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4700 * @return {Roo.Template} this
4702 set : function(html, compile){
4704 this.compiled = null;
4712 * True to disable format functions (defaults to false)
4715 disableFormats : false,
4718 * The regular expression used to match template variables
4722 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4725 * Compiles the template into an internal function, eliminating the RegEx overhead.
4726 * @return {Roo.Template} this
4728 compile : function(){
4729 var fm = Roo.util.Format;
4730 var useF = this.disableFormats !== true;
4731 var sep = Roo.isGecko ? "+" : ",";
4732 var fn = function(m, name, format, args){
4734 args = args ? ',' + args : "";
4735 if(format.substr(0, 5) != "this."){
4736 format = "fm." + format + '(';
4738 format = 'this.call("'+ format.substr(5) + '", ';
4742 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4744 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4747 // branched to use + in gecko and [].join() in others
4749 body = "this.compiled = function(values){ return '" +
4750 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4753 body = ["this.compiled = function(values){ return ['"];
4754 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4755 body.push("'].join('');};");
4756 body = body.join('');
4766 // private function used to call members
4767 call : function(fnName, value, allValues){
4768 return this[fnName](value, allValues);
4772 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4773 * @param {String/HTMLElement/Roo.Element} el The context element
4774 * @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'})
4775 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4776 * @return {HTMLElement/Roo.Element} The new node or Element
4778 insertFirst: function(el, values, returnElement){
4779 return this.doInsert('afterBegin', el, values, returnElement);
4783 * Applies the supplied values to the template and inserts the new node(s) before el.
4784 * @param {String/HTMLElement/Roo.Element} el The context element
4785 * @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'})
4786 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4787 * @return {HTMLElement/Roo.Element} The new node or Element
4789 insertBefore: function(el, values, returnElement){
4790 return this.doInsert('beforeBegin', el, values, returnElement);
4794 * Applies the supplied values to the template and inserts the new node(s) after el.
4795 * @param {String/HTMLElement/Roo.Element} el The context element
4796 * @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'})
4797 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4798 * @return {HTMLElement/Roo.Element} The new node or Element
4800 insertAfter : function(el, values, returnElement){
4801 return this.doInsert('afterEnd', el, values, returnElement);
4805 * Applies the supplied values to the template and appends the new node(s) to el.
4806 * @param {String/HTMLElement/Roo.Element} el The context element
4807 * @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'})
4808 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4809 * @return {HTMLElement/Roo.Element} The new node or Element
4811 append : function(el, values, returnElement){
4812 return this.doInsert('beforeEnd', el, values, returnElement);
4815 doInsert : function(where, el, values, returnEl){
4816 el = Roo.getDom(el);
4817 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4818 return returnEl ? Roo.get(newNode, true) : newNode;
4822 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4823 * @param {String/HTMLElement/Roo.Element} el The context element
4824 * @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'})
4825 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4826 * @return {HTMLElement/Roo.Element} The new node or Element
4828 overwrite : function(el, values, returnElement){
4829 el = Roo.getDom(el);
4830 el.innerHTML = this.applyTemplate(values);
4831 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4835 * Alias for {@link #applyTemplate}
4838 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4841 Roo.DomHelper.Template = Roo.Template;
4844 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4845 * @param {String/HTMLElement} el A DOM element or its id
4846 * @returns {Roo.Template} The created template
4849 Roo.Template.from = function(el){
4850 el = Roo.getDom(el);
4851 return new Roo.Template(el.value || el.innerHTML);
4854 * Ext JS Library 1.1.1
4855 * Copyright(c) 2006-2007, Ext JS, LLC.
4857 * Originally Released Under LGPL - original licence link has changed is not relivant.
4860 * <script type="text/javascript">
4865 * This is code is also distributed under MIT license for use
4866 * with jQuery and prototype JavaScript libraries.
4869 * @class Roo.DomQuery
4870 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).
4872 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>
4875 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.
4877 <h4>Element Selectors:</h4>
4879 <li> <b>*</b> any element</li>
4880 <li> <b>E</b> an element with the tag E</li>
4881 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4882 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4883 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4884 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4886 <h4>Attribute Selectors:</h4>
4887 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4889 <li> <b>E[foo]</b> has an attribute "foo"</li>
4890 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4891 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4892 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4893 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4894 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4895 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4897 <h4>Pseudo Classes:</h4>
4899 <li> <b>E:first-child</b> E is the first child of its parent</li>
4900 <li> <b>E:last-child</b> E is the last child of its parent</li>
4901 <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>
4902 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4903 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4904 <li> <b>E:only-child</b> E is the only child of its parent</li>
4905 <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>
4906 <li> <b>E:first</b> the first E in the resultset</li>
4907 <li> <b>E:last</b> the last E in the resultset</li>
4908 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4909 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4910 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4911 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4912 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4913 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4914 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4915 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4916 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4918 <h4>CSS Value Selectors:</h4>
4920 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4921 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4922 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4923 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4924 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4925 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4929 Roo.DomQuery = function(){
4930 var cache = {}, simpleCache = {}, valueCache = {};
4931 var nonSpace = /\S/;
4932 var trimRe = /^\s+|\s+$/g;
4933 var tplRe = /\{(\d+)\}/g;
4934 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4935 var tagTokenRe = /^(#)?([\w-\*]+)/;
4936 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4938 function child(p, index){
4940 var n = p.firstChild;
4942 if(n.nodeType == 1){
4953 while((n = n.nextSibling) && n.nodeType != 1);
4958 while((n = n.previousSibling) && n.nodeType != 1);
4962 function children(d){
4963 var n = d.firstChild, ni = -1;
4965 var nx = n.nextSibling;
4966 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4976 function byClassName(c, a, v){
4980 var r = [], ri = -1, cn;
4981 for(var i = 0, ci; ci = c[i]; i++){
4982 if((' '+ci.className+' ').indexOf(v) != -1){
4989 function attrValue(n, attr){
4990 if(!n.tagName && typeof n.length != "undefined"){
4999 if(attr == "class" || attr == "className"){
5002 return n.getAttribute(attr) || n[attr];
5006 function getNodes(ns, mode, tagName){
5007 var result = [], ri = -1, cs;
5011 tagName = tagName || "*";
5012 if(typeof ns.getElementsByTagName != "undefined"){
5016 for(var i = 0, ni; ni = ns[i]; i++){
5017 cs = ni.getElementsByTagName(tagName);
5018 for(var j = 0, ci; ci = cs[j]; j++){
5022 }else if(mode == "/" || mode == ">"){
5023 var utag = tagName.toUpperCase();
5024 for(var i = 0, ni, cn; ni = ns[i]; i++){
5025 cn = ni.children || ni.childNodes;
5026 for(var j = 0, cj; cj = cn[j]; j++){
5027 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5032 }else if(mode == "+"){
5033 var utag = tagName.toUpperCase();
5034 for(var i = 0, n; n = ns[i]; i++){
5035 while((n = n.nextSibling) && n.nodeType != 1);
5036 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5040 }else if(mode == "~"){
5041 for(var i = 0, n; n = ns[i]; i++){
5042 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5051 function concat(a, b){
5055 for(var i = 0, l = b.length; i < l; i++){
5061 function byTag(cs, tagName){
5062 if(cs.tagName || cs == document){
5068 var r = [], ri = -1;
5069 tagName = tagName.toLowerCase();
5070 for(var i = 0, ci; ci = cs[i]; i++){
5071 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5078 function byId(cs, attr, id){
5079 if(cs.tagName || cs == document){
5085 var r = [], ri = -1;
5086 for(var i = 0,ci; ci = cs[i]; i++){
5087 if(ci && ci.id == id){
5095 function byAttribute(cs, attr, value, op, custom){
5096 var r = [], ri = -1, st = custom=="{";
5097 var f = Roo.DomQuery.operators[op];
5098 for(var i = 0, ci; ci = cs[i]; i++){
5101 a = Roo.DomQuery.getStyle(ci, attr);
5103 else if(attr == "class" || attr == "className"){
5105 }else if(attr == "for"){
5107 }else if(attr == "href"){
5108 a = ci.getAttribute("href", 2);
5110 a = ci.getAttribute(attr);
5112 if((f && f(a, value)) || (!f && a)){
5119 function byPseudo(cs, name, value){
5120 return Roo.DomQuery.pseudos[name](cs, value);
5123 // This is for IE MSXML which does not support expandos.
5124 // IE runs the same speed using setAttribute, however FF slows way down
5125 // and Safari completely fails so they need to continue to use expandos.
5126 var isIE = window.ActiveXObject ? true : false;
5128 // this eval is stop the compressor from
5129 // renaming the variable to something shorter
5131 /** eval:var:batch */
5136 function nodupIEXml(cs){
5138 cs[0].setAttribute("_nodup", d);
5140 for(var i = 1, len = cs.length; i < len; i++){
5142 if(!c.getAttribute("_nodup") != d){
5143 c.setAttribute("_nodup", d);
5147 for(var i = 0, len = cs.length; i < len; i++){
5148 cs[i].removeAttribute("_nodup");
5157 var len = cs.length, c, i, r = cs, cj, ri = -1;
5158 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5161 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5162 return nodupIEXml(cs);
5166 for(i = 1; c = cs[i]; i++){
5171 for(var j = 0; j < i; j++){
5174 for(j = i+1; cj = cs[j]; j++){
5186 function quickDiffIEXml(c1, c2){
5188 for(var i = 0, len = c1.length; i < len; i++){
5189 c1[i].setAttribute("_qdiff", d);
5192 for(var i = 0, len = c2.length; i < len; i++){
5193 if(c2[i].getAttribute("_qdiff") != d){
5194 r[r.length] = c2[i];
5197 for(var i = 0, len = c1.length; i < len; i++){
5198 c1[i].removeAttribute("_qdiff");
5203 function quickDiff(c1, c2){
5204 var len1 = c1.length;
5208 if(isIE && c1[0].selectSingleNode){
5209 return quickDiffIEXml(c1, c2);
5212 for(var i = 0; i < len1; i++){
5216 for(var i = 0, len = c2.length; i < len; i++){
5217 if(c2[i]._qdiff != d){
5218 r[r.length] = c2[i];
5224 function quickId(ns, mode, root, id){
5226 var d = root.ownerDocument || root;
5227 return d.getElementById(id);
5229 ns = getNodes(ns, mode, "*");
5230 return byId(ns, null, id);
5234 getStyle : function(el, name){
5235 return Roo.fly(el).getStyle(name);
5238 * Compiles a selector/xpath query into a reusable function. The returned function
5239 * takes one parameter "root" (optional), which is the context node from where the query should start.
5240 * @param {String} selector The selector/xpath query
5241 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5242 * @return {Function}
5244 compile : function(path, type){
5245 type = type || "select";
5247 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5248 var q = path, mode, lq;
5249 var tk = Roo.DomQuery.matchers;
5250 var tklen = tk.length;
5253 // accept leading mode switch
5254 var lmode = q.match(modeRe);
5255 if(lmode && lmode[1]){
5256 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5257 q = q.replace(lmode[1], "");
5259 // strip leading slashes
5260 while(path.substr(0, 1)=="/"){
5261 path = path.substr(1);
5264 while(q && lq != q){
5266 var tm = q.match(tagTokenRe);
5267 if(type == "select"){
5270 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5272 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5274 q = q.replace(tm[0], "");
5275 }else if(q.substr(0, 1) != '@'){
5276 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5281 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5283 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5285 q = q.replace(tm[0], "");
5288 while(!(mm = q.match(modeRe))){
5289 var matched = false;
5290 for(var j = 0; j < tklen; j++){
5292 var m = q.match(t.re);
5294 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5297 q = q.replace(m[0], "");
5302 // prevent infinite loop on bad selector
5304 throw 'Error parsing selector, parsing failed at "' + q + '"';
5308 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5309 q = q.replace(mm[1], "");
5312 fn[fn.length] = "return nodup(n);\n}";
5315 * list of variables that need from compression as they are used by eval.
5325 * eval:var:byClassName
5327 * eval:var:byAttribute
5328 * eval:var:attrValue
5336 * Selects a group of elements.
5337 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5338 * @param {Node} root (optional) The start of the query (defaults to document).
5341 select : function(path, root, type){
5342 if(!root || root == document){
5345 if(typeof root == "string"){
5346 root = document.getElementById(root);
5348 var paths = path.split(",");
5350 for(var i = 0, len = paths.length; i < len; i++){
5351 var p = paths[i].replace(trimRe, "");
5353 cache[p] = Roo.DomQuery.compile(p);
5355 throw p + " is not a valid selector";
5358 var result = cache[p](root);
5359 if(result && result != document){
5360 results = results.concat(result);
5363 if(paths.length > 1){
5364 return nodup(results);
5370 * Selects a single element.
5371 * @param {String} selector The selector/xpath query
5372 * @param {Node} root (optional) The start of the query (defaults to document).
5375 selectNode : function(path, root){
5376 return Roo.DomQuery.select(path, root)[0];
5380 * Selects the value of a node, optionally replacing null with the defaultValue.
5381 * @param {String} selector The selector/xpath query
5382 * @param {Node} root (optional) The start of the query (defaults to document).
5383 * @param {String} defaultValue
5385 selectValue : function(path, root, defaultValue){
5386 path = path.replace(trimRe, "");
5387 if(!valueCache[path]){
5388 valueCache[path] = Roo.DomQuery.compile(path, "select");
5390 var n = valueCache[path](root);
5391 n = n[0] ? n[0] : n;
5392 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5393 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5397 * Selects the value of a node, parsing integers and floats.
5398 * @param {String} selector The selector/xpath query
5399 * @param {Node} root (optional) The start of the query (defaults to document).
5400 * @param {Number} defaultValue
5403 selectNumber : function(path, root, defaultValue){
5404 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5405 return parseFloat(v);
5409 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5410 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5411 * @param {String} selector The simple selector to test
5414 is : function(el, ss){
5415 if(typeof el == "string"){
5416 el = document.getElementById(el);
5418 var isArray = (el instanceof Array);
5419 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5420 return isArray ? (result.length == el.length) : (result.length > 0);
5424 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5425 * @param {Array} el An array of elements to filter
5426 * @param {String} selector The simple selector to test
5427 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5428 * the selector instead of the ones that match
5431 filter : function(els, ss, nonMatches){
5432 ss = ss.replace(trimRe, "");
5433 if(!simpleCache[ss]){
5434 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5436 var result = simpleCache[ss](els);
5437 return nonMatches ? quickDiff(result, els) : result;
5441 * Collection of matching regular expressions and code snippets.
5445 select: 'n = byClassName(n, null, " {1} ");'
5447 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5448 select: 'n = byPseudo(n, "{1}", "{2}");'
5450 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5451 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5454 select: 'n = byId(n, null, "{1}");'
5457 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5462 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5463 * 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, > <.
5466 "=" : function(a, v){
5469 "!=" : function(a, v){
5472 "^=" : function(a, v){
5473 return a && a.substr(0, v.length) == v;
5475 "$=" : function(a, v){
5476 return a && a.substr(a.length-v.length) == v;
5478 "*=" : function(a, v){
5479 return a && a.indexOf(v) !== -1;
5481 "%=" : function(a, v){
5482 return (a % v) == 0;
5484 "|=" : function(a, v){
5485 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5487 "~=" : function(a, v){
5488 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5493 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5494 * and the argument (if any) supplied in the selector.
5497 "first-child" : function(c){
5498 var r = [], ri = -1, n;
5499 for(var i = 0, ci; ci = n = c[i]; i++){
5500 while((n = n.previousSibling) && n.nodeType != 1);
5508 "last-child" : function(c){
5509 var r = [], ri = -1, n;
5510 for(var i = 0, ci; ci = n = c[i]; i++){
5511 while((n = n.nextSibling) && n.nodeType != 1);
5519 "nth-child" : function(c, a) {
5520 var r = [], ri = -1;
5521 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5522 var f = (m[1] || 1) - 0, l = m[2] - 0;
5523 for(var i = 0, n; n = c[i]; i++){
5524 var pn = n.parentNode;
5525 if (batch != pn._batch) {
5527 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5528 if(cn.nodeType == 1){
5535 if (l == 0 || n.nodeIndex == l){
5538 } else if ((n.nodeIndex + l) % f == 0){
5546 "only-child" : function(c){
5547 var r = [], ri = -1;;
5548 for(var i = 0, ci; ci = c[i]; i++){
5549 if(!prev(ci) && !next(ci)){
5556 "empty" : function(c){
5557 var r = [], ri = -1;
5558 for(var i = 0, ci; ci = c[i]; i++){
5559 var cns = ci.childNodes, j = 0, cn, empty = true;
5562 if(cn.nodeType == 1 || cn.nodeType == 3){
5574 "contains" : function(c, v){
5575 var r = [], ri = -1;
5576 for(var i = 0, ci; ci = c[i]; i++){
5577 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5584 "nodeValue" : function(c, v){
5585 var r = [], ri = -1;
5586 for(var i = 0, ci; ci = c[i]; i++){
5587 if(ci.firstChild && ci.firstChild.nodeValue == v){
5594 "checked" : function(c){
5595 var r = [], ri = -1;
5596 for(var i = 0, ci; ci = c[i]; i++){
5597 if(ci.checked == true){
5604 "not" : function(c, ss){
5605 return Roo.DomQuery.filter(c, ss, true);
5608 "odd" : function(c){
5609 return this["nth-child"](c, "odd");
5612 "even" : function(c){
5613 return this["nth-child"](c, "even");
5616 "nth" : function(c, a){
5617 return c[a-1] || [];
5620 "first" : function(c){
5624 "last" : function(c){
5625 return c[c.length-1] || [];
5628 "has" : function(c, ss){
5629 var s = Roo.DomQuery.select;
5630 var r = [], ri = -1;
5631 for(var i = 0, ci; ci = c[i]; i++){
5632 if(s(ss, ci).length > 0){
5639 "next" : function(c, ss){
5640 var is = Roo.DomQuery.is;
5641 var r = [], ri = -1;
5642 for(var i = 0, ci; ci = c[i]; i++){
5651 "prev" : function(c, ss){
5652 var is = Roo.DomQuery.is;
5653 var r = [], ri = -1;
5654 for(var i = 0, ci; ci = c[i]; i++){
5667 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5668 * @param {String} path The selector/xpath query
5669 * @param {Node} root (optional) The start of the query (defaults to document).
5674 Roo.query = Roo.DomQuery.select;
5677 * Ext JS Library 1.1.1
5678 * Copyright(c) 2006-2007, Ext JS, LLC.
5680 * Originally Released Under LGPL - original licence link has changed is not relivant.
5683 * <script type="text/javascript">
5687 * @class Roo.util.Observable
5688 * Base class that provides a common interface for publishing events. Subclasses are expected to
5689 * to have a property "events" with all the events defined.<br>
5692 Employee = function(name){
5699 Roo.extend(Employee, Roo.util.Observable);
5701 * @param {Object} config properties to use (incuding events / listeners)
5704 Roo.util.Observable = function(cfg){
5707 this.addEvents(cfg.events || {});
5709 delete cfg.events; // make sure
5712 Roo.apply(this, cfg);
5715 this.on(this.listeners);
5716 delete this.listeners;
5719 Roo.util.Observable.prototype = {
5721 * @cfg {Object} listeners list of events and functions to call for this object,
5725 'click' : function(e) {
5735 * Fires the specified event with the passed parameters (minus the event name).
5736 * @param {String} eventName
5737 * @param {Object...} args Variable number of parameters are passed to handlers
5738 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5740 fireEvent : function(){
5741 var ce = this.events[arguments[0].toLowerCase()];
5742 if(typeof ce == "object"){
5743 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5750 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5753 * Appends an event handler to this component
5754 * @param {String} eventName The type of event to listen for
5755 * @param {Function} handler The method the event invokes
5756 * @param {Object} scope (optional) The scope in which to execute the handler
5757 * function. The handler function's "this" context.
5758 * @param {Object} options (optional) An object containing handler configuration
5759 * properties. This may contain any of the following properties:<ul>
5760 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5761 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5762 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5763 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5764 * by the specified number of milliseconds. If the event fires again within that time, the original
5765 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5768 * <b>Combining Options</b><br>
5769 * Using the options argument, it is possible to combine different types of listeners:<br>
5771 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5773 el.on('click', this.onClick, this, {
5780 * <b>Attaching multiple handlers in 1 call</b><br>
5781 * The method also allows for a single argument to be passed which is a config object containing properties
5782 * which specify multiple handlers.
5791 fn: this.onMouseOver,
5795 fn: this.onMouseOut,
5801 * Or a shorthand syntax which passes the same scope object to all handlers:
5804 'click': this.onClick,
5805 'mouseover': this.onMouseOver,
5806 'mouseout': this.onMouseOut,
5811 addListener : function(eventName, fn, scope, o){
5812 if(typeof eventName == "object"){
5815 if(this.filterOptRe.test(e)){
5818 if(typeof o[e] == "function"){
5820 this.addListener(e, o[e], o.scope, o);
5822 // individual options
5823 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5828 o = (!o || typeof o == "boolean") ? {} : o;
5829 eventName = eventName.toLowerCase();
5830 var ce = this.events[eventName] || true;
5831 if(typeof ce == "boolean"){
5832 ce = new Roo.util.Event(this, eventName);
5833 this.events[eventName] = ce;
5835 ce.addListener(fn, scope, o);
5839 * Removes a listener
5840 * @param {String} eventName The type of event to listen for
5841 * @param {Function} handler The handler to remove
5842 * @param {Object} scope (optional) The scope (this object) for the handler
5844 removeListener : function(eventName, fn, scope){
5845 var ce = this.events[eventName.toLowerCase()];
5846 if(typeof ce == "object"){
5847 ce.removeListener(fn, scope);
5852 * Removes all listeners for this object
5854 purgeListeners : function(){
5855 for(var evt in this.events){
5856 if(typeof this.events[evt] == "object"){
5857 this.events[evt].clearListeners();
5862 relayEvents : function(o, events){
5863 var createHandler = function(ename){
5865 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5868 for(var i = 0, len = events.length; i < len; i++){
5869 var ename = events[i];
5870 if(!this.events[ename]){ this.events[ename] = true; };
5871 o.on(ename, createHandler(ename), this);
5876 * Used to define events on this Observable
5877 * @param {Object} object The object with the events defined
5879 addEvents : function(o){
5883 Roo.applyIf(this.events, o);
5887 * Checks to see if this object has any listeners for a specified event
5888 * @param {String} eventName The name of the event to check for
5889 * @return {Boolean} True if the event is being listened for, else false
5891 hasListener : function(eventName){
5892 var e = this.events[eventName];
5893 return typeof e == "object" && e.listeners.length > 0;
5897 * Appends an event handler to this element (shorthand for addListener)
5898 * @param {String} eventName The type of event to listen for
5899 * @param {Function} handler The method the event invokes
5900 * @param {Object} scope (optional) The scope in which to execute the handler
5901 * function. The handler function's "this" context.
5902 * @param {Object} options (optional)
5905 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5907 * Removes a listener (shorthand for removeListener)
5908 * @param {String} eventName The type of event to listen for
5909 * @param {Function} handler The handler to remove
5910 * @param {Object} scope (optional) The scope (this object) for the handler
5913 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5916 * Starts capture on the specified Observable. All events will be passed
5917 * to the supplied function with the event name + standard signature of the event
5918 * <b>before</b> the event is fired. If the supplied function returns false,
5919 * the event will not fire.
5920 * @param {Observable} o The Observable to capture
5921 * @param {Function} fn The function to call
5922 * @param {Object} scope (optional) The scope (this object) for the fn
5925 Roo.util.Observable.capture = function(o, fn, scope){
5926 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5930 * Removes <b>all</b> added captures from the Observable.
5931 * @param {Observable} o The Observable to release
5934 Roo.util.Observable.releaseCapture = function(o){
5935 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5940 var createBuffered = function(h, o, scope){
5941 var task = new Roo.util.DelayedTask();
5943 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5947 var createSingle = function(h, e, fn, scope){
5949 e.removeListener(fn, scope);
5950 return h.apply(scope, arguments);
5954 var createDelayed = function(h, o, scope){
5956 var args = Array.prototype.slice.call(arguments, 0);
5957 setTimeout(function(){
5958 h.apply(scope, args);
5963 Roo.util.Event = function(obj, name){
5966 this.listeners = [];
5969 Roo.util.Event.prototype = {
5970 addListener : function(fn, scope, options){
5971 var o = options || {};
5972 scope = scope || this.obj;
5973 if(!this.isListening(fn, scope)){
5974 var l = {fn: fn, scope: scope, options: o};
5977 h = createDelayed(h, o, scope);
5980 h = createSingle(h, this, fn, scope);
5983 h = createBuffered(h, o, scope);
5986 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5987 this.listeners.push(l);
5989 this.listeners = this.listeners.slice(0);
5990 this.listeners.push(l);
5995 findListener : function(fn, scope){
5996 scope = scope || this.obj;
5997 var ls = this.listeners;
5998 for(var i = 0, len = ls.length; i < len; i++){
6000 if(l.fn == fn && l.scope == scope){
6007 isListening : function(fn, scope){
6008 return this.findListener(fn, scope) != -1;
6011 removeListener : function(fn, scope){
6013 if((index = this.findListener(fn, scope)) != -1){
6015 this.listeners.splice(index, 1);
6017 this.listeners = this.listeners.slice(0);
6018 this.listeners.splice(index, 1);
6025 clearListeners : function(){
6026 this.listeners = [];
6030 var ls = this.listeners, scope, len = ls.length;
6033 var args = Array.prototype.slice.call(arguments, 0);
6034 for(var i = 0; i < len; i++){
6036 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
6037 this.firing = false;
6041 this.firing = false;
6048 * Ext JS Library 1.1.1
6049 * Copyright(c) 2006-2007, Ext JS, LLC.
6051 * Originally Released Under LGPL - original licence link has changed is not relivant.
6054 * <script type="text/javascript">
6058 * @class Roo.EventManager
6059 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6060 * several useful events directly.
6061 * See {@link Roo.EventObject} for more details on normalized event objects.
6064 Roo.EventManager = function(){
6065 var docReadyEvent, docReadyProcId, docReadyState = false;
6066 var resizeEvent, resizeTask, textEvent, textSize;
6067 var E = Roo.lib.Event;
6068 var D = Roo.lib.Dom;
6073 var fireDocReady = function(){
6075 docReadyState = true;
6078 clearInterval(docReadyProcId);
6080 if(Roo.isGecko || Roo.isOpera) {
6081 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6084 var defer = document.getElementById("ie-deferred-loader");
6086 defer.onreadystatechange = null;
6087 defer.parentNode.removeChild(defer);
6091 docReadyEvent.fire();
6092 docReadyEvent.clearListeners();
6097 var initDocReady = function(){
6098 docReadyEvent = new Roo.util.Event();
6099 if(Roo.isGecko || Roo.isOpera) {
6100 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6102 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6103 var defer = document.getElementById("ie-deferred-loader");
6104 defer.onreadystatechange = function(){
6105 if(this.readyState == "complete"){
6109 }else if(Roo.isSafari){
6110 docReadyProcId = setInterval(function(){
6111 var rs = document.readyState;
6112 if(rs == "complete") {
6117 // no matter what, make sure it fires on load
6118 E.on(window, "load", fireDocReady);
6121 var createBuffered = function(h, o){
6122 var task = new Roo.util.DelayedTask(h);
6124 // create new event object impl so new events don't wipe out properties
6125 e = new Roo.EventObjectImpl(e);
6126 task.delay(o.buffer, h, null, [e]);
6130 var createSingle = function(h, el, ename, fn){
6132 Roo.EventManager.removeListener(el, ename, fn);
6137 var createDelayed = function(h, o){
6139 // create new event object impl so new events don't wipe out properties
6140 e = new Roo.EventObjectImpl(e);
6141 setTimeout(function(){
6146 var transitionEndVal = false;
6148 var transitionEnd = function()
6150 if (transitionEndVal) {
6151 return transitionEndVal;
6153 var el = document.createElement('div');
6155 var transEndEventNames = {
6156 WebkitTransition : 'webkitTransitionEnd',
6157 MozTransition : 'transitionend',
6158 OTransition : 'oTransitionEnd otransitionend',
6159 transition : 'transitionend'
6162 for (var name in transEndEventNames) {
6163 if (el.style[name] !== undefined) {
6164 transitionEndVal = transEndEventNames[name];
6165 return transitionEndVal ;
6171 var listen = function(element, ename, opt, fn, scope){
6172 var o = (!opt || typeof opt == "boolean") ? {} : opt;
6173 fn = fn || o.fn; scope = scope || o.scope;
6174 var el = Roo.getDom(element);
6178 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6181 if (ename == 'transitionend') {
6182 ename = transitionEnd();
6184 var h = function(e){
6185 e = Roo.EventObject.setEvent(e);
6188 t = e.getTarget(o.delegate, el);
6195 if(o.stopEvent === true){
6198 if(o.preventDefault === true){
6201 if(o.stopPropagation === true){
6202 e.stopPropagation();
6205 if(o.normalized === false){
6209 fn.call(scope || el, e, t, o);
6212 h = createDelayed(h, o);
6215 h = createSingle(h, el, ename, fn);
6218 h = createBuffered(h, o);
6220 fn._handlers = fn._handlers || [];
6223 fn._handlers.push([Roo.id(el), ename, h]);
6228 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6229 el.addEventListener("DOMMouseScroll", h, false);
6230 E.on(window, 'unload', function(){
6231 el.removeEventListener("DOMMouseScroll", h, false);
6234 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6235 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6240 var stopListening = function(el, ename, fn){
6241 var id = Roo.id(el), hds = fn._handlers, hd = fn;
6243 for(var i = 0, len = hds.length; i < len; i++){
6245 if(h[0] == id && h[1] == ename){
6252 E.un(el, ename, hd);
6253 el = Roo.getDom(el);
6254 if(ename == "mousewheel" && el.addEventListener){
6255 el.removeEventListener("DOMMouseScroll", hd, false);
6257 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6258 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6262 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6269 * @scope Roo.EventManager
6274 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6275 * object with a Roo.EventObject
6276 * @param {Function} fn The method the event invokes
6277 * @param {Object} scope An object that becomes the scope of the handler
6278 * @param {boolean} override If true, the obj passed in becomes
6279 * the execution scope of the listener
6280 * @return {Function} The wrapped function
6283 wrap : function(fn, scope, override){
6285 Roo.EventObject.setEvent(e);
6286 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6291 * Appends an event handler to an element (shorthand for addListener)
6292 * @param {String/HTMLElement} element The html element or id to assign the
6293 * @param {String} eventName The type of event to listen for
6294 * @param {Function} handler The method the event invokes
6295 * @param {Object} scope (optional) The scope in which to execute the handler
6296 * function. The handler function's "this" context.
6297 * @param {Object} options (optional) An object containing handler configuration
6298 * properties. This may contain any of the following properties:<ul>
6299 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6300 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6301 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6302 * <li>preventDefault {Boolean} True to prevent the default action</li>
6303 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6304 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6305 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6306 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6307 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6308 * by the specified number of milliseconds. If the event fires again within that time, the original
6309 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6312 * <b>Combining Options</b><br>
6313 * Using the options argument, it is possible to combine different types of listeners:<br>
6315 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6317 el.on('click', this.onClick, this, {
6324 * <b>Attaching multiple handlers in 1 call</b><br>
6325 * The method also allows for a single argument to be passed which is a config object containing properties
6326 * which specify multiple handlers.
6336 fn: this.onMouseOver
6345 * Or a shorthand syntax:<br>
6348 'click' : this.onClick,
6349 'mouseover' : this.onMouseOver,
6350 'mouseout' : this.onMouseOut
6354 addListener : function(element, eventName, fn, scope, options){
6355 if(typeof eventName == "object"){
6361 if(typeof o[e] == "function"){
6363 listen(element, e, o, o[e], o.scope);
6365 // individual options
6366 listen(element, e, o[e]);
6371 return listen(element, eventName, options, fn, scope);
6375 * Removes an event handler
6377 * @param {String/HTMLElement} element The id or html element to remove the
6379 * @param {String} eventName The type of event
6380 * @param {Function} fn
6381 * @return {Boolean} True if a listener was actually removed
6383 removeListener : function(element, eventName, fn){
6384 return stopListening(element, eventName, fn);
6388 * Fires when the document is ready (before onload and before images are loaded). Can be
6389 * accessed shorthanded Roo.onReady().
6390 * @param {Function} fn The method the event invokes
6391 * @param {Object} scope An object that becomes the scope of the handler
6392 * @param {boolean} options
6394 onDocumentReady : function(fn, scope, options){
6395 if(docReadyState){ // if it already fired
6396 docReadyEvent.addListener(fn, scope, options);
6397 docReadyEvent.fire();
6398 docReadyEvent.clearListeners();
6404 docReadyEvent.addListener(fn, scope, options);
6408 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6409 * @param {Function} fn The method the event invokes
6410 * @param {Object} scope An object that becomes the scope of the handler
6411 * @param {boolean} options
6413 onWindowResize : function(fn, scope, options){
6415 resizeEvent = new Roo.util.Event();
6416 resizeTask = new Roo.util.DelayedTask(function(){
6417 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6419 E.on(window, "resize", function(){
6421 resizeTask.delay(50);
6423 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6427 resizeEvent.addListener(fn, scope, options);
6431 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6432 * @param {Function} fn The method the event invokes
6433 * @param {Object} scope An object that becomes the scope of the handler
6434 * @param {boolean} options
6436 onTextResize : function(fn, scope, options){
6438 textEvent = new Roo.util.Event();
6439 var textEl = new Roo.Element(document.createElement('div'));
6440 textEl.dom.className = 'x-text-resize';
6441 textEl.dom.innerHTML = 'X';
6442 textEl.appendTo(document.body);
6443 textSize = textEl.dom.offsetHeight;
6444 setInterval(function(){
6445 if(textEl.dom.offsetHeight != textSize){
6446 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6448 }, this.textResizeInterval);
6450 textEvent.addListener(fn, scope, options);
6454 * Removes the passed window resize listener.
6455 * @param {Function} fn The method the event invokes
6456 * @param {Object} scope The scope of handler
6458 removeResizeListener : function(fn, scope){
6460 resizeEvent.removeListener(fn, scope);
6465 fireResize : function(){
6467 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6471 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6475 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6477 textResizeInterval : 50
6482 * @scopeAlias pub=Roo.EventManager
6486 * Appends an event handler to an element (shorthand for addListener)
6487 * @param {String/HTMLElement} element The html element or id to assign the
6488 * @param {String} eventName The type of event to listen for
6489 * @param {Function} handler The method the event invokes
6490 * @param {Object} scope (optional) The scope in which to execute the handler
6491 * function. The handler function's "this" context.
6492 * @param {Object} options (optional) An object containing handler configuration
6493 * properties. This may contain any of the following properties:<ul>
6494 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6495 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6496 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6497 * <li>preventDefault {Boolean} True to prevent the default action</li>
6498 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6499 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6500 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6501 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6502 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6503 * by the specified number of milliseconds. If the event fires again within that time, the original
6504 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6507 * <b>Combining Options</b><br>
6508 * Using the options argument, it is possible to combine different types of listeners:<br>
6510 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6512 el.on('click', this.onClick, this, {
6519 * <b>Attaching multiple handlers in 1 call</b><br>
6520 * The method also allows for a single argument to be passed which is a config object containing properties
6521 * which specify multiple handlers.
6531 fn: this.onMouseOver
6540 * Or a shorthand syntax:<br>
6543 'click' : this.onClick,
6544 'mouseover' : this.onMouseOver,
6545 'mouseout' : this.onMouseOut
6549 pub.on = pub.addListener;
6550 pub.un = pub.removeListener;
6552 pub.stoppedMouseDownEvent = new Roo.util.Event();
6556 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6557 * @param {Function} fn The method the event invokes
6558 * @param {Object} scope An object that becomes the scope of the handler
6559 * @param {boolean} override If true, the obj passed in becomes
6560 * the execution scope of the listener
6564 Roo.onReady = Roo.EventManager.onDocumentReady;
6566 Roo.onReady(function(){
6567 var bd = Roo.get(document.body);
6572 : Roo.isGecko ? "roo-gecko"
6573 : Roo.isOpera ? "roo-opera"
6574 : Roo.isSafari ? "roo-safari" : ""];
6577 cls.push("roo-mac");
6580 cls.push("roo-linux");
6583 cls.push("roo-ios");
6585 if(Roo.isBorderBox){
6586 cls.push('roo-border-box');
6588 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6589 var p = bd.dom.parentNode;
6591 p.className += ' roo-strict';
6594 bd.addClass(cls.join(' '));
6598 * @class Roo.EventObject
6599 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6600 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6603 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6605 var target = e.getTarget();
6608 var myDiv = Roo.get("myDiv");
6609 myDiv.on("click", handleClick);
6611 Roo.EventManager.on("myDiv", 'click', handleClick);
6612 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6616 Roo.EventObject = function(){
6618 var E = Roo.lib.Event;
6620 // safari keypress events for special keys return bad keycodes
6623 63235 : 39, // right
6626 63276 : 33, // page up
6627 63277 : 34, // page down
6628 63272 : 46, // delete
6633 // normalize button clicks
6634 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6635 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6637 Roo.EventObjectImpl = function(e){
6639 this.setEvent(e.browserEvent || e);
6642 Roo.EventObjectImpl.prototype = {
6644 * Used to fix doc tools.
6645 * @scope Roo.EventObject.prototype
6651 /** The normal browser event */
6652 browserEvent : null,
6653 /** The button pressed in a mouse event */
6655 /** True if the shift key was down during the event */
6657 /** True if the control key was down during the event */
6659 /** True if the alt key was down during the event */
6718 setEvent : function(e){
6719 if(e == this || (e && e.browserEvent)){ // already wrapped
6722 this.browserEvent = e;
6724 // normalize buttons
6725 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6726 if(e.type == 'click' && this.button == -1){
6730 this.shiftKey = e.shiftKey;
6731 // mac metaKey behaves like ctrlKey
6732 this.ctrlKey = e.ctrlKey || e.metaKey;
6733 this.altKey = e.altKey;
6734 // in getKey these will be normalized for the mac
6735 this.keyCode = e.keyCode;
6736 // keyup warnings on firefox.
6737 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6738 // cache the target for the delayed and or buffered events
6739 this.target = E.getTarget(e);
6741 this.xy = E.getXY(e);
6744 this.shiftKey = false;
6745 this.ctrlKey = false;
6746 this.altKey = false;
6756 * Stop the event (preventDefault and stopPropagation)
6758 stopEvent : function(){
6759 if(this.browserEvent){
6760 if(this.browserEvent.type == 'mousedown'){
6761 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6763 E.stopEvent(this.browserEvent);
6768 * Prevents the browsers default handling of the event.
6770 preventDefault : function(){
6771 if(this.browserEvent){
6772 E.preventDefault(this.browserEvent);
6777 isNavKeyPress : function(){
6778 var k = this.keyCode;
6779 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6780 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6783 isSpecialKey : function(){
6784 var k = this.keyCode;
6785 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6786 (k == 16) || (k == 17) ||
6787 (k >= 18 && k <= 20) ||
6788 (k >= 33 && k <= 35) ||
6789 (k >= 36 && k <= 39) ||
6790 (k >= 44 && k <= 45);
6793 * Cancels bubbling of the event.
6795 stopPropagation : function(){
6796 if(this.browserEvent){
6797 if(this.type == 'mousedown'){
6798 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6800 E.stopPropagation(this.browserEvent);
6805 * Gets the key code for the event.
6808 getCharCode : function(){
6809 return this.charCode || this.keyCode;
6813 * Returns a normalized keyCode for the event.
6814 * @return {Number} The key code
6816 getKey : function(){
6817 var k = this.keyCode || this.charCode;
6818 return Roo.isSafari ? (safariKeys[k] || k) : k;
6822 * Gets the x coordinate of the event.
6825 getPageX : function(){
6830 * Gets the y coordinate of the event.
6833 getPageY : function(){
6838 * Gets the time of the event.
6841 getTime : function(){
6842 if(this.browserEvent){
6843 return E.getTime(this.browserEvent);
6849 * Gets the page coordinates of the event.
6850 * @return {Array} The xy values like [x, y]
6857 * Gets the target for the event.
6858 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6859 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6860 search as a number or element (defaults to 10 || document.body)
6861 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6862 * @return {HTMLelement}
6864 getTarget : function(selector, maxDepth, returnEl){
6865 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6868 * Gets the related target.
6869 * @return {HTMLElement}
6871 getRelatedTarget : function(){
6872 if(this.browserEvent){
6873 return E.getRelatedTarget(this.browserEvent);
6879 * Normalizes mouse wheel delta across browsers
6880 * @return {Number} The delta
6882 getWheelDelta : function(){
6883 var e = this.browserEvent;
6885 if(e.wheelDelta){ /* IE/Opera. */
6886 delta = e.wheelDelta/120;
6887 }else if(e.detail){ /* Mozilla case. */
6888 delta = -e.detail/3;
6894 * Returns true if the control, meta, shift or alt key was pressed during this event.
6897 hasModifier : function(){
6898 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6902 * Returns true if the target of this event equals el or is a child of el
6903 * @param {String/HTMLElement/Element} el
6904 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6907 within : function(el, related){
6908 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6909 return t && Roo.fly(el).contains(t);
6912 getPoint : function(){
6913 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6917 return new Roo.EventObjectImpl();
6922 * Ext JS Library 1.1.1
6923 * Copyright(c) 2006-2007, Ext JS, LLC.
6925 * Originally Released Under LGPL - original licence link has changed is not relivant.
6928 * <script type="text/javascript">
6932 // was in Composite Element!??!?!
6935 var D = Roo.lib.Dom;
6936 var E = Roo.lib.Event;
6937 var A = Roo.lib.Anim;
6939 // local style camelizing for speed
6941 var camelRe = /(-[a-z])/gi;
6942 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6943 var view = document.defaultView;
6946 * @class Roo.Element
6947 * Represents an Element in the DOM.<br><br>
6950 var el = Roo.get("my-div");
6953 var el = getEl("my-div");
6955 // or with a DOM element
6956 var el = Roo.get(myDivElement);
6958 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6959 * each call instead of constructing a new one.<br><br>
6960 * <b>Animations</b><br />
6961 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6962 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6964 Option Default Description
6965 --------- -------- ---------------------------------------------
6966 duration .35 The duration of the animation in seconds
6967 easing easeOut The YUI easing method
6968 callback none A function to execute when the anim completes
6969 scope this The scope (this) of the callback function
6971 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6972 * manipulate the animation. Here's an example:
6974 var el = Roo.get("my-div");
6979 // default animation
6980 el.setWidth(100, true);
6982 // animation with some options set
6989 // using the "anim" property to get the Anim object
6995 el.setWidth(100, opt);
6997 if(opt.anim.isAnimated()){
7001 * <b> Composite (Collections of) Elements</b><br />
7002 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7003 * @constructor Create a new Element directly.
7004 * @param {String/HTMLElement} element
7005 * @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).
7007 Roo.Element = function(element, forceNew){
7008 var dom = typeof element == "string" ?
7009 document.getElementById(element) : element;
7010 if(!dom){ // invalid id/element
7014 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7015 return Roo.Element.cache[id];
7025 * The DOM element ID
7028 this.id = id || Roo.id(dom);
7031 var El = Roo.Element;
7035 * The element's default display mode (defaults to "")
7038 originalDisplay : "",
7042 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7047 * Sets the element's visibility mode. When setVisible() is called it
7048 * will use this to determine whether to set the visibility or the display property.
7049 * @param visMode Element.VISIBILITY or Element.DISPLAY
7050 * @return {Roo.Element} this
7052 setVisibilityMode : function(visMode){
7053 this.visibilityMode = visMode;
7057 * Convenience method for setVisibilityMode(Element.DISPLAY)
7058 * @param {String} display (optional) What to set display to when visible
7059 * @return {Roo.Element} this
7061 enableDisplayMode : function(display){
7062 this.setVisibilityMode(El.DISPLAY);
7063 if(typeof display != "undefined") this.originalDisplay = display;
7068 * 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)
7069 * @param {String} selector The simple selector to test
7070 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7071 search as a number or element (defaults to 10 || document.body)
7072 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7073 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7075 findParent : function(simpleSelector, maxDepth, returnEl){
7076 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7077 maxDepth = maxDepth || 50;
7078 if(typeof maxDepth != "number"){
7079 stopEl = Roo.getDom(maxDepth);
7082 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7083 if(dq.is(p, simpleSelector)){
7084 return returnEl ? Roo.get(p) : p;
7094 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7095 * @param {String} selector The simple selector to test
7096 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7097 search as a number or element (defaults to 10 || document.body)
7098 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7099 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7101 findParentNode : function(simpleSelector, maxDepth, returnEl){
7102 var p = Roo.fly(this.dom.parentNode, '_internal');
7103 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7107 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
7108 * This is a shortcut for findParentNode() that always returns an Roo.Element.
7109 * @param {String} selector The simple selector to test
7110 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7111 search as a number or element (defaults to 10 || document.body)
7112 * @return {Roo.Element} The matching DOM node (or null if no match was found)
7114 up : function(simpleSelector, maxDepth){
7115 return this.findParentNode(simpleSelector, maxDepth, true);
7121 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
7122 * @param {String} selector The simple selector to test
7123 * @return {Boolean} True if this element matches the selector, else false
7125 is : function(simpleSelector){
7126 return Roo.DomQuery.is(this.dom, simpleSelector);
7130 * Perform animation on this element.
7131 * @param {Object} args The YUI animation control args
7132 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
7133 * @param {Function} onComplete (optional) Function to call when animation completes
7134 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
7135 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
7136 * @return {Roo.Element} this
7138 animate : function(args, duration, onComplete, easing, animType){
7139 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7144 * @private Internal animation call
7146 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7147 animType = animType || 'run';
7149 var anim = Roo.lib.Anim[animType](
7151 (opt.duration || defaultDur) || .35,
7152 (opt.easing || defaultEase) || 'easeOut',
7154 Roo.callback(cb, this);
7155 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7163 // private legacy anim prep
7164 preanim : function(a, i){
7165 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7169 * Removes worthless text nodes
7170 * @param {Boolean} forceReclean (optional) By default the element
7171 * keeps track if it has been cleaned already so
7172 * you can call this over and over. However, if you update the element and
7173 * need to force a reclean, you can pass true.
7175 clean : function(forceReclean){
7176 if(this.isCleaned && forceReclean !== true){
7180 var d = this.dom, n = d.firstChild, ni = -1;
7182 var nx = n.nextSibling;
7183 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7190 this.isCleaned = true;
7195 calcOffsetsTo : function(el){
7198 var restorePos = false;
7199 if(el.getStyle('position') == 'static'){
7200 el.position('relative');
7205 while(op && op != d && op.tagName != 'HTML'){
7208 op = op.offsetParent;
7211 el.position('static');
7217 * Scrolls this element into view within the passed container.
7218 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7219 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7220 * @return {Roo.Element} this
7222 scrollIntoView : function(container, hscroll){
7223 var c = Roo.getDom(container) || document.body;
7226 var o = this.calcOffsetsTo(c),
7229 b = t+el.offsetHeight,
7230 r = l+el.offsetWidth;
7232 var ch = c.clientHeight;
7233 var ct = parseInt(c.scrollTop, 10);
7234 var cl = parseInt(c.scrollLeft, 10);
7236 var cr = cl + c.clientWidth;
7244 if(hscroll !== false){
7248 c.scrollLeft = r-c.clientWidth;
7255 scrollChildIntoView : function(child, hscroll){
7256 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7260 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7261 * the new height may not be available immediately.
7262 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7263 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7264 * @param {Function} onComplete (optional) Function to call when animation completes
7265 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7266 * @return {Roo.Element} this
7268 autoHeight : function(animate, duration, onComplete, easing){
7269 var oldHeight = this.getHeight();
7271 this.setHeight(1); // force clipping
7272 setTimeout(function(){
7273 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7275 this.setHeight(height);
7277 if(typeof onComplete == "function"){
7281 this.setHeight(oldHeight); // restore original height
7282 this.setHeight(height, animate, duration, function(){
7284 if(typeof onComplete == "function") onComplete();
7285 }.createDelegate(this), easing);
7287 }.createDelegate(this), 0);
7292 * Returns true if this element is an ancestor of the passed element
7293 * @param {HTMLElement/String} el The element to check
7294 * @return {Boolean} True if this element is an ancestor of el, else false
7296 contains : function(el){
7297 if(!el){return false;}
7298 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7302 * Checks whether the element is currently visible using both visibility and display properties.
7303 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7304 * @return {Boolean} True if the element is currently visible, else false
7306 isVisible : function(deep) {
7307 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7308 if(deep !== true || !vis){
7311 var p = this.dom.parentNode;
7312 while(p && p.tagName.toLowerCase() != "body"){
7313 if(!Roo.fly(p, '_isVisible').isVisible()){
7322 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7323 * @param {String} selector The CSS selector
7324 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7325 * @return {CompositeElement/CompositeElementLite} The composite element
7327 select : function(selector, unique){
7328 return El.select(selector, unique, this.dom);
7332 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7333 * @param {String} selector The CSS selector
7334 * @return {Array} An array of the matched nodes
7336 query : function(selector, unique){
7337 return Roo.DomQuery.select(selector, this.dom);
7341 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7342 * @param {String} selector The CSS selector
7343 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7344 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7346 child : function(selector, returnDom){
7347 var n = Roo.DomQuery.selectNode(selector, this.dom);
7348 return returnDom ? n : Roo.get(n);
7352 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7353 * @param {String} selector The CSS selector
7354 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7355 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7357 down : function(selector, returnDom){
7358 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7359 return returnDom ? n : Roo.get(n);
7363 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7364 * @param {String} group The group the DD object is member of
7365 * @param {Object} config The DD config object
7366 * @param {Object} overrides An object containing methods to override/implement on the DD object
7367 * @return {Roo.dd.DD} The DD object
7369 initDD : function(group, config, overrides){
7370 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7371 return Roo.apply(dd, overrides);
7375 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7376 * @param {String} group The group the DDProxy object is member of
7377 * @param {Object} config The DDProxy config object
7378 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7379 * @return {Roo.dd.DDProxy} The DDProxy object
7381 initDDProxy : function(group, config, overrides){
7382 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7383 return Roo.apply(dd, overrides);
7387 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7388 * @param {String} group The group the DDTarget object is member of
7389 * @param {Object} config The DDTarget config object
7390 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7391 * @return {Roo.dd.DDTarget} The DDTarget object
7393 initDDTarget : function(group, config, overrides){
7394 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7395 return Roo.apply(dd, overrides);
7399 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7400 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7401 * @param {Boolean} visible Whether the element is visible
7402 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7403 * @return {Roo.Element} this
7405 setVisible : function(visible, animate){
7407 if(this.visibilityMode == El.DISPLAY){
7408 this.setDisplayed(visible);
7411 this.dom.style.visibility = visible ? "visible" : "hidden";
7414 // closure for composites
7416 var visMode = this.visibilityMode;
7418 this.setOpacity(.01);
7419 this.setVisible(true);
7421 this.anim({opacity: { to: (visible?1:0) }},
7422 this.preanim(arguments, 1),
7423 null, .35, 'easeIn', function(){
7425 if(visMode == El.DISPLAY){
7426 dom.style.display = "none";
7428 dom.style.visibility = "hidden";
7430 Roo.get(dom).setOpacity(1);
7438 * Returns true if display is not "none"
7441 isDisplayed : function() {
7442 return this.getStyle("display") != "none";
7446 * Toggles the element's visibility or display, depending on visibility mode.
7447 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7448 * @return {Roo.Element} this
7450 toggle : function(animate){
7451 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7456 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7457 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7458 * @return {Roo.Element} this
7460 setDisplayed : function(value) {
7461 if(typeof value == "boolean"){
7462 value = value ? this.originalDisplay : "none";
7464 this.setStyle("display", value);
7469 * Tries to focus the element. Any exceptions are caught and ignored.
7470 * @return {Roo.Element} this
7472 focus : function() {
7480 * Tries to blur the element. Any exceptions are caught and ignored.
7481 * @return {Roo.Element} this
7491 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7492 * @param {String/Array} className The CSS class to add, or an array of classes
7493 * @return {Roo.Element} this
7495 addClass : function(className){
7496 if(className instanceof Array){
7497 for(var i = 0, len = className.length; i < len; i++) {
7498 this.addClass(className[i]);
7501 if(className && !this.hasClass(className)){
7502 this.dom.className = this.dom.className + " " + className;
7509 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7510 * @param {String/Array} className The CSS class to add, or an array of classes
7511 * @return {Roo.Element} this
7513 radioClass : function(className){
7514 var siblings = this.dom.parentNode.childNodes;
7515 for(var i = 0; i < siblings.length; i++) {
7516 var s = siblings[i];
7517 if(s.nodeType == 1){
7518 Roo.get(s).removeClass(className);
7521 this.addClass(className);
7526 * Removes one or more CSS classes from the element.
7527 * @param {String/Array} className The CSS class to remove, or an array of classes
7528 * @return {Roo.Element} this
7530 removeClass : function(className){
7531 if(!className || !this.dom.className){
7534 if(className instanceof Array){
7535 for(var i = 0, len = className.length; i < len; i++) {
7536 this.removeClass(className[i]);
7539 if(this.hasClass(className)){
7540 var re = this.classReCache[className];
7542 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7543 this.classReCache[className] = re;
7545 this.dom.className =
7546 this.dom.className.replace(re, " ");
7556 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7557 * @param {String} className The CSS class to toggle
7558 * @return {Roo.Element} this
7560 toggleClass : function(className){
7561 if(this.hasClass(className)){
7562 this.removeClass(className);
7564 this.addClass(className);
7570 * Checks if the specified CSS class exists on this element's DOM node.
7571 * @param {String} className The CSS class to check for
7572 * @return {Boolean} True if the class exists, else false
7574 hasClass : function(className){
7575 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7579 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7580 * @param {String} oldClassName The CSS class to replace
7581 * @param {String} newClassName The replacement CSS class
7582 * @return {Roo.Element} this
7584 replaceClass : function(oldClassName, newClassName){
7585 this.removeClass(oldClassName);
7586 this.addClass(newClassName);
7591 * Returns an object with properties matching the styles requested.
7592 * For example, el.getStyles('color', 'font-size', 'width') might return
7593 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7594 * @param {String} style1 A style name
7595 * @param {String} style2 A style name
7596 * @param {String} etc.
7597 * @return {Object} The style object
7599 getStyles : function(){
7600 var a = arguments, len = a.length, r = {};
7601 for(var i = 0; i < len; i++){
7602 r[a[i]] = this.getStyle(a[i]);
7608 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7609 * @param {String} property The style property whose value is returned.
7610 * @return {String} The current value of the style property for this element.
7612 getStyle : function(){
7613 return view && view.getComputedStyle ?
7615 var el = this.dom, v, cs, camel;
7616 if(prop == 'float'){
7619 if(el.style && (v = el.style[prop])){
7622 if(cs = view.getComputedStyle(el, "")){
7623 if(!(camel = propCache[prop])){
7624 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7631 var el = this.dom, v, cs, camel;
7632 if(prop == 'opacity'){
7633 if(typeof el.style.filter == 'string'){
7634 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7636 var fv = parseFloat(m[1]);
7638 return fv ? fv / 100 : 0;
7643 }else if(prop == 'float'){
7644 prop = "styleFloat";
7646 if(!(camel = propCache[prop])){
7647 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7649 if(v = el.style[camel]){
7652 if(cs = el.currentStyle){
7660 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7661 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7662 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7663 * @return {Roo.Element} this
7665 setStyle : function(prop, value){
7666 if(typeof prop == "string"){
7668 if (prop == 'float') {
7669 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7674 if(!(camel = propCache[prop])){
7675 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7678 if(camel == 'opacity') {
7679 this.setOpacity(value);
7681 this.dom.style[camel] = value;
7684 for(var style in prop){
7685 if(typeof prop[style] != "function"){
7686 this.setStyle(style, prop[style]);
7694 * More flexible version of {@link #setStyle} for setting style properties.
7695 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7696 * a function which returns such a specification.
7697 * @return {Roo.Element} this
7699 applyStyles : function(style){
7700 Roo.DomHelper.applyStyles(this.dom, style);
7705 * 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).
7706 * @return {Number} The X position of the element
7709 return D.getX(this.dom);
7713 * 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).
7714 * @return {Number} The Y position of the element
7717 return D.getY(this.dom);
7721 * 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).
7722 * @return {Array} The XY position of the element
7725 return D.getXY(this.dom);
7729 * 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).
7730 * @param {Number} The X position of the element
7731 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7732 * @return {Roo.Element} this
7734 setX : function(x, animate){
7736 D.setX(this.dom, x);
7738 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7744 * 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).
7745 * @param {Number} The Y position of the element
7746 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7747 * @return {Roo.Element} this
7749 setY : function(y, animate){
7751 D.setY(this.dom, y);
7753 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7759 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7760 * @param {String} left The left CSS property value
7761 * @return {Roo.Element} this
7763 setLeft : function(left){
7764 this.setStyle("left", this.addUnits(left));
7769 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7770 * @param {String} top The top CSS property value
7771 * @return {Roo.Element} this
7773 setTop : function(top){
7774 this.setStyle("top", this.addUnits(top));
7779 * Sets the element's CSS right style.
7780 * @param {String} right The right CSS property value
7781 * @return {Roo.Element} this
7783 setRight : function(right){
7784 this.setStyle("right", this.addUnits(right));
7789 * Sets the element's CSS bottom style.
7790 * @param {String} bottom The bottom CSS property value
7791 * @return {Roo.Element} this
7793 setBottom : function(bottom){
7794 this.setStyle("bottom", this.addUnits(bottom));
7799 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7800 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7801 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7802 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7803 * @return {Roo.Element} this
7805 setXY : function(pos, animate){
7807 D.setXY(this.dom, pos);
7809 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7815 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7816 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7817 * @param {Number} x X value for new position (coordinates are page-based)
7818 * @param {Number} y Y value for new position (coordinates are page-based)
7819 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7820 * @return {Roo.Element} this
7822 setLocation : function(x, y, animate){
7823 this.setXY([x, y], this.preanim(arguments, 2));
7828 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7829 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7830 * @param {Number} x X value for new position (coordinates are page-based)
7831 * @param {Number} y Y value for new position (coordinates are page-based)
7832 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7833 * @return {Roo.Element} this
7835 moveTo : function(x, y, animate){
7836 this.setXY([x, y], this.preanim(arguments, 2));
7841 * Returns the region of the given element.
7842 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7843 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7845 getRegion : function(){
7846 return D.getRegion(this.dom);
7850 * Returns the offset height of the element
7851 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7852 * @return {Number} The element's height
7854 getHeight : function(contentHeight){
7855 var h = this.dom.offsetHeight || 0;
7856 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7860 * Returns the offset width of the element
7861 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7862 * @return {Number} The element's width
7864 getWidth : function(contentWidth){
7865 var w = this.dom.offsetWidth || 0;
7866 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7870 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7871 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7872 * if a height has not been set using CSS.
7875 getComputedHeight : function(){
7876 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7878 h = parseInt(this.getStyle('height'), 10) || 0;
7879 if(!this.isBorderBox()){
7880 h += this.getFrameWidth('tb');
7887 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7888 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7889 * if a width has not been set using CSS.
7892 getComputedWidth : function(){
7893 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7895 w = parseInt(this.getStyle('width'), 10) || 0;
7896 if(!this.isBorderBox()){
7897 w += this.getFrameWidth('lr');
7904 * Returns the size of the element.
7905 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7906 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7908 getSize : function(contentSize){
7909 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7913 * Returns the width and height of the viewport.
7914 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7916 getViewSize : function(){
7917 var d = this.dom, doc = document, aw = 0, ah = 0;
7918 if(d == doc || d == doc.body){
7919 return {width : D.getViewWidth(), height: D.getViewHeight()};
7922 width : d.clientWidth,
7923 height: d.clientHeight
7929 * Returns the value of the "value" attribute
7930 * @param {Boolean} asNumber true to parse the value as a number
7931 * @return {String/Number}
7933 getValue : function(asNumber){
7934 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7938 adjustWidth : function(width){
7939 if(typeof width == "number"){
7940 if(this.autoBoxAdjust && !this.isBorderBox()){
7941 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7951 adjustHeight : function(height){
7952 if(typeof height == "number"){
7953 if(this.autoBoxAdjust && !this.isBorderBox()){
7954 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7964 * Set the width of the element
7965 * @param {Number} width The new width
7966 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7967 * @return {Roo.Element} this
7969 setWidth : function(width, animate){
7970 width = this.adjustWidth(width);
7972 this.dom.style.width = this.addUnits(width);
7974 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7980 * Set the height of the element
7981 * @param {Number} height The new height
7982 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7983 * @return {Roo.Element} this
7985 setHeight : function(height, animate){
7986 height = this.adjustHeight(height);
7988 this.dom.style.height = this.addUnits(height);
7990 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7996 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7997 * @param {Number} width The new width
7998 * @param {Number} height The new height
7999 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8000 * @return {Roo.Element} this
8002 setSize : function(width, height, animate){
8003 if(typeof width == "object"){ // in case of object from getSize()
8004 height = width.height; width = width.width;
8006 width = this.adjustWidth(width); height = this.adjustHeight(height);
8008 this.dom.style.width = this.addUnits(width);
8009 this.dom.style.height = this.addUnits(height);
8011 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
8017 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
8018 * @param {Number} x X value for new position (coordinates are page-based)
8019 * @param {Number} y Y value for new position (coordinates are page-based)
8020 * @param {Number} width The new width
8021 * @param {Number} height The new height
8022 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8023 * @return {Roo.Element} this
8025 setBounds : function(x, y, width, height, animate){
8027 this.setSize(width, height);
8028 this.setLocation(x, y);
8030 width = this.adjustWidth(width); height = this.adjustHeight(height);
8031 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
8032 this.preanim(arguments, 4), 'motion');
8038 * 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.
8039 * @param {Roo.lib.Region} region The region to fill
8040 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8041 * @return {Roo.Element} this
8043 setRegion : function(region, animate){
8044 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8049 * Appends an event handler
8051 * @param {String} eventName The type of event to append
8052 * @param {Function} fn The method the event invokes
8053 * @param {Object} scope (optional) The scope (this object) of the fn
8054 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8056 addListener : function(eventName, fn, scope, options){
8058 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
8063 * Removes an event handler from this element
8064 * @param {String} eventName the type of event to remove
8065 * @param {Function} fn the method the event invokes
8066 * @return {Roo.Element} this
8068 removeListener : function(eventName, fn){
8069 Roo.EventManager.removeListener(this.dom, eventName, fn);
8074 * Removes all previous added listeners from this element
8075 * @return {Roo.Element} this
8077 removeAllListeners : function(){
8078 E.purgeElement(this.dom);
8082 relayEvent : function(eventName, observable){
8083 this.on(eventName, function(e){
8084 observable.fireEvent(eventName, e);
8089 * Set the opacity of the element
8090 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
8091 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8092 * @return {Roo.Element} this
8094 setOpacity : function(opacity, animate){
8096 var s = this.dom.style;
8099 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
8100 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
8102 s.opacity = opacity;
8105 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
8111 * Gets the left X coordinate
8112 * @param {Boolean} local True to get the local css position instead of page coordinate
8115 getLeft : function(local){
8119 return parseInt(this.getStyle("left"), 10) || 0;
8124 * Gets the right X coordinate of the element (element X position + element width)
8125 * @param {Boolean} local True to get the local css position instead of page coordinate
8128 getRight : function(local){
8130 return this.getX() + this.getWidth();
8132 return (this.getLeft(true) + this.getWidth()) || 0;
8137 * Gets the top Y coordinate
8138 * @param {Boolean} local True to get the local css position instead of page coordinate
8141 getTop : function(local) {
8145 return parseInt(this.getStyle("top"), 10) || 0;
8150 * Gets the bottom Y coordinate of the element (element Y position + element height)
8151 * @param {Boolean} local True to get the local css position instead of page coordinate
8154 getBottom : function(local){
8156 return this.getY() + this.getHeight();
8158 return (this.getTop(true) + this.getHeight()) || 0;
8163 * Initializes positioning on this element. If a desired position is not passed, it will make the
8164 * the element positioned relative IF it is not already positioned.
8165 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8166 * @param {Number} zIndex (optional) The zIndex to apply
8167 * @param {Number} x (optional) Set the page X position
8168 * @param {Number} y (optional) Set the page Y position
8170 position : function(pos, zIndex, x, y){
8172 if(this.getStyle('position') == 'static'){
8173 this.setStyle('position', 'relative');
8176 this.setStyle("position", pos);
8179 this.setStyle("z-index", zIndex);
8181 if(x !== undefined && y !== undefined){
8183 }else if(x !== undefined){
8185 }else if(y !== undefined){
8191 * Clear positioning back to the default when the document was loaded
8192 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8193 * @return {Roo.Element} this
8195 clearPositioning : function(value){
8203 "position" : "static"
8209 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8210 * snapshot before performing an update and then restoring the element.
8213 getPositioning : function(){
8214 var l = this.getStyle("left");
8215 var t = this.getStyle("top");
8217 "position" : this.getStyle("position"),
8219 "right" : l ? "" : this.getStyle("right"),
8221 "bottom" : t ? "" : this.getStyle("bottom"),
8222 "z-index" : this.getStyle("z-index")
8227 * Gets the width of the border(s) for the specified side(s)
8228 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8229 * passing lr would get the border (l)eft width + the border (r)ight width.
8230 * @return {Number} The width of the sides passed added together
8232 getBorderWidth : function(side){
8233 return this.addStyles(side, El.borders);
8237 * Gets the width of the padding(s) for the specified side(s)
8238 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8239 * passing lr would get the padding (l)eft + the padding (r)ight.
8240 * @return {Number} The padding of the sides passed added together
8242 getPadding : function(side){
8243 return this.addStyles(side, El.paddings);
8247 * Set positioning with an object returned by getPositioning().
8248 * @param {Object} posCfg
8249 * @return {Roo.Element} this
8251 setPositioning : function(pc){
8252 this.applyStyles(pc);
8253 if(pc.right == "auto"){
8254 this.dom.style.right = "";
8256 if(pc.bottom == "auto"){
8257 this.dom.style.bottom = "";
8263 fixDisplay : function(){
8264 if(this.getStyle("display") == "none"){
8265 this.setStyle("visibility", "hidden");
8266 this.setStyle("display", this.originalDisplay); // first try reverting to default
8267 if(this.getStyle("display") == "none"){ // if that fails, default to block
8268 this.setStyle("display", "block");
8274 * Quick set left and top adding default units
8275 * @param {String} left The left CSS property value
8276 * @param {String} top The top CSS property value
8277 * @return {Roo.Element} this
8279 setLeftTop : function(left, top){
8280 this.dom.style.left = this.addUnits(left);
8281 this.dom.style.top = this.addUnits(top);
8286 * Move this element relative to its current position.
8287 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8288 * @param {Number} distance How far to move the element in pixels
8289 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8290 * @return {Roo.Element} this
8292 move : function(direction, distance, animate){
8293 var xy = this.getXY();
8294 direction = direction.toLowerCase();
8298 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8302 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8307 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8312 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8319 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8320 * @return {Roo.Element} this
8323 if(!this.isClipped){
8324 this.isClipped = true;
8325 this.originalClip = {
8326 "o": this.getStyle("overflow"),
8327 "x": this.getStyle("overflow-x"),
8328 "y": this.getStyle("overflow-y")
8330 this.setStyle("overflow", "hidden");
8331 this.setStyle("overflow-x", "hidden");
8332 this.setStyle("overflow-y", "hidden");
8338 * Return clipping (overflow) to original clipping before clip() was called
8339 * @return {Roo.Element} this
8341 unclip : function(){
8343 this.isClipped = false;
8344 var o = this.originalClip;
8345 if(o.o){this.setStyle("overflow", o.o);}
8346 if(o.x){this.setStyle("overflow-x", o.x);}
8347 if(o.y){this.setStyle("overflow-y", o.y);}
8354 * Gets the x,y coordinates specified by the anchor position on the element.
8355 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8356 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8357 * {width: (target width), height: (target height)} (defaults to the element's current size)
8358 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8359 * @return {Array} [x, y] An array containing the element's x and y coordinates
8361 getAnchorXY : function(anchor, local, s){
8362 //Passing a different size is useful for pre-calculating anchors,
8363 //especially for anchored animations that change the el size.
8365 var w, h, vp = false;
8368 if(d == document.body || d == document){
8370 w = D.getViewWidth(); h = D.getViewHeight();
8372 w = this.getWidth(); h = this.getHeight();
8375 w = s.width; h = s.height;
8377 var x = 0, y = 0, r = Math.round;
8378 switch((anchor || "tl").toLowerCase()){
8420 var sc = this.getScroll();
8421 return [x + sc.left, y + sc.top];
8423 //Add the element's offset xy
8424 var o = this.getXY();
8425 return [x+o[0], y+o[1]];
8429 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8430 * supported position values.
8431 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8432 * @param {String} position The position to align to.
8433 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8434 * @return {Array} [x, y]
8436 getAlignToXY : function(el, p, o){
8440 throw "Element.alignTo with an element that doesn't exist";
8442 var c = false; //constrain to viewport
8443 var p1 = "", p2 = "";
8450 }else if(p.indexOf("-") == -1){
8453 p = p.toLowerCase();
8454 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8456 throw "Element.alignTo with an invalid alignment " + p;
8458 p1 = m[1]; p2 = m[2]; c = !!m[3];
8460 //Subtract the aligned el's internal xy from the target's offset xy
8461 //plus custom offset to get the aligned el's new offset xy
8462 var a1 = this.getAnchorXY(p1, true);
8463 var a2 = el.getAnchorXY(p2, false);
8464 var x = a2[0] - a1[0] + o[0];
8465 var y = a2[1] - a1[1] + o[1];
8467 //constrain the aligned el to viewport if necessary
8468 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8469 // 5px of margin for ie
8470 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8472 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8473 //perpendicular to the vp border, allow the aligned el to slide on that border,
8474 //otherwise swap the aligned el to the opposite border of the target.
8475 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8476 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8477 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8478 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8481 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8482 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8484 if((x+w) > dw + scrollX){
8485 x = swapX ? r.left-w : dw+scrollX-w;
8488 x = swapX ? r.right : scrollX;
8490 if((y+h) > dh + scrollY){
8491 y = swapY ? r.top-h : dh+scrollY-h;
8494 y = swapY ? r.bottom : scrollY;
8501 getConstrainToXY : function(){
8502 var os = {top:0, left:0, bottom:0, right: 0};
8504 return function(el, local, offsets, proposedXY){
8506 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8508 var vw, vh, vx = 0, vy = 0;
8509 if(el.dom == document.body || el.dom == document){
8510 vw = Roo.lib.Dom.getViewWidth();
8511 vh = Roo.lib.Dom.getViewHeight();
8513 vw = el.dom.clientWidth;
8514 vh = el.dom.clientHeight;
8516 var vxy = el.getXY();
8522 var s = el.getScroll();
8524 vx += offsets.left + s.left;
8525 vy += offsets.top + s.top;
8527 vw -= offsets.right;
8528 vh -= offsets.bottom;
8533 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8534 var x = xy[0], y = xy[1];
8535 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8537 // only move it if it needs it
8540 // first validate right/bottom
8549 // then make sure top/left isn't negative
8558 return moved ? [x, y] : false;
8563 adjustForConstraints : function(xy, parent, offsets){
8564 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8568 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8569 * document it aligns it to the viewport.
8570 * The position parameter is optional, and can be specified in any one of the following formats:
8572 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8573 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8574 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8575 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8576 * <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
8577 * element's anchor point, and the second value is used as the target's anchor point.</li>
8579 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8580 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8581 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8582 * that specified in order to enforce the viewport constraints.
8583 * Following are all of the supported anchor positions:
8586 ----- -----------------------------
8587 tl The top left corner (default)
8588 t The center of the top edge
8589 tr The top right corner
8590 l The center of the left edge
8591 c In the center of the element
8592 r The center of the right edge
8593 bl The bottom left corner
8594 b The center of the bottom edge
8595 br The bottom right corner
8599 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8600 el.alignTo("other-el");
8602 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8603 el.alignTo("other-el", "tr?");
8605 // align the bottom right corner of el with the center left edge of other-el
8606 el.alignTo("other-el", "br-l?");
8608 // align the center of el with the bottom left corner of other-el and
8609 // adjust the x position by -6 pixels (and the y position by 0)
8610 el.alignTo("other-el", "c-bl", [-6, 0]);
8612 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8613 * @param {String} position The position to align to.
8614 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8615 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8616 * @return {Roo.Element} this
8618 alignTo : function(element, position, offsets, animate){
8619 var xy = this.getAlignToXY(element, position, offsets);
8620 this.setXY(xy, this.preanim(arguments, 3));
8625 * Anchors an element to another element and realigns it when the window is resized.
8626 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8627 * @param {String} position The position to align to.
8628 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8629 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8630 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8631 * is a number, it is used as the buffer delay (defaults to 50ms).
8632 * @param {Function} callback The function to call after the animation finishes
8633 * @return {Roo.Element} this
8635 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8636 var action = function(){
8637 this.alignTo(el, alignment, offsets, animate);
8638 Roo.callback(callback, this);
8640 Roo.EventManager.onWindowResize(action, this);
8641 var tm = typeof monitorScroll;
8642 if(tm != 'undefined'){
8643 Roo.EventManager.on(window, 'scroll', action, this,
8644 {buffer: tm == 'number' ? monitorScroll : 50});
8646 action.call(this); // align immediately
8650 * Clears any opacity settings from this element. Required in some cases for IE.
8651 * @return {Roo.Element} this
8653 clearOpacity : function(){
8654 if (window.ActiveXObject) {
8655 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8656 this.dom.style.filter = "";
8659 this.dom.style.opacity = "";
8660 this.dom.style["-moz-opacity"] = "";
8661 this.dom.style["-khtml-opacity"] = "";
8667 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8668 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8669 * @return {Roo.Element} this
8671 hide : function(animate){
8672 this.setVisible(false, this.preanim(arguments, 0));
8677 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8678 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8679 * @return {Roo.Element} this
8681 show : function(animate){
8682 this.setVisible(true, this.preanim(arguments, 0));
8687 * @private Test if size has a unit, otherwise appends the default
8689 addUnits : function(size){
8690 return Roo.Element.addUnits(size, this.defaultUnit);
8694 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8695 * @return {Roo.Element} this
8697 beginMeasure : function(){
8699 if(el.offsetWidth || el.offsetHeight){
8700 return this; // offsets work already
8703 var p = this.dom, b = document.body; // start with this element
8704 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8705 var pe = Roo.get(p);
8706 if(pe.getStyle('display') == 'none'){
8707 changed.push({el: p, visibility: pe.getStyle("visibility")});
8708 p.style.visibility = "hidden";
8709 p.style.display = "block";
8713 this._measureChanged = changed;
8719 * Restores displays to before beginMeasure was called
8720 * @return {Roo.Element} this
8722 endMeasure : function(){
8723 var changed = this._measureChanged;
8725 for(var i = 0, len = changed.length; i < len; i++) {
8727 r.el.style.visibility = r.visibility;
8728 r.el.style.display = "none";
8730 this._measureChanged = null;
8736 * Update the innerHTML of this element, optionally searching for and processing scripts
8737 * @param {String} html The new HTML
8738 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8739 * @param {Function} callback For async script loading you can be noticed when the update completes
8740 * @return {Roo.Element} this
8742 update : function(html, loadScripts, callback){
8743 if(typeof html == "undefined"){
8746 if(loadScripts !== true){
8747 this.dom.innerHTML = html;
8748 if(typeof callback == "function"){
8756 html += '<span id="' + id + '"></span>';
8758 E.onAvailable(id, function(){
8759 var hd = document.getElementsByTagName("head")[0];
8760 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8761 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8762 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8765 while(match = re.exec(html)){
8766 var attrs = match[1];
8767 var srcMatch = attrs ? attrs.match(srcRe) : false;
8768 if(srcMatch && srcMatch[2]){
8769 var s = document.createElement("script");
8770 s.src = srcMatch[2];
8771 var typeMatch = attrs.match(typeRe);
8772 if(typeMatch && typeMatch[2]){
8773 s.type = typeMatch[2];
8776 }else if(match[2] && match[2].length > 0){
8777 if(window.execScript) {
8778 window.execScript(match[2]);
8786 window.eval(match[2]);
8790 var el = document.getElementById(id);
8791 if(el){el.parentNode.removeChild(el);}
8792 if(typeof callback == "function"){
8796 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8801 * Direct access to the UpdateManager update() method (takes the same parameters).
8802 * @param {String/Function} url The url for this request or a function to call to get the url
8803 * @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}
8804 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8805 * @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.
8806 * @return {Roo.Element} this
8809 var um = this.getUpdateManager();
8810 um.update.apply(um, arguments);
8815 * Gets this element's UpdateManager
8816 * @return {Roo.UpdateManager} The UpdateManager
8818 getUpdateManager : function(){
8819 if(!this.updateManager){
8820 this.updateManager = new Roo.UpdateManager(this);
8822 return this.updateManager;
8826 * Disables text selection for this element (normalized across browsers)
8827 * @return {Roo.Element} this
8829 unselectable : function(){
8830 this.dom.unselectable = "on";
8831 this.swallowEvent("selectstart", true);
8832 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8833 this.addClass("x-unselectable");
8838 * Calculates the x, y to center this element on the screen
8839 * @return {Array} The x, y values [x, y]
8841 getCenterXY : function(){
8842 return this.getAlignToXY(document, 'c-c');
8846 * Centers the Element in either the viewport, or another Element.
8847 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8849 center : function(centerIn){
8850 this.alignTo(centerIn || document, 'c-c');
8855 * Tests various css rules/browsers to determine if this element uses a border box
8858 isBorderBox : function(){
8859 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8863 * Return a box {x, y, width, height} that can be used to set another elements
8864 * size/location to match this element.
8865 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8866 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8867 * @return {Object} box An object in the format {x, y, width, height}
8869 getBox : function(contentBox, local){
8874 var left = parseInt(this.getStyle("left"), 10) || 0;
8875 var top = parseInt(this.getStyle("top"), 10) || 0;
8878 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8880 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8882 var l = this.getBorderWidth("l")+this.getPadding("l");
8883 var r = this.getBorderWidth("r")+this.getPadding("r");
8884 var t = this.getBorderWidth("t")+this.getPadding("t");
8885 var b = this.getBorderWidth("b")+this.getPadding("b");
8886 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)};
8888 bx.right = bx.x + bx.width;
8889 bx.bottom = bx.y + bx.height;
8894 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8895 for more information about the sides.
8896 * @param {String} sides
8899 getFrameWidth : function(sides, onlyContentBox){
8900 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8904 * 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.
8905 * @param {Object} box The box to fill {x, y, width, height}
8906 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8907 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8908 * @return {Roo.Element} this
8910 setBox : function(box, adjust, animate){
8911 var w = box.width, h = box.height;
8912 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8913 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8914 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8916 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8921 * Forces the browser to repaint this element
8922 * @return {Roo.Element} this
8924 repaint : function(){
8926 this.addClass("x-repaint");
8927 setTimeout(function(){
8928 Roo.get(dom).removeClass("x-repaint");
8934 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8935 * then it returns the calculated width of the sides (see getPadding)
8936 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8937 * @return {Object/Number}
8939 getMargins : function(side){
8942 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8943 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8944 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8945 right: parseInt(this.getStyle("margin-right"), 10) || 0
8948 return this.addStyles(side, El.margins);
8953 addStyles : function(sides, styles){
8955 for(var i = 0, len = sides.length; i < len; i++){
8956 v = this.getStyle(styles[sides.charAt(i)]);
8958 w = parseInt(v, 10);
8966 * Creates a proxy element of this element
8967 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8968 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8969 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8970 * @return {Roo.Element} The new proxy element
8972 createProxy : function(config, renderTo, matchBox){
8974 renderTo = Roo.getDom(renderTo);
8976 renderTo = document.body;
8978 config = typeof config == "object" ?
8979 config : {tag : "div", cls: config};
8980 var proxy = Roo.DomHelper.append(renderTo, config, true);
8982 proxy.setBox(this.getBox());
8988 * Puts a mask over this element to disable user interaction. Requires core.css.
8989 * This method can only be applied to elements which accept child nodes.
8990 * @param {String} msg (optional) A message to display in the mask
8991 * @param {String} msgCls (optional) A css class to apply to the msg element
8992 * @return {Element} The mask element
8994 mask : function(msg, msgCls)
8996 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
8997 this.setStyle("position", "relative");
9000 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
9002 this.addClass("x-masked");
9003 this._mask.setDisplayed(true);
9008 while (dom && dom.style) {
9009 if (!isNaN(parseInt(dom.style.zIndex))) {
9010 z = Math.max(z, parseInt(dom.style.zIndex));
9012 dom = dom.parentNode;
9014 // if we are masking the body - then it hides everything..
9015 if (this.dom == document.body) {
9017 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
9018 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
9021 if(typeof msg == 'string'){
9023 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
9025 var mm = this._maskMsg;
9026 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
9027 if (mm.dom.firstChild) { // weird IE issue?
9028 mm.dom.firstChild.innerHTML = msg;
9030 mm.setDisplayed(true);
9032 mm.setStyle('z-index', z + 102);
9034 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
9035 this._mask.setHeight(this.getHeight());
9037 this._mask.setStyle('z-index', z + 100);
9043 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
9044 * it is cached for reuse.
9046 unmask : function(removeEl){
9048 if(removeEl === true){
9049 this._mask.remove();
9052 this._maskMsg.remove();
9053 delete this._maskMsg;
9056 this._mask.setDisplayed(false);
9058 this._maskMsg.setDisplayed(false);
9062 this.removeClass("x-masked");
9066 * Returns true if this element is masked
9069 isMasked : function(){
9070 return this._mask && this._mask.isVisible();
9074 * Creates an iframe shim for this element to keep selects and other windowed objects from
9076 * @return {Roo.Element} The new shim element
9078 createShim : function(){
9079 var el = document.createElement('iframe');
9080 el.frameBorder = 'no';
9081 el.className = 'roo-shim';
9082 if(Roo.isIE && Roo.isSecure){
9083 el.src = Roo.SSL_SECURE_URL;
9085 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
9086 shim.autoBoxAdjust = false;
9091 * Removes this element from the DOM and deletes it from the cache
9093 remove : function(){
9094 if(this.dom.parentNode){
9095 this.dom.parentNode.removeChild(this.dom);
9097 delete El.cache[this.dom.id];
9101 * Sets up event handlers to add and remove a css class when the mouse is over this element
9102 * @param {String} className
9103 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
9104 * mouseout events for children elements
9105 * @return {Roo.Element} this
9107 addClassOnOver : function(className, preventFlicker){
9108 this.on("mouseover", function(){
9109 Roo.fly(this, '_internal').addClass(className);
9111 var removeFn = function(e){
9112 if(preventFlicker !== true || !e.within(this, true)){
9113 Roo.fly(this, '_internal').removeClass(className);
9116 this.on("mouseout", removeFn, this.dom);
9121 * Sets up event handlers to add and remove a css class when this element has the focus
9122 * @param {String} className
9123 * @return {Roo.Element} this
9125 addClassOnFocus : function(className){
9126 this.on("focus", function(){
9127 Roo.fly(this, '_internal').addClass(className);
9129 this.on("blur", function(){
9130 Roo.fly(this, '_internal').removeClass(className);
9135 * 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)
9136 * @param {String} className
9137 * @return {Roo.Element} this
9139 addClassOnClick : function(className){
9141 this.on("mousedown", function(){
9142 Roo.fly(dom, '_internal').addClass(className);
9143 var d = Roo.get(document);
9144 var fn = function(){
9145 Roo.fly(dom, '_internal').removeClass(className);
9146 d.removeListener("mouseup", fn);
9148 d.on("mouseup", fn);
9154 * Stops the specified event from bubbling and optionally prevents the default action
9155 * @param {String} eventName
9156 * @param {Boolean} preventDefault (optional) true to prevent the default action too
9157 * @return {Roo.Element} this
9159 swallowEvent : function(eventName, preventDefault){
9160 var fn = function(e){
9161 e.stopPropagation();
9166 if(eventName instanceof Array){
9167 for(var i = 0, len = eventName.length; i < len; i++){
9168 this.on(eventName[i], fn);
9172 this.on(eventName, fn);
9179 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9182 * Sizes this element to its parent element's dimensions performing
9183 * neccessary box adjustments.
9184 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9185 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9186 * @return {Roo.Element} this
9188 fitToParent : function(monitorResize, targetParent) {
9189 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9190 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9191 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9194 var p = Roo.get(targetParent || this.dom.parentNode);
9195 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9196 if (monitorResize === true) {
9197 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9198 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9204 * Gets the next sibling, skipping text nodes
9205 * @return {HTMLElement} The next sibling or null
9207 getNextSibling : function(){
9208 var n = this.dom.nextSibling;
9209 while(n && n.nodeType != 1){
9216 * Gets the previous sibling, skipping text nodes
9217 * @return {HTMLElement} The previous sibling or null
9219 getPrevSibling : function(){
9220 var n = this.dom.previousSibling;
9221 while(n && n.nodeType != 1){
9222 n = n.previousSibling;
9229 * Appends the passed element(s) to this element
9230 * @param {String/HTMLElement/Array/Element/CompositeElement} el
9231 * @return {Roo.Element} this
9233 appendChild: function(el){
9240 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9241 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
9242 * automatically generated with the specified attributes.
9243 * @param {HTMLElement} insertBefore (optional) a child element of this element
9244 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9245 * @return {Roo.Element} The new child element
9247 createChild: function(config, insertBefore, returnDom){
9248 config = config || {tag:'div'};
9250 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9252 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
9256 * Appends this element to the passed element
9257 * @param {String/HTMLElement/Element} el The new parent element
9258 * @return {Roo.Element} this
9260 appendTo: function(el){
9261 el = Roo.getDom(el);
9262 el.appendChild(this.dom);
9267 * Inserts this element before the passed element in the DOM
9268 * @param {String/HTMLElement/Element} el The element to insert before
9269 * @return {Roo.Element} this
9271 insertBefore: function(el){
9272 el = Roo.getDom(el);
9273 el.parentNode.insertBefore(this.dom, el);
9278 * Inserts this element after the passed element in the DOM
9279 * @param {String/HTMLElement/Element} el The element to insert after
9280 * @return {Roo.Element} this
9282 insertAfter: function(el){
9283 el = Roo.getDom(el);
9284 el.parentNode.insertBefore(this.dom, el.nextSibling);
9289 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9290 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9291 * @return {Roo.Element} The new child
9293 insertFirst: function(el, returnDom){
9295 if(typeof el == 'object' && !el.nodeType){ // dh config
9296 return this.createChild(el, this.dom.firstChild, returnDom);
9298 el = Roo.getDom(el);
9299 this.dom.insertBefore(el, this.dom.firstChild);
9300 return !returnDom ? Roo.get(el) : el;
9305 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9306 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9307 * @param {String} where (optional) 'before' or 'after' defaults to before
9308 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9309 * @return {Roo.Element} the inserted Element
9311 insertSibling: function(el, where, returnDom){
9312 where = where ? where.toLowerCase() : 'before';
9314 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9316 if(typeof el == 'object' && !el.nodeType){ // dh config
9317 if(where == 'after' && !this.dom.nextSibling){
9318 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9320 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9324 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9325 where == 'before' ? this.dom : this.dom.nextSibling);
9334 * Creates and wraps this element with another element
9335 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9336 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9337 * @return {HTMLElement/Element} The newly created wrapper element
9339 wrap: function(config, returnDom){
9341 config = {tag: "div"};
9343 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9344 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9349 * Replaces the passed element with this element
9350 * @param {String/HTMLElement/Element} el The element to replace
9351 * @return {Roo.Element} this
9353 replace: function(el){
9355 this.insertBefore(el);
9361 * Inserts an html fragment into this element
9362 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9363 * @param {String} html The HTML fragment
9364 * @param {Boolean} returnEl True to return an Roo.Element
9365 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9367 insertHtml : function(where, html, returnEl){
9368 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9369 return returnEl ? Roo.get(el) : el;
9373 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9374 * @param {Object} o The object with the attributes
9375 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9376 * @return {Roo.Element} this
9378 set : function(o, useSet){
9380 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9382 if(attr == "style" || typeof o[attr] == "function") continue;
9384 el.className = o["cls"];
9386 if(useSet) el.setAttribute(attr, o[attr]);
9387 else el[attr] = o[attr];
9391 Roo.DomHelper.applyStyles(el, o.style);
9397 * Convenience method for constructing a KeyMap
9398 * @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:
9399 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9400 * @param {Function} fn The function to call
9401 * @param {Object} scope (optional) The scope of the function
9402 * @return {Roo.KeyMap} The KeyMap created
9404 addKeyListener : function(key, fn, scope){
9406 if(typeof key != "object" || key instanceof Array){
9422 return new Roo.KeyMap(this, config);
9426 * Creates a KeyMap for this element
9427 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9428 * @return {Roo.KeyMap} The KeyMap created
9430 addKeyMap : function(config){
9431 return new Roo.KeyMap(this, config);
9435 * Returns true if this element is scrollable.
9438 isScrollable : function(){
9440 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9444 * 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().
9445 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9446 * @param {Number} value The new scroll value
9447 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9448 * @return {Element} this
9451 scrollTo : function(side, value, animate){
9452 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9454 this.dom[prop] = value;
9456 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9457 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9463 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9464 * within this element's scrollable range.
9465 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9466 * @param {Number} distance How far to scroll the element in pixels
9467 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9468 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9469 * was scrolled as far as it could go.
9471 scroll : function(direction, distance, animate){
9472 if(!this.isScrollable()){
9476 var l = el.scrollLeft, t = el.scrollTop;
9477 var w = el.scrollWidth, h = el.scrollHeight;
9478 var cw = el.clientWidth, ch = el.clientHeight;
9479 direction = direction.toLowerCase();
9480 var scrolled = false;
9481 var a = this.preanim(arguments, 2);
9486 var v = Math.min(l + distance, w-cw);
9487 this.scrollTo("left", v, a);
9494 var v = Math.max(l - distance, 0);
9495 this.scrollTo("left", v, a);
9503 var v = Math.max(t - distance, 0);
9504 this.scrollTo("top", v, a);
9512 var v = Math.min(t + distance, h-ch);
9513 this.scrollTo("top", v, a);
9522 * Translates the passed page coordinates into left/top css values for this element
9523 * @param {Number/Array} x The page x or an array containing [x, y]
9524 * @param {Number} y The page y
9525 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9527 translatePoints : function(x, y){
9528 if(typeof x == 'object' || x instanceof Array){
9531 var p = this.getStyle('position');
9532 var o = this.getXY();
9534 var l = parseInt(this.getStyle('left'), 10);
9535 var t = parseInt(this.getStyle('top'), 10);
9538 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9541 t = (p == "relative") ? 0 : this.dom.offsetTop;
9544 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9548 * Returns the current scroll position of the element.
9549 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9551 getScroll : function(){
9552 var d = this.dom, doc = document;
9553 if(d == doc || d == doc.body){
9554 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9555 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9556 return {left: l, top: t};
9558 return {left: d.scrollLeft, top: d.scrollTop};
9563 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9564 * are convert to standard 6 digit hex color.
9565 * @param {String} attr The css attribute
9566 * @param {String} defaultValue The default value to use when a valid color isn't found
9567 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9570 getColor : function(attr, defaultValue, prefix){
9571 var v = this.getStyle(attr);
9572 if(!v || v == "transparent" || v == "inherit") {
9573 return defaultValue;
9575 var color = typeof prefix == "undefined" ? "#" : prefix;
9576 if(v.substr(0, 4) == "rgb("){
9577 var rvs = v.slice(4, v.length -1).split(",");
9578 for(var i = 0; i < 3; i++){
9579 var h = parseInt(rvs[i]).toString(16);
9586 if(v.substr(0, 1) == "#"){
9588 for(var i = 1; i < 4; i++){
9589 var c = v.charAt(i);
9592 }else if(v.length == 7){
9593 color += v.substr(1);
9597 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9601 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9602 * gradient background, rounded corners and a 4-way shadow.
9603 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9604 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9605 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9606 * @return {Roo.Element} this
9608 boxWrap : function(cls){
9609 cls = cls || 'x-box';
9610 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9611 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9616 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9617 * @param {String} namespace The namespace in which to look for the attribute
9618 * @param {String} name The attribute name
9619 * @return {String} The attribute value
9621 getAttributeNS : Roo.isIE ? function(ns, name){
9623 var type = typeof d[ns+":"+name];
9624 if(type != 'undefined' && type != 'unknown'){
9625 return d[ns+":"+name];
9628 } : function(ns, name){
9630 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9635 * Sets or Returns the value the dom attribute value
9636 * @param {String|Object} name The attribute name (or object to set multiple attributes)
9637 * @param {String} value (optional) The value to set the attribute to
9638 * @return {String} The attribute value
9640 attr : function(name){
9641 if (arguments.length > 1) {
9642 this.dom.setAttribute(name, arguments[1]);
9643 return arguments[1];
9645 if (typeof(name) == 'object') {
9646 for(var i in name) {
9647 this.attr(i, name[i]);
9653 if (!this.dom.hasAttribute(name)) {
9656 return this.dom.getAttribute(name);
9663 var ep = El.prototype;
9666 * Appends an event handler (Shorthand for addListener)
9667 * @param {String} eventName The type of event to append
9668 * @param {Function} fn The method the event invokes
9669 * @param {Object} scope (optional) The scope (this object) of the fn
9670 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9673 ep.on = ep.addListener;
9675 ep.mon = ep.addListener;
9678 * Removes an event handler from this element (shorthand for removeListener)
9679 * @param {String} eventName the type of event to remove
9680 * @param {Function} fn the method the event invokes
9681 * @return {Roo.Element} this
9684 ep.un = ep.removeListener;
9687 * true to automatically adjust width and height settings for box-model issues (default to true)
9689 ep.autoBoxAdjust = true;
9692 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9695 El.addUnits = function(v, defaultUnit){
9696 if(v === "" || v == "auto"){
9699 if(v === undefined){
9702 if(typeof v == "number" || !El.unitPattern.test(v)){
9703 return v + (defaultUnit || 'px');
9708 // special markup used throughout Roo when box wrapping elements
9709 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>';
9711 * Visibility mode constant - Use visibility to hide element
9717 * Visibility mode constant - Use display to hide element
9723 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9724 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9725 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9737 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9738 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9739 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9740 * @return {Element} The Element object
9743 El.get = function(el){
9745 if(!el){ return null; }
9746 if(typeof el == "string"){ // element id
9747 if(!(elm = document.getElementById(el))){
9750 if(ex = El.cache[el]){
9753 ex = El.cache[el] = new El(elm);
9756 }else if(el.tagName){ // dom element
9760 if(ex = El.cache[id]){
9763 ex = El.cache[id] = new El(el);
9766 }else if(el instanceof El){
9768 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9769 // catch case where it hasn't been appended
9770 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9773 }else if(el.isComposite){
9775 }else if(el instanceof Array){
9776 return El.select(el);
9777 }else if(el == document){
9778 // create a bogus element object representing the document object
9780 var f = function(){};
9781 f.prototype = El.prototype;
9783 docEl.dom = document;
9791 El.uncache = function(el){
9792 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9794 delete El.cache[a[i].id || a[i]];
9800 // Garbage collection - uncache elements/purge listeners on orphaned elements
9801 // so we don't hold a reference and cause the browser to retain them
9802 El.garbageCollect = function(){
9803 if(!Roo.enableGarbageCollector){
9804 clearInterval(El.collectorThread);
9807 for(var eid in El.cache){
9808 var el = El.cache[eid], d = el.dom;
9809 // -------------------------------------------------------
9810 // Determining what is garbage:
9811 // -------------------------------------------------------
9813 // dom node is null, definitely garbage
9814 // -------------------------------------------------------
9816 // no parentNode == direct orphan, definitely garbage
9817 // -------------------------------------------------------
9818 // !d.offsetParent && !document.getElementById(eid)
9819 // display none elements have no offsetParent so we will
9820 // also try to look it up by it's id. However, check
9821 // offsetParent first so we don't do unneeded lookups.
9822 // This enables collection of elements that are not orphans
9823 // directly, but somewhere up the line they have an orphan
9825 // -------------------------------------------------------
9826 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9827 delete El.cache[eid];
9828 if(d && Roo.enableListenerCollection){
9834 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9838 El.Flyweight = function(dom){
9841 El.Flyweight.prototype = El.prototype;
9843 El._flyweights = {};
9845 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9846 * the dom node can be overwritten by other code.
9847 * @param {String/HTMLElement} el The dom node or id
9848 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9849 * prevent conflicts (e.g. internally Roo uses "_internal")
9851 * @return {Element} The shared Element object
9853 El.fly = function(el, named){
9854 named = named || '_global';
9855 el = Roo.getDom(el);
9859 if(!El._flyweights[named]){
9860 El._flyweights[named] = new El.Flyweight();
9862 El._flyweights[named].dom = el;
9863 return El._flyweights[named];
9867 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9868 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9869 * Shorthand of {@link Roo.Element#get}
9870 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9871 * @return {Element} The Element object
9877 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9878 * the dom node can be overwritten by other code.
9879 * Shorthand of {@link Roo.Element#fly}
9880 * @param {String/HTMLElement} el The dom node or id
9881 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9882 * prevent conflicts (e.g. internally Roo uses "_internal")
9884 * @return {Element} The shared Element object
9890 // speedy lookup for elements never to box adjust
9891 var noBoxAdjust = Roo.isStrict ? {
9894 input:1, select:1, textarea:1
9896 if(Roo.isIE || Roo.isGecko){
9897 noBoxAdjust['button'] = 1;
9901 Roo.EventManager.on(window, 'unload', function(){
9903 delete El._flyweights;
9911 Roo.Element.selectorFunction = Roo.DomQuery.select;
9914 Roo.Element.select = function(selector, unique, root){
9916 if(typeof selector == "string"){
9917 els = Roo.Element.selectorFunction(selector, root);
9918 }else if(selector.length !== undefined){
9921 throw "Invalid selector";
9923 if(unique === true){
9924 return new Roo.CompositeElement(els);
9926 return new Roo.CompositeElementLite(els);
9930 * Selects elements based on the passed CSS selector to enable working on them as 1.
9931 * @param {String/Array} selector The CSS selector or an array of elements
9932 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9933 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9934 * @return {CompositeElementLite/CompositeElement}
9938 Roo.select = Roo.Element.select;
9955 * Ext JS Library 1.1.1
9956 * Copyright(c) 2006-2007, Ext JS, LLC.
9958 * Originally Released Under LGPL - original licence link has changed is not relivant.
9961 * <script type="text/javascript">
9966 //Notifies Element that fx methods are available
9967 Roo.enableFx = true;
9971 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9972 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9973 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9974 * Element effects to work.</p><br/>
9976 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9977 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9978 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9979 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
9980 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9981 * expected results and should be done with care.</p><br/>
9983 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9984 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
9987 ----- -----------------------------
9988 tl The top left corner
9989 t The center of the top edge
9990 tr The top right corner
9991 l The center of the left edge
9992 r The center of the right edge
9993 bl The bottom left corner
9994 b The center of the bottom edge
9995 br The bottom right corner
9997 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9998 * below are common options that can be passed to any Fx method.</b>
9999 * @cfg {Function} callback A function called when the effect is finished
10000 * @cfg {Object} scope The scope of the effect function
10001 * @cfg {String} easing A valid Easing value for the effect
10002 * @cfg {String} afterCls A css class to apply after the effect
10003 * @cfg {Number} duration The length of time (in seconds) that the effect should last
10004 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
10005 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
10006 * effects that end with the element being visually hidden, ignored otherwise)
10007 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
10008 * a function which returns such a specification that will be applied to the Element after the effect finishes
10009 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
10010 * @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
10011 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
10015 * Slides the element into view. An anchor point can be optionally passed to set the point of
10016 * origin for the slide effect. This function automatically handles wrapping the element with
10017 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10020 // default: slide the element in from the top
10023 // custom: slide the element in from the right with a 2-second duration
10024 el.slideIn('r', { duration: 2 });
10026 // common config options shown with default values
10032 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10033 * @param {Object} options (optional) Object literal with any of the Fx config options
10034 * @return {Roo.Element} The Element
10036 slideIn : function(anchor, o){
10037 var el = this.getFxEl();
10040 el.queueFx(o, function(){
10042 anchor = anchor || "t";
10044 // fix display to visibility
10047 // restore values after effect
10048 var r = this.getFxRestore();
10049 var b = this.getBox();
10050 // fixed size for slide
10054 var wrap = this.fxWrap(r.pos, o, "hidden");
10056 var st = this.dom.style;
10057 st.visibility = "visible";
10058 st.position = "absolute";
10060 // clear out temp styles after slide and unwrap
10061 var after = function(){
10062 el.fxUnwrap(wrap, r.pos, o);
10063 st.width = r.width;
10064 st.height = r.height;
10067 // time to calc the positions
10068 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
10070 switch(anchor.toLowerCase()){
10072 wrap.setSize(b.width, 0);
10073 st.left = st.bottom = "0";
10077 wrap.setSize(0, b.height);
10078 st.right = st.top = "0";
10082 wrap.setSize(0, b.height);
10083 wrap.setX(b.right);
10084 st.left = st.top = "0";
10085 a = {width: bw, points: pt};
10088 wrap.setSize(b.width, 0);
10089 wrap.setY(b.bottom);
10090 st.left = st.top = "0";
10091 a = {height: bh, points: pt};
10094 wrap.setSize(0, 0);
10095 st.right = st.bottom = "0";
10096 a = {width: bw, height: bh};
10099 wrap.setSize(0, 0);
10100 wrap.setY(b.y+b.height);
10101 st.right = st.top = "0";
10102 a = {width: bw, height: bh, points: pt};
10105 wrap.setSize(0, 0);
10106 wrap.setXY([b.right, b.bottom]);
10107 st.left = st.top = "0";
10108 a = {width: bw, height: bh, points: pt};
10111 wrap.setSize(0, 0);
10112 wrap.setX(b.x+b.width);
10113 st.left = st.bottom = "0";
10114 a = {width: bw, height: bh, points: pt};
10117 this.dom.style.visibility = "visible";
10120 arguments.callee.anim = wrap.fxanim(a,
10130 * Slides the element out of view. An anchor point can be optionally passed to set the end point
10131 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
10132 * 'hidden') but block elements will still take up space in the document. The element must be removed
10133 * from the DOM using the 'remove' config option if desired. This function automatically handles
10134 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10137 // default: slide the element out to the top
10140 // custom: slide the element out to the right with a 2-second duration
10141 el.slideOut('r', { duration: 2 });
10143 // common config options shown with default values
10151 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10152 * @param {Object} options (optional) Object literal with any of the Fx config options
10153 * @return {Roo.Element} The Element
10155 slideOut : function(anchor, o){
10156 var el = this.getFxEl();
10159 el.queueFx(o, function(){
10161 anchor = anchor || "t";
10163 // restore values after effect
10164 var r = this.getFxRestore();
10166 var b = this.getBox();
10167 // fixed size for slide
10171 var wrap = this.fxWrap(r.pos, o, "visible");
10173 var st = this.dom.style;
10174 st.visibility = "visible";
10175 st.position = "absolute";
10179 var after = function(){
10181 el.setDisplayed(false);
10186 el.fxUnwrap(wrap, r.pos, o);
10188 st.width = r.width;
10189 st.height = r.height;
10194 var a, zero = {to: 0};
10195 switch(anchor.toLowerCase()){
10197 st.left = st.bottom = "0";
10198 a = {height: zero};
10201 st.right = st.top = "0";
10205 st.left = st.top = "0";
10206 a = {width: zero, points: {to:[b.right, b.y]}};
10209 st.left = st.top = "0";
10210 a = {height: zero, points: {to:[b.x, b.bottom]}};
10213 st.right = st.bottom = "0";
10214 a = {width: zero, height: zero};
10217 st.right = st.top = "0";
10218 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10221 st.left = st.top = "0";
10222 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10225 st.left = st.bottom = "0";
10226 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10230 arguments.callee.anim = wrap.fxanim(a,
10240 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
10241 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
10242 * The element must be removed from the DOM using the 'remove' config option if desired.
10248 // common config options shown with default values
10256 * @param {Object} options (optional) Object literal with any of the Fx config options
10257 * @return {Roo.Element} The Element
10259 puff : function(o){
10260 var el = this.getFxEl();
10263 el.queueFx(o, function(){
10264 this.clearOpacity();
10267 // restore values after effect
10268 var r = this.getFxRestore();
10269 var st = this.dom.style;
10271 var after = function(){
10273 el.setDisplayed(false);
10280 el.setPositioning(r.pos);
10281 st.width = r.width;
10282 st.height = r.height;
10287 var width = this.getWidth();
10288 var height = this.getHeight();
10290 arguments.callee.anim = this.fxanim({
10291 width : {to: this.adjustWidth(width * 2)},
10292 height : {to: this.adjustHeight(height * 2)},
10293 points : {by: [-(width * .5), -(height * .5)]},
10295 fontSize: {to:200, unit: "%"}
10306 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10307 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10308 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10314 // all config options shown with default values
10322 * @param {Object} options (optional) Object literal with any of the Fx config options
10323 * @return {Roo.Element} The Element
10325 switchOff : function(o){
10326 var el = this.getFxEl();
10329 el.queueFx(o, function(){
10330 this.clearOpacity();
10333 // restore values after effect
10334 var r = this.getFxRestore();
10335 var st = this.dom.style;
10337 var after = function(){
10339 el.setDisplayed(false);
10345 el.setPositioning(r.pos);
10346 st.width = r.width;
10347 st.height = r.height;
10352 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10353 this.clearOpacity();
10357 points:{by:[0, this.getHeight() * .5]}
10358 }, o, 'motion', 0.3, 'easeIn', after);
10359 }).defer(100, this);
10366 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10367 * changed using the "attr" config option) and then fading back to the original color. If no original
10368 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10371 // default: highlight background to yellow
10374 // custom: highlight foreground text to blue for 2 seconds
10375 el.highlight("0000ff", { attr: 'color', duration: 2 });
10377 // common config options shown with default values
10378 el.highlight("ffff9c", {
10379 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10380 endColor: (current color) or "ffffff",
10385 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10386 * @param {Object} options (optional) Object literal with any of the Fx config options
10387 * @return {Roo.Element} The Element
10389 highlight : function(color, o){
10390 var el = this.getFxEl();
10393 el.queueFx(o, function(){
10394 color = color || "ffff9c";
10395 attr = o.attr || "backgroundColor";
10397 this.clearOpacity();
10400 var origColor = this.getColor(attr);
10401 var restoreColor = this.dom.style[attr];
10402 endColor = (o.endColor || origColor) || "ffffff";
10404 var after = function(){
10405 el.dom.style[attr] = restoreColor;
10410 a[attr] = {from: color, to: endColor};
10411 arguments.callee.anim = this.fxanim(a,
10421 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10424 // default: a single light blue ripple
10427 // custom: 3 red ripples lasting 3 seconds total
10428 el.frame("ff0000", 3, { duration: 3 });
10430 // common config options shown with default values
10431 el.frame("C3DAF9", 1, {
10432 duration: 1 //duration of entire animation (not each individual ripple)
10433 // Note: Easing is not configurable and will be ignored if included
10436 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10437 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10438 * @param {Object} options (optional) Object literal with any of the Fx config options
10439 * @return {Roo.Element} The Element
10441 frame : function(color, count, o){
10442 var el = this.getFxEl();
10445 el.queueFx(o, function(){
10446 color = color || "#C3DAF9";
10447 if(color.length == 6){
10448 color = "#" + color;
10450 count = count || 1;
10451 duration = o.duration || 1;
10454 var b = this.getBox();
10455 var animFn = function(){
10456 var proxy = this.createProxy({
10459 visbility:"hidden",
10460 position:"absolute",
10461 "z-index":"35000", // yee haw
10462 border:"0px solid " + color
10465 var scale = Roo.isBorderBox ? 2 : 1;
10467 top:{from:b.y, to:b.y - 20},
10468 left:{from:b.x, to:b.x - 20},
10469 borderWidth:{from:0, to:10},
10470 opacity:{from:1, to:0},
10471 height:{from:b.height, to:(b.height + (20*scale))},
10472 width:{from:b.width, to:(b.width + (20*scale))}
10473 }, duration, function(){
10477 animFn.defer((duration/2)*1000, this);
10488 * Creates a pause before any subsequent queued effects begin. If there are
10489 * no effects queued after the pause it will have no effect.
10494 * @param {Number} seconds The length of time to pause (in seconds)
10495 * @return {Roo.Element} The Element
10497 pause : function(seconds){
10498 var el = this.getFxEl();
10501 el.queueFx(o, function(){
10502 setTimeout(function(){
10504 }, seconds * 1000);
10510 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10511 * using the "endOpacity" config option.
10514 // default: fade in from opacity 0 to 100%
10517 // custom: fade in from opacity 0 to 75% over 2 seconds
10518 el.fadeIn({ endOpacity: .75, duration: 2});
10520 // common config options shown with default values
10522 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10527 * @param {Object} options (optional) Object literal with any of the Fx config options
10528 * @return {Roo.Element} The Element
10530 fadeIn : function(o){
10531 var el = this.getFxEl();
10533 el.queueFx(o, function(){
10534 this.setOpacity(0);
10536 this.dom.style.visibility = 'visible';
10537 var to = o.endOpacity || 1;
10538 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10539 o, null, .5, "easeOut", function(){
10541 this.clearOpacity();
10550 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10551 * using the "endOpacity" config option.
10554 // default: fade out from the element's current opacity to 0
10557 // custom: fade out from the element's current opacity to 25% over 2 seconds
10558 el.fadeOut({ endOpacity: .25, duration: 2});
10560 // common config options shown with default values
10562 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10569 * @param {Object} options (optional) Object literal with any of the Fx config options
10570 * @return {Roo.Element} The Element
10572 fadeOut : function(o){
10573 var el = this.getFxEl();
10575 el.queueFx(o, function(){
10576 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10577 o, null, .5, "easeOut", function(){
10578 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10579 this.dom.style.display = "none";
10581 this.dom.style.visibility = "hidden";
10583 this.clearOpacity();
10591 * Animates the transition of an element's dimensions from a starting height/width
10592 * to an ending height/width.
10595 // change height and width to 100x100 pixels
10596 el.scale(100, 100);
10598 // common config options shown with default values. The height and width will default to
10599 // the element's existing values if passed as null.
10602 [element's height], {
10607 * @param {Number} width The new width (pass undefined to keep the original width)
10608 * @param {Number} height The new height (pass undefined to keep the original height)
10609 * @param {Object} options (optional) Object literal with any of the Fx config options
10610 * @return {Roo.Element} The Element
10612 scale : function(w, h, o){
10613 this.shift(Roo.apply({}, o, {
10621 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10622 * Any of these properties not specified in the config object will not be changed. This effect
10623 * requires that at least one new dimension, position or opacity setting must be passed in on
10624 * the config object in order for the function to have any effect.
10627 // slide the element horizontally to x position 200 while changing the height and opacity
10628 el.shift({ x: 200, height: 50, opacity: .8 });
10630 // common config options shown with default values.
10632 width: [element's width],
10633 height: [element's height],
10634 x: [element's x position],
10635 y: [element's y position],
10636 opacity: [element's opacity],
10641 * @param {Object} options Object literal with any of the Fx config options
10642 * @return {Roo.Element} The Element
10644 shift : function(o){
10645 var el = this.getFxEl();
10647 el.queueFx(o, function(){
10648 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10649 if(w !== undefined){
10650 a.width = {to: this.adjustWidth(w)};
10652 if(h !== undefined){
10653 a.height = {to: this.adjustHeight(h)};
10655 if(x !== undefined || y !== undefined){
10657 x !== undefined ? x : this.getX(),
10658 y !== undefined ? y : this.getY()
10661 if(op !== undefined){
10662 a.opacity = {to: op};
10664 if(o.xy !== undefined){
10665 a.points = {to: o.xy};
10667 arguments.callee.anim = this.fxanim(a,
10668 o, 'motion', .35, "easeOut", function(){
10676 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10677 * ending point of the effect.
10680 // default: slide the element downward while fading out
10683 // custom: slide the element out to the right with a 2-second duration
10684 el.ghost('r', { duration: 2 });
10686 // common config options shown with default values
10694 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10695 * @param {Object} options (optional) Object literal with any of the Fx config options
10696 * @return {Roo.Element} The Element
10698 ghost : function(anchor, o){
10699 var el = this.getFxEl();
10702 el.queueFx(o, function(){
10703 anchor = anchor || "b";
10705 // restore values after effect
10706 var r = this.getFxRestore();
10707 var w = this.getWidth(),
10708 h = this.getHeight();
10710 var st = this.dom.style;
10712 var after = function(){
10714 el.setDisplayed(false);
10720 el.setPositioning(r.pos);
10721 st.width = r.width;
10722 st.height = r.height;
10727 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10728 switch(anchor.toLowerCase()){
10755 arguments.callee.anim = this.fxanim(a,
10765 * Ensures that all effects queued after syncFx is called on the element are
10766 * run concurrently. This is the opposite of {@link #sequenceFx}.
10767 * @return {Roo.Element} The Element
10769 syncFx : function(){
10770 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10779 * Ensures that all effects queued after sequenceFx is called on the element are
10780 * run in sequence. This is the opposite of {@link #syncFx}.
10781 * @return {Roo.Element} The Element
10783 sequenceFx : function(){
10784 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10786 concurrent : false,
10793 nextFx : function(){
10794 var ef = this.fxQueue[0];
10801 * Returns true if the element has any effects actively running or queued, else returns false.
10802 * @return {Boolean} True if element has active effects, else false
10804 hasActiveFx : function(){
10805 return this.fxQueue && this.fxQueue[0];
10809 * Stops any running effects and clears the element's internal effects queue if it contains
10810 * any additional effects that haven't started yet.
10811 * @return {Roo.Element} The Element
10813 stopFx : function(){
10814 if(this.hasActiveFx()){
10815 var cur = this.fxQueue[0];
10816 if(cur && cur.anim && cur.anim.isAnimated()){
10817 this.fxQueue = [cur]; // clear out others
10818 cur.anim.stop(true);
10825 beforeFx : function(o){
10826 if(this.hasActiveFx() && !o.concurrent){
10837 * Returns true if the element is currently blocking so that no other effect can be queued
10838 * until this effect is finished, else returns false if blocking is not set. This is commonly
10839 * used to ensure that an effect initiated by a user action runs to completion prior to the
10840 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10841 * @return {Boolean} True if blocking, else false
10843 hasFxBlock : function(){
10844 var q = this.fxQueue;
10845 return q && q[0] && q[0].block;
10849 queueFx : function(o, fn){
10853 if(!this.hasFxBlock()){
10854 Roo.applyIf(o, this.fxDefaults);
10856 var run = this.beforeFx(o);
10857 fn.block = o.block;
10858 this.fxQueue.push(fn);
10870 fxWrap : function(pos, o, vis){
10872 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10875 wrapXY = this.getXY();
10877 var div = document.createElement("div");
10878 div.style.visibility = vis;
10879 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10880 wrap.setPositioning(pos);
10881 if(wrap.getStyle("position") == "static"){
10882 wrap.position("relative");
10884 this.clearPositioning('auto');
10886 wrap.dom.appendChild(this.dom);
10888 wrap.setXY(wrapXY);
10895 fxUnwrap : function(wrap, pos, o){
10896 this.clearPositioning();
10897 this.setPositioning(pos);
10899 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10905 getFxRestore : function(){
10906 var st = this.dom.style;
10907 return {pos: this.getPositioning(), width: st.width, height : st.height};
10911 afterFx : function(o){
10913 this.applyStyles(o.afterStyle);
10916 this.addClass(o.afterCls);
10918 if(o.remove === true){
10921 Roo.callback(o.callback, o.scope, [this]);
10923 this.fxQueue.shift();
10929 getFxEl : function(){ // support for composite element fx
10930 return Roo.get(this.dom);
10934 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10935 animType = animType || 'run';
10937 var anim = Roo.lib.Anim[animType](
10939 (opt.duration || defaultDur) || .35,
10940 (opt.easing || defaultEase) || 'easeOut',
10942 Roo.callback(cb, this);
10951 // backwords compat
10952 Roo.Fx.resize = Roo.Fx.scale;
10954 //When included, Roo.Fx is automatically applied to Element so that all basic
10955 //effects are available directly via the Element API
10956 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10958 * Ext JS Library 1.1.1
10959 * Copyright(c) 2006-2007, Ext JS, LLC.
10961 * Originally Released Under LGPL - original licence link has changed is not relivant.
10964 * <script type="text/javascript">
10969 * @class Roo.CompositeElement
10970 * Standard composite class. Creates a Roo.Element for every element in the collection.
10972 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10973 * actions will be performed on all the elements in this collection.</b>
10975 * All methods return <i>this</i> and can be chained.
10977 var els = Roo.select("#some-el div.some-class", true);
10978 // or select directly from an existing element
10979 var el = Roo.get('some-el');
10980 el.select('div.some-class', true);
10982 els.setWidth(100); // all elements become 100 width
10983 els.hide(true); // all elements fade out and hide
10985 els.setWidth(100).hide(true);
10988 Roo.CompositeElement = function(els){
10989 this.elements = [];
10990 this.addElements(els);
10992 Roo.CompositeElement.prototype = {
10994 addElements : function(els){
10995 if(!els) return this;
10996 if(typeof els == "string"){
10997 els = Roo.Element.selectorFunction(els);
10999 var yels = this.elements;
11000 var index = yels.length-1;
11001 for(var i = 0, len = els.length; i < len; i++) {
11002 yels[++index] = Roo.get(els[i]);
11008 * Clears this composite and adds the elements returned by the passed selector.
11009 * @param {String/Array} els A string CSS selector, an array of elements or an element
11010 * @return {CompositeElement} this
11012 fill : function(els){
11013 this.elements = [];
11019 * Filters this composite to only elements that match the passed selector.
11020 * @param {String} selector A string CSS selector
11021 * @param {Boolean} inverse return inverse filter (not matches)
11022 * @return {CompositeElement} this
11024 filter : function(selector, inverse){
11026 inverse = inverse || false;
11027 this.each(function(el){
11028 var match = inverse ? !el.is(selector) : el.is(selector);
11030 els[els.length] = el.dom;
11037 invoke : function(fn, args){
11038 var els = this.elements;
11039 for(var i = 0, len = els.length; i < len; i++) {
11040 Roo.Element.prototype[fn].apply(els[i], args);
11045 * Adds elements to this composite.
11046 * @param {String/Array} els A string CSS selector, an array of elements or an element
11047 * @return {CompositeElement} this
11049 add : function(els){
11050 if(typeof els == "string"){
11051 this.addElements(Roo.Element.selectorFunction(els));
11052 }else if(els.length !== undefined){
11053 this.addElements(els);
11055 this.addElements([els]);
11060 * Calls the passed function passing (el, this, index) for each element in this composite.
11061 * @param {Function} fn The function to call
11062 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11063 * @return {CompositeElement} this
11065 each : function(fn, scope){
11066 var els = this.elements;
11067 for(var i = 0, len = els.length; i < len; i++){
11068 if(fn.call(scope || els[i], els[i], this, i) === false) {
11076 * Returns the Element object at the specified index
11077 * @param {Number} index
11078 * @return {Roo.Element}
11080 item : function(index){
11081 return this.elements[index] || null;
11085 * Returns the first Element
11086 * @return {Roo.Element}
11088 first : function(){
11089 return this.item(0);
11093 * Returns the last Element
11094 * @return {Roo.Element}
11097 return this.item(this.elements.length-1);
11101 * Returns the number of elements in this composite
11104 getCount : function(){
11105 return this.elements.length;
11109 * Returns true if this composite contains the passed element
11112 contains : function(el){
11113 return this.indexOf(el) !== -1;
11117 * Returns true if this composite contains the passed element
11120 indexOf : function(el){
11121 return this.elements.indexOf(Roo.get(el));
11126 * Removes the specified element(s).
11127 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
11128 * or an array of any of those.
11129 * @param {Boolean} removeDom (optional) True to also remove the element from the document
11130 * @return {CompositeElement} this
11132 removeElement : function(el, removeDom){
11133 if(el instanceof Array){
11134 for(var i = 0, len = el.length; i < len; i++){
11135 this.removeElement(el[i]);
11139 var index = typeof el == 'number' ? el : this.indexOf(el);
11142 var d = this.elements[index];
11146 d.parentNode.removeChild(d);
11149 this.elements.splice(index, 1);
11155 * Replaces the specified element with the passed element.
11156 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
11158 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
11159 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
11160 * @return {CompositeElement} this
11162 replaceElement : function(el, replacement, domReplace){
11163 var index = typeof el == 'number' ? el : this.indexOf(el);
11166 this.elements[index].replaceWith(replacement);
11168 this.elements.splice(index, 1, Roo.get(replacement))
11175 * Removes all elements.
11177 clear : function(){
11178 this.elements = [];
11182 Roo.CompositeElement.createCall = function(proto, fnName){
11183 if(!proto[fnName]){
11184 proto[fnName] = function(){
11185 return this.invoke(fnName, arguments);
11189 for(var fnName in Roo.Element.prototype){
11190 if(typeof Roo.Element.prototype[fnName] == "function"){
11191 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11197 * Ext JS Library 1.1.1
11198 * Copyright(c) 2006-2007, Ext JS, LLC.
11200 * Originally Released Under LGPL - original licence link has changed is not relivant.
11203 * <script type="text/javascript">
11207 * @class Roo.CompositeElementLite
11208 * @extends Roo.CompositeElement
11209 * Flyweight composite class. Reuses the same Roo.Element for element operations.
11211 var els = Roo.select("#some-el div.some-class");
11212 // or select directly from an existing element
11213 var el = Roo.get('some-el');
11214 el.select('div.some-class');
11216 els.setWidth(100); // all elements become 100 width
11217 els.hide(true); // all elements fade out and hide
11219 els.setWidth(100).hide(true);
11220 </code></pre><br><br>
11221 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11222 * actions will be performed on all the elements in this collection.</b>
11224 Roo.CompositeElementLite = function(els){
11225 Roo.CompositeElementLite.superclass.constructor.call(this, els);
11226 this.el = new Roo.Element.Flyweight();
11228 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11229 addElements : function(els){
11231 if(els instanceof Array){
11232 this.elements = this.elements.concat(els);
11234 var yels = this.elements;
11235 var index = yels.length-1;
11236 for(var i = 0, len = els.length; i < len; i++) {
11237 yels[++index] = els[i];
11243 invoke : function(fn, args){
11244 var els = this.elements;
11246 for(var i = 0, len = els.length; i < len; i++) {
11248 Roo.Element.prototype[fn].apply(el, args);
11253 * Returns a flyweight Element of the dom element object at the specified index
11254 * @param {Number} index
11255 * @return {Roo.Element}
11257 item : function(index){
11258 if(!this.elements[index]){
11261 this.el.dom = this.elements[index];
11265 // fixes scope with flyweight
11266 addListener : function(eventName, handler, scope, opt){
11267 var els = this.elements;
11268 for(var i = 0, len = els.length; i < len; i++) {
11269 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11275 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11276 * passed is the flyweight (shared) Roo.Element instance, so if you require a
11277 * a reference to the dom node, use el.dom.</b>
11278 * @param {Function} fn The function to call
11279 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11280 * @return {CompositeElement} this
11282 each : function(fn, scope){
11283 var els = this.elements;
11285 for(var i = 0, len = els.length; i < len; i++){
11287 if(fn.call(scope || el, el, this, i) === false){
11294 indexOf : function(el){
11295 return this.elements.indexOf(Roo.getDom(el));
11298 replaceElement : function(el, replacement, domReplace){
11299 var index = typeof el == 'number' ? el : this.indexOf(el);
11301 replacement = Roo.getDom(replacement);
11303 var d = this.elements[index];
11304 d.parentNode.insertBefore(replacement, d);
11305 d.parentNode.removeChild(d);
11307 this.elements.splice(index, 1, replacement);
11312 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11316 * Ext JS Library 1.1.1
11317 * Copyright(c) 2006-2007, Ext JS, LLC.
11319 * Originally Released Under LGPL - original licence link has changed is not relivant.
11322 * <script type="text/javascript">
11328 * @class Roo.data.Connection
11329 * @extends Roo.util.Observable
11330 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11331 * either to a configured URL, or to a URL specified at request time.<br><br>
11333 * Requests made by this class are asynchronous, and will return immediately. No data from
11334 * the server will be available to the statement immediately following the {@link #request} call.
11335 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11337 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11338 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11339 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11340 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11341 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11342 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11343 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11344 * standard DOM methods.
11346 * @param {Object} config a configuration object.
11348 Roo.data.Connection = function(config){
11349 Roo.apply(this, config);
11352 * @event beforerequest
11353 * Fires before a network request is made to retrieve a data object.
11354 * @param {Connection} conn This Connection object.
11355 * @param {Object} options The options config object passed to the {@link #request} method.
11357 "beforerequest" : true,
11359 * @event requestcomplete
11360 * Fires if the request was successfully completed.
11361 * @param {Connection} conn This Connection object.
11362 * @param {Object} response The XHR object containing the response data.
11363 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11364 * @param {Object} options The options config object passed to the {@link #request} method.
11366 "requestcomplete" : true,
11368 * @event requestexception
11369 * Fires if an error HTTP status was returned from the server.
11370 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11371 * @param {Connection} conn This Connection object.
11372 * @param {Object} response The XHR object containing the response data.
11373 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11374 * @param {Object} options The options config object passed to the {@link #request} method.
11376 "requestexception" : true
11378 Roo.data.Connection.superclass.constructor.call(this);
11381 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11383 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11386 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11387 * extra parameters to each request made by this object. (defaults to undefined)
11390 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11391 * to each request made by this object. (defaults to undefined)
11394 * @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)
11397 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11401 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11407 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11410 disableCaching: true,
11413 * Sends an HTTP request to a remote server.
11414 * @param {Object} options An object which may contain the following properties:<ul>
11415 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11416 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11417 * request, a url encoded string or a function to call to get either.</li>
11418 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11419 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11420 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11421 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11422 * <li>options {Object} The parameter to the request call.</li>
11423 * <li>success {Boolean} True if the request succeeded.</li>
11424 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11426 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11427 * The callback is passed the following parameters:<ul>
11428 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11429 * <li>options {Object} The parameter to the request call.</li>
11431 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11432 * The callback is passed the following parameters:<ul>
11433 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11434 * <li>options {Object} The parameter to the request call.</li>
11436 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11437 * for the callback function. Defaults to the browser window.</li>
11438 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11439 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11440 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11441 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11442 * params for the post data. Any params will be appended to the URL.</li>
11443 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11445 * @return {Number} transactionId
11447 request : function(o){
11448 if(this.fireEvent("beforerequest", this, o) !== false){
11451 if(typeof p == "function"){
11452 p = p.call(o.scope||window, o);
11454 if(typeof p == "object"){
11455 p = Roo.urlEncode(o.params);
11457 if(this.extraParams){
11458 var extras = Roo.urlEncode(this.extraParams);
11459 p = p ? (p + '&' + extras) : extras;
11462 var url = o.url || this.url;
11463 if(typeof url == 'function'){
11464 url = url.call(o.scope||window, o);
11468 var form = Roo.getDom(o.form);
11469 url = url || form.action;
11471 var enctype = form.getAttribute("enctype");
11472 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11473 return this.doFormUpload(o, p, url);
11475 var f = Roo.lib.Ajax.serializeForm(form);
11476 p = p ? (p + '&' + f) : f;
11479 var hs = o.headers;
11480 if(this.defaultHeaders){
11481 hs = Roo.apply(hs || {}, this.defaultHeaders);
11488 success: this.handleResponse,
11489 failure: this.handleFailure,
11491 argument: {options: o},
11492 timeout : o.timeout || this.timeout
11495 var method = o.method||this.method||(p ? "POST" : "GET");
11497 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11498 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11501 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11505 }else if(this.autoAbort !== false){
11509 if((method == 'GET' && p) || o.xmlData){
11510 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11513 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11514 return this.transId;
11516 Roo.callback(o.callback, o.scope, [o, null, null]);
11522 * Determine whether this object has a request outstanding.
11523 * @param {Number} transactionId (Optional) defaults to the last transaction
11524 * @return {Boolean} True if there is an outstanding request.
11526 isLoading : function(transId){
11528 return Roo.lib.Ajax.isCallInProgress(transId);
11530 return this.transId ? true : false;
11535 * Aborts any outstanding request.
11536 * @param {Number} transactionId (Optional) defaults to the last transaction
11538 abort : function(transId){
11539 if(transId || this.isLoading()){
11540 Roo.lib.Ajax.abort(transId || this.transId);
11545 handleResponse : function(response){
11546 this.transId = false;
11547 var options = response.argument.options;
11548 response.argument = options ? options.argument : null;
11549 this.fireEvent("requestcomplete", this, response, options);
11550 Roo.callback(options.success, options.scope, [response, options]);
11551 Roo.callback(options.callback, options.scope, [options, true, response]);
11555 handleFailure : function(response, e){
11556 this.transId = false;
11557 var options = response.argument.options;
11558 response.argument = options ? options.argument : null;
11559 this.fireEvent("requestexception", this, response, options, e);
11560 Roo.callback(options.failure, options.scope, [response, options]);
11561 Roo.callback(options.callback, options.scope, [options, false, response]);
11565 doFormUpload : function(o, ps, url){
11567 var frame = document.createElement('iframe');
11570 frame.className = 'x-hidden';
11572 frame.src = Roo.SSL_SECURE_URL;
11574 document.body.appendChild(frame);
11577 document.frames[id].name = id;
11580 var form = Roo.getDom(o.form);
11582 form.method = 'POST';
11583 form.enctype = form.encoding = 'multipart/form-data';
11589 if(ps){ // add dynamic params
11591 ps = Roo.urlDecode(ps, false);
11593 if(ps.hasOwnProperty(k)){
11594 hd = document.createElement('input');
11595 hd.type = 'hidden';
11598 form.appendChild(hd);
11605 var r = { // bogus response object
11610 r.argument = o ? o.argument : null;
11615 doc = frame.contentWindow.document;
11617 doc = (frame.contentDocument || window.frames[id].document);
11619 if(doc && doc.body){
11620 r.responseText = doc.body.innerHTML;
11622 if(doc && doc.XMLDocument){
11623 r.responseXML = doc.XMLDocument;
11625 r.responseXML = doc;
11632 Roo.EventManager.removeListener(frame, 'load', cb, this);
11634 this.fireEvent("requestcomplete", this, r, o);
11635 Roo.callback(o.success, o.scope, [r, o]);
11636 Roo.callback(o.callback, o.scope, [o, true, r]);
11638 setTimeout(function(){document.body.removeChild(frame);}, 100);
11641 Roo.EventManager.on(frame, 'load', cb, this);
11644 if(hiddens){ // remove dynamic params
11645 for(var i = 0, len = hiddens.length; i < len; i++){
11646 form.removeChild(hiddens[i]);
11653 * Ext JS Library 1.1.1
11654 * Copyright(c) 2006-2007, Ext JS, LLC.
11656 * Originally Released Under LGPL - original licence link has changed is not relivant.
11659 * <script type="text/javascript">
11663 * Global Ajax request class.
11666 * @extends Roo.data.Connection
11669 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
11670 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
11671 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
11672 * @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)
11673 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11674 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
11675 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11677 Roo.Ajax = new Roo.data.Connection({
11686 * Serialize the passed form into a url encoded string
11688 * @param {String/HTMLElement} form
11691 serializeForm : function(form){
11692 return Roo.lib.Ajax.serializeForm(form);
11696 * Ext JS Library 1.1.1
11697 * Copyright(c) 2006-2007, Ext JS, LLC.
11699 * Originally Released Under LGPL - original licence link has changed is not relivant.
11702 * <script type="text/javascript">
11707 * @class Roo.UpdateManager
11708 * @extends Roo.util.Observable
11709 * Provides AJAX-style update for Element object.<br><br>
11712 * // Get it from a Roo.Element object
11713 * var el = Roo.get("foo");
11714 * var mgr = el.getUpdateManager();
11715 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11717 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11719 * // or directly (returns the same UpdateManager instance)
11720 * var mgr = new Roo.UpdateManager("myElementId");
11721 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11722 * mgr.on("update", myFcnNeedsToKnow);
11724 // short handed call directly from the element object
11725 Roo.get("foo").load({
11729 text: "Loading Foo..."
11733 * Create new UpdateManager directly.
11734 * @param {String/HTMLElement/Roo.Element} el The element to update
11735 * @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).
11737 Roo.UpdateManager = function(el, forceNew){
11739 if(!forceNew && el.updateManager){
11740 return el.updateManager;
11743 * The Element object
11744 * @type Roo.Element
11748 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11751 this.defaultUrl = null;
11755 * @event beforeupdate
11756 * Fired before an update is made, return false from your handler and the update is cancelled.
11757 * @param {Roo.Element} el
11758 * @param {String/Object/Function} url
11759 * @param {String/Object} params
11761 "beforeupdate": true,
11764 * Fired after successful update is made.
11765 * @param {Roo.Element} el
11766 * @param {Object} oResponseObject The response Object
11771 * Fired on update failure.
11772 * @param {Roo.Element} el
11773 * @param {Object} oResponseObject The response Object
11777 var d = Roo.UpdateManager.defaults;
11779 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11782 this.sslBlankUrl = d.sslBlankUrl;
11784 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11787 this.disableCaching = d.disableCaching;
11789 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11792 this.indicatorText = d.indicatorText;
11794 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11797 this.showLoadIndicator = d.showLoadIndicator;
11799 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11802 this.timeout = d.timeout;
11805 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11808 this.loadScripts = d.loadScripts;
11811 * Transaction object of current executing transaction
11813 this.transaction = null;
11818 this.autoRefreshProcId = null;
11820 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11823 this.refreshDelegate = this.refresh.createDelegate(this);
11825 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11828 this.updateDelegate = this.update.createDelegate(this);
11830 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11833 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11837 this.successDelegate = this.processSuccess.createDelegate(this);
11841 this.failureDelegate = this.processFailure.createDelegate(this);
11843 if(!this.renderer){
11845 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11847 this.renderer = new Roo.UpdateManager.BasicRenderer();
11850 Roo.UpdateManager.superclass.constructor.call(this);
11853 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11855 * Get the Element this UpdateManager is bound to
11856 * @return {Roo.Element} The element
11858 getEl : function(){
11862 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11863 * @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:
11866 url: "your-url.php",<br/>
11867 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11868 callback: yourFunction,<br/>
11869 scope: yourObject, //(optional scope) <br/>
11870 discardUrl: false, <br/>
11871 nocache: false,<br/>
11872 text: "Loading...",<br/>
11874 scripts: false<br/>
11877 * The only required property is url. The optional properties nocache, text and scripts
11878 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11879 * @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}
11880 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11881 * @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.
11883 update : function(url, params, callback, discardUrl){
11884 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11885 var method = this.method,
11887 if(typeof url == "object"){ // must be config object
11890 params = params || cfg.params;
11891 callback = callback || cfg.callback;
11892 discardUrl = discardUrl || cfg.discardUrl;
11893 if(callback && cfg.scope){
11894 callback = callback.createDelegate(cfg.scope);
11896 if(typeof cfg.method != "undefined"){method = cfg.method;};
11897 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11898 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11899 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11900 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11902 this.showLoading();
11904 this.defaultUrl = url;
11906 if(typeof url == "function"){
11907 url = url.call(this);
11910 method = method || (params ? "POST" : "GET");
11911 if(method == "GET"){
11912 url = this.prepareUrl(url);
11915 var o = Roo.apply(cfg ||{}, {
11918 success: this.successDelegate,
11919 failure: this.failureDelegate,
11920 callback: undefined,
11921 timeout: (this.timeout*1000),
11922 argument: {"url": url, "form": null, "callback": callback, "params": params}
11924 Roo.log("updated manager called with timeout of " + o.timeout);
11925 this.transaction = Roo.Ajax.request(o);
11930 * 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.
11931 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11932 * @param {String/HTMLElement} form The form Id or form element
11933 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11934 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11935 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11937 formUpdate : function(form, url, reset, callback){
11938 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11939 if(typeof url == "function"){
11940 url = url.call(this);
11942 form = Roo.getDom(form);
11943 this.transaction = Roo.Ajax.request({
11946 success: this.successDelegate,
11947 failure: this.failureDelegate,
11948 timeout: (this.timeout*1000),
11949 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11951 this.showLoading.defer(1, this);
11956 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11957 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11959 refresh : function(callback){
11960 if(this.defaultUrl == null){
11963 this.update(this.defaultUrl, null, callback, true);
11967 * Set this element to auto refresh.
11968 * @param {Number} interval How often to update (in seconds).
11969 * @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)
11970 * @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}
11971 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11972 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11974 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11976 this.update(url || this.defaultUrl, params, callback, true);
11978 if(this.autoRefreshProcId){
11979 clearInterval(this.autoRefreshProcId);
11981 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11985 * Stop auto refresh on this element.
11987 stopAutoRefresh : function(){
11988 if(this.autoRefreshProcId){
11989 clearInterval(this.autoRefreshProcId);
11990 delete this.autoRefreshProcId;
11994 isAutoRefreshing : function(){
11995 return this.autoRefreshProcId ? true : false;
11998 * Called to update the element to "Loading" state. Override to perform custom action.
12000 showLoading : function(){
12001 if(this.showLoadIndicator){
12002 this.el.update(this.indicatorText);
12007 * Adds unique parameter to query string if disableCaching = true
12010 prepareUrl : function(url){
12011 if(this.disableCaching){
12012 var append = "_dc=" + (new Date().getTime());
12013 if(url.indexOf("?") !== -1){
12014 url += "&" + append;
12016 url += "?" + append;
12025 processSuccess : function(response){
12026 this.transaction = null;
12027 if(response.argument.form && response.argument.reset){
12028 try{ // put in try/catch since some older FF releases had problems with this
12029 response.argument.form.reset();
12032 if(this.loadScripts){
12033 this.renderer.render(this.el, response, this,
12034 this.updateComplete.createDelegate(this, [response]));
12036 this.renderer.render(this.el, response, this);
12037 this.updateComplete(response);
12041 updateComplete : function(response){
12042 this.fireEvent("update", this.el, response);
12043 if(typeof response.argument.callback == "function"){
12044 response.argument.callback(this.el, true, response);
12051 processFailure : function(response){
12052 this.transaction = null;
12053 this.fireEvent("failure", this.el, response);
12054 if(typeof response.argument.callback == "function"){
12055 response.argument.callback(this.el, false, response);
12060 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
12061 * @param {Object} renderer The object implementing the render() method
12063 setRenderer : function(renderer){
12064 this.renderer = renderer;
12067 getRenderer : function(){
12068 return this.renderer;
12072 * Set the defaultUrl used for updates
12073 * @param {String/Function} defaultUrl The url or a function to call to get the url
12075 setDefaultUrl : function(defaultUrl){
12076 this.defaultUrl = defaultUrl;
12080 * Aborts the executing transaction
12082 abort : function(){
12083 if(this.transaction){
12084 Roo.Ajax.abort(this.transaction);
12089 * Returns true if an update is in progress
12090 * @return {Boolean}
12092 isUpdating : function(){
12093 if(this.transaction){
12094 return Roo.Ajax.isLoading(this.transaction);
12101 * @class Roo.UpdateManager.defaults
12102 * @static (not really - but it helps the doc tool)
12103 * The defaults collection enables customizing the default properties of UpdateManager
12105 Roo.UpdateManager.defaults = {
12107 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12113 * True to process scripts by default (Defaults to false).
12116 loadScripts : false,
12119 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12122 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12124 * Whether to append unique parameter on get request to disable caching (Defaults to false).
12127 disableCaching : false,
12129 * Whether to show indicatorText when loading (Defaults to true).
12132 showLoadIndicator : true,
12134 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
12137 indicatorText : '<div class="loading-indicator">Loading...</div>'
12141 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12143 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12144 * @param {String/HTMLElement/Roo.Element} el The element to update
12145 * @param {String} url The url
12146 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12147 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12150 * @member Roo.UpdateManager
12152 Roo.UpdateManager.updateElement = function(el, url, params, options){
12153 var um = Roo.get(el, true).getUpdateManager();
12154 Roo.apply(um, options);
12155 um.update(url, params, options ? options.callback : null);
12157 // alias for backwards compat
12158 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12160 * @class Roo.UpdateManager.BasicRenderer
12161 * Default Content renderer. Updates the elements innerHTML with the responseText.
12163 Roo.UpdateManager.BasicRenderer = function(){};
12165 Roo.UpdateManager.BasicRenderer.prototype = {
12167 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12168 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12169 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12170 * @param {Roo.Element} el The element being rendered
12171 * @param {Object} response The YUI Connect response object
12172 * @param {UpdateManager} updateManager The calling update manager
12173 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12175 render : function(el, response, updateManager, callback){
12176 el.update(response.responseText, updateManager.loadScripts, callback);
12182 * (c)) Alan Knowles
12188 * @class Roo.DomTemplate
12189 * @extends Roo.Template
12190 * An effort at a dom based template engine..
12192 * Similar to XTemplate, except it uses dom parsing to create the template..
12194 * Supported features:
12199 {a_variable} - output encoded.
12200 {a_variable.format:("Y-m-d")} - call a method on the variable
12201 {a_variable:raw} - unencoded output
12202 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
12203 {a_variable:this.method_on_template(...)} - call a method on the template object.
12208 <div roo-for="a_variable or condition.."></div>
12209 <div roo-if="a_variable or condition"></div>
12210 <div roo-exec="some javascript"></div>
12211 <div roo-name="named_template"></div>
12216 Roo.DomTemplate = function()
12218 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
12225 Roo.extend(Roo.DomTemplate, Roo.Template, {
12227 * id counter for sub templates.
12231 * flag to indicate if dom parser is inside a pre,
12232 * it will strip whitespace if not.
12237 * The various sub templates
12245 * basic tag replacing syntax
12248 * // you can fake an object call by doing this
12252 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
12253 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
12255 iterChild : function (node, method) {
12257 var oldPre = this.inPre;
12258 if (node.tagName == 'PRE') {
12261 for( var i = 0; i < node.childNodes.length; i++) {
12262 method.call(this, node.childNodes[i]);
12264 this.inPre = oldPre;
12270 * compile the template
12272 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
12275 compile: function()
12279 // covert the html into DOM...
12283 doc = document.implementation.createHTMLDocument("");
12284 doc.documentElement.innerHTML = this.html ;
12285 div = doc.documentElement;
12287 // old IE... - nasty -- it causes all sorts of issues.. with
12288 // images getting pulled from server..
12289 div = document.createElement('div');
12290 div.innerHTML = this.html;
12292 //doc.documentElement.innerHTML = htmlBody
12298 this.iterChild(div, function(n) {_t.compileNode(n, true); });
12300 var tpls = this.tpls;
12302 // create a top level template from the snippet..
12304 //Roo.log(div.innerHTML);
12311 body : div.innerHTML,
12324 Roo.each(tpls, function(tp){
12325 this.compileTpl(tp);
12326 this.tpls[tp.id] = tp;
12329 this.master = tpls[0];
12335 compileNode : function(node, istop) {
12340 // skip anything not a tag..
12341 if (node.nodeType != 1) {
12342 if (node.nodeType == 3 && !this.inPre) {
12343 // reduce white space..
12344 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
12367 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
12368 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
12369 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
12370 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
12376 // just itterate children..
12377 this.iterChild(node,this.compileNode);
12380 tpl.uid = this.id++;
12381 tpl.value = node.getAttribute('roo-' + tpl.attr);
12382 node.removeAttribute('roo-'+ tpl.attr);
12383 if (tpl.attr != 'name') {
12384 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
12385 node.parentNode.replaceChild(placeholder, node);
12388 var placeholder = document.createElement('span');
12389 placeholder.className = 'roo-tpl-' + tpl.value;
12390 node.parentNode.replaceChild(placeholder, node);
12393 // parent now sees '{domtplXXXX}
12394 this.iterChild(node,this.compileNode);
12396 // we should now have node body...
12397 var div = document.createElement('div');
12398 div.appendChild(node);
12400 // this has the unfortunate side effect of converting tagged attributes
12401 // eg. href="{...}" into %7C...%7D
12402 // this has been fixed by searching for those combo's although it's a bit hacky..
12405 tpl.body = div.innerHTML;
12412 switch (tpl.value) {
12413 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
12414 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
12415 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
12420 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12424 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12428 tpl.id = tpl.value; // replace non characters???
12434 this.tpls.push(tpl);
12444 * Compile a segment of the template into a 'sub-template'
12450 compileTpl : function(tpl)
12452 var fm = Roo.util.Format;
12453 var useF = this.disableFormats !== true;
12455 var sep = Roo.isGecko ? "+\n" : ",\n";
12457 var undef = function(str) {
12458 Roo.debug && Roo.log("Property not found :" + str);
12462 //Roo.log(tpl.body);
12466 var fn = function(m, lbrace, name, format, args)
12469 //Roo.log(arguments);
12470 args = args ? args.replace(/\\'/g,"'") : args;
12471 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
12472 if (typeof(format) == 'undefined') {
12473 format = 'htmlEncode';
12475 if (format == 'raw' ) {
12479 if(name.substr(0, 6) == 'domtpl'){
12480 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
12483 // build an array of options to determine if value is undefined..
12485 // basically get 'xxxx.yyyy' then do
12486 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
12487 // (function () { Roo.log("Property not found"); return ''; })() :
12492 Roo.each(name.split('.'), function(st) {
12493 lookfor += (lookfor.length ? '.': '') + st;
12494 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
12497 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
12500 if(format && useF){
12502 args = args ? ',' + args : "";
12504 if(format.substr(0, 5) != "this."){
12505 format = "fm." + format + '(';
12507 format = 'this.call("'+ format.substr(5) + '", ';
12511 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
12514 if (args && args.length) {
12515 // called with xxyx.yuu:(test,test)
12517 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
12519 // raw.. - :raw modifier..
12520 return "'"+ sep + udef_st + name + ")"+sep+"'";
12524 // branched to use + in gecko and [].join() in others
12526 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
12527 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
12530 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
12531 body.push(tpl.body.replace(/(\r\n|\n)/g,
12532 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
12533 body.push("'].join('');};};");
12534 body = body.join('');
12537 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
12539 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
12546 * same as applyTemplate, except it's done to one of the subTemplates
12547 * when using named templates, you can do:
12549 * var str = pl.applySubTemplate('your-name', values);
12552 * @param {Number} id of the template
12553 * @param {Object} values to apply to template
12554 * @param {Object} parent (normaly the instance of this object)
12556 applySubTemplate : function(id, values, parent)
12560 var t = this.tpls[id];
12564 if(t.ifCall && !t.ifCall.call(this, values, parent)){
12565 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
12569 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
12576 if(t.execCall && t.execCall.call(this, values, parent)){
12580 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12586 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
12587 parent = t.target ? values : parent;
12588 if(t.forCall && vs instanceof Array){
12590 for(var i = 0, len = vs.length; i < len; i++){
12592 buf[buf.length] = t.compiled.call(this, vs[i], parent);
12594 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12596 //Roo.log(t.compiled);
12600 return buf.join('');
12603 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12608 return t.compiled.call(this, vs, parent);
12610 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12612 //Roo.log(t.compiled);
12620 applyTemplate : function(values){
12621 return this.master.compiled.call(this, values, {});
12622 //var s = this.subs;
12625 apply : function(){
12626 return this.applyTemplate.apply(this, arguments);
12631 Roo.DomTemplate.from = function(el){
12632 el = Roo.getDom(el);
12633 return new Roo.Domtemplate(el.value || el.innerHTML);
12636 * Ext JS Library 1.1.1
12637 * Copyright(c) 2006-2007, Ext JS, LLC.
12639 * Originally Released Under LGPL - original licence link has changed is not relivant.
12642 * <script type="text/javascript">
12646 * @class Roo.util.DelayedTask
12647 * Provides a convenient method of performing setTimeout where a new
12648 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12649 * You can use this class to buffer
12650 * the keypress events for a certain number of milliseconds, and perform only if they stop
12651 * for that amount of time.
12652 * @constructor The parameters to this constructor serve as defaults and are not required.
12653 * @param {Function} fn (optional) The default function to timeout
12654 * @param {Object} scope (optional) The default scope of that timeout
12655 * @param {Array} args (optional) The default Array of arguments
12657 Roo.util.DelayedTask = function(fn, scope, args){
12658 var id = null, d, t;
12660 var call = function(){
12661 var now = new Date().getTime();
12665 fn.apply(scope, args || []);
12669 * Cancels any pending timeout and queues a new one
12670 * @param {Number} delay The milliseconds to delay
12671 * @param {Function} newFn (optional) Overrides function passed to constructor
12672 * @param {Object} newScope (optional) Overrides scope passed to constructor
12673 * @param {Array} newArgs (optional) Overrides args passed to constructor
12675 this.delay = function(delay, newFn, newScope, newArgs){
12676 if(id && delay != d){
12680 t = new Date().getTime();
12682 scope = newScope || scope;
12683 args = newArgs || args;
12685 id = setInterval(call, d);
12690 * Cancel the last queued timeout
12692 this.cancel = function(){
12700 * Ext JS Library 1.1.1
12701 * Copyright(c) 2006-2007, Ext JS, LLC.
12703 * Originally Released Under LGPL - original licence link has changed is not relivant.
12706 * <script type="text/javascript">
12710 Roo.util.TaskRunner = function(interval){
12711 interval = interval || 10;
12712 var tasks = [], removeQueue = [];
12714 var running = false;
12716 var stopThread = function(){
12722 var startThread = function(){
12725 id = setInterval(runTasks, interval);
12729 var removeTask = function(task){
12730 removeQueue.push(task);
12736 var runTasks = function(){
12737 if(removeQueue.length > 0){
12738 for(var i = 0, len = removeQueue.length; i < len; i++){
12739 tasks.remove(removeQueue[i]);
12742 if(tasks.length < 1){
12747 var now = new Date().getTime();
12748 for(var i = 0, len = tasks.length; i < len; ++i){
12750 var itime = now - t.taskRunTime;
12751 if(t.interval <= itime){
12752 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12753 t.taskRunTime = now;
12754 if(rt === false || t.taskRunCount === t.repeat){
12759 if(t.duration && t.duration <= (now - t.taskStartTime)){
12766 * Queues a new task.
12767 * @param {Object} task
12769 this.start = function(task){
12771 task.taskStartTime = new Date().getTime();
12772 task.taskRunTime = 0;
12773 task.taskRunCount = 0;
12778 this.stop = function(task){
12783 this.stopAll = function(){
12785 for(var i = 0, len = tasks.length; i < len; i++){
12786 if(tasks[i].onStop){
12795 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12797 * Ext JS Library 1.1.1
12798 * Copyright(c) 2006-2007, Ext JS, LLC.
12800 * Originally Released Under LGPL - original licence link has changed is not relivant.
12803 * <script type="text/javascript">
12808 * @class Roo.util.MixedCollection
12809 * @extends Roo.util.Observable
12810 * A Collection class that maintains both numeric indexes and keys and exposes events.
12812 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12813 * collection (defaults to false)
12814 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12815 * and return the key value for that item. This is used when available to look up the key on items that
12816 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12817 * equivalent to providing an implementation for the {@link #getKey} method.
12819 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12827 * Fires when the collection is cleared.
12832 * Fires when an item is added to the collection.
12833 * @param {Number} index The index at which the item was added.
12834 * @param {Object} o The item added.
12835 * @param {String} key The key associated with the added item.
12840 * Fires when an item is replaced in the collection.
12841 * @param {String} key he key associated with the new added.
12842 * @param {Object} old The item being replaced.
12843 * @param {Object} new The new item.
12848 * Fires when an item is removed from the collection.
12849 * @param {Object} o The item being removed.
12850 * @param {String} key (optional) The key associated with the removed item.
12855 this.allowFunctions = allowFunctions === true;
12857 this.getKey = keyFn;
12859 Roo.util.MixedCollection.superclass.constructor.call(this);
12862 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12863 allowFunctions : false,
12866 * Adds an item to the collection.
12867 * @param {String} key The key to associate with the item
12868 * @param {Object} o The item to add.
12869 * @return {Object} The item added.
12871 add : function(key, o){
12872 if(arguments.length == 1){
12874 key = this.getKey(o);
12876 if(typeof key == "undefined" || key === null){
12878 this.items.push(o);
12879 this.keys.push(null);
12881 var old = this.map[key];
12883 return this.replace(key, o);
12886 this.items.push(o);
12888 this.keys.push(key);
12890 this.fireEvent("add", this.length-1, o, key);
12895 * MixedCollection has a generic way to fetch keys if you implement getKey.
12898 var mc = new Roo.util.MixedCollection();
12899 mc.add(someEl.dom.id, someEl);
12900 mc.add(otherEl.dom.id, otherEl);
12904 var mc = new Roo.util.MixedCollection();
12905 mc.getKey = function(el){
12911 // or via the constructor
12912 var mc = new Roo.util.MixedCollection(false, function(el){
12918 * @param o {Object} The item for which to find the key.
12919 * @return {Object} The key for the passed item.
12921 getKey : function(o){
12926 * Replaces an item in the collection.
12927 * @param {String} key The key associated with the item to replace, or the item to replace.
12928 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12929 * @return {Object} The new item.
12931 replace : function(key, o){
12932 if(arguments.length == 1){
12934 key = this.getKey(o);
12936 var old = this.item(key);
12937 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12938 return this.add(key, o);
12940 var index = this.indexOfKey(key);
12941 this.items[index] = o;
12943 this.fireEvent("replace", key, old, o);
12948 * Adds all elements of an Array or an Object to the collection.
12949 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12950 * an Array of values, each of which are added to the collection.
12952 addAll : function(objs){
12953 if(arguments.length > 1 || objs instanceof Array){
12954 var args = arguments.length > 1 ? arguments : objs;
12955 for(var i = 0, len = args.length; i < len; i++){
12959 for(var key in objs){
12960 if(this.allowFunctions || typeof objs[key] != "function"){
12961 this.add(key, objs[key]);
12968 * Executes the specified function once for every item in the collection, passing each
12969 * item as the first and only parameter. returning false from the function will stop the iteration.
12970 * @param {Function} fn The function to execute for each item.
12971 * @param {Object} scope (optional) The scope in which to execute the function.
12973 each : function(fn, scope){
12974 var items = [].concat(this.items); // each safe for removal
12975 for(var i = 0, len = items.length; i < len; i++){
12976 if(fn.call(scope || items[i], items[i], i, len) === false){
12983 * Executes the specified function once for every key in the collection, passing each
12984 * key, and its associated item as the first two parameters.
12985 * @param {Function} fn The function to execute for each item.
12986 * @param {Object} scope (optional) The scope in which to execute the function.
12988 eachKey : function(fn, scope){
12989 for(var i = 0, len = this.keys.length; i < len; i++){
12990 fn.call(scope || window, this.keys[i], this.items[i], i, len);
12995 * Returns the first item in the collection which elicits a true return value from the
12996 * passed selection function.
12997 * @param {Function} fn The selection function to execute for each item.
12998 * @param {Object} scope (optional) The scope in which to execute the function.
12999 * @return {Object} The first item in the collection which returned true from the selection function.
13001 find : function(fn, scope){
13002 for(var i = 0, len = this.items.length; i < len; i++){
13003 if(fn.call(scope || window, this.items[i], this.keys[i])){
13004 return this.items[i];
13011 * Inserts an item at the specified index in the collection.
13012 * @param {Number} index The index to insert the item at.
13013 * @param {String} key The key to associate with the new item, or the item itself.
13014 * @param {Object} o (optional) If the second parameter was a key, the new item.
13015 * @return {Object} The item inserted.
13017 insert : function(index, key, o){
13018 if(arguments.length == 2){
13020 key = this.getKey(o);
13022 if(index >= this.length){
13023 return this.add(key, o);
13026 this.items.splice(index, 0, o);
13027 if(typeof key != "undefined" && key != null){
13030 this.keys.splice(index, 0, key);
13031 this.fireEvent("add", index, o, key);
13036 * Removed an item from the collection.
13037 * @param {Object} o The item to remove.
13038 * @return {Object} The item removed.
13040 remove : function(o){
13041 return this.removeAt(this.indexOf(o));
13045 * Remove an item from a specified index in the collection.
13046 * @param {Number} index The index within the collection of the item to remove.
13048 removeAt : function(index){
13049 if(index < this.length && index >= 0){
13051 var o = this.items[index];
13052 this.items.splice(index, 1);
13053 var key = this.keys[index];
13054 if(typeof key != "undefined"){
13055 delete this.map[key];
13057 this.keys.splice(index, 1);
13058 this.fireEvent("remove", o, key);
13063 * Removed an item associated with the passed key fom the collection.
13064 * @param {String} key The key of the item to remove.
13066 removeKey : function(key){
13067 return this.removeAt(this.indexOfKey(key));
13071 * Returns the number of items in the collection.
13072 * @return {Number} the number of items in the collection.
13074 getCount : function(){
13075 return this.length;
13079 * Returns index within the collection of the passed Object.
13080 * @param {Object} o The item to find the index of.
13081 * @return {Number} index of the item.
13083 indexOf : function(o){
13084 if(!this.items.indexOf){
13085 for(var i = 0, len = this.items.length; i < len; i++){
13086 if(this.items[i] == o) return i;
13090 return this.items.indexOf(o);
13095 * Returns index within the collection of the passed key.
13096 * @param {String} key The key to find the index of.
13097 * @return {Number} index of the key.
13099 indexOfKey : function(key){
13100 if(!this.keys.indexOf){
13101 for(var i = 0, len = this.keys.length; i < len; i++){
13102 if(this.keys[i] == key) return i;
13106 return this.keys.indexOf(key);
13111 * Returns the item associated with the passed key OR index. Key has priority over index.
13112 * @param {String/Number} key The key or index of the item.
13113 * @return {Object} The item associated with the passed key.
13115 item : function(key){
13116 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
13117 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
13121 * Returns the item at the specified index.
13122 * @param {Number} index The index of the item.
13125 itemAt : function(index){
13126 return this.items[index];
13130 * Returns the item associated with the passed key.
13131 * @param {String/Number} key The key of the item.
13132 * @return {Object} The item associated with the passed key.
13134 key : function(key){
13135 return this.map[key];
13139 * Returns true if the collection contains the passed Object as an item.
13140 * @param {Object} o The Object to look for in the collection.
13141 * @return {Boolean} True if the collection contains the Object as an item.
13143 contains : function(o){
13144 return this.indexOf(o) != -1;
13148 * Returns true if the collection contains the passed Object as a key.
13149 * @param {String} key The key to look for in the collection.
13150 * @return {Boolean} True if the collection contains the Object as a key.
13152 containsKey : function(key){
13153 return typeof this.map[key] != "undefined";
13157 * Removes all items from the collection.
13159 clear : function(){
13164 this.fireEvent("clear");
13168 * Returns the first item in the collection.
13169 * @return {Object} the first item in the collection..
13171 first : function(){
13172 return this.items[0];
13176 * Returns the last item in the collection.
13177 * @return {Object} the last item in the collection..
13180 return this.items[this.length-1];
13183 _sort : function(property, dir, fn){
13184 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
13185 fn = fn || function(a, b){
13188 var c = [], k = this.keys, items = this.items;
13189 for(var i = 0, len = items.length; i < len; i++){
13190 c[c.length] = {key: k[i], value: items[i], index: i};
13192 c.sort(function(a, b){
13193 var v = fn(a[property], b[property]) * dsc;
13195 v = (a.index < b.index ? -1 : 1);
13199 for(var i = 0, len = c.length; i < len; i++){
13200 items[i] = c[i].value;
13203 this.fireEvent("sort", this);
13207 * Sorts this collection with the passed comparison function
13208 * @param {String} direction (optional) "ASC" or "DESC"
13209 * @param {Function} fn (optional) comparison function
13211 sort : function(dir, fn){
13212 this._sort("value", dir, fn);
13216 * Sorts this collection by keys
13217 * @param {String} direction (optional) "ASC" or "DESC"
13218 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
13220 keySort : function(dir, fn){
13221 this._sort("key", dir, fn || function(a, b){
13222 return String(a).toUpperCase()-String(b).toUpperCase();
13227 * Returns a range of items in this collection
13228 * @param {Number} startIndex (optional) defaults to 0
13229 * @param {Number} endIndex (optional) default to the last item
13230 * @return {Array} An array of items
13232 getRange : function(start, end){
13233 var items = this.items;
13234 if(items.length < 1){
13237 start = start || 0;
13238 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
13241 for(var i = start; i <= end; i++) {
13242 r[r.length] = items[i];
13245 for(var i = start; i >= end; i--) {
13246 r[r.length] = items[i];
13253 * Filter the <i>objects</i> in this collection by a specific property.
13254 * Returns a new collection that has been filtered.
13255 * @param {String} property A property on your objects
13256 * @param {String/RegExp} value Either string that the property values
13257 * should start with or a RegExp to test against the property
13258 * @return {MixedCollection} The new filtered collection
13260 filter : function(property, value){
13261 if(!value.exec){ // not a regex
13262 value = String(value);
13263 if(value.length == 0){
13264 return this.clone();
13266 value = new RegExp("^" + Roo.escapeRe(value), "i");
13268 return this.filterBy(function(o){
13269 return o && value.test(o[property]);
13274 * Filter by a function. * Returns a new collection that has been filtered.
13275 * The passed function will be called with each
13276 * object in the collection. If the function returns true, the value is included
13277 * otherwise it is filtered.
13278 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
13279 * @param {Object} scope (optional) The scope of the function (defaults to this)
13280 * @return {MixedCollection} The new filtered collection
13282 filterBy : function(fn, scope){
13283 var r = new Roo.util.MixedCollection();
13284 r.getKey = this.getKey;
13285 var k = this.keys, it = this.items;
13286 for(var i = 0, len = it.length; i < len; i++){
13287 if(fn.call(scope||this, it[i], k[i])){
13288 r.add(k[i], it[i]);
13295 * Creates a duplicate of this collection
13296 * @return {MixedCollection}
13298 clone : function(){
13299 var r = new Roo.util.MixedCollection();
13300 var k = this.keys, it = this.items;
13301 for(var i = 0, len = it.length; i < len; i++){
13302 r.add(k[i], it[i]);
13304 r.getKey = this.getKey;
13309 * Returns the item associated with the passed key or index.
13311 * @param {String/Number} key The key or index of the item.
13312 * @return {Object} The item associated with the passed key.
13314 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
13316 * Ext JS Library 1.1.1
13317 * Copyright(c) 2006-2007, Ext JS, LLC.
13319 * Originally Released Under LGPL - original licence link has changed is not relivant.
13322 * <script type="text/javascript">
13325 * @class Roo.util.JSON
13326 * Modified version of Douglas Crockford"s json.js that doesn"t
13327 * mess with the Object prototype
13328 * http://www.json.org/js.html
13331 Roo.util.JSON = new (function(){
13332 var useHasOwn = {}.hasOwnProperty ? true : false;
13334 // crashes Safari in some instances
13335 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
13337 var pad = function(n) {
13338 return n < 10 ? "0" + n : n;
13351 var encodeString = function(s){
13352 if (/["\\\x00-\x1f]/.test(s)) {
13353 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
13358 c = b.charCodeAt();
13360 Math.floor(c / 16).toString(16) +
13361 (c % 16).toString(16);
13364 return '"' + s + '"';
13367 var encodeArray = function(o){
13368 var a = ["["], b, i, l = o.length, v;
13369 for (i = 0; i < l; i += 1) {
13371 switch (typeof v) {
13380 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
13388 var encodeDate = function(o){
13389 return '"' + o.getFullYear() + "-" +
13390 pad(o.getMonth() + 1) + "-" +
13391 pad(o.getDate()) + "T" +
13392 pad(o.getHours()) + ":" +
13393 pad(o.getMinutes()) + ":" +
13394 pad(o.getSeconds()) + '"';
13398 * Encodes an Object, Array or other value
13399 * @param {Mixed} o The variable to encode
13400 * @return {String} The JSON string
13402 this.encode = function(o)
13404 // should this be extended to fully wrap stringify..
13406 if(typeof o == "undefined" || o === null){
13408 }else if(o instanceof Array){
13409 return encodeArray(o);
13410 }else if(o instanceof Date){
13411 return encodeDate(o);
13412 }else if(typeof o == "string"){
13413 return encodeString(o);
13414 }else if(typeof o == "number"){
13415 return isFinite(o) ? String(o) : "null";
13416 }else if(typeof o == "boolean"){
13419 var a = ["{"], b, i, v;
13421 if(!useHasOwn || o.hasOwnProperty(i)) {
13423 switch (typeof v) {
13432 a.push(this.encode(i), ":",
13433 v === null ? "null" : this.encode(v));
13444 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
13445 * @param {String} json The JSON string
13446 * @return {Object} The resulting object
13448 this.decode = function(json){
13450 return /** eval:var:json */ eval("(" + json + ')');
13454 * Shorthand for {@link Roo.util.JSON#encode}
13455 * @member Roo encode
13457 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
13459 * Shorthand for {@link Roo.util.JSON#decode}
13460 * @member Roo decode
13462 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
13465 * Ext JS Library 1.1.1
13466 * Copyright(c) 2006-2007, Ext JS, LLC.
13468 * Originally Released Under LGPL - original licence link has changed is not relivant.
13471 * <script type="text/javascript">
13475 * @class Roo.util.Format
13476 * Reusable data formatting functions
13479 Roo.util.Format = function(){
13480 var trimRe = /^\s+|\s+$/g;
13483 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
13484 * @param {String} value The string to truncate
13485 * @param {Number} length The maximum length to allow before truncating
13486 * @return {String} The converted text
13488 ellipsis : function(value, len){
13489 if(value && value.length > len){
13490 return value.substr(0, len-3)+"...";
13496 * Checks a reference and converts it to empty string if it is undefined
13497 * @param {Mixed} value Reference to check
13498 * @return {Mixed} Empty string if converted, otherwise the original value
13500 undef : function(value){
13501 return typeof value != "undefined" ? value : "";
13505 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
13506 * @param {String} value The string to encode
13507 * @return {String} The encoded text
13509 htmlEncode : function(value){
13510 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
13514 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13515 * @param {String} value The string to decode
13516 * @return {String} The decoded text
13518 htmlDecode : function(value){
13519 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
13523 * Trims any whitespace from either side of a string
13524 * @param {String} value The text to trim
13525 * @return {String} The trimmed text
13527 trim : function(value){
13528 return String(value).replace(trimRe, "");
13532 * Returns a substring from within an original string
13533 * @param {String} value The original text
13534 * @param {Number} start The start index of the substring
13535 * @param {Number} length The length of the substring
13536 * @return {String} The substring
13538 substr : function(value, start, length){
13539 return String(value).substr(start, length);
13543 * Converts a string to all lower case letters
13544 * @param {String} value The text to convert
13545 * @return {String} The converted text
13547 lowercase : function(value){
13548 return String(value).toLowerCase();
13552 * Converts a string to all upper case letters
13553 * @param {String} value The text to convert
13554 * @return {String} The converted text
13556 uppercase : function(value){
13557 return String(value).toUpperCase();
13561 * Converts the first character only of a string to upper case
13562 * @param {String} value The text to convert
13563 * @return {String} The converted text
13565 capitalize : function(value){
13566 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13570 call : function(value, fn){
13571 if(arguments.length > 2){
13572 var args = Array.prototype.slice.call(arguments, 2);
13573 args.unshift(value);
13575 return /** eval:var:value */ eval(fn).apply(window, args);
13577 /** eval:var:value */
13578 return /** eval:var:value */ eval(fn).call(window, value);
13584 * safer version of Math.toFixed..??/
13585 * @param {Number/String} value The numeric value to format
13586 * @param {Number/String} value Decimal places
13587 * @return {String} The formatted currency string
13589 toFixed : function(v, n)
13591 // why not use to fixed - precision is buggered???
13593 return Math.round(v-0);
13595 var fact = Math.pow(10,n+1);
13596 v = (Math.round((v-0)*fact))/fact;
13597 var z = (''+fact).substring(2);
13598 if (v == Math.floor(v)) {
13599 return Math.floor(v) + '.' + z;
13602 // now just padd decimals..
13603 var ps = String(v).split('.');
13604 var fd = (ps[1] + z);
13605 var r = fd.substring(0,n);
13606 var rm = fd.substring(n);
13608 return ps[0] + '.' + r;
13610 r*=1; // turn it into a number;
13612 if (String(r).length != n) {
13615 r = String(r).substring(1); // chop the end off.
13618 return ps[0] + '.' + r;
13623 * Format a number as US currency
13624 * @param {Number/String} value The numeric value to format
13625 * @return {String} The formatted currency string
13627 usMoney : function(v){
13628 return '$' + Roo.util.Format.number(v);
13633 * eventually this should probably emulate php's number_format
13634 * @param {Number/String} value The numeric value to format
13635 * @param {Number} decimals number of decimal places
13636 * @return {String} The formatted currency string
13638 number : function(v,decimals)
13640 // multiply and round.
13641 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
13642 var mul = Math.pow(10, decimals);
13643 var zero = String(mul).substring(1);
13644 v = (Math.round((v-0)*mul))/mul;
13646 // if it's '0' number.. then
13648 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13650 var ps = v.split('.');
13654 var r = /(\d+)(\d{3})/;
13656 while (r.test(whole)) {
13657 whole = whole.replace(r, '$1' + ',' + '$2');
13663 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
13664 // does not have decimals
13665 (decimals ? ('.' + zero) : '');
13668 return whole + sub ;
13672 * Parse a value into a formatted date using the specified format pattern.
13673 * @param {Mixed} value The value to format
13674 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13675 * @return {String} The formatted date string
13677 date : function(v, format){
13681 if(!(v instanceof Date)){
13682 v = new Date(Date.parse(v));
13684 return v.dateFormat(format || Roo.util.Format.defaults.date);
13688 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13689 * @param {String} format Any valid date format string
13690 * @return {Function} The date formatting function
13692 dateRenderer : function(format){
13693 return function(v){
13694 return Roo.util.Format.date(v, format);
13699 stripTagsRE : /<\/?[^>]+>/gi,
13702 * Strips all HTML tags
13703 * @param {Mixed} value The text from which to strip tags
13704 * @return {String} The stripped text
13706 stripTags : function(v){
13707 return !v ? v : String(v).replace(this.stripTagsRE, "");
13711 Roo.util.Format.defaults = {
13715 * Ext JS Library 1.1.1
13716 * Copyright(c) 2006-2007, Ext JS, LLC.
13718 * Originally Released Under LGPL - original licence link has changed is not relivant.
13721 * <script type="text/javascript">
13728 * @class Roo.MasterTemplate
13729 * @extends Roo.Template
13730 * Provides a template that can have child templates. The syntax is:
13732 var t = new Roo.MasterTemplate(
13733 '<select name="{name}">',
13734 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13737 t.add('options', {value: 'foo', text: 'bar'});
13738 // or you can add multiple child elements in one shot
13739 t.addAll('options', [
13740 {value: 'foo', text: 'bar'},
13741 {value: 'foo2', text: 'bar2'},
13742 {value: 'foo3', text: 'bar3'}
13744 // then append, applying the master template values
13745 t.append('my-form', {name: 'my-select'});
13747 * A name attribute for the child template is not required if you have only one child
13748 * template or you want to refer to them by index.
13750 Roo.MasterTemplate = function(){
13751 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13752 this.originalHtml = this.html;
13754 var m, re = this.subTemplateRe;
13757 while(m = re.exec(this.html)){
13758 var name = m[1], content = m[2];
13763 tpl : new Roo.Template(content)
13766 st[name] = st[subIndex];
13768 st[subIndex].tpl.compile();
13769 st[subIndex].tpl.call = this.call.createDelegate(this);
13772 this.subCount = subIndex;
13775 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13777 * The regular expression used to match sub templates
13781 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13784 * Applies the passed values to a child template.
13785 * @param {String/Number} name (optional) The name or index of the child template
13786 * @param {Array/Object} values The values to be applied to the template
13787 * @return {MasterTemplate} this
13789 add : function(name, values){
13790 if(arguments.length == 1){
13791 values = arguments[0];
13794 var s = this.subs[name];
13795 s.buffer[s.buffer.length] = s.tpl.apply(values);
13800 * Applies all the passed values to a child template.
13801 * @param {String/Number} name (optional) The name or index of the child template
13802 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13803 * @param {Boolean} reset (optional) True to reset the template first
13804 * @return {MasterTemplate} this
13806 fill : function(name, values, reset){
13808 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13816 for(var i = 0, len = values.length; i < len; i++){
13817 this.add(name, values[i]);
13823 * Resets the template for reuse
13824 * @return {MasterTemplate} this
13826 reset : function(){
13828 for(var i = 0; i < this.subCount; i++){
13834 applyTemplate : function(values){
13836 var replaceIndex = -1;
13837 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13838 return s[++replaceIndex].buffer.join("");
13840 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13843 apply : function(){
13844 return this.applyTemplate.apply(this, arguments);
13847 compile : function(){return this;}
13851 * Alias for fill().
13854 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13856 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13857 * var tpl = Roo.MasterTemplate.from('element-id');
13858 * @param {String/HTMLElement} el
13859 * @param {Object} config
13862 Roo.MasterTemplate.from = function(el, config){
13863 el = Roo.getDom(el);
13864 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13867 * Ext JS Library 1.1.1
13868 * Copyright(c) 2006-2007, Ext JS, LLC.
13870 * Originally Released Under LGPL - original licence link has changed is not relivant.
13873 * <script type="text/javascript">
13878 * @class Roo.util.CSS
13879 * Utility class for manipulating CSS rules
13882 Roo.util.CSS = function(){
13884 var doc = document;
13886 var camelRe = /(-[a-z])/gi;
13887 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13891 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13892 * tag and appended to the HEAD of the document.
13893 * @param {String|Object} cssText The text containing the css rules
13894 * @param {String} id An id to add to the stylesheet for later removal
13895 * @return {StyleSheet}
13897 createStyleSheet : function(cssText, id){
13899 var head = doc.getElementsByTagName("head")[0];
13900 var nrules = doc.createElement("style");
13901 nrules.setAttribute("type", "text/css");
13903 nrules.setAttribute("id", id);
13905 if (typeof(cssText) != 'string') {
13906 // support object maps..
13907 // not sure if this a good idea..
13908 // perhaps it should be merged with the general css handling
13909 // and handle js style props.
13910 var cssTextNew = [];
13911 for(var n in cssText) {
13913 for(var k in cssText[n]) {
13914 citems.push( k + ' : ' +cssText[n][k] + ';' );
13916 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13919 cssText = cssTextNew.join("\n");
13925 head.appendChild(nrules);
13926 ss = nrules.styleSheet;
13927 ss.cssText = cssText;
13930 nrules.appendChild(doc.createTextNode(cssText));
13932 nrules.cssText = cssText;
13934 head.appendChild(nrules);
13935 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13937 this.cacheStyleSheet(ss);
13942 * Removes a style or link tag by id
13943 * @param {String} id The id of the tag
13945 removeStyleSheet : function(id){
13946 var existing = doc.getElementById(id);
13948 existing.parentNode.removeChild(existing);
13953 * Dynamically swaps an existing stylesheet reference for a new one
13954 * @param {String} id The id of an existing link tag to remove
13955 * @param {String} url The href of the new stylesheet to include
13957 swapStyleSheet : function(id, url){
13958 this.removeStyleSheet(id);
13959 var ss = doc.createElement("link");
13960 ss.setAttribute("rel", "stylesheet");
13961 ss.setAttribute("type", "text/css");
13962 ss.setAttribute("id", id);
13963 ss.setAttribute("href", url);
13964 doc.getElementsByTagName("head")[0].appendChild(ss);
13968 * Refresh the rule cache if you have dynamically added stylesheets
13969 * @return {Object} An object (hash) of rules indexed by selector
13971 refreshCache : function(){
13972 return this.getRules(true);
13976 cacheStyleSheet : function(stylesheet){
13980 try{// try catch for cross domain access issue
13981 var ssRules = stylesheet.cssRules || stylesheet.rules;
13982 for(var j = ssRules.length-1; j >= 0; --j){
13983 rules[ssRules[j].selectorText] = ssRules[j];
13989 * Gets all css rules for the document
13990 * @param {Boolean} refreshCache true to refresh the internal cache
13991 * @return {Object} An object (hash) of rules indexed by selector
13993 getRules : function(refreshCache){
13994 if(rules == null || refreshCache){
13996 var ds = doc.styleSheets;
13997 for(var i =0, len = ds.length; i < len; i++){
13999 this.cacheStyleSheet(ds[i]);
14007 * Gets an an individual CSS rule by selector(s)
14008 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
14009 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
14010 * @return {CSSRule} The CSS rule or null if one is not found
14012 getRule : function(selector, refreshCache){
14013 var rs = this.getRules(refreshCache);
14014 if(!(selector instanceof Array)){
14015 return rs[selector];
14017 for(var i = 0; i < selector.length; i++){
14018 if(rs[selector[i]]){
14019 return rs[selector[i]];
14027 * Updates a rule property
14028 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
14029 * @param {String} property The css property
14030 * @param {String} value The new value for the property
14031 * @return {Boolean} true If a rule was found and updated
14033 updateRule : function(selector, property, value){
14034 if(!(selector instanceof Array)){
14035 var rule = this.getRule(selector);
14037 rule.style[property.replace(camelRe, camelFn)] = value;
14041 for(var i = 0; i < selector.length; i++){
14042 if(this.updateRule(selector[i], property, value)){
14052 * Ext JS Library 1.1.1
14053 * Copyright(c) 2006-2007, Ext JS, LLC.
14055 * Originally Released Under LGPL - original licence link has changed is not relivant.
14058 * <script type="text/javascript">
14064 * @class Roo.util.ClickRepeater
14065 * @extends Roo.util.Observable
14067 * A wrapper class which can be applied to any element. Fires a "click" event while the
14068 * mouse is pressed. The interval between firings may be specified in the config but
14069 * defaults to 10 milliseconds.
14071 * Optionally, a CSS class may be applied to the element during the time it is pressed.
14073 * @cfg {String/HTMLElement/Element} el The element to act as a button.
14074 * @cfg {Number} delay The initial delay before the repeating event begins firing.
14075 * Similar to an autorepeat key delay.
14076 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
14077 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
14078 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
14079 * "interval" and "delay" are ignored. "immediate" is honored.
14080 * @cfg {Boolean} preventDefault True to prevent the default click event
14081 * @cfg {Boolean} stopDefault True to stop the default click event
14084 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
14085 * 2007-02-02 jvs Renamed to ClickRepeater
14086 * 2007-02-03 jvs Modifications for FF Mac and Safari
14089 * @param {String/HTMLElement/Element} el The element to listen on
14090 * @param {Object} config
14092 Roo.util.ClickRepeater = function(el, config)
14094 this.el = Roo.get(el);
14095 this.el.unselectable();
14097 Roo.apply(this, config);
14102 * Fires when the mouse button is depressed.
14103 * @param {Roo.util.ClickRepeater} this
14105 "mousedown" : true,
14108 * Fires on a specified interval during the time the element is pressed.
14109 * @param {Roo.util.ClickRepeater} this
14114 * Fires when the mouse key is released.
14115 * @param {Roo.util.ClickRepeater} this
14120 this.el.on("mousedown", this.handleMouseDown, this);
14121 if(this.preventDefault || this.stopDefault){
14122 this.el.on("click", function(e){
14123 if(this.preventDefault){
14124 e.preventDefault();
14126 if(this.stopDefault){
14132 // allow inline handler
14134 this.on("click", this.handler, this.scope || this);
14137 Roo.util.ClickRepeater.superclass.constructor.call(this);
14140 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
14143 preventDefault : true,
14144 stopDefault : false,
14148 handleMouseDown : function(){
14149 clearTimeout(this.timer);
14151 if(this.pressClass){
14152 this.el.addClass(this.pressClass);
14154 this.mousedownTime = new Date();
14156 Roo.get(document).on("mouseup", this.handleMouseUp, this);
14157 this.el.on("mouseout", this.handleMouseOut, this);
14159 this.fireEvent("mousedown", this);
14160 this.fireEvent("click", this);
14162 this.timer = this.click.defer(this.delay || this.interval, this);
14166 click : function(){
14167 this.fireEvent("click", this);
14168 this.timer = this.click.defer(this.getInterval(), this);
14172 getInterval: function(){
14173 if(!this.accelerate){
14174 return this.interval;
14176 var pressTime = this.mousedownTime.getElapsed();
14177 if(pressTime < 500){
14179 }else if(pressTime < 1700){
14181 }else if(pressTime < 2600){
14183 }else if(pressTime < 3500){
14185 }else if(pressTime < 4400){
14187 }else if(pressTime < 5300){
14189 }else if(pressTime < 6200){
14197 handleMouseOut : function(){
14198 clearTimeout(this.timer);
14199 if(this.pressClass){
14200 this.el.removeClass(this.pressClass);
14202 this.el.on("mouseover", this.handleMouseReturn, this);
14206 handleMouseReturn : function(){
14207 this.el.un("mouseover", this.handleMouseReturn);
14208 if(this.pressClass){
14209 this.el.addClass(this.pressClass);
14215 handleMouseUp : function(){
14216 clearTimeout(this.timer);
14217 this.el.un("mouseover", this.handleMouseReturn);
14218 this.el.un("mouseout", this.handleMouseOut);
14219 Roo.get(document).un("mouseup", this.handleMouseUp);
14220 this.el.removeClass(this.pressClass);
14221 this.fireEvent("mouseup", this);
14225 * Ext JS Library 1.1.1
14226 * Copyright(c) 2006-2007, Ext JS, LLC.
14228 * Originally Released Under LGPL - original licence link has changed is not relivant.
14231 * <script type="text/javascript">
14236 * @class Roo.KeyNav
14237 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
14238 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
14239 * way to implement custom navigation schemes for any UI component.</p>
14240 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
14241 * pageUp, pageDown, del, home, end. Usage:</p>
14243 var nav = new Roo.KeyNav("my-element", {
14244 "left" : function(e){
14245 this.moveLeft(e.ctrlKey);
14247 "right" : function(e){
14248 this.moveRight(e.ctrlKey);
14250 "enter" : function(e){
14257 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14258 * @param {Object} config The config
14260 Roo.KeyNav = function(el, config){
14261 this.el = Roo.get(el);
14262 Roo.apply(this, config);
14263 if(!this.disabled){
14264 this.disabled = true;
14269 Roo.KeyNav.prototype = {
14271 * @cfg {Boolean} disabled
14272 * True to disable this KeyNav instance (defaults to false)
14276 * @cfg {String} defaultEventAction
14277 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
14278 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
14279 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
14281 defaultEventAction: "stopEvent",
14283 * @cfg {Boolean} forceKeyDown
14284 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
14285 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
14286 * handle keydown instead of keypress.
14288 forceKeyDown : false,
14291 prepareEvent : function(e){
14292 var k = e.getKey();
14293 var h = this.keyToHandler[k];
14294 //if(h && this[h]){
14295 // e.stopPropagation();
14297 if(Roo.isSafari && h && k >= 37 && k <= 40){
14303 relay : function(e){
14304 var k = e.getKey();
14305 var h = this.keyToHandler[k];
14307 if(this.doRelay(e, this[h], h) !== true){
14308 e[this.defaultEventAction]();
14314 doRelay : function(e, h, hname){
14315 return h.call(this.scope || this, e);
14318 // possible handlers
14332 // quick lookup hash
14349 * Enable this KeyNav
14351 enable: function(){
14353 // ie won't do special keys on keypress, no one else will repeat keys with keydown
14354 // the EventObject will normalize Safari automatically
14355 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14356 this.el.on("keydown", this.relay, this);
14358 this.el.on("keydown", this.prepareEvent, this);
14359 this.el.on("keypress", this.relay, this);
14361 this.disabled = false;
14366 * Disable this KeyNav
14368 disable: function(){
14369 if(!this.disabled){
14370 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14371 this.el.un("keydown", this.relay);
14373 this.el.un("keydown", this.prepareEvent);
14374 this.el.un("keypress", this.relay);
14376 this.disabled = true;
14381 * Ext JS Library 1.1.1
14382 * Copyright(c) 2006-2007, Ext JS, LLC.
14384 * Originally Released Under LGPL - original licence link has changed is not relivant.
14387 * <script type="text/javascript">
14392 * @class Roo.KeyMap
14393 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
14394 * The constructor accepts the same config object as defined by {@link #addBinding}.
14395 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
14396 * combination it will call the function with this signature (if the match is a multi-key
14397 * combination the callback will still be called only once): (String key, Roo.EventObject e)
14398 * A KeyMap can also handle a string representation of keys.<br />
14401 // map one key by key code
14402 var map = new Roo.KeyMap("my-element", {
14403 key: 13, // or Roo.EventObject.ENTER
14408 // map multiple keys to one action by string
14409 var map = new Roo.KeyMap("my-element", {
14415 // map multiple keys to multiple actions by strings and array of codes
14416 var map = new Roo.KeyMap("my-element", [
14419 fn: function(){ alert("Return was pressed"); }
14422 fn: function(){ alert('a, b or c was pressed'); }
14427 fn: function(){ alert('Control + shift + tab was pressed.'); }
14431 * <b>Note: A KeyMap starts enabled</b>
14433 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14434 * @param {Object} config The config (see {@link #addBinding})
14435 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
14437 Roo.KeyMap = function(el, config, eventName){
14438 this.el = Roo.get(el);
14439 this.eventName = eventName || "keydown";
14440 this.bindings = [];
14442 this.addBinding(config);
14447 Roo.KeyMap.prototype = {
14449 * True to stop the event from bubbling and prevent the default browser action if the
14450 * key was handled by the KeyMap (defaults to false)
14456 * Add a new binding to this KeyMap. The following config object properties are supported:
14458 Property Type Description
14459 ---------- --------------- ----------------------------------------------------------------------
14460 key String/Array A single keycode or an array of keycodes to handle
14461 shift Boolean True to handle key only when shift is pressed (defaults to false)
14462 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
14463 alt Boolean True to handle key only when alt is pressed (defaults to false)
14464 fn Function The function to call when KeyMap finds the expected key combination
14465 scope Object The scope of the callback function
14471 var map = new Roo.KeyMap(document, {
14472 key: Roo.EventObject.ENTER,
14477 //Add a new binding to the existing KeyMap later
14485 * @param {Object/Array} config A single KeyMap config or an array of configs
14487 addBinding : function(config){
14488 if(config instanceof Array){
14489 for(var i = 0, len = config.length; i < len; i++){
14490 this.addBinding(config[i]);
14494 var keyCode = config.key,
14495 shift = config.shift,
14496 ctrl = config.ctrl,
14499 scope = config.scope;
14500 if(typeof keyCode == "string"){
14502 var keyString = keyCode.toUpperCase();
14503 for(var j = 0, len = keyString.length; j < len; j++){
14504 ks.push(keyString.charCodeAt(j));
14508 var keyArray = keyCode instanceof Array;
14509 var handler = function(e){
14510 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14511 var k = e.getKey();
14513 for(var i = 0, len = keyCode.length; i < len; i++){
14514 if(keyCode[i] == k){
14515 if(this.stopEvent){
14518 fn.call(scope || window, k, e);
14524 if(this.stopEvent){
14527 fn.call(scope || window, k, e);
14532 this.bindings.push(handler);
14536 * Shorthand for adding a single key listener
14537 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
14538 * following options:
14539 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14540 * @param {Function} fn The function to call
14541 * @param {Object} scope (optional) The scope of the function
14543 on : function(key, fn, scope){
14544 var keyCode, shift, ctrl, alt;
14545 if(typeof key == "object" && !(key instanceof Array)){
14564 handleKeyDown : function(e){
14565 if(this.enabled){ //just in case
14566 var b = this.bindings;
14567 for(var i = 0, len = b.length; i < len; i++){
14568 b[i].call(this, e);
14574 * Returns true if this KeyMap is enabled
14575 * @return {Boolean}
14577 isEnabled : function(){
14578 return this.enabled;
14582 * Enables this KeyMap
14584 enable: function(){
14586 this.el.on(this.eventName, this.handleKeyDown, this);
14587 this.enabled = true;
14592 * Disable this KeyMap
14594 disable: function(){
14596 this.el.removeListener(this.eventName, this.handleKeyDown, this);
14597 this.enabled = false;
14602 * Ext JS Library 1.1.1
14603 * Copyright(c) 2006-2007, Ext JS, LLC.
14605 * Originally Released Under LGPL - original licence link has changed is not relivant.
14608 * <script type="text/javascript">
14613 * @class Roo.util.TextMetrics
14614 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14615 * wide, in pixels, a given block of text will be.
14618 Roo.util.TextMetrics = function(){
14622 * Measures the size of the specified text
14623 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14624 * that can affect the size of the rendered text
14625 * @param {String} text The text to measure
14626 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14627 * in order to accurately measure the text height
14628 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14630 measure : function(el, text, fixedWidth){
14632 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14635 shared.setFixedWidth(fixedWidth || 'auto');
14636 return shared.getSize(text);
14640 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
14641 * the overhead of multiple calls to initialize the style properties on each measurement.
14642 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14643 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14644 * in order to accurately measure the text height
14645 * @return {Roo.util.TextMetrics.Instance} instance The new instance
14647 createInstance : function(el, fixedWidth){
14648 return Roo.util.TextMetrics.Instance(el, fixedWidth);
14655 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14656 var ml = new Roo.Element(document.createElement('div'));
14657 document.body.appendChild(ml.dom);
14658 ml.position('absolute');
14659 ml.setLeftTop(-1000, -1000);
14663 ml.setWidth(fixedWidth);
14668 * Returns the size of the specified text based on the internal element's style and width properties
14669 * @memberOf Roo.util.TextMetrics.Instance#
14670 * @param {String} text The text to measure
14671 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14673 getSize : function(text){
14675 var s = ml.getSize();
14681 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14682 * that can affect the size of the rendered text
14683 * @memberOf Roo.util.TextMetrics.Instance#
14684 * @param {String/HTMLElement} el The element, dom node or id
14686 bind : function(el){
14688 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14693 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
14694 * to set a fixed width in order to accurately measure the text height.
14695 * @memberOf Roo.util.TextMetrics.Instance#
14696 * @param {Number} width The width to set on the element
14698 setFixedWidth : function(width){
14699 ml.setWidth(width);
14703 * Returns the measured width of the specified text
14704 * @memberOf Roo.util.TextMetrics.Instance#
14705 * @param {String} text The text to measure
14706 * @return {Number} width The width in pixels
14708 getWidth : function(text){
14709 ml.dom.style.width = 'auto';
14710 return this.getSize(text).width;
14714 * Returns the measured height of the specified text. For multiline text, be sure to call
14715 * {@link #setFixedWidth} if necessary.
14716 * @memberOf Roo.util.TextMetrics.Instance#
14717 * @param {String} text The text to measure
14718 * @return {Number} height The height in pixels
14720 getHeight : function(text){
14721 return this.getSize(text).height;
14725 instance.bind(bindTo);
14730 // backwards compat
14731 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14733 * Ext JS Library 1.1.1
14734 * Copyright(c) 2006-2007, Ext JS, LLC.
14736 * Originally Released Under LGPL - original licence link has changed is not relivant.
14739 * <script type="text/javascript">
14743 * @class Roo.state.Provider
14744 * Abstract base class for state provider implementations. This class provides methods
14745 * for encoding and decoding <b>typed</b> variables including dates and defines the
14746 * Provider interface.
14748 Roo.state.Provider = function(){
14750 * @event statechange
14751 * Fires when a state change occurs.
14752 * @param {Provider} this This state provider
14753 * @param {String} key The state key which was changed
14754 * @param {String} value The encoded value for the state
14757 "statechange": true
14760 Roo.state.Provider.superclass.constructor.call(this);
14762 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14764 * Returns the current value for a key
14765 * @param {String} name The key name
14766 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14767 * @return {Mixed} The state data
14769 get : function(name, defaultValue){
14770 return typeof this.state[name] == "undefined" ?
14771 defaultValue : this.state[name];
14775 * Clears a value from the state
14776 * @param {String} name The key name
14778 clear : function(name){
14779 delete this.state[name];
14780 this.fireEvent("statechange", this, name, null);
14784 * Sets the value for a key
14785 * @param {String} name The key name
14786 * @param {Mixed} value The value to set
14788 set : function(name, value){
14789 this.state[name] = value;
14790 this.fireEvent("statechange", this, name, value);
14794 * Decodes a string previously encoded with {@link #encodeValue}.
14795 * @param {String} value The value to decode
14796 * @return {Mixed} The decoded value
14798 decodeValue : function(cookie){
14799 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14800 var matches = re.exec(unescape(cookie));
14801 if(!matches || !matches[1]) return; // non state cookie
14802 var type = matches[1];
14803 var v = matches[2];
14806 return parseFloat(v);
14808 return new Date(Date.parse(v));
14813 var values = v.split("^");
14814 for(var i = 0, len = values.length; i < len; i++){
14815 all.push(this.decodeValue(values[i]));
14820 var values = v.split("^");
14821 for(var i = 0, len = values.length; i < len; i++){
14822 var kv = values[i].split("=");
14823 all[kv[0]] = this.decodeValue(kv[1]);
14832 * Encodes a value including type information. Decode with {@link #decodeValue}.
14833 * @param {Mixed} value The value to encode
14834 * @return {String} The encoded value
14836 encodeValue : function(v){
14838 if(typeof v == "number"){
14840 }else if(typeof v == "boolean"){
14841 enc = "b:" + (v ? "1" : "0");
14842 }else if(v instanceof Date){
14843 enc = "d:" + v.toGMTString();
14844 }else if(v instanceof Array){
14846 for(var i = 0, len = v.length; i < len; i++){
14847 flat += this.encodeValue(v[i]);
14848 if(i != len-1) flat += "^";
14851 }else if(typeof v == "object"){
14854 if(typeof v[key] != "function"){
14855 flat += key + "=" + this.encodeValue(v[key]) + "^";
14858 enc = "o:" + flat.substring(0, flat.length-1);
14862 return escape(enc);
14868 * Ext JS Library 1.1.1
14869 * Copyright(c) 2006-2007, Ext JS, LLC.
14871 * Originally Released Under LGPL - original licence link has changed is not relivant.
14874 * <script type="text/javascript">
14877 * @class Roo.state.Manager
14878 * This is the global state manager. By default all components that are "state aware" check this class
14879 * for state information if you don't pass them a custom state provider. In order for this class
14880 * to be useful, it must be initialized with a provider when your application initializes.
14882 // in your initialization function
14884 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14886 // supposed you have a {@link Roo.BorderLayout}
14887 var layout = new Roo.BorderLayout(...);
14888 layout.restoreState();
14889 // or a {Roo.BasicDialog}
14890 var dialog = new Roo.BasicDialog(...);
14891 dialog.restoreState();
14895 Roo.state.Manager = function(){
14896 var provider = new Roo.state.Provider();
14900 * Configures the default state provider for your application
14901 * @param {Provider} stateProvider The state provider to set
14903 setProvider : function(stateProvider){
14904 provider = stateProvider;
14908 * Returns the current value for a key
14909 * @param {String} name The key name
14910 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14911 * @return {Mixed} The state data
14913 get : function(key, defaultValue){
14914 return provider.get(key, defaultValue);
14918 * Sets the value for a key
14919 * @param {String} name The key name
14920 * @param {Mixed} value The state data
14922 set : function(key, value){
14923 provider.set(key, value);
14927 * Clears a value from the state
14928 * @param {String} name The key name
14930 clear : function(key){
14931 provider.clear(key);
14935 * Gets the currently configured state provider
14936 * @return {Provider} The state provider
14938 getProvider : function(){
14945 * Ext JS Library 1.1.1
14946 * Copyright(c) 2006-2007, Ext JS, LLC.
14948 * Originally Released Under LGPL - original licence link has changed is not relivant.
14951 * <script type="text/javascript">
14954 * @class Roo.state.CookieProvider
14955 * @extends Roo.state.Provider
14956 * The default Provider implementation which saves state via cookies.
14959 var cp = new Roo.state.CookieProvider({
14961 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14962 domain: "roojs.com"
14964 Roo.state.Manager.setProvider(cp);
14966 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14967 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14968 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14969 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14970 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14971 * domain the page is running on including the 'www' like 'www.roojs.com')
14972 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14974 * Create a new CookieProvider
14975 * @param {Object} config The configuration object
14977 Roo.state.CookieProvider = function(config){
14978 Roo.state.CookieProvider.superclass.constructor.call(this);
14980 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14981 this.domain = null;
14982 this.secure = false;
14983 Roo.apply(this, config);
14984 this.state = this.readCookies();
14987 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14989 set : function(name, value){
14990 if(typeof value == "undefined" || value === null){
14994 this.setCookie(name, value);
14995 Roo.state.CookieProvider.superclass.set.call(this, name, value);
14999 clear : function(name){
15000 this.clearCookie(name);
15001 Roo.state.CookieProvider.superclass.clear.call(this, name);
15005 readCookies : function(){
15007 var c = document.cookie + ";";
15008 var re = /\s?(.*?)=(.*?);/g;
15010 while((matches = re.exec(c)) != null){
15011 var name = matches[1];
15012 var value = matches[2];
15013 if(name && name.substring(0,3) == "ys-"){
15014 cookies[name.substr(3)] = this.decodeValue(value);
15021 setCookie : function(name, value){
15022 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
15023 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
15024 ((this.path == null) ? "" : ("; path=" + this.path)) +
15025 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15026 ((this.secure == true) ? "; secure" : "");
15030 clearCookie : function(name){
15031 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
15032 ((this.path == null) ? "" : ("; path=" + this.path)) +
15033 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15034 ((this.secure == true) ? "; secure" : "");
15038 * Ext JS Library 1.1.1
15039 * Copyright(c) 2006-2007, Ext JS, LLC.
15041 * Originally Released Under LGPL - original licence link has changed is not relivant.
15044 * <script type="text/javascript">
15049 * @class Roo.ComponentMgr
15050 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
15053 Roo.ComponentMgr = function(){
15054 var all = new Roo.util.MixedCollection();
15058 * Registers a component.
15059 * @param {Roo.Component} c The component
15061 register : function(c){
15066 * Unregisters a component.
15067 * @param {Roo.Component} c The component
15069 unregister : function(c){
15074 * Returns a component by id
15075 * @param {String} id The component id
15077 get : function(id){
15078 return all.get(id);
15082 * Registers a function that will be called when a specified component is added to ComponentMgr
15083 * @param {String} id The component id
15084 * @param {Funtction} fn The callback function
15085 * @param {Object} scope The scope of the callback
15087 onAvailable : function(id, fn, scope){
15088 all.on("add", function(index, o){
15090 fn.call(scope || o, o);
15091 all.un("add", fn, scope);
15098 * Ext JS Library 1.1.1
15099 * Copyright(c) 2006-2007, Ext JS, LLC.
15101 * Originally Released Under LGPL - original licence link has changed is not relivant.
15104 * <script type="text/javascript">
15108 * @class Roo.Component
15109 * @extends Roo.util.Observable
15110 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
15111 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
15112 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
15113 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
15114 * All visual components (widgets) that require rendering into a layout should subclass Component.
15116 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
15117 * 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
15118 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
15120 Roo.Component = function(config){
15121 config = config || {};
15122 if(config.tagName || config.dom || typeof config == "string"){ // element object
15123 config = {el: config, id: config.id || config};
15125 this.initialConfig = config;
15127 Roo.apply(this, config);
15131 * Fires after the component is disabled.
15132 * @param {Roo.Component} this
15137 * Fires after the component is enabled.
15138 * @param {Roo.Component} this
15142 * @event beforeshow
15143 * Fires before the component is shown. Return false to stop the show.
15144 * @param {Roo.Component} this
15149 * Fires after the component is shown.
15150 * @param {Roo.Component} this
15154 * @event beforehide
15155 * Fires before the component is hidden. Return false to stop the hide.
15156 * @param {Roo.Component} this
15161 * Fires after the component is hidden.
15162 * @param {Roo.Component} this
15166 * @event beforerender
15167 * Fires before the component is rendered. Return false to stop the render.
15168 * @param {Roo.Component} this
15170 beforerender : true,
15173 * Fires after the component is rendered.
15174 * @param {Roo.Component} this
15178 * @event beforedestroy
15179 * Fires before the component is destroyed. Return false to stop the destroy.
15180 * @param {Roo.Component} this
15182 beforedestroy : true,
15185 * Fires after the component is destroyed.
15186 * @param {Roo.Component} this
15191 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
15193 Roo.ComponentMgr.register(this);
15194 Roo.Component.superclass.constructor.call(this);
15195 this.initComponent();
15196 if(this.renderTo){ // not supported by all components yet. use at your own risk!
15197 this.render(this.renderTo);
15198 delete this.renderTo;
15203 Roo.Component.AUTO_ID = 1000;
15205 Roo.extend(Roo.Component, Roo.util.Observable, {
15207 * @scope Roo.Component.prototype
15209 * true if this component is hidden. Read-only.
15214 * true if this component is disabled. Read-only.
15219 * true if this component has been rendered. Read-only.
15223 /** @cfg {String} disableClass
15224 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
15226 disabledClass : "x-item-disabled",
15227 /** @cfg {Boolean} allowDomMove
15228 * Whether the component can move the Dom node when rendering (defaults to true).
15230 allowDomMove : true,
15231 /** @cfg {String} hideMode (display|visibility)
15232 * How this component should hidden. Supported values are
15233 * "visibility" (css visibility), "offsets" (negative offset position) and
15234 * "display" (css display) - defaults to "display".
15236 hideMode: 'display',
15239 ctype : "Roo.Component",
15242 * @cfg {String} actionMode
15243 * which property holds the element that used for hide() / show() / disable() / enable()
15249 getActionEl : function(){
15250 return this[this.actionMode];
15253 initComponent : Roo.emptyFn,
15255 * If this is a lazy rendering component, render it to its container element.
15256 * @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.
15258 render : function(container, position){
15259 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
15260 if(!container && this.el){
15261 this.el = Roo.get(this.el);
15262 container = this.el.dom.parentNode;
15263 this.allowDomMove = false;
15265 this.container = Roo.get(container);
15266 this.rendered = true;
15267 if(position !== undefined){
15268 if(typeof position == 'number'){
15269 position = this.container.dom.childNodes[position];
15271 position = Roo.getDom(position);
15274 this.onRender(this.container, position || null);
15276 this.el.addClass(this.cls);
15280 this.el.applyStyles(this.style);
15283 this.fireEvent("render", this);
15284 this.afterRender(this.container);
15296 // default function is not really useful
15297 onRender : function(ct, position){
15299 this.el = Roo.get(this.el);
15300 if(this.allowDomMove !== false){
15301 ct.dom.insertBefore(this.el.dom, position);
15307 getAutoCreate : function(){
15308 var cfg = typeof this.autoCreate == "object" ?
15309 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
15310 if(this.id && !cfg.id){
15317 afterRender : Roo.emptyFn,
15320 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
15321 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
15323 destroy : function(){
15324 if(this.fireEvent("beforedestroy", this) !== false){
15325 this.purgeListeners();
15326 this.beforeDestroy();
15328 this.el.removeAllListeners();
15330 if(this.actionMode == "container"){
15331 this.container.remove();
15335 Roo.ComponentMgr.unregister(this);
15336 this.fireEvent("destroy", this);
15341 beforeDestroy : function(){
15346 onDestroy : function(){
15351 * Returns the underlying {@link Roo.Element}.
15352 * @return {Roo.Element} The element
15354 getEl : function(){
15359 * Returns the id of this component.
15362 getId : function(){
15367 * Try to focus this component.
15368 * @param {Boolean} selectText True to also select the text in this component (if applicable)
15369 * @return {Roo.Component} this
15371 focus : function(selectText){
15374 if(selectText === true){
15375 this.el.dom.select();
15390 * Disable this component.
15391 * @return {Roo.Component} this
15393 disable : function(){
15397 this.disabled = true;
15398 this.fireEvent("disable", this);
15403 onDisable : function(){
15404 this.getActionEl().addClass(this.disabledClass);
15405 this.el.dom.disabled = true;
15409 * Enable this component.
15410 * @return {Roo.Component} this
15412 enable : function(){
15416 this.disabled = false;
15417 this.fireEvent("enable", this);
15422 onEnable : function(){
15423 this.getActionEl().removeClass(this.disabledClass);
15424 this.el.dom.disabled = false;
15428 * Convenience function for setting disabled/enabled by boolean.
15429 * @param {Boolean} disabled
15431 setDisabled : function(disabled){
15432 this[disabled ? "disable" : "enable"]();
15436 * Show this component.
15437 * @return {Roo.Component} this
15440 if(this.fireEvent("beforeshow", this) !== false){
15441 this.hidden = false;
15445 this.fireEvent("show", this);
15451 onShow : function(){
15452 var ae = this.getActionEl();
15453 if(this.hideMode == 'visibility'){
15454 ae.dom.style.visibility = "visible";
15455 }else if(this.hideMode == 'offsets'){
15456 ae.removeClass('x-hidden');
15458 ae.dom.style.display = "";
15463 * Hide this component.
15464 * @return {Roo.Component} this
15467 if(this.fireEvent("beforehide", this) !== false){
15468 this.hidden = true;
15472 this.fireEvent("hide", this);
15478 onHide : function(){
15479 var ae = this.getActionEl();
15480 if(this.hideMode == 'visibility'){
15481 ae.dom.style.visibility = "hidden";
15482 }else if(this.hideMode == 'offsets'){
15483 ae.addClass('x-hidden');
15485 ae.dom.style.display = "none";
15490 * Convenience function to hide or show this component by boolean.
15491 * @param {Boolean} visible True to show, false to hide
15492 * @return {Roo.Component} this
15494 setVisible: function(visible){
15504 * Returns true if this component is visible.
15506 isVisible : function(){
15507 return this.getActionEl().isVisible();
15510 cloneConfig : function(overrides){
15511 overrides = overrides || {};
15512 var id = overrides.id || Roo.id();
15513 var cfg = Roo.applyIf(overrides, this.initialConfig);
15514 cfg.id = id; // prevent dup id
15515 return new this.constructor(cfg);
15519 * Ext JS Library 1.1.1
15520 * Copyright(c) 2006-2007, Ext JS, LLC.
15522 * Originally Released Under LGPL - original licence link has changed is not relivant.
15525 * <script type="text/javascript">
15529 * @class Roo.BoxComponent
15530 * @extends Roo.Component
15531 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
15532 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
15533 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
15534 * layout containers.
15536 * @param {Roo.Element/String/Object} config The configuration options.
15538 Roo.BoxComponent = function(config){
15539 Roo.Component.call(this, config);
15543 * Fires after the component is resized.
15544 * @param {Roo.Component} this
15545 * @param {Number} adjWidth The box-adjusted width that was set
15546 * @param {Number} adjHeight The box-adjusted height that was set
15547 * @param {Number} rawWidth The width that was originally specified
15548 * @param {Number} rawHeight The height that was originally specified
15553 * Fires after the component is moved.
15554 * @param {Roo.Component} this
15555 * @param {Number} x The new x position
15556 * @param {Number} y The new y position
15562 Roo.extend(Roo.BoxComponent, Roo.Component, {
15563 // private, set in afterRender to signify that the component has been rendered
15565 // private, used to defer height settings to subclasses
15566 deferHeight: false,
15567 /** @cfg {Number} width
15568 * width (optional) size of component
15570 /** @cfg {Number} height
15571 * height (optional) size of component
15575 * Sets the width and height of the component. This method fires the resize event. This method can accept
15576 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
15577 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
15578 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
15579 * @return {Roo.BoxComponent} this
15581 setSize : function(w, h){
15582 // support for standard size objects
15583 if(typeof w == 'object'){
15588 if(!this.boxReady){
15594 // prevent recalcs when not needed
15595 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
15598 this.lastSize = {width: w, height: h};
15600 var adj = this.adjustSize(w, h);
15601 var aw = adj.width, ah = adj.height;
15602 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
15603 var rz = this.getResizeEl();
15604 if(!this.deferHeight && aw !== undefined && ah !== undefined){
15605 rz.setSize(aw, ah);
15606 }else if(!this.deferHeight && ah !== undefined){
15608 }else if(aw !== undefined){
15611 this.onResize(aw, ah, w, h);
15612 this.fireEvent('resize', this, aw, ah, w, h);
15618 * Gets the current size of the component's underlying element.
15619 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
15621 getSize : function(){
15622 return this.el.getSize();
15626 * Gets the current XY position of the component's underlying element.
15627 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15628 * @return {Array} The XY position of the element (e.g., [100, 200])
15630 getPosition : function(local){
15631 if(local === true){
15632 return [this.el.getLeft(true), this.el.getTop(true)];
15634 return this.xy || this.el.getXY();
15638 * Gets the current box measurements of the component's underlying element.
15639 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15640 * @returns {Object} box An object in the format {x, y, width, height}
15642 getBox : function(local){
15643 var s = this.el.getSize();
15645 s.x = this.el.getLeft(true);
15646 s.y = this.el.getTop(true);
15648 var xy = this.xy || this.el.getXY();
15656 * Sets the current box measurements of the component's underlying element.
15657 * @param {Object} box An object in the format {x, y, width, height}
15658 * @returns {Roo.BoxComponent} this
15660 updateBox : function(box){
15661 this.setSize(box.width, box.height);
15662 this.setPagePosition(box.x, box.y);
15667 getResizeEl : function(){
15668 return this.resizeEl || this.el;
15672 getPositionEl : function(){
15673 return this.positionEl || this.el;
15677 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
15678 * This method fires the move event.
15679 * @param {Number} left The new left
15680 * @param {Number} top The new top
15681 * @returns {Roo.BoxComponent} this
15683 setPosition : function(x, y){
15686 if(!this.boxReady){
15689 var adj = this.adjustPosition(x, y);
15690 var ax = adj.x, ay = adj.y;
15692 var el = this.getPositionEl();
15693 if(ax !== undefined || ay !== undefined){
15694 if(ax !== undefined && ay !== undefined){
15695 el.setLeftTop(ax, ay);
15696 }else if(ax !== undefined){
15698 }else if(ay !== undefined){
15701 this.onPosition(ax, ay);
15702 this.fireEvent('move', this, ax, ay);
15708 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
15709 * This method fires the move event.
15710 * @param {Number} x The new x position
15711 * @param {Number} y The new y position
15712 * @returns {Roo.BoxComponent} this
15714 setPagePosition : function(x, y){
15717 if(!this.boxReady){
15720 if(x === undefined || y === undefined){ // cannot translate undefined points
15723 var p = this.el.translatePoints(x, y);
15724 this.setPosition(p.left, p.top);
15729 onRender : function(ct, position){
15730 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
15732 this.resizeEl = Roo.get(this.resizeEl);
15734 if(this.positionEl){
15735 this.positionEl = Roo.get(this.positionEl);
15740 afterRender : function(){
15741 Roo.BoxComponent.superclass.afterRender.call(this);
15742 this.boxReady = true;
15743 this.setSize(this.width, this.height);
15744 if(this.x || this.y){
15745 this.setPosition(this.x, this.y);
15747 if(this.pageX || this.pageY){
15748 this.setPagePosition(this.pageX, this.pageY);
15753 * Force the component's size to recalculate based on the underlying element's current height and width.
15754 * @returns {Roo.BoxComponent} this
15756 syncSize : function(){
15757 delete this.lastSize;
15758 this.setSize(this.el.getWidth(), this.el.getHeight());
15763 * Called after the component is resized, this method is empty by default but can be implemented by any
15764 * subclass that needs to perform custom logic after a resize occurs.
15765 * @param {Number} adjWidth The box-adjusted width that was set
15766 * @param {Number} adjHeight The box-adjusted height that was set
15767 * @param {Number} rawWidth The width that was originally specified
15768 * @param {Number} rawHeight The height that was originally specified
15770 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
15775 * Called after the component is moved, this method is empty by default but can be implemented by any
15776 * subclass that needs to perform custom logic after a move occurs.
15777 * @param {Number} x The new x position
15778 * @param {Number} y The new y position
15780 onPosition : function(x, y){
15785 adjustSize : function(w, h){
15786 if(this.autoWidth){
15789 if(this.autoHeight){
15792 return {width : w, height: h};
15796 adjustPosition : function(x, y){
15797 return {x : x, y: y};
15800 * Original code for Roojs - LGPL
15801 * <script type="text/javascript">
15805 * @class Roo.XComponent
15806 * A delayed Element creator...
15807 * Or a way to group chunks of interface together.
15808 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
15809 * used in conjunction with XComponent.build() it will create an instance of each element,
15810 * then call addxtype() to build the User interface.
15812 * Mypart.xyx = new Roo.XComponent({
15814 parent : 'Mypart.xyz', // empty == document.element.!!
15818 disabled : function() {}
15820 tree : function() { // return an tree of xtype declared components
15824 xtype : 'NestedLayoutPanel',
15831 * It can be used to build a big heiracy, with parent etc.
15832 * or you can just use this to render a single compoent to a dom element
15833 * MYPART.render(Roo.Element | String(id) | dom_element )
15840 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
15841 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
15843 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
15845 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
15846 * - if mulitple topModules exist, the last one is defined as the top module.
15850 * When the top level or multiple modules are to embedded into a existing HTML page,
15851 * the parent element can container '#id' of the element where the module will be drawn.
15855 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
15856 * it relies more on a include mechanism, where sub modules are included into an outer page.
15857 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
15859 * Bootstrap Roo Included elements
15861 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
15862 * hence confusing the component builder as it thinks there are multiple top level elements.
15866 * @extends Roo.util.Observable
15868 * @param cfg {Object} configuration of component
15871 Roo.XComponent = function(cfg) {
15872 Roo.apply(this, cfg);
15876 * Fires when this the componnt is built
15877 * @param {Roo.XComponent} c the component
15882 this.region = this.region || 'center'; // default..
15883 Roo.XComponent.register(this);
15884 this.modules = false;
15885 this.el = false; // where the layout goes..
15889 Roo.extend(Roo.XComponent, Roo.util.Observable, {
15892 * The created element (with Roo.factory())
15893 * @type {Roo.Layout}
15899 * for BC - use el in new code
15900 * @type {Roo.Layout}
15906 * for BC - use el in new code
15907 * @type {Roo.Layout}
15912 * @cfg {Function|boolean} disabled
15913 * If this module is disabled by some rule, return true from the funtion
15918 * @cfg {String} parent
15919 * Name of parent element which it get xtype added to..
15924 * @cfg {String} order
15925 * Used to set the order in which elements are created (usefull for multiple tabs)
15930 * @cfg {String} name
15931 * String to display while loading.
15935 * @cfg {String} region
15936 * Region to render component to (defaults to center)
15941 * @cfg {Array} items
15942 * A single item array - the first element is the root of the tree..
15943 * It's done this way to stay compatible with the Xtype system...
15949 * The method that retuns the tree of parts that make up this compoennt
15956 * render element to dom or tree
15957 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
15960 render : function(el)
15964 var hp = this.parent ? 1 : 0;
15965 Roo.debug && Roo.log(this);
15967 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
15968 // if parent is a '#.....' string, then let's use that..
15969 var ename = this.parent.substr(1);
15970 this.parent = false;
15971 Roo.debug && Roo.log(ename);
15973 case 'bootstrap-body' :
15974 if (typeof(Roo.bootstrap.Body) != 'undefined') {
15975 this.parent = { el : new Roo.bootstrap.Body() };
15976 Roo.debug && Roo.log("setting el to doc body");
15979 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
15983 this.parent = { el : true};
15986 el = Roo.get(ename);
15991 if (!el && !this.parent) {
15992 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
15996 Roo.debug && Roo.log("EL:");
15997 Roo.debug && Roo.log(el);
15998 Roo.debug && Roo.log("this.parent.el:");
15999 Roo.debug && Roo.log(this.parent.el);
16001 var tree = this._tree ? this._tree() : this.tree();
16003 // altertive root elements ??? - we need a better way to indicate these.
16004 var is_alt = (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
16005 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
16007 if (!this.parent && is_alt) {
16008 //el = Roo.get(document.body);
16009 this.parent = { el : true };
16014 if (!this.parent) {
16016 Roo.debug && Roo.log("no parent - creating one");
16018 el = el ? Roo.get(el) : false;
16020 // it's a top level one..
16022 el : new Roo.BorderLayout(el || document.body, {
16028 tabPosition: 'top',
16029 //resizeTabs: true,
16030 alwaysShowTabs: el && hp? false : true,
16031 hideTabs: el || !hp ? true : false,
16038 if (!this.parent.el) {
16039 // probably an old style ctor, which has been disabled.
16043 // The 'tree' method is '_tree now'
16045 tree.region = tree.region || this.region;
16047 if (this.parent.el === true) {
16048 // bootstrap... - body..
16049 this.parent.el = Roo.factory(tree);
16052 this.el = this.parent.el.addxtype(tree);
16053 this.fireEvent('built', this);
16055 this.panel = this.el;
16056 this.layout = this.panel.layout;
16057 this.parentLayout = this.parent.layout || false;
16063 Roo.apply(Roo.XComponent, {
16065 * @property hideProgress
16066 * true to disable the building progress bar.. usefull on single page renders.
16069 hideProgress : false,
16071 * @property buildCompleted
16072 * True when the builder has completed building the interface.
16075 buildCompleted : false,
16078 * @property topModule
16079 * the upper most module - uses document.element as it's constructor.
16086 * @property modules
16087 * array of modules to be created by registration system.
16088 * @type {Array} of Roo.XComponent
16093 * @property elmodules
16094 * array of modules to be created by which use #ID
16095 * @type {Array} of Roo.XComponent
16101 * @property build_from_html
16102 * Build elements from html - used by bootstrap HTML stuff
16103 * - this is cleared after build is completed
16104 * @type {boolean} true (default false)
16107 build_from_html : false,
16110 * Register components to be built later.
16112 * This solves the following issues
16113 * - Building is not done on page load, but after an authentication process has occured.
16114 * - Interface elements are registered on page load
16115 * - Parent Interface elements may not be loaded before child, so this handles that..
16122 module : 'Pman.Tab.projectMgr',
16124 parent : 'Pman.layout',
16125 disabled : false, // or use a function..
16128 * * @param {Object} details about module
16130 register : function(obj) {
16132 Roo.XComponent.event.fireEvent('register', obj);
16133 switch(typeof(obj.disabled) ) {
16139 if ( obj.disabled() ) {
16145 if (obj.disabled) {
16151 this.modules.push(obj);
16155 * convert a string to an object..
16156 * eg. 'AAA.BBB' -> finds AAA.BBB
16160 toObject : function(str)
16162 if (!str || typeof(str) == 'object') {
16165 if (str.substring(0,1) == '#') {
16169 var ar = str.split('.');
16174 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
16176 throw "Module not found : " + str;
16180 throw "Module not found : " + str;
16182 Roo.each(ar, function(e) {
16183 if (typeof(o[e]) == 'undefined') {
16184 throw "Module not found : " + str;
16195 * move modules into their correct place in the tree..
16198 preBuild : function ()
16201 Roo.each(this.modules , function (obj)
16203 Roo.XComponent.event.fireEvent('beforebuild', obj);
16205 var opar = obj.parent;
16207 obj.parent = this.toObject(opar);
16209 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
16214 Roo.debug && Roo.log("GOT top level module");
16215 Roo.debug && Roo.log(obj);
16216 obj.modules = new Roo.util.MixedCollection(false,
16217 function(o) { return o.order + '' }
16219 this.topModule = obj;
16222 // parent is a string (usually a dom element name..)
16223 if (typeof(obj.parent) == 'string') {
16224 this.elmodules.push(obj);
16227 if (obj.parent.constructor != Roo.XComponent) {
16228 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
16230 if (!obj.parent.modules) {
16231 obj.parent.modules = new Roo.util.MixedCollection(false,
16232 function(o) { return o.order + '' }
16235 if (obj.parent.disabled) {
16236 obj.disabled = true;
16238 obj.parent.modules.add(obj);
16243 * make a list of modules to build.
16244 * @return {Array} list of modules.
16247 buildOrder : function()
16250 var cmp = function(a,b) {
16251 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
16253 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
16254 throw "No top level modules to build";
16257 // make a flat list in order of modules to build.
16258 var mods = this.topModule ? [ this.topModule ] : [];
16261 // elmodules (is a list of DOM based modules )
16262 Roo.each(this.elmodules, function(e) {
16264 if (!this.topModule &&
16265 typeof(e.parent) == 'string' &&
16266 e.parent.substring(0,1) == '#' &&
16267 Roo.get(e.parent.substr(1))
16270 _this.topModule = e;
16276 // add modules to their parents..
16277 var addMod = function(m) {
16278 Roo.debug && Roo.log("build Order: add: " + m.name);
16281 if (m.modules && !m.disabled) {
16282 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
16283 m.modules.keySort('ASC', cmp );
16284 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
16286 m.modules.each(addMod);
16288 Roo.debug && Roo.log("build Order: no child modules");
16290 // not sure if this is used any more..
16292 m.finalize.name = m.name + " (clean up) ";
16293 mods.push(m.finalize);
16297 if (this.topModule && this.topModule.modules) {
16298 this.topModule.modules.keySort('ASC', cmp );
16299 this.topModule.modules.each(addMod);
16305 * Build the registered modules.
16306 * @param {Object} parent element.
16307 * @param {Function} optional method to call after module has been added.
16311 build : function(opts)
16314 if (typeof(opts) != 'undefined') {
16315 Roo.apply(this,opts);
16319 var mods = this.buildOrder();
16321 //this.allmods = mods;
16322 //Roo.debug && Roo.log(mods);
16324 if (!mods.length) { // should not happen
16325 throw "NO modules!!!";
16329 var msg = "Building Interface...";
16330 // flash it up as modal - so we store the mask!?
16331 if (!this.hideProgress && Roo.MessageBox) {
16332 Roo.MessageBox.show({ title: 'loading' });
16333 Roo.MessageBox.show({
16334 title: "Please wait...",
16343 var total = mods.length;
16346 var progressRun = function() {
16347 if (!mods.length) {
16348 Roo.debug && Roo.log('hide?');
16349 if (!this.hideProgress && Roo.MessageBox) {
16350 Roo.MessageBox.hide();
16352 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
16354 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
16360 var m = mods.shift();
16363 Roo.debug && Roo.log(m);
16364 // not sure if this is supported any more.. - modules that are are just function
16365 if (typeof(m) == 'function') {
16367 return progressRun.defer(10, _this);
16371 msg = "Building Interface " + (total - mods.length) +
16373 (m.name ? (' - ' + m.name) : '');
16374 Roo.debug && Roo.log(msg);
16375 if (!this.hideProgress && Roo.MessageBox) {
16376 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
16380 // is the module disabled?
16381 var disabled = (typeof(m.disabled) == 'function') ?
16382 m.disabled.call(m.module.disabled) : m.disabled;
16386 return progressRun(); // we do not update the display!
16394 // it's 10 on top level, and 1 on others??? why...
16395 return progressRun.defer(10, _this);
16398 progressRun.defer(1, _this);
16412 * wrapper for event.on - aliased later..
16413 * Typically use to register a event handler for register:
16415 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
16424 Roo.XComponent.event = new Roo.util.Observable({
16428 * Fires when an Component is registered,
16429 * set the disable property on the Component to stop registration.
16430 * @param {Roo.XComponent} c the component being registerd.
16435 * @event beforebuild
16436 * Fires before each Component is built
16437 * can be used to apply permissions.
16438 * @param {Roo.XComponent} c the component being registerd.
16441 'beforebuild' : true,
16443 * @event buildcomplete
16444 * Fires on the top level element when all elements have been built
16445 * @param {Roo.XComponent} the top level component.
16447 'buildcomplete' : true
16452 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
16455 * Ext JS Library 1.1.1
16456 * Copyright(c) 2006-2007, Ext JS, LLC.
16458 * Originally Released Under LGPL - original licence link has changed is not relivant.
16461 * <script type="text/javascript">
16467 * These classes are derivatives of the similarly named classes in the YUI Library.
16468 * The original license:
16469 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
16470 * Code licensed under the BSD License:
16471 * http://developer.yahoo.net/yui/license.txt
16476 var Event=Roo.EventManager;
16477 var Dom=Roo.lib.Dom;
16480 * @class Roo.dd.DragDrop
16481 * @extends Roo.util.Observable
16482 * Defines the interface and base operation of items that that can be
16483 * dragged or can be drop targets. It was designed to be extended, overriding
16484 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
16485 * Up to three html elements can be associated with a DragDrop instance:
16487 * <li>linked element: the element that is passed into the constructor.
16488 * This is the element which defines the boundaries for interaction with
16489 * other DragDrop objects.</li>
16490 * <li>handle element(s): The drag operation only occurs if the element that
16491 * was clicked matches a handle element. By default this is the linked
16492 * element, but there are times that you will want only a portion of the
16493 * linked element to initiate the drag operation, and the setHandleElId()
16494 * method provides a way to define this.</li>
16495 * <li>drag element: this represents the element that would be moved along
16496 * with the cursor during a drag operation. By default, this is the linked
16497 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
16498 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
16501 * This class should not be instantiated until the onload event to ensure that
16502 * the associated elements are available.
16503 * The following would define a DragDrop obj that would interact with any
16504 * other DragDrop obj in the "group1" group:
16506 * dd = new Roo.dd.DragDrop("div1", "group1");
16508 * Since none of the event handlers have been implemented, nothing would
16509 * actually happen if you were to run the code above. Normally you would
16510 * override this class or one of the default implementations, but you can
16511 * also override the methods you want on an instance of the class...
16513 * dd.onDragDrop = function(e, id) {
16514 * alert("dd was dropped on " + id);
16518 * @param {String} id of the element that is linked to this instance
16519 * @param {String} sGroup the group of related DragDrop objects
16520 * @param {object} config an object containing configurable attributes
16521 * Valid properties for DragDrop:
16522 * padding, isTarget, maintainOffset, primaryButtonOnly
16524 Roo.dd.DragDrop = function(id, sGroup, config) {
16526 this.init(id, sGroup, config);
16531 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
16534 * The id of the element associated with this object. This is what we
16535 * refer to as the "linked element" because the size and position of
16536 * this element is used to determine when the drag and drop objects have
16544 * Configuration attributes passed into the constructor
16551 * The id of the element that will be dragged. By default this is same
16552 * as the linked element , but could be changed to another element. Ex:
16554 * @property dragElId
16561 * the id of the element that initiates the drag operation. By default
16562 * this is the linked element, but could be changed to be a child of this
16563 * element. This lets us do things like only starting the drag when the
16564 * header element within the linked html element is clicked.
16565 * @property handleElId
16572 * An associative array of HTML tags that will be ignored if clicked.
16573 * @property invalidHandleTypes
16574 * @type {string: string}
16576 invalidHandleTypes: null,
16579 * An associative array of ids for elements that will be ignored if clicked
16580 * @property invalidHandleIds
16581 * @type {string: string}
16583 invalidHandleIds: null,
16586 * An indexted array of css class names for elements that will be ignored
16588 * @property invalidHandleClasses
16591 invalidHandleClasses: null,
16594 * The linked element's absolute X position at the time the drag was
16596 * @property startPageX
16603 * The linked element's absolute X position at the time the drag was
16605 * @property startPageY
16612 * The group defines a logical collection of DragDrop objects that are
16613 * related. Instances only get events when interacting with other
16614 * DragDrop object in the same group. This lets us define multiple
16615 * groups using a single DragDrop subclass if we want.
16617 * @type {string: string}
16622 * Individual drag/drop instances can be locked. This will prevent
16623 * onmousedown start drag.
16631 * Lock this instance
16634 lock: function() { this.locked = true; },
16637 * Unlock this instace
16640 unlock: function() { this.locked = false; },
16643 * By default, all insances can be a drop target. This can be disabled by
16644 * setting isTarget to false.
16651 * The padding configured for this drag and drop object for calculating
16652 * the drop zone intersection with this object.
16659 * Cached reference to the linked element
16660 * @property _domRef
16666 * Internal typeof flag
16667 * @property __ygDragDrop
16670 __ygDragDrop: true,
16673 * Set to true when horizontal contraints are applied
16674 * @property constrainX
16681 * Set to true when vertical contraints are applied
16682 * @property constrainY
16689 * The left constraint
16697 * The right constraint
16705 * The up constraint
16714 * The down constraint
16722 * Maintain offsets when we resetconstraints. Set to true when you want
16723 * the position of the element relative to its parent to stay the same
16724 * when the page changes
16726 * @property maintainOffset
16729 maintainOffset: false,
16732 * Array of pixel locations the element will snap to if we specified a
16733 * horizontal graduation/interval. This array is generated automatically
16734 * when you define a tick interval.
16741 * Array of pixel locations the element will snap to if we specified a
16742 * vertical graduation/interval. This array is generated automatically
16743 * when you define a tick interval.
16750 * By default the drag and drop instance will only respond to the primary
16751 * button click (left button for a right-handed mouse). Set to true to
16752 * allow drag and drop to start with any mouse click that is propogated
16754 * @property primaryButtonOnly
16757 primaryButtonOnly: true,
16760 * The availabe property is false until the linked dom element is accessible.
16761 * @property available
16767 * By default, drags can only be initiated if the mousedown occurs in the
16768 * region the linked element is. This is done in part to work around a
16769 * bug in some browsers that mis-report the mousedown if the previous
16770 * mouseup happened outside of the window. This property is set to true
16771 * if outer handles are defined.
16773 * @property hasOuterHandles
16777 hasOuterHandles: false,
16780 * Code that executes immediately before the startDrag event
16781 * @method b4StartDrag
16784 b4StartDrag: function(x, y) { },
16787 * Abstract method called after a drag/drop object is clicked
16788 * and the drag or mousedown time thresholds have beeen met.
16789 * @method startDrag
16790 * @param {int} X click location
16791 * @param {int} Y click location
16793 startDrag: function(x, y) { /* override this */ },
16796 * Code that executes immediately before the onDrag event
16800 b4Drag: function(e) { },
16803 * Abstract method called during the onMouseMove event while dragging an
16806 * @param {Event} e the mousemove event
16808 onDrag: function(e) { /* override this */ },
16811 * Abstract method called when this element fist begins hovering over
16812 * another DragDrop obj
16813 * @method onDragEnter
16814 * @param {Event} e the mousemove event
16815 * @param {String|DragDrop[]} id In POINT mode, the element
16816 * id this is hovering over. In INTERSECT mode, an array of one or more
16817 * dragdrop items being hovered over.
16819 onDragEnter: function(e, id) { /* override this */ },
16822 * Code that executes immediately before the onDragOver event
16823 * @method b4DragOver
16826 b4DragOver: function(e) { },
16829 * Abstract method called when this element is hovering over another
16831 * @method onDragOver
16832 * @param {Event} e the mousemove event
16833 * @param {String|DragDrop[]} id In POINT mode, the element
16834 * id this is hovering over. In INTERSECT mode, an array of dd items
16835 * being hovered over.
16837 onDragOver: function(e, id) { /* override this */ },
16840 * Code that executes immediately before the onDragOut event
16841 * @method b4DragOut
16844 b4DragOut: function(e) { },
16847 * Abstract method called when we are no longer hovering over an element
16848 * @method onDragOut
16849 * @param {Event} e the mousemove event
16850 * @param {String|DragDrop[]} id In POINT mode, the element
16851 * id this was hovering over. In INTERSECT mode, an array of dd items
16852 * that the mouse is no longer over.
16854 onDragOut: function(e, id) { /* override this */ },
16857 * Code that executes immediately before the onDragDrop event
16858 * @method b4DragDrop
16861 b4DragDrop: function(e) { },
16864 * Abstract method called when this item is dropped on another DragDrop
16866 * @method onDragDrop
16867 * @param {Event} e the mouseup event
16868 * @param {String|DragDrop[]} id In POINT mode, the element
16869 * id this was dropped on. In INTERSECT mode, an array of dd items this
16872 onDragDrop: function(e, id) { /* override this */ },
16875 * Abstract method called when this item is dropped on an area with no
16877 * @method onInvalidDrop
16878 * @param {Event} e the mouseup event
16880 onInvalidDrop: function(e) { /* override this */ },
16883 * Code that executes immediately before the endDrag event
16884 * @method b4EndDrag
16887 b4EndDrag: function(e) { },
16890 * Fired when we are done dragging the object
16892 * @param {Event} e the mouseup event
16894 endDrag: function(e) { /* override this */ },
16897 * Code executed immediately before the onMouseDown event
16898 * @method b4MouseDown
16899 * @param {Event} e the mousedown event
16902 b4MouseDown: function(e) { },
16905 * Event handler that fires when a drag/drop obj gets a mousedown
16906 * @method onMouseDown
16907 * @param {Event} e the mousedown event
16909 onMouseDown: function(e) { /* override this */ },
16912 * Event handler that fires when a drag/drop obj gets a mouseup
16913 * @method onMouseUp
16914 * @param {Event} e the mouseup event
16916 onMouseUp: function(e) { /* override this */ },
16919 * Override the onAvailable method to do what is needed after the initial
16920 * position was determined.
16921 * @method onAvailable
16923 onAvailable: function () {
16927 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
16930 defaultPadding : {left:0, right:0, top:0, bottom:0},
16933 * Initializes the drag drop object's constraints to restrict movement to a certain element.
16937 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
16938 { dragElId: "existingProxyDiv" });
16939 dd.startDrag = function(){
16940 this.constrainTo("parent-id");
16943 * Or you can initalize it using the {@link Roo.Element} object:
16945 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
16946 startDrag : function(){
16947 this.constrainTo("parent-id");
16951 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
16952 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
16953 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
16954 * an object containing the sides to pad. For example: {right:10, bottom:10}
16955 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
16957 constrainTo : function(constrainTo, pad, inContent){
16958 if(typeof pad == "number"){
16959 pad = {left: pad, right:pad, top:pad, bottom:pad};
16961 pad = pad || this.defaultPadding;
16962 var b = Roo.get(this.getEl()).getBox();
16963 var ce = Roo.get(constrainTo);
16964 var s = ce.getScroll();
16965 var c, cd = ce.dom;
16966 if(cd == document.body){
16967 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
16970 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
16974 var topSpace = b.y - c.y;
16975 var leftSpace = b.x - c.x;
16977 this.resetConstraints();
16978 this.setXConstraint(leftSpace - (pad.left||0), // left
16979 c.width - leftSpace - b.width - (pad.right||0) //right
16981 this.setYConstraint(topSpace - (pad.top||0), //top
16982 c.height - topSpace - b.height - (pad.bottom||0) //bottom
16987 * Returns a reference to the linked element
16989 * @return {HTMLElement} the html element
16991 getEl: function() {
16992 if (!this._domRef) {
16993 this._domRef = Roo.getDom(this.id);
16996 return this._domRef;
17000 * Returns a reference to the actual element to drag. By default this is
17001 * the same as the html element, but it can be assigned to another
17002 * element. An example of this can be found in Roo.dd.DDProxy
17003 * @method getDragEl
17004 * @return {HTMLElement} the html element
17006 getDragEl: function() {
17007 return Roo.getDom(this.dragElId);
17011 * Sets up the DragDrop object. Must be called in the constructor of any
17012 * Roo.dd.DragDrop subclass
17014 * @param id the id of the linked element
17015 * @param {String} sGroup the group of related items
17016 * @param {object} config configuration attributes
17018 init: function(id, sGroup, config) {
17019 this.initTarget(id, sGroup, config);
17020 if (!Roo.isTouch) {
17021 Event.on(this.id, "mousedown", this.handleMouseDown, this);
17023 Event.on(this.id, "touchstart", this.handleMouseDown, this);
17024 // Event.on(this.id, "selectstart", Event.preventDefault);
17028 * Initializes Targeting functionality only... the object does not
17029 * get a mousedown handler.
17030 * @method initTarget
17031 * @param id the id of the linked element
17032 * @param {String} sGroup the group of related items
17033 * @param {object} config configuration attributes
17035 initTarget: function(id, sGroup, config) {
17037 // configuration attributes
17038 this.config = config || {};
17040 // create a local reference to the drag and drop manager
17041 this.DDM = Roo.dd.DDM;
17042 // initialize the groups array
17045 // assume that we have an element reference instead of an id if the
17046 // parameter is not a string
17047 if (typeof id !== "string") {
17054 // add to an interaction group
17055 this.addToGroup((sGroup) ? sGroup : "default");
17057 // We don't want to register this as the handle with the manager
17058 // so we just set the id rather than calling the setter.
17059 this.handleElId = id;
17061 // the linked element is the element that gets dragged by default
17062 this.setDragElId(id);
17064 // by default, clicked anchors will not start drag operations.
17065 this.invalidHandleTypes = { A: "A" };
17066 this.invalidHandleIds = {};
17067 this.invalidHandleClasses = [];
17069 this.applyConfig();
17071 this.handleOnAvailable();
17075 * Applies the configuration parameters that were passed into the constructor.
17076 * This is supposed to happen at each level through the inheritance chain. So
17077 * a DDProxy implentation will execute apply config on DDProxy, DD, and
17078 * DragDrop in order to get all of the parameters that are available in
17080 * @method applyConfig
17082 applyConfig: function() {
17084 // configurable properties:
17085 // padding, isTarget, maintainOffset, primaryButtonOnly
17086 this.padding = this.config.padding || [0, 0, 0, 0];
17087 this.isTarget = (this.config.isTarget !== false);
17088 this.maintainOffset = (this.config.maintainOffset);
17089 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
17094 * Executed when the linked element is available
17095 * @method handleOnAvailable
17098 handleOnAvailable: function() {
17099 this.available = true;
17100 this.resetConstraints();
17101 this.onAvailable();
17105 * Configures the padding for the target zone in px. Effectively expands
17106 * (or reduces) the virtual object size for targeting calculations.
17107 * Supports css-style shorthand; if only one parameter is passed, all sides
17108 * will have that padding, and if only two are passed, the top and bottom
17109 * will have the first param, the left and right the second.
17110 * @method setPadding
17111 * @param {int} iTop Top pad
17112 * @param {int} iRight Right pad
17113 * @param {int} iBot Bot pad
17114 * @param {int} iLeft Left pad
17116 setPadding: function(iTop, iRight, iBot, iLeft) {
17117 // this.padding = [iLeft, iRight, iTop, iBot];
17118 if (!iRight && 0 !== iRight) {
17119 this.padding = [iTop, iTop, iTop, iTop];
17120 } else if (!iBot && 0 !== iBot) {
17121 this.padding = [iTop, iRight, iTop, iRight];
17123 this.padding = [iTop, iRight, iBot, iLeft];
17128 * Stores the initial placement of the linked element.
17129 * @method setInitialPosition
17130 * @param {int} diffX the X offset, default 0
17131 * @param {int} diffY the Y offset, default 0
17133 setInitPosition: function(diffX, diffY) {
17134 var el = this.getEl();
17136 if (!this.DDM.verifyEl(el)) {
17140 var dx = diffX || 0;
17141 var dy = diffY || 0;
17143 var p = Dom.getXY( el );
17145 this.initPageX = p[0] - dx;
17146 this.initPageY = p[1] - dy;
17148 this.lastPageX = p[0];
17149 this.lastPageY = p[1];
17152 this.setStartPosition(p);
17156 * Sets the start position of the element. This is set when the obj
17157 * is initialized, the reset when a drag is started.
17158 * @method setStartPosition
17159 * @param pos current position (from previous lookup)
17162 setStartPosition: function(pos) {
17163 var p = pos || Dom.getXY( this.getEl() );
17164 this.deltaSetXY = null;
17166 this.startPageX = p[0];
17167 this.startPageY = p[1];
17171 * Add this instance to a group of related drag/drop objects. All
17172 * instances belong to at least one group, and can belong to as many
17173 * groups as needed.
17174 * @method addToGroup
17175 * @param sGroup {string} the name of the group
17177 addToGroup: function(sGroup) {
17178 this.groups[sGroup] = true;
17179 this.DDM.regDragDrop(this, sGroup);
17183 * Remove's this instance from the supplied interaction group
17184 * @method removeFromGroup
17185 * @param {string} sGroup The group to drop
17187 removeFromGroup: function(sGroup) {
17188 if (this.groups[sGroup]) {
17189 delete this.groups[sGroup];
17192 this.DDM.removeDDFromGroup(this, sGroup);
17196 * Allows you to specify that an element other than the linked element
17197 * will be moved with the cursor during a drag
17198 * @method setDragElId
17199 * @param id {string} the id of the element that will be used to initiate the drag
17201 setDragElId: function(id) {
17202 this.dragElId = id;
17206 * Allows you to specify a child of the linked element that should be
17207 * used to initiate the drag operation. An example of this would be if
17208 * you have a content div with text and links. Clicking anywhere in the
17209 * content area would normally start the drag operation. Use this method
17210 * to specify that an element inside of the content div is the element
17211 * that starts the drag operation.
17212 * @method setHandleElId
17213 * @param id {string} the id of the element that will be used to
17214 * initiate the drag.
17216 setHandleElId: function(id) {
17217 if (typeof id !== "string") {
17220 this.handleElId = id;
17221 this.DDM.regHandle(this.id, id);
17225 * Allows you to set an element outside of the linked element as a drag
17227 * @method setOuterHandleElId
17228 * @param id the id of the element that will be used to initiate the drag
17230 setOuterHandleElId: function(id) {
17231 if (typeof id !== "string") {
17234 Event.on(id, "mousedown",
17235 this.handleMouseDown, this);
17236 this.setHandleElId(id);
17238 this.hasOuterHandles = true;
17242 * Remove all drag and drop hooks for this element
17245 unreg: function() {
17246 Event.un(this.id, "mousedown",
17247 this.handleMouseDown);
17248 Event.un(this.id, "touchstart",
17249 this.handleMouseDown);
17250 this._domRef = null;
17251 this.DDM._remove(this);
17254 destroy : function(){
17259 * Returns true if this instance is locked, or the drag drop mgr is locked
17260 * (meaning that all drag/drop is disabled on the page.)
17262 * @return {boolean} true if this obj or all drag/drop is locked, else
17265 isLocked: function() {
17266 return (this.DDM.isLocked() || this.locked);
17270 * Fired when this object is clicked
17271 * @method handleMouseDown
17273 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
17276 handleMouseDown: function(e, oDD){
17278 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
17279 //Roo.log('not touch/ button !=0');
17282 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
17283 return; // double touch..
17287 if (this.isLocked()) {
17288 //Roo.log('locked');
17292 this.DDM.refreshCache(this.groups);
17293 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
17294 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
17295 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
17296 //Roo.log('no outer handes or not over target');
17299 // Roo.log('check validator');
17300 if (this.clickValidator(e)) {
17301 // Roo.log('validate success');
17302 // set the initial element position
17303 this.setStartPosition();
17306 this.b4MouseDown(e);
17307 this.onMouseDown(e);
17309 this.DDM.handleMouseDown(e, this);
17311 this.DDM.stopEvent(e);
17319 clickValidator: function(e) {
17320 var target = e.getTarget();
17321 return ( this.isValidHandleChild(target) &&
17322 (this.id == this.handleElId ||
17323 this.DDM.handleWasClicked(target, this.id)) );
17327 * Allows you to specify a tag name that should not start a drag operation
17328 * when clicked. This is designed to facilitate embedding links within a
17329 * drag handle that do something other than start the drag.
17330 * @method addInvalidHandleType
17331 * @param {string} tagName the type of element to exclude
17333 addInvalidHandleType: function(tagName) {
17334 var type = tagName.toUpperCase();
17335 this.invalidHandleTypes[type] = type;
17339 * Lets you to specify an element id for a child of a drag handle
17340 * that should not initiate a drag
17341 * @method addInvalidHandleId
17342 * @param {string} id the element id of the element you wish to ignore
17344 addInvalidHandleId: function(id) {
17345 if (typeof id !== "string") {
17348 this.invalidHandleIds[id] = id;
17352 * Lets you specify a css class of elements that will not initiate a drag
17353 * @method addInvalidHandleClass
17354 * @param {string} cssClass the class of the elements you wish to ignore
17356 addInvalidHandleClass: function(cssClass) {
17357 this.invalidHandleClasses.push(cssClass);
17361 * Unsets an excluded tag name set by addInvalidHandleType
17362 * @method removeInvalidHandleType
17363 * @param {string} tagName the type of element to unexclude
17365 removeInvalidHandleType: function(tagName) {
17366 var type = tagName.toUpperCase();
17367 // this.invalidHandleTypes[type] = null;
17368 delete this.invalidHandleTypes[type];
17372 * Unsets an invalid handle id
17373 * @method removeInvalidHandleId
17374 * @param {string} id the id of the element to re-enable
17376 removeInvalidHandleId: function(id) {
17377 if (typeof id !== "string") {
17380 delete this.invalidHandleIds[id];
17384 * Unsets an invalid css class
17385 * @method removeInvalidHandleClass
17386 * @param {string} cssClass the class of the element(s) you wish to
17389 removeInvalidHandleClass: function(cssClass) {
17390 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
17391 if (this.invalidHandleClasses[i] == cssClass) {
17392 delete this.invalidHandleClasses[i];
17398 * Checks the tag exclusion list to see if this click should be ignored
17399 * @method isValidHandleChild
17400 * @param {HTMLElement} node the HTMLElement to evaluate
17401 * @return {boolean} true if this is a valid tag type, false if not
17403 isValidHandleChild: function(node) {
17406 // var n = (node.nodeName == "#text") ? node.parentNode : node;
17409 nodeName = node.nodeName.toUpperCase();
17411 nodeName = node.nodeName;
17413 valid = valid && !this.invalidHandleTypes[nodeName];
17414 valid = valid && !this.invalidHandleIds[node.id];
17416 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
17417 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
17426 * Create the array of horizontal tick marks if an interval was specified
17427 * in setXConstraint().
17428 * @method setXTicks
17431 setXTicks: function(iStartX, iTickSize) {
17433 this.xTickSize = iTickSize;
17437 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
17439 this.xTicks[this.xTicks.length] = i;
17444 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
17446 this.xTicks[this.xTicks.length] = i;
17451 this.xTicks.sort(this.DDM.numericSort) ;
17455 * Create the array of vertical tick marks if an interval was specified in
17456 * setYConstraint().
17457 * @method setYTicks
17460 setYTicks: function(iStartY, iTickSize) {
17462 this.yTickSize = iTickSize;
17466 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
17468 this.yTicks[this.yTicks.length] = i;
17473 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
17475 this.yTicks[this.yTicks.length] = i;
17480 this.yTicks.sort(this.DDM.numericSort) ;
17484 * By default, the element can be dragged any place on the screen. Use
17485 * this method to limit the horizontal travel of the element. Pass in
17486 * 0,0 for the parameters if you want to lock the drag to the y axis.
17487 * @method setXConstraint
17488 * @param {int} iLeft the number of pixels the element can move to the left
17489 * @param {int} iRight the number of pixels the element can move to the
17491 * @param {int} iTickSize optional parameter for specifying that the
17493 * should move iTickSize pixels at a time.
17495 setXConstraint: function(iLeft, iRight, iTickSize) {
17496 this.leftConstraint = iLeft;
17497 this.rightConstraint = iRight;
17499 this.minX = this.initPageX - iLeft;
17500 this.maxX = this.initPageX + iRight;
17501 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
17503 this.constrainX = true;
17507 * Clears any constraints applied to this instance. Also clears ticks
17508 * since they can't exist independent of a constraint at this time.
17509 * @method clearConstraints
17511 clearConstraints: function() {
17512 this.constrainX = false;
17513 this.constrainY = false;
17518 * Clears any tick interval defined for this instance
17519 * @method clearTicks
17521 clearTicks: function() {
17522 this.xTicks = null;
17523 this.yTicks = null;
17524 this.xTickSize = 0;
17525 this.yTickSize = 0;
17529 * By default, the element can be dragged any place on the screen. Set
17530 * this to limit the vertical travel of the element. Pass in 0,0 for the
17531 * parameters if you want to lock the drag to the x axis.
17532 * @method setYConstraint
17533 * @param {int} iUp the number of pixels the element can move up
17534 * @param {int} iDown the number of pixels the element can move down
17535 * @param {int} iTickSize optional parameter for specifying that the
17536 * element should move iTickSize pixels at a time.
17538 setYConstraint: function(iUp, iDown, iTickSize) {
17539 this.topConstraint = iUp;
17540 this.bottomConstraint = iDown;
17542 this.minY = this.initPageY - iUp;
17543 this.maxY = this.initPageY + iDown;
17544 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
17546 this.constrainY = true;
17551 * resetConstraints must be called if you manually reposition a dd element.
17552 * @method resetConstraints
17553 * @param {boolean} maintainOffset
17555 resetConstraints: function() {
17558 // Maintain offsets if necessary
17559 if (this.initPageX || this.initPageX === 0) {
17560 // figure out how much this thing has moved
17561 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
17562 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
17564 this.setInitPosition(dx, dy);
17566 // This is the first time we have detected the element's position
17568 this.setInitPosition();
17571 if (this.constrainX) {
17572 this.setXConstraint( this.leftConstraint,
17573 this.rightConstraint,
17577 if (this.constrainY) {
17578 this.setYConstraint( this.topConstraint,
17579 this.bottomConstraint,
17585 * Normally the drag element is moved pixel by pixel, but we can specify
17586 * that it move a number of pixels at a time. This method resolves the
17587 * location when we have it set up like this.
17589 * @param {int} val where we want to place the object
17590 * @param {int[]} tickArray sorted array of valid points
17591 * @return {int} the closest tick
17594 getTick: function(val, tickArray) {
17597 // If tick interval is not defined, it is effectively 1 pixel,
17598 // so we return the value passed to us.
17600 } else if (tickArray[0] >= val) {
17601 // The value is lower than the first tick, so we return the first
17603 return tickArray[0];
17605 for (var i=0, len=tickArray.length; i<len; ++i) {
17607 if (tickArray[next] && tickArray[next] >= val) {
17608 var diff1 = val - tickArray[i];
17609 var diff2 = tickArray[next] - val;
17610 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
17614 // The value is larger than the last tick, so we return the last
17616 return tickArray[tickArray.length - 1];
17623 * @return {string} string representation of the dd obj
17625 toString: function() {
17626 return ("DragDrop " + this.id);
17634 * Ext JS Library 1.1.1
17635 * Copyright(c) 2006-2007, Ext JS, LLC.
17637 * Originally Released Under LGPL - original licence link has changed is not relivant.
17640 * <script type="text/javascript">
17645 * The drag and drop utility provides a framework for building drag and drop
17646 * applications. In addition to enabling drag and drop for specific elements,
17647 * the drag and drop elements are tracked by the manager class, and the
17648 * interactions between the various elements are tracked during the drag and
17649 * the implementing code is notified about these important moments.
17652 // Only load the library once. Rewriting the manager class would orphan
17653 // existing drag and drop instances.
17654 if (!Roo.dd.DragDropMgr) {
17657 * @class Roo.dd.DragDropMgr
17658 * DragDropMgr is a singleton that tracks the element interaction for
17659 * all DragDrop items in the window. Generally, you will not call
17660 * this class directly, but it does have helper methods that could
17661 * be useful in your DragDrop implementations.
17664 Roo.dd.DragDropMgr = function() {
17666 var Event = Roo.EventManager;
17671 * Two dimensional Array of registered DragDrop objects. The first
17672 * dimension is the DragDrop item group, the second the DragDrop
17675 * @type {string: string}
17682 * Array of element ids defined as drag handles. Used to determine
17683 * if the element that generated the mousedown event is actually the
17684 * handle and not the html element itself.
17685 * @property handleIds
17686 * @type {string: string}
17693 * the DragDrop object that is currently being dragged
17694 * @property dragCurrent
17702 * the DragDrop object(s) that are being hovered over
17703 * @property dragOvers
17711 * the X distance between the cursor and the object being dragged
17720 * the Y distance between the cursor and the object being dragged
17729 * Flag to determine if we should prevent the default behavior of the
17730 * events we define. By default this is true, but this can be set to
17731 * false if you need the default behavior (not recommended)
17732 * @property preventDefault
17736 preventDefault: true,
17739 * Flag to determine if we should stop the propagation of the events
17740 * we generate. This is true by default but you may want to set it to
17741 * false if the html element contains other features that require the
17743 * @property stopPropagation
17747 stopPropagation: true,
17750 * Internal flag that is set to true when drag and drop has been
17752 * @property initialized
17759 * All drag and drop can be disabled.
17767 * Called the first time an element is registered.
17773 this.initialized = true;
17777 * In point mode, drag and drop interaction is defined by the
17778 * location of the cursor during the drag/drop
17786 * In intersect mode, drag and drop interactio nis defined by the
17787 * overlap of two or more drag and drop objects.
17788 * @property INTERSECT
17795 * The current drag and drop mode. Default: POINT
17803 * Runs method on all drag and drop objects
17804 * @method _execOnAll
17808 _execOnAll: function(sMethod, args) {
17809 for (var i in this.ids) {
17810 for (var j in this.ids[i]) {
17811 var oDD = this.ids[i][j];
17812 if (! this.isTypeOfDD(oDD)) {
17815 oDD[sMethod].apply(oDD, args);
17821 * Drag and drop initialization. Sets up the global event handlers
17826 _onLoad: function() {
17830 if (!Roo.isTouch) {
17831 Event.on(document, "mouseup", this.handleMouseUp, this, true);
17832 Event.on(document, "mousemove", this.handleMouseMove, this, true);
17834 Event.on(document, "touchend", this.handleMouseUp, this, true);
17835 Event.on(document, "touchmove", this.handleMouseMove, this, true);
17837 Event.on(window, "unload", this._onUnload, this, true);
17838 Event.on(window, "resize", this._onResize, this, true);
17839 // Event.on(window, "mouseout", this._test);
17844 * Reset constraints on all drag and drop objs
17845 * @method _onResize
17849 _onResize: function(e) {
17850 this._execOnAll("resetConstraints", []);
17854 * Lock all drag and drop functionality
17858 lock: function() { this.locked = true; },
17861 * Unlock all drag and drop functionality
17865 unlock: function() { this.locked = false; },
17868 * Is drag and drop locked?
17870 * @return {boolean} True if drag and drop is locked, false otherwise.
17873 isLocked: function() { return this.locked; },
17876 * Location cache that is set for all drag drop objects when a drag is
17877 * initiated, cleared when the drag is finished.
17878 * @property locationCache
17885 * Set useCache to false if you want to force object the lookup of each
17886 * drag and drop linked element constantly during a drag.
17887 * @property useCache
17894 * The number of pixels that the mouse needs to move after the
17895 * mousedown before the drag is initiated. Default=3;
17896 * @property clickPixelThresh
17900 clickPixelThresh: 3,
17903 * The number of milliseconds after the mousedown event to initiate the
17904 * drag if we don't get a mouseup event. Default=1000
17905 * @property clickTimeThresh
17909 clickTimeThresh: 350,
17912 * Flag that indicates that either the drag pixel threshold or the
17913 * mousdown time threshold has been met
17914 * @property dragThreshMet
17919 dragThreshMet: false,
17922 * Timeout used for the click time threshold
17923 * @property clickTimeout
17928 clickTimeout: null,
17931 * The X position of the mousedown event stored for later use when a
17932 * drag threshold is met.
17941 * The Y position of the mousedown event stored for later use when a
17942 * drag threshold is met.
17951 * Each DragDrop instance must be registered with the DragDropMgr.
17952 * This is executed in DragDrop.init()
17953 * @method regDragDrop
17954 * @param {DragDrop} oDD the DragDrop object to register
17955 * @param {String} sGroup the name of the group this element belongs to
17958 regDragDrop: function(oDD, sGroup) {
17959 if (!this.initialized) { this.init(); }
17961 if (!this.ids[sGroup]) {
17962 this.ids[sGroup] = {};
17964 this.ids[sGroup][oDD.id] = oDD;
17968 * Removes the supplied dd instance from the supplied group. Executed
17969 * by DragDrop.removeFromGroup, so don't call this function directly.
17970 * @method removeDDFromGroup
17974 removeDDFromGroup: function(oDD, sGroup) {
17975 if (!this.ids[sGroup]) {
17976 this.ids[sGroup] = {};
17979 var obj = this.ids[sGroup];
17980 if (obj && obj[oDD.id]) {
17981 delete obj[oDD.id];
17986 * Unregisters a drag and drop item. This is executed in
17987 * DragDrop.unreg, use that method instead of calling this directly.
17992 _remove: function(oDD) {
17993 for (var g in oDD.groups) {
17994 if (g && this.ids[g][oDD.id]) {
17995 delete this.ids[g][oDD.id];
17998 delete this.handleIds[oDD.id];
18002 * Each DragDrop handle element must be registered. This is done
18003 * automatically when executing DragDrop.setHandleElId()
18004 * @method regHandle
18005 * @param {String} sDDId the DragDrop id this element is a handle for
18006 * @param {String} sHandleId the id of the element that is the drag
18010 regHandle: function(sDDId, sHandleId) {
18011 if (!this.handleIds[sDDId]) {
18012 this.handleIds[sDDId] = {};
18014 this.handleIds[sDDId][sHandleId] = sHandleId;
18018 * Utility function to determine if a given element has been
18019 * registered as a drag drop item.
18020 * @method isDragDrop
18021 * @param {String} id the element id to check
18022 * @return {boolean} true if this element is a DragDrop item,
18026 isDragDrop: function(id) {
18027 return ( this.getDDById(id) ) ? true : false;
18031 * Returns the drag and drop instances that are in all groups the
18032 * passed in instance belongs to.
18033 * @method getRelated
18034 * @param {DragDrop} p_oDD the obj to get related data for
18035 * @param {boolean} bTargetsOnly if true, only return targetable objs
18036 * @return {DragDrop[]} the related instances
18039 getRelated: function(p_oDD, bTargetsOnly) {
18041 for (var i in p_oDD.groups) {
18042 for (j in this.ids[i]) {
18043 var dd = this.ids[i][j];
18044 if (! this.isTypeOfDD(dd)) {
18047 if (!bTargetsOnly || dd.isTarget) {
18048 oDDs[oDDs.length] = dd;
18057 * Returns true if the specified dd target is a legal target for
18058 * the specifice drag obj
18059 * @method isLegalTarget
18060 * @param {DragDrop} the drag obj
18061 * @param {DragDrop} the target
18062 * @return {boolean} true if the target is a legal target for the
18066 isLegalTarget: function (oDD, oTargetDD) {
18067 var targets = this.getRelated(oDD, true);
18068 for (var i=0, len=targets.length;i<len;++i) {
18069 if (targets[i].id == oTargetDD.id) {
18078 * My goal is to be able to transparently determine if an object is
18079 * typeof DragDrop, and the exact subclass of DragDrop. typeof
18080 * returns "object", oDD.constructor.toString() always returns
18081 * "DragDrop" and not the name of the subclass. So for now it just
18082 * evaluates a well-known variable in DragDrop.
18083 * @method isTypeOfDD
18084 * @param {Object} the object to evaluate
18085 * @return {boolean} true if typeof oDD = DragDrop
18088 isTypeOfDD: function (oDD) {
18089 return (oDD && oDD.__ygDragDrop);
18093 * Utility function to determine if a given element has been
18094 * registered as a drag drop handle for the given Drag Drop object.
18096 * @param {String} id the element id to check
18097 * @return {boolean} true if this element is a DragDrop handle, false
18101 isHandle: function(sDDId, sHandleId) {
18102 return ( this.handleIds[sDDId] &&
18103 this.handleIds[sDDId][sHandleId] );
18107 * Returns the DragDrop instance for a given id
18108 * @method getDDById
18109 * @param {String} id the id of the DragDrop object
18110 * @return {DragDrop} the drag drop object, null if it is not found
18113 getDDById: function(id) {
18114 for (var i in this.ids) {
18115 if (this.ids[i][id]) {
18116 return this.ids[i][id];
18123 * Fired after a registered DragDrop object gets the mousedown event.
18124 * Sets up the events required to track the object being dragged
18125 * @method handleMouseDown
18126 * @param {Event} e the event
18127 * @param oDD the DragDrop object being dragged
18131 handleMouseDown: function(e, oDD) {
18133 Roo.QuickTips.disable();
18135 this.currentTarget = e.getTarget();
18137 this.dragCurrent = oDD;
18139 var el = oDD.getEl();
18141 // track start position
18142 this.startX = e.getPageX();
18143 this.startY = e.getPageY();
18145 this.deltaX = this.startX - el.offsetLeft;
18146 this.deltaY = this.startY - el.offsetTop;
18148 this.dragThreshMet = false;
18150 this.clickTimeout = setTimeout(
18152 var DDM = Roo.dd.DDM;
18153 DDM.startDrag(DDM.startX, DDM.startY);
18155 this.clickTimeThresh );
18159 * Fired when either the drag pixel threshol or the mousedown hold
18160 * time threshold has been met.
18161 * @method startDrag
18162 * @param x {int} the X position of the original mousedown
18163 * @param y {int} the Y position of the original mousedown
18166 startDrag: function(x, y) {
18167 clearTimeout(this.clickTimeout);
18168 if (this.dragCurrent) {
18169 this.dragCurrent.b4StartDrag(x, y);
18170 this.dragCurrent.startDrag(x, y);
18172 this.dragThreshMet = true;
18176 * Internal function to handle the mouseup event. Will be invoked
18177 * from the context of the document.
18178 * @method handleMouseUp
18179 * @param {Event} e the event
18183 handleMouseUp: function(e) {
18186 Roo.QuickTips.enable();
18188 if (! this.dragCurrent) {
18192 clearTimeout(this.clickTimeout);
18194 if (this.dragThreshMet) {
18195 this.fireEvents(e, true);
18205 * Utility to stop event propagation and event default, if these
18206 * features are turned on.
18207 * @method stopEvent
18208 * @param {Event} e the event as returned by this.getEvent()
18211 stopEvent: function(e){
18212 if(this.stopPropagation) {
18213 e.stopPropagation();
18216 if (this.preventDefault) {
18217 e.preventDefault();
18222 * Internal function to clean up event handlers after the drag
18223 * operation is complete
18225 * @param {Event} e the event
18229 stopDrag: function(e) {
18230 // Fire the drag end event for the item that was dragged
18231 if (this.dragCurrent) {
18232 if (this.dragThreshMet) {
18233 this.dragCurrent.b4EndDrag(e);
18234 this.dragCurrent.endDrag(e);
18237 this.dragCurrent.onMouseUp(e);
18240 this.dragCurrent = null;
18241 this.dragOvers = {};
18245 * Internal function to handle the mousemove event. Will be invoked
18246 * from the context of the html element.
18248 * @TODO figure out what we can do about mouse events lost when the
18249 * user drags objects beyond the window boundary. Currently we can
18250 * detect this in internet explorer by verifying that the mouse is
18251 * down during the mousemove event. Firefox doesn't give us the
18252 * button state on the mousemove event.
18253 * @method handleMouseMove
18254 * @param {Event} e the event
18258 handleMouseMove: function(e) {
18259 if (! this.dragCurrent) {
18263 // var button = e.which || e.button;
18265 // check for IE mouseup outside of page boundary
18266 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
18268 return this.handleMouseUp(e);
18271 if (!this.dragThreshMet) {
18272 var diffX = Math.abs(this.startX - e.getPageX());
18273 var diffY = Math.abs(this.startY - e.getPageY());
18274 if (diffX > this.clickPixelThresh ||
18275 diffY > this.clickPixelThresh) {
18276 this.startDrag(this.startX, this.startY);
18280 if (this.dragThreshMet) {
18281 this.dragCurrent.b4Drag(e);
18282 this.dragCurrent.onDrag(e);
18283 if(!this.dragCurrent.moveOnly){
18284 this.fireEvents(e, false);
18294 * Iterates over all of the DragDrop elements to find ones we are
18295 * hovering over or dropping on
18296 * @method fireEvents
18297 * @param {Event} e the event
18298 * @param {boolean} isDrop is this a drop op or a mouseover op?
18302 fireEvents: function(e, isDrop) {
18303 var dc = this.dragCurrent;
18305 // If the user did the mouse up outside of the window, we could
18306 // get here even though we have ended the drag.
18307 if (!dc || dc.isLocked()) {
18311 var pt = e.getPoint();
18313 // cache the previous dragOver array
18319 var enterEvts = [];
18321 // Check to see if the object(s) we were hovering over is no longer
18322 // being hovered over so we can fire the onDragOut event
18323 for (var i in this.dragOvers) {
18325 var ddo = this.dragOvers[i];
18327 if (! this.isTypeOfDD(ddo)) {
18331 if (! this.isOverTarget(pt, ddo, this.mode)) {
18332 outEvts.push( ddo );
18335 oldOvers[i] = true;
18336 delete this.dragOvers[i];
18339 for (var sGroup in dc.groups) {
18341 if ("string" != typeof sGroup) {
18345 for (i in this.ids[sGroup]) {
18346 var oDD = this.ids[sGroup][i];
18347 if (! this.isTypeOfDD(oDD)) {
18351 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
18352 if (this.isOverTarget(pt, oDD, this.mode)) {
18353 // look for drop interactions
18355 dropEvts.push( oDD );
18356 // look for drag enter and drag over interactions
18359 // initial drag over: dragEnter fires
18360 if (!oldOvers[oDD.id]) {
18361 enterEvts.push( oDD );
18362 // subsequent drag overs: dragOver fires
18364 overEvts.push( oDD );
18367 this.dragOvers[oDD.id] = oDD;
18375 if (outEvts.length) {
18376 dc.b4DragOut(e, outEvts);
18377 dc.onDragOut(e, outEvts);
18380 if (enterEvts.length) {
18381 dc.onDragEnter(e, enterEvts);
18384 if (overEvts.length) {
18385 dc.b4DragOver(e, overEvts);
18386 dc.onDragOver(e, overEvts);
18389 if (dropEvts.length) {
18390 dc.b4DragDrop(e, dropEvts);
18391 dc.onDragDrop(e, dropEvts);
18395 // fire dragout events
18397 for (i=0, len=outEvts.length; i<len; ++i) {
18398 dc.b4DragOut(e, outEvts[i].id);
18399 dc.onDragOut(e, outEvts[i].id);
18402 // fire enter events
18403 for (i=0,len=enterEvts.length; i<len; ++i) {
18404 // dc.b4DragEnter(e, oDD.id);
18405 dc.onDragEnter(e, enterEvts[i].id);
18408 // fire over events
18409 for (i=0,len=overEvts.length; i<len; ++i) {
18410 dc.b4DragOver(e, overEvts[i].id);
18411 dc.onDragOver(e, overEvts[i].id);
18414 // fire drop events
18415 for (i=0, len=dropEvts.length; i<len; ++i) {
18416 dc.b4DragDrop(e, dropEvts[i].id);
18417 dc.onDragDrop(e, dropEvts[i].id);
18422 // notify about a drop that did not find a target
18423 if (isDrop && !dropEvts.length) {
18424 dc.onInvalidDrop(e);
18430 * Helper function for getting the best match from the list of drag
18431 * and drop objects returned by the drag and drop events when we are
18432 * in INTERSECT mode. It returns either the first object that the
18433 * cursor is over, or the object that has the greatest overlap with
18434 * the dragged element.
18435 * @method getBestMatch
18436 * @param {DragDrop[]} dds The array of drag and drop objects
18438 * @return {DragDrop} The best single match
18441 getBestMatch: function(dds) {
18443 // Return null if the input is not what we expect
18444 //if (!dds || !dds.length || dds.length == 0) {
18446 // If there is only one item, it wins
18447 //} else if (dds.length == 1) {
18449 var len = dds.length;
18454 // Loop through the targeted items
18455 for (var i=0; i<len; ++i) {
18457 // If the cursor is over the object, it wins. If the
18458 // cursor is over multiple matches, the first one we come
18460 if (dd.cursorIsOver) {
18463 // Otherwise the object with the most overlap wins
18466 winner.overlap.getArea() < dd.overlap.getArea()) {
18477 * Refreshes the cache of the top-left and bottom-right points of the
18478 * drag and drop objects in the specified group(s). This is in the
18479 * format that is stored in the drag and drop instance, so typical
18482 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
18486 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
18488 * @TODO this really should be an indexed array. Alternatively this
18489 * method could accept both.
18490 * @method refreshCache
18491 * @param {Object} groups an associative array of groups to refresh
18494 refreshCache: function(groups) {
18495 for (var sGroup in groups) {
18496 if ("string" != typeof sGroup) {
18499 for (var i in this.ids[sGroup]) {
18500 var oDD = this.ids[sGroup][i];
18502 if (this.isTypeOfDD(oDD)) {
18503 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
18504 var loc = this.getLocation(oDD);
18506 this.locationCache[oDD.id] = loc;
18508 delete this.locationCache[oDD.id];
18509 // this will unregister the drag and drop object if
18510 // the element is not in a usable state
18519 * This checks to make sure an element exists and is in the DOM. The
18520 * main purpose is to handle cases where innerHTML is used to remove
18521 * drag and drop objects from the DOM. IE provides an 'unspecified
18522 * error' when trying to access the offsetParent of such an element
18524 * @param {HTMLElement} el the element to check
18525 * @return {boolean} true if the element looks usable
18528 verifyEl: function(el) {
18533 parent = el.offsetParent;
18536 parent = el.offsetParent;
18547 * Returns a Region object containing the drag and drop element's position
18548 * and size, including the padding configured for it
18549 * @method getLocation
18550 * @param {DragDrop} oDD the drag and drop object to get the
18552 * @return {Roo.lib.Region} a Region object representing the total area
18553 * the element occupies, including any padding
18554 * the instance is configured for.
18557 getLocation: function(oDD) {
18558 if (! this.isTypeOfDD(oDD)) {
18562 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
18565 pos= Roo.lib.Dom.getXY(el);
18573 x2 = x1 + el.offsetWidth;
18575 y2 = y1 + el.offsetHeight;
18577 t = y1 - oDD.padding[0];
18578 r = x2 + oDD.padding[1];
18579 b = y2 + oDD.padding[2];
18580 l = x1 - oDD.padding[3];
18582 return new Roo.lib.Region( t, r, b, l );
18586 * Checks the cursor location to see if it over the target
18587 * @method isOverTarget
18588 * @param {Roo.lib.Point} pt The point to evaluate
18589 * @param {DragDrop} oTarget the DragDrop object we are inspecting
18590 * @return {boolean} true if the mouse is over the target
18594 isOverTarget: function(pt, oTarget, intersect) {
18595 // use cache if available
18596 var loc = this.locationCache[oTarget.id];
18597 if (!loc || !this.useCache) {
18598 loc = this.getLocation(oTarget);
18599 this.locationCache[oTarget.id] = loc;
18607 oTarget.cursorIsOver = loc.contains( pt );
18609 // DragDrop is using this as a sanity check for the initial mousedown
18610 // in this case we are done. In POINT mode, if the drag obj has no
18611 // contraints, we are also done. Otherwise we need to evaluate the
18612 // location of the target as related to the actual location of the
18613 // dragged element.
18614 var dc = this.dragCurrent;
18615 if (!dc || !dc.getTargetCoord ||
18616 (!intersect && !dc.constrainX && !dc.constrainY)) {
18617 return oTarget.cursorIsOver;
18620 oTarget.overlap = null;
18622 // Get the current location of the drag element, this is the
18623 // location of the mouse event less the delta that represents
18624 // where the original mousedown happened on the element. We
18625 // need to consider constraints and ticks as well.
18626 var pos = dc.getTargetCoord(pt.x, pt.y);
18628 var el = dc.getDragEl();
18629 var curRegion = new Roo.lib.Region( pos.y,
18630 pos.x + el.offsetWidth,
18631 pos.y + el.offsetHeight,
18634 var overlap = curRegion.intersect(loc);
18637 oTarget.overlap = overlap;
18638 return (intersect) ? true : oTarget.cursorIsOver;
18645 * unload event handler
18646 * @method _onUnload
18650 _onUnload: function(e, me) {
18651 Roo.dd.DragDropMgr.unregAll();
18655 * Cleans up the drag and drop events and objects.
18660 unregAll: function() {
18662 if (this.dragCurrent) {
18664 this.dragCurrent = null;
18667 this._execOnAll("unreg", []);
18669 for (i in this.elementCache) {
18670 delete this.elementCache[i];
18673 this.elementCache = {};
18678 * A cache of DOM elements
18679 * @property elementCache
18686 * Get the wrapper for the DOM element specified
18687 * @method getElWrapper
18688 * @param {String} id the id of the element to get
18689 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
18691 * @deprecated This wrapper isn't that useful
18694 getElWrapper: function(id) {
18695 var oWrapper = this.elementCache[id];
18696 if (!oWrapper || !oWrapper.el) {
18697 oWrapper = this.elementCache[id] =
18698 new this.ElementWrapper(Roo.getDom(id));
18704 * Returns the actual DOM element
18705 * @method getElement
18706 * @param {String} id the id of the elment to get
18707 * @return {Object} The element
18708 * @deprecated use Roo.getDom instead
18711 getElement: function(id) {
18712 return Roo.getDom(id);
18716 * Returns the style property for the DOM element (i.e.,
18717 * document.getElById(id).style)
18719 * @param {String} id the id of the elment to get
18720 * @return {Object} The style property of the element
18721 * @deprecated use Roo.getDom instead
18724 getCss: function(id) {
18725 var el = Roo.getDom(id);
18726 return (el) ? el.style : null;
18730 * Inner class for cached elements
18731 * @class DragDropMgr.ElementWrapper
18736 ElementWrapper: function(el) {
18741 this.el = el || null;
18746 this.id = this.el && el.id;
18748 * A reference to the style property
18751 this.css = this.el && el.style;
18755 * Returns the X position of an html element
18757 * @param el the element for which to get the position
18758 * @return {int} the X coordinate
18760 * @deprecated use Roo.lib.Dom.getX instead
18763 getPosX: function(el) {
18764 return Roo.lib.Dom.getX(el);
18768 * Returns the Y position of an html element
18770 * @param el the element for which to get the position
18771 * @return {int} the Y coordinate
18772 * @deprecated use Roo.lib.Dom.getY instead
18775 getPosY: function(el) {
18776 return Roo.lib.Dom.getY(el);
18780 * Swap two nodes. In IE, we use the native method, for others we
18781 * emulate the IE behavior
18783 * @param n1 the first node to swap
18784 * @param n2 the other node to swap
18787 swapNode: function(n1, n2) {
18791 var p = n2.parentNode;
18792 var s = n2.nextSibling;
18795 p.insertBefore(n1, n2);
18796 } else if (n2 == n1.nextSibling) {
18797 p.insertBefore(n2, n1);
18799 n1.parentNode.replaceChild(n2, n1);
18800 p.insertBefore(n1, s);
18806 * Returns the current scroll position
18807 * @method getScroll
18811 getScroll: function () {
18812 var t, l, dde=document.documentElement, db=document.body;
18813 if (dde && (dde.scrollTop || dde.scrollLeft)) {
18815 l = dde.scrollLeft;
18822 return { top: t, left: l };
18826 * Returns the specified element style property
18828 * @param {HTMLElement} el the element
18829 * @param {string} styleProp the style property
18830 * @return {string} The value of the style property
18831 * @deprecated use Roo.lib.Dom.getStyle
18834 getStyle: function(el, styleProp) {
18835 return Roo.fly(el).getStyle(styleProp);
18839 * Gets the scrollTop
18840 * @method getScrollTop
18841 * @return {int} the document's scrollTop
18844 getScrollTop: function () { return this.getScroll().top; },
18847 * Gets the scrollLeft
18848 * @method getScrollLeft
18849 * @return {int} the document's scrollTop
18852 getScrollLeft: function () { return this.getScroll().left; },
18855 * Sets the x/y position of an element to the location of the
18858 * @param {HTMLElement} moveEl The element to move
18859 * @param {HTMLElement} targetEl The position reference element
18862 moveToEl: function (moveEl, targetEl) {
18863 var aCoord = Roo.lib.Dom.getXY(targetEl);
18864 Roo.lib.Dom.setXY(moveEl, aCoord);
18868 * Numeric array sort function
18869 * @method numericSort
18872 numericSort: function(a, b) { return (a - b); },
18876 * @property _timeoutCount
18883 * Trying to make the load order less important. Without this we get
18884 * an error if this file is loaded before the Event Utility.
18885 * @method _addListeners
18889 _addListeners: function() {
18890 var DDM = Roo.dd.DDM;
18891 if ( Roo.lib.Event && document ) {
18894 if (DDM._timeoutCount > 2000) {
18896 setTimeout(DDM._addListeners, 10);
18897 if (document && document.body) {
18898 DDM._timeoutCount += 1;
18905 * Recursively searches the immediate parent and all child nodes for
18906 * the handle element in order to determine wheter or not it was
18908 * @method handleWasClicked
18909 * @param node the html element to inspect
18912 handleWasClicked: function(node, id) {
18913 if (this.isHandle(id, node.id)) {
18916 // check to see if this is a text node child of the one we want
18917 var p = node.parentNode;
18920 if (this.isHandle(id, p.id)) {
18935 // shorter alias, save a few bytes
18936 Roo.dd.DDM = Roo.dd.DragDropMgr;
18937 Roo.dd.DDM._addListeners();
18941 * Ext JS Library 1.1.1
18942 * Copyright(c) 2006-2007, Ext JS, LLC.
18944 * Originally Released Under LGPL - original licence link has changed is not relivant.
18947 * <script type="text/javascript">
18952 * A DragDrop implementation where the linked element follows the
18953 * mouse cursor during a drag.
18954 * @extends Roo.dd.DragDrop
18956 * @param {String} id the id of the linked element
18957 * @param {String} sGroup the group of related DragDrop items
18958 * @param {object} config an object containing configurable attributes
18959 * Valid properties for DD:
18962 Roo.dd.DD = function(id, sGroup, config) {
18964 this.init(id, sGroup, config);
18968 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
18971 * When set to true, the utility automatically tries to scroll the browser
18972 * window wehn a drag and drop element is dragged near the viewport boundary.
18973 * Defaults to true.
18980 * Sets the pointer offset to the distance between the linked element's top
18981 * left corner and the location the element was clicked
18982 * @method autoOffset
18983 * @param {int} iPageX the X coordinate of the click
18984 * @param {int} iPageY the Y coordinate of the click
18986 autoOffset: function(iPageX, iPageY) {
18987 var x = iPageX - this.startPageX;
18988 var y = iPageY - this.startPageY;
18989 this.setDelta(x, y);
18993 * Sets the pointer offset. You can call this directly to force the
18994 * offset to be in a particular location (e.g., pass in 0,0 to set it
18995 * to the center of the object)
18997 * @param {int} iDeltaX the distance from the left
18998 * @param {int} iDeltaY the distance from the top
19000 setDelta: function(iDeltaX, iDeltaY) {
19001 this.deltaX = iDeltaX;
19002 this.deltaY = iDeltaY;
19006 * Sets the drag element to the location of the mousedown or click event,
19007 * maintaining the cursor location relative to the location on the element
19008 * that was clicked. Override this if you want to place the element in a
19009 * location other than where the cursor is.
19010 * @method setDragElPos
19011 * @param {int} iPageX the X coordinate of the mousedown or drag event
19012 * @param {int} iPageY the Y coordinate of the mousedown or drag event
19014 setDragElPos: function(iPageX, iPageY) {
19015 // the first time we do this, we are going to check to make sure
19016 // the element has css positioning
19018 var el = this.getDragEl();
19019 this.alignElWithMouse(el, iPageX, iPageY);
19023 * Sets the element to the location of the mousedown or click event,
19024 * maintaining the cursor location relative to the location on the element
19025 * that was clicked. Override this if you want to place the element in a
19026 * location other than where the cursor is.
19027 * @method alignElWithMouse
19028 * @param {HTMLElement} el the element to move
19029 * @param {int} iPageX the X coordinate of the mousedown or drag event
19030 * @param {int} iPageY the Y coordinate of the mousedown or drag event
19032 alignElWithMouse: function(el, iPageX, iPageY) {
19033 var oCoord = this.getTargetCoord(iPageX, iPageY);
19034 var fly = el.dom ? el : Roo.fly(el);
19035 if (!this.deltaSetXY) {
19036 var aCoord = [oCoord.x, oCoord.y];
19038 var newLeft = fly.getLeft(true);
19039 var newTop = fly.getTop(true);
19040 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
19042 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
19045 this.cachePosition(oCoord.x, oCoord.y);
19046 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
19051 * Saves the most recent position so that we can reset the constraints and
19052 * tick marks on-demand. We need to know this so that we can calculate the
19053 * number of pixels the element is offset from its original position.
19054 * @method cachePosition
19055 * @param iPageX the current x position (optional, this just makes it so we
19056 * don't have to look it up again)
19057 * @param iPageY the current y position (optional, this just makes it so we
19058 * don't have to look it up again)
19060 cachePosition: function(iPageX, iPageY) {
19062 this.lastPageX = iPageX;
19063 this.lastPageY = iPageY;
19065 var aCoord = Roo.lib.Dom.getXY(this.getEl());
19066 this.lastPageX = aCoord[0];
19067 this.lastPageY = aCoord[1];
19072 * Auto-scroll the window if the dragged object has been moved beyond the
19073 * visible window boundary.
19074 * @method autoScroll
19075 * @param {int} x the drag element's x position
19076 * @param {int} y the drag element's y position
19077 * @param {int} h the height of the drag element
19078 * @param {int} w the width of the drag element
19081 autoScroll: function(x, y, h, w) {
19084 // The client height
19085 var clientH = Roo.lib.Dom.getViewWidth();
19087 // The client width
19088 var clientW = Roo.lib.Dom.getViewHeight();
19090 // The amt scrolled down
19091 var st = this.DDM.getScrollTop();
19093 // The amt scrolled right
19094 var sl = this.DDM.getScrollLeft();
19096 // Location of the bottom of the element
19099 // Location of the right of the element
19102 // The distance from the cursor to the bottom of the visible area,
19103 // adjusted so that we don't scroll if the cursor is beyond the
19104 // element drag constraints
19105 var toBot = (clientH + st - y - this.deltaY);
19107 // The distance from the cursor to the right of the visible area
19108 var toRight = (clientW + sl - x - this.deltaX);
19111 // How close to the edge the cursor must be before we scroll
19112 // var thresh = (document.all) ? 100 : 40;
19115 // How many pixels to scroll per autoscroll op. This helps to reduce
19116 // clunky scrolling. IE is more sensitive about this ... it needs this
19117 // value to be higher.
19118 var scrAmt = (document.all) ? 80 : 30;
19120 // Scroll down if we are near the bottom of the visible page and the
19121 // obj extends below the crease
19122 if ( bot > clientH && toBot < thresh ) {
19123 window.scrollTo(sl, st + scrAmt);
19126 // Scroll up if the window is scrolled down and the top of the object
19127 // goes above the top border
19128 if ( y < st && st > 0 && y - st < thresh ) {
19129 window.scrollTo(sl, st - scrAmt);
19132 // Scroll right if the obj is beyond the right border and the cursor is
19133 // near the border.
19134 if ( right > clientW && toRight < thresh ) {
19135 window.scrollTo(sl + scrAmt, st);
19138 // Scroll left if the window has been scrolled to the right and the obj
19139 // extends past the left border
19140 if ( x < sl && sl > 0 && x - sl < thresh ) {
19141 window.scrollTo(sl - scrAmt, st);
19147 * Finds the location the element should be placed if we want to move
19148 * it to where the mouse location less the click offset would place us.
19149 * @method getTargetCoord
19150 * @param {int} iPageX the X coordinate of the click
19151 * @param {int} iPageY the Y coordinate of the click
19152 * @return an object that contains the coordinates (Object.x and Object.y)
19155 getTargetCoord: function(iPageX, iPageY) {
19158 var x = iPageX - this.deltaX;
19159 var y = iPageY - this.deltaY;
19161 if (this.constrainX) {
19162 if (x < this.minX) { x = this.minX; }
19163 if (x > this.maxX) { x = this.maxX; }
19166 if (this.constrainY) {
19167 if (y < this.minY) { y = this.minY; }
19168 if (y > this.maxY) { y = this.maxY; }
19171 x = this.getTick(x, this.xTicks);
19172 y = this.getTick(y, this.yTicks);
19179 * Sets up config options specific to this class. Overrides
19180 * Roo.dd.DragDrop, but all versions of this method through the
19181 * inheritance chain are called
19183 applyConfig: function() {
19184 Roo.dd.DD.superclass.applyConfig.call(this);
19185 this.scroll = (this.config.scroll !== false);
19189 * Event that fires prior to the onMouseDown event. Overrides
19192 b4MouseDown: function(e) {
19193 // this.resetConstraints();
19194 this.autoOffset(e.getPageX(),
19199 * Event that fires prior to the onDrag event. Overrides
19202 b4Drag: function(e) {
19203 this.setDragElPos(e.getPageX(),
19207 toString: function() {
19208 return ("DD " + this.id);
19211 //////////////////////////////////////////////////////////////////////////
19212 // Debugging ygDragDrop events that can be overridden
19213 //////////////////////////////////////////////////////////////////////////
19215 startDrag: function(x, y) {
19218 onDrag: function(e) {
19221 onDragEnter: function(e, id) {
19224 onDragOver: function(e, id) {
19227 onDragOut: function(e, id) {
19230 onDragDrop: function(e, id) {
19233 endDrag: function(e) {
19240 * Ext JS Library 1.1.1
19241 * Copyright(c) 2006-2007, Ext JS, LLC.
19243 * Originally Released Under LGPL - original licence link has changed is not relivant.
19246 * <script type="text/javascript">
19250 * @class Roo.dd.DDProxy
19251 * A DragDrop implementation that inserts an empty, bordered div into
19252 * the document that follows the cursor during drag operations. At the time of
19253 * the click, the frame div is resized to the dimensions of the linked html
19254 * element, and moved to the exact location of the linked element.
19256 * References to the "frame" element refer to the single proxy element that
19257 * was created to be dragged in place of all DDProxy elements on the
19260 * @extends Roo.dd.DD
19262 * @param {String} id the id of the linked html element
19263 * @param {String} sGroup the group of related DragDrop objects
19264 * @param {object} config an object containing configurable attributes
19265 * Valid properties for DDProxy in addition to those in DragDrop:
19266 * resizeFrame, centerFrame, dragElId
19268 Roo.dd.DDProxy = function(id, sGroup, config) {
19270 this.init(id, sGroup, config);
19276 * The default drag frame div id
19277 * @property Roo.dd.DDProxy.dragElId
19281 Roo.dd.DDProxy.dragElId = "ygddfdiv";
19283 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
19286 * By default we resize the drag frame to be the same size as the element
19287 * we want to drag (this is to get the frame effect). We can turn it off
19288 * if we want a different behavior.
19289 * @property resizeFrame
19295 * By default the frame is positioned exactly where the drag element is, so
19296 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
19297 * you do not have constraints on the obj is to have the drag frame centered
19298 * around the cursor. Set centerFrame to true for this effect.
19299 * @property centerFrame
19302 centerFrame: false,
19305 * Creates the proxy element if it does not yet exist
19306 * @method createFrame
19308 createFrame: function() {
19310 var body = document.body;
19312 if (!body || !body.firstChild) {
19313 setTimeout( function() { self.createFrame(); }, 50 );
19317 var div = this.getDragEl();
19320 div = document.createElement("div");
19321 div.id = this.dragElId;
19324 s.position = "absolute";
19325 s.visibility = "hidden";
19327 s.border = "2px solid #aaa";
19330 // appendChild can blow up IE if invoked prior to the window load event
19331 // while rendering a table. It is possible there are other scenarios
19332 // that would cause this to happen as well.
19333 body.insertBefore(div, body.firstChild);
19338 * Initialization for the drag frame element. Must be called in the
19339 * constructor of all subclasses
19340 * @method initFrame
19342 initFrame: function() {
19343 this.createFrame();
19346 applyConfig: function() {
19347 Roo.dd.DDProxy.superclass.applyConfig.call(this);
19349 this.resizeFrame = (this.config.resizeFrame !== false);
19350 this.centerFrame = (this.config.centerFrame);
19351 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
19355 * Resizes the drag frame to the dimensions of the clicked object, positions
19356 * it over the object, and finally displays it
19357 * @method showFrame
19358 * @param {int} iPageX X click position
19359 * @param {int} iPageY Y click position
19362 showFrame: function(iPageX, iPageY) {
19363 var el = this.getEl();
19364 var dragEl = this.getDragEl();
19365 var s = dragEl.style;
19367 this._resizeProxy();
19369 if (this.centerFrame) {
19370 this.setDelta( Math.round(parseInt(s.width, 10)/2),
19371 Math.round(parseInt(s.height, 10)/2) );
19374 this.setDragElPos(iPageX, iPageY);
19376 Roo.fly(dragEl).show();
19380 * The proxy is automatically resized to the dimensions of the linked
19381 * element when a drag is initiated, unless resizeFrame is set to false
19382 * @method _resizeProxy
19385 _resizeProxy: function() {
19386 if (this.resizeFrame) {
19387 var el = this.getEl();
19388 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
19392 // overrides Roo.dd.DragDrop
19393 b4MouseDown: function(e) {
19394 var x = e.getPageX();
19395 var y = e.getPageY();
19396 this.autoOffset(x, y);
19397 this.setDragElPos(x, y);
19400 // overrides Roo.dd.DragDrop
19401 b4StartDrag: function(x, y) {
19402 // show the drag frame
19403 this.showFrame(x, y);
19406 // overrides Roo.dd.DragDrop
19407 b4EndDrag: function(e) {
19408 Roo.fly(this.getDragEl()).hide();
19411 // overrides Roo.dd.DragDrop
19412 // By default we try to move the element to the last location of the frame.
19413 // This is so that the default behavior mirrors that of Roo.dd.DD.
19414 endDrag: function(e) {
19416 var lel = this.getEl();
19417 var del = this.getDragEl();
19419 // Show the drag frame briefly so we can get its position
19420 del.style.visibility = "";
19423 // Hide the linked element before the move to get around a Safari
19425 lel.style.visibility = "hidden";
19426 Roo.dd.DDM.moveToEl(lel, del);
19427 del.style.visibility = "hidden";
19428 lel.style.visibility = "";
19433 beforeMove : function(){
19437 afterDrag : function(){
19441 toString: function() {
19442 return ("DDProxy " + this.id);
19448 * Ext JS Library 1.1.1
19449 * Copyright(c) 2006-2007, Ext JS, LLC.
19451 * Originally Released Under LGPL - original licence link has changed is not relivant.
19454 * <script type="text/javascript">
19458 * @class Roo.dd.DDTarget
19459 * A DragDrop implementation that does not move, but can be a drop
19460 * target. You would get the same result by simply omitting implementation
19461 * for the event callbacks, but this way we reduce the processing cost of the
19462 * event listener and the callbacks.
19463 * @extends Roo.dd.DragDrop
19465 * @param {String} id the id of the element that is a drop target
19466 * @param {String} sGroup the group of related DragDrop objects
19467 * @param {object} config an object containing configurable attributes
19468 * Valid properties for DDTarget in addition to those in
19472 Roo.dd.DDTarget = function(id, sGroup, config) {
19474 this.initTarget(id, sGroup, config);
19476 if (config.listeners || config.events) {
19477 Roo.dd.DragDrop.superclass.constructor.call(this, {
19478 listeners : config.listeners || {},
19479 events : config.events || {}
19484 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
19485 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
19486 toString: function() {
19487 return ("DDTarget " + this.id);
19492 * Ext JS Library 1.1.1
19493 * Copyright(c) 2006-2007, Ext JS, LLC.
19495 * Originally Released Under LGPL - original licence link has changed is not relivant.
19498 * <script type="text/javascript">
19503 * @class Roo.dd.ScrollManager
19504 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
19505 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
19508 Roo.dd.ScrollManager = function(){
19509 var ddm = Roo.dd.DragDropMgr;
19516 var onStop = function(e){
19521 var triggerRefresh = function(){
19522 if(ddm.dragCurrent){
19523 ddm.refreshCache(ddm.dragCurrent.groups);
19527 var doScroll = function(){
19528 if(ddm.dragCurrent){
19529 var dds = Roo.dd.ScrollManager;
19531 if(proc.el.scroll(proc.dir, dds.increment)){
19535 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
19540 var clearProc = function(){
19542 clearInterval(proc.id);
19549 var startProc = function(el, dir){
19550 Roo.log('scroll startproc');
19554 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
19557 var onFire = function(e, isDrop){
19559 if(isDrop || !ddm.dragCurrent){ return; }
19560 var dds = Roo.dd.ScrollManager;
19561 if(!dragEl || dragEl != ddm.dragCurrent){
19562 dragEl = ddm.dragCurrent;
19563 // refresh regions on drag start
19564 dds.refreshCache();
19567 var xy = Roo.lib.Event.getXY(e);
19568 var pt = new Roo.lib.Point(xy[0], xy[1]);
19569 for(var id in els){
19570 var el = els[id], r = el._region;
19571 if(r && r.contains(pt) && el.isScrollable()){
19572 if(r.bottom - pt.y <= dds.thresh){
19574 startProc(el, "down");
19577 }else if(r.right - pt.x <= dds.thresh){
19579 startProc(el, "left");
19582 }else if(pt.y - r.top <= dds.thresh){
19584 startProc(el, "up");
19587 }else if(pt.x - r.left <= dds.thresh){
19589 startProc(el, "right");
19598 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
19599 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
19603 * Registers new overflow element(s) to auto scroll
19604 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
19606 register : function(el){
19607 if(el instanceof Array){
19608 for(var i = 0, len = el.length; i < len; i++) {
19609 this.register(el[i]);
19615 Roo.dd.ScrollManager.els = els;
19619 * Unregisters overflow element(s) so they are no longer scrolled
19620 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
19622 unregister : function(el){
19623 if(el instanceof Array){
19624 for(var i = 0, len = el.length; i < len; i++) {
19625 this.unregister(el[i]);
19634 * The number of pixels from the edge of a container the pointer needs to be to
19635 * trigger scrolling (defaults to 25)
19641 * The number of pixels to scroll in each scroll increment (defaults to 50)
19647 * The frequency of scrolls in milliseconds (defaults to 500)
19653 * True to animate the scroll (defaults to true)
19659 * The animation duration in seconds -
19660 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
19666 * Manually trigger a cache refresh.
19668 refreshCache : function(){
19669 for(var id in els){
19670 if(typeof els[id] == 'object'){ // for people extending the object prototype
19671 els[id]._region = els[id].getRegion();
19678 * Ext JS Library 1.1.1
19679 * Copyright(c) 2006-2007, Ext JS, LLC.
19681 * Originally Released Under LGPL - original licence link has changed is not relivant.
19684 * <script type="text/javascript">
19689 * @class Roo.dd.Registry
19690 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
19691 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
19694 Roo.dd.Registry = function(){
19697 var autoIdSeed = 0;
19699 var getId = function(el, autogen){
19700 if(typeof el == "string"){
19704 if(!id && autogen !== false){
19705 id = "roodd-" + (++autoIdSeed);
19713 * Register a drag drop element
19714 * @param {String|HTMLElement} element The id or DOM node to register
19715 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
19716 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
19717 * knows how to interpret, plus there are some specific properties known to the Registry that should be
19718 * populated in the data object (if applicable):
19720 Value Description<br />
19721 --------- ------------------------------------------<br />
19722 handles Array of DOM nodes that trigger dragging<br />
19723 for the element being registered<br />
19724 isHandle True if the element passed in triggers<br />
19725 dragging itself, else false
19728 register : function(el, data){
19730 if(typeof el == "string"){
19731 el = document.getElementById(el);
19734 elements[getId(el)] = data;
19735 if(data.isHandle !== false){
19736 handles[data.ddel.id] = data;
19739 var hs = data.handles;
19740 for(var i = 0, len = hs.length; i < len; i++){
19741 handles[getId(hs[i])] = data;
19747 * Unregister a drag drop element
19748 * @param {String|HTMLElement} element The id or DOM node to unregister
19750 unregister : function(el){
19751 var id = getId(el, false);
19752 var data = elements[id];
19754 delete elements[id];
19756 var hs = data.handles;
19757 for(var i = 0, len = hs.length; i < len; i++){
19758 delete handles[getId(hs[i], false)];
19765 * Returns the handle registered for a DOM Node by id
19766 * @param {String|HTMLElement} id The DOM node or id to look up
19767 * @return {Object} handle The custom handle data
19769 getHandle : function(id){
19770 if(typeof id != "string"){ // must be element?
19773 return handles[id];
19777 * Returns the handle that is registered for the DOM node that is the target of the event
19778 * @param {Event} e The event
19779 * @return {Object} handle The custom handle data
19781 getHandleFromEvent : function(e){
19782 var t = Roo.lib.Event.getTarget(e);
19783 return t ? handles[t.id] : null;
19787 * Returns a custom data object that is registered for a DOM node by id
19788 * @param {String|HTMLElement} id The DOM node or id to look up
19789 * @return {Object} data The custom data
19791 getTarget : function(id){
19792 if(typeof id != "string"){ // must be element?
19795 return elements[id];
19799 * Returns a custom data object that is registered for the DOM node that is the target of the event
19800 * @param {Event} e The event
19801 * @return {Object} data The custom data
19803 getTargetFromEvent : function(e){
19804 var t = Roo.lib.Event.getTarget(e);
19805 return t ? elements[t.id] || handles[t.id] : null;
19810 * Ext JS Library 1.1.1
19811 * Copyright(c) 2006-2007, Ext JS, LLC.
19813 * Originally Released Under LGPL - original licence link has changed is not relivant.
19816 * <script type="text/javascript">
19821 * @class Roo.dd.StatusProxy
19822 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
19823 * default drag proxy used by all Roo.dd components.
19825 * @param {Object} config
19827 Roo.dd.StatusProxy = function(config){
19828 Roo.apply(this, config);
19829 this.id = this.id || Roo.id();
19830 this.el = new Roo.Layer({
19832 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
19833 {tag: "div", cls: "x-dd-drop-icon"},
19834 {tag: "div", cls: "x-dd-drag-ghost"}
19837 shadow: !config || config.shadow !== false
19839 this.ghost = Roo.get(this.el.dom.childNodes[1]);
19840 this.dropStatus = this.dropNotAllowed;
19843 Roo.dd.StatusProxy.prototype = {
19845 * @cfg {String} dropAllowed
19846 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
19848 dropAllowed : "x-dd-drop-ok",
19850 * @cfg {String} dropNotAllowed
19851 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
19853 dropNotAllowed : "x-dd-drop-nodrop",
19856 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
19857 * over the current target element.
19858 * @param {String} cssClass The css class for the new drop status indicator image
19860 setStatus : function(cssClass){
19861 cssClass = cssClass || this.dropNotAllowed;
19862 if(this.dropStatus != cssClass){
19863 this.el.replaceClass(this.dropStatus, cssClass);
19864 this.dropStatus = cssClass;
19869 * Resets the status indicator to the default dropNotAllowed value
19870 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
19872 reset : function(clearGhost){
19873 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
19874 this.dropStatus = this.dropNotAllowed;
19876 this.ghost.update("");
19881 * Updates the contents of the ghost element
19882 * @param {String} html The html that will replace the current innerHTML of the ghost element
19884 update : function(html){
19885 if(typeof html == "string"){
19886 this.ghost.update(html);
19888 this.ghost.update("");
19889 html.style.margin = "0";
19890 this.ghost.dom.appendChild(html);
19892 // ensure float = none set?? cant remember why though.
19893 var el = this.ghost.dom.firstChild;
19895 Roo.fly(el).setStyle('float', 'none');
19900 * Returns the underlying proxy {@link Roo.Layer}
19901 * @return {Roo.Layer} el
19903 getEl : function(){
19908 * Returns the ghost element
19909 * @return {Roo.Element} el
19911 getGhost : function(){
19917 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
19919 hide : function(clear){
19927 * Stops the repair animation if it's currently running
19930 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
19936 * Displays this proxy
19943 * Force the Layer to sync its shadow and shim positions to the element
19950 * Causes the proxy to return to its position of origin via an animation. Should be called after an
19951 * invalid drop operation by the item being dragged.
19952 * @param {Array} xy The XY position of the element ([x, y])
19953 * @param {Function} callback The function to call after the repair is complete
19954 * @param {Object} scope The scope in which to execute the callback
19956 repair : function(xy, callback, scope){
19957 this.callback = callback;
19958 this.scope = scope;
19959 if(xy && this.animRepair !== false){
19960 this.el.addClass("x-dd-drag-repair");
19961 this.el.hideUnders(true);
19962 this.anim = this.el.shift({
19963 duration: this.repairDuration || .5,
19967 callback: this.afterRepair,
19971 this.afterRepair();
19976 afterRepair : function(){
19978 if(typeof this.callback == "function"){
19979 this.callback.call(this.scope || this);
19981 this.callback = null;
19986 * Ext JS Library 1.1.1
19987 * Copyright(c) 2006-2007, Ext JS, LLC.
19989 * Originally Released Under LGPL - original licence link has changed is not relivant.
19992 * <script type="text/javascript">
19996 * @class Roo.dd.DragSource
19997 * @extends Roo.dd.DDProxy
19998 * A simple class that provides the basic implementation needed to make any element draggable.
20000 * @param {String/HTMLElement/Element} el The container element
20001 * @param {Object} config
20003 Roo.dd.DragSource = function(el, config){
20004 this.el = Roo.get(el);
20005 this.dragData = {};
20007 Roo.apply(this, config);
20010 this.proxy = new Roo.dd.StatusProxy();
20013 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
20014 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
20016 this.dragging = false;
20019 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
20021 * @cfg {String} dropAllowed
20022 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
20024 dropAllowed : "x-dd-drop-ok",
20026 * @cfg {String} dropNotAllowed
20027 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
20029 dropNotAllowed : "x-dd-drop-nodrop",
20032 * Returns the data object associated with this drag source
20033 * @return {Object} data An object containing arbitrary data
20035 getDragData : function(e){
20036 return this.dragData;
20040 onDragEnter : function(e, id){
20041 var target = Roo.dd.DragDropMgr.getDDById(id);
20042 this.cachedTarget = target;
20043 if(this.beforeDragEnter(target, e, id) !== false){
20044 if(target.isNotifyTarget){
20045 var status = target.notifyEnter(this, e, this.dragData);
20046 this.proxy.setStatus(status);
20048 this.proxy.setStatus(this.dropAllowed);
20051 if(this.afterDragEnter){
20053 * An empty function by default, but provided so that you can perform a custom action
20054 * when the dragged item enters the drop target by providing an implementation.
20055 * @param {Roo.dd.DragDrop} target The drop target
20056 * @param {Event} e The event object
20057 * @param {String} id The id of the dragged element
20058 * @method afterDragEnter
20060 this.afterDragEnter(target, e, id);
20066 * An empty function by default, but provided so that you can perform a custom action
20067 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
20068 * @param {Roo.dd.DragDrop} target The drop target
20069 * @param {Event} e The event object
20070 * @param {String} id The id of the dragged element
20071 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20073 beforeDragEnter : function(target, e, id){
20078 alignElWithMouse: function() {
20079 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
20084 onDragOver : function(e, id){
20085 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20086 if(this.beforeDragOver(target, e, id) !== false){
20087 if(target.isNotifyTarget){
20088 var status = target.notifyOver(this, e, this.dragData);
20089 this.proxy.setStatus(status);
20092 if(this.afterDragOver){
20094 * An empty function by default, but provided so that you can perform a custom action
20095 * while the dragged item is over the drop target by providing an implementation.
20096 * @param {Roo.dd.DragDrop} target The drop target
20097 * @param {Event} e The event object
20098 * @param {String} id The id of the dragged element
20099 * @method afterDragOver
20101 this.afterDragOver(target, e, id);
20107 * An empty function by default, but provided so that you can perform a custom action
20108 * while the dragged item is over the drop target and optionally cancel the onDragOver.
20109 * @param {Roo.dd.DragDrop} target The drop target
20110 * @param {Event} e The event object
20111 * @param {String} id The id of the dragged element
20112 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20114 beforeDragOver : function(target, e, id){
20119 onDragOut : function(e, id){
20120 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20121 if(this.beforeDragOut(target, e, id) !== false){
20122 if(target.isNotifyTarget){
20123 target.notifyOut(this, e, this.dragData);
20125 this.proxy.reset();
20126 if(this.afterDragOut){
20128 * An empty function by default, but provided so that you can perform a custom action
20129 * after the dragged item is dragged out of the target without dropping.
20130 * @param {Roo.dd.DragDrop} target The drop target
20131 * @param {Event} e The event object
20132 * @param {String} id The id of the dragged element
20133 * @method afterDragOut
20135 this.afterDragOut(target, e, id);
20138 this.cachedTarget = null;
20142 * An empty function by default, but provided so that you can perform a custom action before the dragged
20143 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
20144 * @param {Roo.dd.DragDrop} target The drop target
20145 * @param {Event} e The event object
20146 * @param {String} id The id of the dragged element
20147 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20149 beforeDragOut : function(target, e, id){
20154 onDragDrop : function(e, id){
20155 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
20156 if(this.beforeDragDrop(target, e, id) !== false){
20157 if(target.isNotifyTarget){
20158 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
20159 this.onValidDrop(target, e, id);
20161 this.onInvalidDrop(target, e, id);
20164 this.onValidDrop(target, e, id);
20167 if(this.afterDragDrop){
20169 * An empty function by default, but provided so that you can perform a custom action
20170 * after a valid drag drop has occurred by providing an implementation.
20171 * @param {Roo.dd.DragDrop} target The drop target
20172 * @param {Event} e The event object
20173 * @param {String} id The id of the dropped element
20174 * @method afterDragDrop
20176 this.afterDragDrop(target, e, id);
20179 delete this.cachedTarget;
20183 * An empty function by default, but provided so that you can perform a custom action before the dragged
20184 * item is dropped onto the target and optionally cancel the onDragDrop.
20185 * @param {Roo.dd.DragDrop} target The drop target
20186 * @param {Event} e The event object
20187 * @param {String} id The id of the dragged element
20188 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
20190 beforeDragDrop : function(target, e, id){
20195 onValidDrop : function(target, e, id){
20197 if(this.afterValidDrop){
20199 * An empty function by default, but provided so that you can perform a custom action
20200 * after a valid drop has occurred by providing an implementation.
20201 * @param {Object} target The target DD
20202 * @param {Event} e The event object
20203 * @param {String} id The id of the dropped element
20204 * @method afterInvalidDrop
20206 this.afterValidDrop(target, e, id);
20211 getRepairXY : function(e, data){
20212 return this.el.getXY();
20216 onInvalidDrop : function(target, e, id){
20217 this.beforeInvalidDrop(target, e, id);
20218 if(this.cachedTarget){
20219 if(this.cachedTarget.isNotifyTarget){
20220 this.cachedTarget.notifyOut(this, e, this.dragData);
20222 this.cacheTarget = null;
20224 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
20226 if(this.afterInvalidDrop){
20228 * An empty function by default, but provided so that you can perform a custom action
20229 * after an invalid drop has occurred by providing an implementation.
20230 * @param {Event} e The event object
20231 * @param {String} id The id of the dropped element
20232 * @method afterInvalidDrop
20234 this.afterInvalidDrop(e, id);
20239 afterRepair : function(){
20241 this.el.highlight(this.hlColor || "c3daf9");
20243 this.dragging = false;
20247 * An empty function by default, but provided so that you can perform a custom action after an invalid
20248 * drop has occurred.
20249 * @param {Roo.dd.DragDrop} target The drop target
20250 * @param {Event} e The event object
20251 * @param {String} id The id of the dragged element
20252 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
20254 beforeInvalidDrop : function(target, e, id){
20259 handleMouseDown : function(e){
20260 if(this.dragging) {
20263 var data = this.getDragData(e);
20264 if(data && this.onBeforeDrag(data, e) !== false){
20265 this.dragData = data;
20267 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
20272 * An empty function by default, but provided so that you can perform a custom action before the initial
20273 * drag event begins and optionally cancel it.
20274 * @param {Object} data An object containing arbitrary data to be shared with drop targets
20275 * @param {Event} e The event object
20276 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
20278 onBeforeDrag : function(data, e){
20283 * An empty function by default, but provided so that you can perform a custom action once the initial
20284 * drag event has begun. The drag cannot be canceled from this function.
20285 * @param {Number} x The x position of the click on the dragged object
20286 * @param {Number} y The y position of the click on the dragged object
20288 onStartDrag : Roo.emptyFn,
20290 // private - YUI override
20291 startDrag : function(x, y){
20292 this.proxy.reset();
20293 this.dragging = true;
20294 this.proxy.update("");
20295 this.onInitDrag(x, y);
20300 onInitDrag : function(x, y){
20301 var clone = this.el.dom.cloneNode(true);
20302 clone.id = Roo.id(); // prevent duplicate ids
20303 this.proxy.update(clone);
20304 this.onStartDrag(x, y);
20309 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
20310 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
20312 getProxy : function(){
20317 * Hides the drag source's {@link Roo.dd.StatusProxy}
20319 hideProxy : function(){
20321 this.proxy.reset(true);
20322 this.dragging = false;
20326 triggerCacheRefresh : function(){
20327 Roo.dd.DDM.refreshCache(this.groups);
20330 // private - override to prevent hiding
20331 b4EndDrag: function(e) {
20334 // private - override to prevent moving
20335 endDrag : function(e){
20336 this.onEndDrag(this.dragData, e);
20340 onEndDrag : function(data, e){
20343 // private - pin to cursor
20344 autoOffset : function(x, y) {
20345 this.setDelta(-12, -20);
20349 * Ext JS Library 1.1.1
20350 * Copyright(c) 2006-2007, Ext JS, LLC.
20352 * Originally Released Under LGPL - original licence link has changed is not relivant.
20355 * <script type="text/javascript">
20360 * @class Roo.dd.DropTarget
20361 * @extends Roo.dd.DDTarget
20362 * A simple class that provides the basic implementation needed to make any element a drop target that can have
20363 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
20365 * @param {String/HTMLElement/Element} el The container element
20366 * @param {Object} config
20368 Roo.dd.DropTarget = function(el, config){
20369 this.el = Roo.get(el);
20371 var listeners = false; ;
20372 if (config && config.listeners) {
20373 listeners= config.listeners;
20374 delete config.listeners;
20376 Roo.apply(this, config);
20378 if(this.containerScroll){
20379 Roo.dd.ScrollManager.register(this.el);
20383 * @scope Roo.dd.DropTarget
20388 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
20389 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
20390 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
20392 * IMPORTANT : it should set this.overClass and this.dropAllowed
20394 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20395 * @param {Event} e The event
20396 * @param {Object} data An object containing arbitrary data supplied by the drag source
20402 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
20403 * This method will be called on every mouse movement while the drag source is over the drop target.
20404 * This default implementation simply returns the dropAllowed config value.
20406 * IMPORTANT : it should set this.dropAllowed
20408 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20409 * @param {Event} e The event
20410 * @param {Object} data An object containing arbitrary data supplied by the drag source
20416 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
20417 * out of the target without dropping. This default implementation simply removes the CSS class specified by
20418 * overClass (if any) from the drop element.
20420 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20421 * @param {Event} e The event
20422 * @param {Object} data An object containing arbitrary data supplied by the drag source
20428 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
20429 * been dropped on it. This method has no default implementation and returns false, so you must provide an
20430 * implementation that does something to process the drop event and returns true so that the drag source's
20431 * repair action does not run.
20433 * IMPORTANT : it should set this.success
20435 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20436 * @param {Event} e The event
20437 * @param {Object} data An object containing arbitrary data supplied by the drag source
20443 Roo.dd.DropTarget.superclass.constructor.call( this,
20445 this.ddGroup || this.group,
20448 listeners : listeners || {}
20456 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
20458 * @cfg {String} overClass
20459 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
20462 * @cfg {String} ddGroup
20463 * The drag drop group to handle drop events for
20467 * @cfg {String} dropAllowed
20468 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
20470 dropAllowed : "x-dd-drop-ok",
20472 * @cfg {String} dropNotAllowed
20473 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
20475 dropNotAllowed : "x-dd-drop-nodrop",
20477 * @cfg {boolean} success
20478 * set this after drop listener..
20482 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
20483 * if the drop point is valid for over/enter..
20490 isNotifyTarget : true,
20495 notifyEnter : function(dd, e, data)
20498 this.fireEvent('enter', dd, e, data);
20499 if(this.overClass){
20500 this.el.addClass(this.overClass);
20502 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
20503 this.valid ? this.dropAllowed : this.dropNotAllowed
20510 notifyOver : function(dd, e, data)
20513 this.fireEvent('over', dd, e, data);
20514 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
20515 this.valid ? this.dropAllowed : this.dropNotAllowed
20522 notifyOut : function(dd, e, data)
20524 this.fireEvent('out', dd, e, data);
20525 if(this.overClass){
20526 this.el.removeClass(this.overClass);
20533 notifyDrop : function(dd, e, data)
20535 this.success = false;
20536 this.fireEvent('drop', dd, e, data);
20537 return this.success;
20541 * Ext JS Library 1.1.1
20542 * Copyright(c) 2006-2007, Ext JS, LLC.
20544 * Originally Released Under LGPL - original licence link has changed is not relivant.
20547 * <script type="text/javascript">
20552 * @class Roo.dd.DragZone
20553 * @extends Roo.dd.DragSource
20554 * This class provides a container DD instance that proxies for multiple child node sources.<br />
20555 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
20557 * @param {String/HTMLElement/Element} el The container element
20558 * @param {Object} config
20560 Roo.dd.DragZone = function(el, config){
20561 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
20562 if(this.containerScroll){
20563 Roo.dd.ScrollManager.register(this.el);
20567 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
20569 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
20570 * for auto scrolling during drag operations.
20573 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
20574 * method after a failed drop (defaults to "c3daf9" - light blue)
20578 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
20579 * for a valid target to drag based on the mouse down. Override this method
20580 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
20581 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
20582 * @param {EventObject} e The mouse down event
20583 * @return {Object} The dragData
20585 getDragData : function(e){
20586 return Roo.dd.Registry.getHandleFromEvent(e);
20590 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
20591 * this.dragData.ddel
20592 * @param {Number} x The x position of the click on the dragged object
20593 * @param {Number} y The y position of the click on the dragged object
20594 * @return {Boolean} true to continue the drag, false to cancel
20596 onInitDrag : function(x, y){
20597 this.proxy.update(this.dragData.ddel.cloneNode(true));
20598 this.onStartDrag(x, y);
20603 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
20605 afterRepair : function(){
20607 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
20609 this.dragging = false;
20613 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
20614 * the XY of this.dragData.ddel
20615 * @param {EventObject} e The mouse up event
20616 * @return {Array} The xy location (e.g. [100, 200])
20618 getRepairXY : function(e){
20619 return Roo.Element.fly(this.dragData.ddel).getXY();
20623 * Ext JS Library 1.1.1
20624 * Copyright(c) 2006-2007, Ext JS, LLC.
20626 * Originally Released Under LGPL - original licence link has changed is not relivant.
20629 * <script type="text/javascript">
20632 * @class Roo.dd.DropZone
20633 * @extends Roo.dd.DropTarget
20634 * This class provides a container DD instance that proxies for multiple child node targets.<br />
20635 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
20637 * @param {String/HTMLElement/Element} el The container element
20638 * @param {Object} config
20640 Roo.dd.DropZone = function(el, config){
20641 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
20644 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
20646 * Returns a custom data object associated with the DOM node that is the target of the event. By default
20647 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
20648 * provide your own custom lookup.
20649 * @param {Event} e The event
20650 * @return {Object} data The custom data
20652 getTargetFromEvent : function(e){
20653 return Roo.dd.Registry.getTargetFromEvent(e);
20657 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
20658 * that it has registered. This method has no default implementation and should be overridden to provide
20659 * node-specific processing if necessary.
20660 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20661 * {@link #getTargetFromEvent} for this node)
20662 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20663 * @param {Event} e The event
20664 * @param {Object} data An object containing arbitrary data supplied by the drag source
20666 onNodeEnter : function(n, dd, e, data){
20671 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
20672 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
20673 * overridden to provide the proper feedback.
20674 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20675 * {@link #getTargetFromEvent} for this node)
20676 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20677 * @param {Event} e The event
20678 * @param {Object} data An object containing arbitrary data supplied by the drag source
20679 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20680 * underlying {@link Roo.dd.StatusProxy} can be updated
20682 onNodeOver : function(n, dd, e, data){
20683 return this.dropAllowed;
20687 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
20688 * the drop node without dropping. This method has no default implementation and should be overridden to provide
20689 * node-specific processing if necessary.
20690 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20691 * {@link #getTargetFromEvent} for this node)
20692 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20693 * @param {Event} e The event
20694 * @param {Object} data An object containing arbitrary data supplied by the drag source
20696 onNodeOut : function(n, dd, e, data){
20701 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
20702 * the drop node. The default implementation returns false, so it should be overridden to provide the
20703 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
20704 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
20705 * {@link #getTargetFromEvent} for this node)
20706 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20707 * @param {Event} e The event
20708 * @param {Object} data An object containing arbitrary data supplied by the drag source
20709 * @return {Boolean} True if the drop was valid, else false
20711 onNodeDrop : function(n, dd, e, data){
20716 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
20717 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
20718 * it should be overridden to provide the proper feedback if necessary.
20719 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20720 * @param {Event} e The event
20721 * @param {Object} data An object containing arbitrary data supplied by the drag source
20722 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20723 * underlying {@link Roo.dd.StatusProxy} can be updated
20725 onContainerOver : function(dd, e, data){
20726 return this.dropNotAllowed;
20730 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
20731 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
20732 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
20733 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
20734 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20735 * @param {Event} e The event
20736 * @param {Object} data An object containing arbitrary data supplied by the drag source
20737 * @return {Boolean} True if the drop was valid, else false
20739 onContainerDrop : function(dd, e, data){
20744 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
20745 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
20746 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
20747 * you should override this method and provide a custom implementation.
20748 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20749 * @param {Event} e The event
20750 * @param {Object} data An object containing arbitrary data supplied by the drag source
20751 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20752 * underlying {@link Roo.dd.StatusProxy} can be updated
20754 notifyEnter : function(dd, e, data){
20755 return this.dropNotAllowed;
20759 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
20760 * This method will be called on every mouse movement while the drag source is over the drop zone.
20761 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
20762 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
20763 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
20764 * registered node, it will call {@link #onContainerOver}.
20765 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20766 * @param {Event} e The event
20767 * @param {Object} data An object containing arbitrary data supplied by the drag source
20768 * @return {String} status The CSS class that communicates the drop status back to the source so that the
20769 * underlying {@link Roo.dd.StatusProxy} can be updated
20771 notifyOver : function(dd, e, data){
20772 var n = this.getTargetFromEvent(e);
20773 if(!n){ // not over valid drop target
20774 if(this.lastOverNode){
20775 this.onNodeOut(this.lastOverNode, dd, e, data);
20776 this.lastOverNode = null;
20778 return this.onContainerOver(dd, e, data);
20780 if(this.lastOverNode != n){
20781 if(this.lastOverNode){
20782 this.onNodeOut(this.lastOverNode, dd, e, data);
20784 this.onNodeEnter(n, dd, e, data);
20785 this.lastOverNode = n;
20787 return this.onNodeOver(n, dd, e, data);
20791 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
20792 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
20793 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
20794 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
20795 * @param {Event} e The event
20796 * @param {Object} data An object containing arbitrary data supplied by the drag zone
20798 notifyOut : function(dd, e, data){
20799 if(this.lastOverNode){
20800 this.onNodeOut(this.lastOverNode, dd, e, data);
20801 this.lastOverNode = null;
20806 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
20807 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
20808 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
20809 * otherwise it will call {@link #onContainerDrop}.
20810 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
20811 * @param {Event} e The event
20812 * @param {Object} data An object containing arbitrary data supplied by the drag source
20813 * @return {Boolean} True if the drop was valid, else false
20815 notifyDrop : function(dd, e, data){
20816 if(this.lastOverNode){
20817 this.onNodeOut(this.lastOverNode, dd, e, data);
20818 this.lastOverNode = null;
20820 var n = this.getTargetFromEvent(e);
20822 this.onNodeDrop(n, dd, e, data) :
20823 this.onContainerDrop(dd, e, data);
20827 triggerCacheRefresh : function(){
20828 Roo.dd.DDM.refreshCache(this.groups);
20832 * Ext JS Library 1.1.1
20833 * Copyright(c) 2006-2007, Ext JS, LLC.
20835 * Originally Released Under LGPL - original licence link has changed is not relivant.
20838 * <script type="text/javascript">
20843 * @class Roo.data.SortTypes
20845 * Defines the default sorting (casting?) comparison functions used when sorting data.
20847 Roo.data.SortTypes = {
20849 * Default sort that does nothing
20850 * @param {Mixed} s The value being converted
20851 * @return {Mixed} The comparison value
20853 none : function(s){
20858 * The regular expression used to strip tags
20862 stripTagsRE : /<\/?[^>]+>/gi,
20865 * Strips all HTML tags to sort on text only
20866 * @param {Mixed} s The value being converted
20867 * @return {String} The comparison value
20869 asText : function(s){
20870 return String(s).replace(this.stripTagsRE, "");
20874 * Strips all HTML tags to sort on text only - Case insensitive
20875 * @param {Mixed} s The value being converted
20876 * @return {String} The comparison value
20878 asUCText : function(s){
20879 return String(s).toUpperCase().replace(this.stripTagsRE, "");
20883 * Case insensitive string
20884 * @param {Mixed} s The value being converted
20885 * @return {String} The comparison value
20887 asUCString : function(s) {
20888 return String(s).toUpperCase();
20893 * @param {Mixed} s The value being converted
20894 * @return {Number} The comparison value
20896 asDate : function(s) {
20900 if(s instanceof Date){
20901 return s.getTime();
20903 return Date.parse(String(s));
20908 * @param {Mixed} s The value being converted
20909 * @return {Float} The comparison value
20911 asFloat : function(s) {
20912 var val = parseFloat(String(s).replace(/,/g, ""));
20913 if(isNaN(val)) val = 0;
20919 * @param {Mixed} s The value being converted
20920 * @return {Number} The comparison value
20922 asInt : function(s) {
20923 var val = parseInt(String(s).replace(/,/g, ""));
20924 if(isNaN(val)) val = 0;
20929 * Ext JS Library 1.1.1
20930 * Copyright(c) 2006-2007, Ext JS, LLC.
20932 * Originally Released Under LGPL - original licence link has changed is not relivant.
20935 * <script type="text/javascript">
20939 * @class Roo.data.Record
20940 * Instances of this class encapsulate both record <em>definition</em> information, and record
20941 * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
20942 * to access Records cached in an {@link Roo.data.Store} object.<br>
20944 * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
20945 * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
20948 * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
20950 * This constructor should not be used to create Record objects. Instead, use the constructor generated by
20951 * {@link #create}. The parameters are the same.
20952 * @param {Array} data An associative Array of data values keyed by the field name.
20953 * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
20954 * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
20955 * not specified an integer id is generated.
20957 Roo.data.Record = function(data, id){
20958 this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
20963 * Generate a constructor for a specific record layout.
20964 * @param {Array} o An Array of field definition objects which specify field names, and optionally,
20965 * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
20966 * Each field definition object may contain the following properties: <ul>
20967 * <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,
20968 * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
20969 * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
20970 * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
20971 * is being used, then this is a string containing the javascript expression to reference the data relative to
20972 * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
20973 * to the data item relative to the record element. If the mapping expression is the same as the field name,
20974 * this may be omitted.</p></li>
20975 * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
20976 * <ul><li>auto (Default, implies no conversion)</li>
20981 * <li>date</li></ul></p></li>
20982 * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
20983 * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
20984 * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
20985 * by the Reader into an object that will be stored in the Record. It is passed the
20986 * following parameters:<ul>
20987 * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
20989 * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
20991 * <br>usage:<br><pre><code>
20992 var TopicRecord = Roo.data.Record.create(
20993 {name: 'title', mapping: 'topic_title'},
20994 {name: 'author', mapping: 'username'},
20995 {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
20996 {name: 'lastPost', mapping: 'post_time', type: 'date'},
20997 {name: 'lastPoster', mapping: 'user2'},
20998 {name: 'excerpt', mapping: 'post_text'}
21001 var myNewRecord = new TopicRecord({
21002 title: 'Do my job please',
21005 lastPost: new Date(),
21006 lastPoster: 'Animal',
21007 excerpt: 'No way dude!'
21009 myStore.add(myNewRecord);
21014 Roo.data.Record.create = function(o){
21015 var f = function(){
21016 f.superclass.constructor.apply(this, arguments);
21018 Roo.extend(f, Roo.data.Record);
21019 var p = f.prototype;
21020 p.fields = new Roo.util.MixedCollection(false, function(field){
21023 for(var i = 0, len = o.length; i < len; i++){
21024 p.fields.add(new Roo.data.Field(o[i]));
21026 f.getField = function(name){
21027 return p.fields.get(name);
21032 Roo.data.Record.AUTO_ID = 1000;
21033 Roo.data.Record.EDIT = 'edit';
21034 Roo.data.Record.REJECT = 'reject';
21035 Roo.data.Record.COMMIT = 'commit';
21037 Roo.data.Record.prototype = {
21039 * Readonly flag - true if this record has been modified.
21048 join : function(store){
21049 this.store = store;
21053 * Set the named field to the specified value.
21054 * @param {String} name The name of the field to set.
21055 * @param {Object} value The value to set the field to.
21057 set : function(name, value){
21058 if(this.data[name] == value){
21062 if(!this.modified){
21063 this.modified = {};
21065 if(typeof this.modified[name] == 'undefined'){
21066 this.modified[name] = this.data[name];
21068 this.data[name] = value;
21069 if(!this.editing && this.store){
21070 this.store.afterEdit(this);
21075 * Get the value of the named field.
21076 * @param {String} name The name of the field to get the value of.
21077 * @return {Object} The value of the field.
21079 get : function(name){
21080 return this.data[name];
21084 beginEdit : function(){
21085 this.editing = true;
21086 this.modified = {};
21090 cancelEdit : function(){
21091 this.editing = false;
21092 delete this.modified;
21096 endEdit : function(){
21097 this.editing = false;
21098 if(this.dirty && this.store){
21099 this.store.afterEdit(this);
21104 * Usually called by the {@link Roo.data.Store} which owns the Record.
21105 * Rejects all changes made to the Record since either creation, or the last commit operation.
21106 * Modified fields are reverted to their original values.
21108 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
21109 * of reject operations.
21111 reject : function(){
21112 var m = this.modified;
21114 if(typeof m[n] != "function"){
21115 this.data[n] = m[n];
21118 this.dirty = false;
21119 delete this.modified;
21120 this.editing = false;
21122 this.store.afterReject(this);
21127 * Usually called by the {@link Roo.data.Store} which owns the Record.
21128 * Commits all changes made to the Record since either creation, or the last commit operation.
21130 * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
21131 * of commit operations.
21133 commit : function(){
21134 this.dirty = false;
21135 delete this.modified;
21136 this.editing = false;
21138 this.store.afterCommit(this);
21143 hasError : function(){
21144 return this.error != null;
21148 clearError : function(){
21153 * Creates a copy of this record.
21154 * @param {String} id (optional) A new record id if you don't want to use this record's id
21157 copy : function(newId) {
21158 return new this.constructor(Roo.apply({}, this.data), newId || this.id);
21162 * Ext JS Library 1.1.1
21163 * Copyright(c) 2006-2007, Ext JS, LLC.
21165 * Originally Released Under LGPL - original licence link has changed is not relivant.
21168 * <script type="text/javascript">
21174 * @class Roo.data.Store
21175 * @extends Roo.util.Observable
21176 * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
21177 * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
21179 * 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
21180 * has no knowledge of the format of the data returned by the Proxy.<br>
21182 * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
21183 * instances from the data object. These records are cached and made available through accessor functions.
21185 * Creates a new Store.
21186 * @param {Object} config A config object containing the objects needed for the Store to access data,
21187 * and read the data into Records.
21189 Roo.data.Store = function(config){
21190 this.data = new Roo.util.MixedCollection(false);
21191 this.data.getKey = function(o){
21194 this.baseParams = {};
21196 this.paramNames = {
21201 "multisort" : "_multisort"
21204 if(config && config.data){
21205 this.inlineData = config.data;
21206 delete config.data;
21209 Roo.apply(this, config);
21211 if(this.reader){ // reader passed
21212 this.reader = Roo.factory(this.reader, Roo.data);
21213 this.reader.xmodule = this.xmodule || false;
21214 if(!this.recordType){
21215 this.recordType = this.reader.recordType;
21217 if(this.reader.onMetaChange){
21218 this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
21222 if(this.recordType){
21223 this.fields = this.recordType.prototype.fields;
21225 this.modified = [];
21229 * @event datachanged
21230 * Fires when the data cache has changed, and a widget which is using this Store
21231 * as a Record cache should refresh its view.
21232 * @param {Store} this
21234 datachanged : true,
21236 * @event metachange
21237 * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
21238 * @param {Store} this
21239 * @param {Object} meta The JSON metadata
21244 * Fires when Records have been added to the Store
21245 * @param {Store} this
21246 * @param {Roo.data.Record[]} records The array of Records added
21247 * @param {Number} index The index at which the record(s) were added
21252 * Fires when a Record has been removed from the Store
21253 * @param {Store} this
21254 * @param {Roo.data.Record} record The Record that was removed
21255 * @param {Number} index The index at which the record was removed
21260 * Fires when a Record has been updated
21261 * @param {Store} this
21262 * @param {Roo.data.Record} record The Record that was updated
21263 * @param {String} operation The update operation being performed. Value may be one of:
21265 Roo.data.Record.EDIT
21266 Roo.data.Record.REJECT
21267 Roo.data.Record.COMMIT
21273 * Fires when the data cache has been cleared.
21274 * @param {Store} this
21278 * @event beforeload
21279 * Fires before a request is made for a new data object. If the beforeload handler returns false
21280 * the load action will be canceled.
21281 * @param {Store} this
21282 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21286 * @event beforeloadadd
21287 * Fires after a new set of Records has been loaded.
21288 * @param {Store} this
21289 * @param {Roo.data.Record[]} records The Records that were loaded
21290 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21292 beforeloadadd : true,
21295 * Fires after a new set of Records has been loaded, before they are added to the store.
21296 * @param {Store} this
21297 * @param {Roo.data.Record[]} records The Records that were loaded
21298 * @param {Object} options The loading options that were specified (see {@link #load} for details)
21299 * @params {Object} return from reader
21303 * @event loadexception
21304 * Fires if an exception occurs in the Proxy during loading.
21305 * Called with the signature of the Proxy's "loadexception" event.
21306 * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
21309 * @param {Object} return from JsonData.reader() - success, totalRecords, records
21310 * @param {Object} load options
21311 * @param {Object} jsonData from your request (normally this contains the Exception)
21313 loadexception : true
21317 this.proxy = Roo.factory(this.proxy, Roo.data);
21318 this.proxy.xmodule = this.xmodule || false;
21319 this.relayEvents(this.proxy, ["loadexception"]);
21321 this.sortToggle = {};
21322 this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
21324 Roo.data.Store.superclass.constructor.call(this);
21326 if(this.inlineData){
21327 this.loadData(this.inlineData);
21328 delete this.inlineData;
21332 Roo.extend(Roo.data.Store, Roo.util.Observable, {
21334 * @cfg {boolean} isLocal flag if data is locally available (and can be always looked up
21335 * without a remote query - used by combo/forms at present.
21339 * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
21342 * @cfg {Array} data Inline data to be loaded when the store is initialized.
21345 * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
21346 * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
21349 * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
21350 * on any HTTP request
21353 * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
21356 * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
21360 * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
21361 * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
21363 remoteSort : false,
21366 * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
21367 * loaded or when a record is removed. (defaults to false).
21369 pruneModifiedRecords : false,
21372 lastOptions : null,
21375 * Add Records to the Store and fires the add event.
21376 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
21378 add : function(records){
21379 records = [].concat(records);
21380 for(var i = 0, len = records.length; i < len; i++){
21381 records[i].join(this);
21383 var index = this.data.length;
21384 this.data.addAll(records);
21385 this.fireEvent("add", this, records, index);
21389 * Remove a Record from the Store and fires the remove event.
21390 * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
21392 remove : function(record){
21393 var index = this.data.indexOf(record);
21394 this.data.removeAt(index);
21395 if(this.pruneModifiedRecords){
21396 this.modified.remove(record);
21398 this.fireEvent("remove", this, record, index);
21402 * Remove all Records from the Store and fires the clear event.
21404 removeAll : function(){
21406 if(this.pruneModifiedRecords){
21407 this.modified = [];
21409 this.fireEvent("clear", this);
21413 * Inserts Records to the Store at the given index and fires the add event.
21414 * @param {Number} index The start index at which to insert the passed Records.
21415 * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
21417 insert : function(index, records){
21418 records = [].concat(records);
21419 for(var i = 0, len = records.length; i < len; i++){
21420 this.data.insert(index, records[i]);
21421 records[i].join(this);
21423 this.fireEvent("add", this, records, index);
21427 * Get the index within the cache of the passed Record.
21428 * @param {Roo.data.Record} record The Roo.data.Record object to to find.
21429 * @return {Number} The index of the passed Record. Returns -1 if not found.
21431 indexOf : function(record){
21432 return this.data.indexOf(record);
21436 * Get the index within the cache of the Record with the passed id.
21437 * @param {String} id The id of the Record to find.
21438 * @return {Number} The index of the Record. Returns -1 if not found.
21440 indexOfId : function(id){
21441 return this.data.indexOfKey(id);
21445 * Get the Record with the specified id.
21446 * @param {String} id The id of the Record to find.
21447 * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
21449 getById : function(id){
21450 return this.data.key(id);
21454 * Get the Record at the specified index.
21455 * @param {Number} index The index of the Record to find.
21456 * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
21458 getAt : function(index){
21459 return this.data.itemAt(index);
21463 * Returns a range of Records between specified indices.
21464 * @param {Number} startIndex (optional) The starting index (defaults to 0)
21465 * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
21466 * @return {Roo.data.Record[]} An array of Records
21468 getRange : function(start, end){
21469 return this.data.getRange(start, end);
21473 storeOptions : function(o){
21474 o = Roo.apply({}, o);
21477 this.lastOptions = o;
21481 * Loads the Record cache from the configured Proxy using the configured Reader.
21483 * If using remote paging, then the first load call must specify the <em>start</em>
21484 * and <em>limit</em> properties in the options.params property to establish the initial
21485 * position within the dataset, and the number of Records to cache on each read from the Proxy.
21487 * <strong>It is important to note that for remote data sources, loading is asynchronous,
21488 * and this call will return before the new data has been loaded. Perform any post-processing
21489 * in a callback function, or in a "load" event handler.</strong>
21491 * @param {Object} options An object containing properties which control loading options:<ul>
21492 * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
21493 * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
21494 * passed the following arguments:<ul>
21495 * <li>r : Roo.data.Record[]</li>
21496 * <li>options: Options object from the load call</li>
21497 * <li>success: Boolean success indicator</li></ul></li>
21498 * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
21499 * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
21502 load : function(options){
21503 options = options || {};
21504 if(this.fireEvent("beforeload", this, options) !== false){
21505 this.storeOptions(options);
21506 var p = Roo.apply(options.params || {}, this.baseParams);
21507 // if meta was not loaded from remote source.. try requesting it.
21508 if (!this.reader.metaFromRemote) {
21509 p._requestMeta = 1;
21511 if(this.sortInfo && this.remoteSort){
21512 var pn = this.paramNames;
21513 p[pn["sort"]] = this.sortInfo.field;
21514 p[pn["dir"]] = this.sortInfo.direction;
21516 if (this.multiSort) {
21517 var pn = this.paramNames;
21518 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
21521 this.proxy.load(p, this.reader, this.loadRecords, this, options);
21526 * Reloads the Record cache from the configured Proxy using the configured Reader and
21527 * the options from the last load operation performed.
21528 * @param {Object} options (optional) An object containing properties which may override the options
21529 * used in the last load operation. See {@link #load} for details (defaults to null, in which case
21530 * the most recently used options are reused).
21532 reload : function(options){
21533 this.load(Roo.applyIf(options||{}, this.lastOptions));
21537 // Called as a callback by the Reader during a load operation.
21538 loadRecords : function(o, options, success){
21539 if(!o || success === false){
21540 if(success !== false){
21541 this.fireEvent("load", this, [], options, o);
21543 if(options.callback){
21544 options.callback.call(options.scope || this, [], options, false);
21548 // if data returned failure - throw an exception.
21549 if (o.success === false) {
21550 // show a message if no listener is registered.
21551 if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
21552 Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
21554 // loadmask wil be hooked into this..
21555 this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
21558 var r = o.records, t = o.totalRecords || r.length;
21560 this.fireEvent("beforeloadadd", this, r, options, o);
21562 if(!options || options.add !== true){
21563 if(this.pruneModifiedRecords){
21564 this.modified = [];
21566 for(var i = 0, len = r.length; i < len; i++){
21570 this.data = this.snapshot;
21571 delete this.snapshot;
21574 this.data.addAll(r);
21575 this.totalLength = t;
21577 this.fireEvent("datachanged", this);
21579 this.totalLength = Math.max(t, this.data.length+r.length);
21582 this.fireEvent("load", this, r, options, o);
21583 if(options.callback){
21584 options.callback.call(options.scope || this, r, options, true);
21590 * Loads data from a passed data block. A Reader which understands the format of the data
21591 * must have been configured in the constructor.
21592 * @param {Object} data The data block from which to read the Records. The format of the data expected
21593 * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
21594 * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
21596 loadData : function(o, append){
21597 var r = this.reader.readRecords(o);
21598 this.loadRecords(r, {add: append}, true);
21602 * Gets the number of cached records.
21604 * <em>If using paging, this may not be the total size of the dataset. If the data object
21605 * used by the Reader contains the dataset size, then the getTotalCount() function returns
21606 * the data set size</em>
21608 getCount : function(){
21609 return this.data.length || 0;
21613 * Gets the total number of records in the dataset as returned by the server.
21615 * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
21616 * the dataset size</em>
21618 getTotalCount : function(){
21619 return this.totalLength || 0;
21623 * Returns the sort state of the Store as an object with two properties:
21625 field {String} The name of the field by which the Records are sorted
21626 direction {String} The sort order, "ASC" or "DESC"
21629 getSortState : function(){
21630 return this.sortInfo;
21634 applySort : function(){
21635 if(this.sortInfo && !this.remoteSort){
21636 var s = this.sortInfo, f = s.field;
21637 var st = this.fields.get(f).sortType;
21638 var fn = function(r1, r2){
21639 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
21640 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
21642 this.data.sort(s.direction, fn);
21643 if(this.snapshot && this.snapshot != this.data){
21644 this.snapshot.sort(s.direction, fn);
21650 * Sets the default sort column and order to be used by the next load operation.
21651 * @param {String} fieldName The name of the field to sort by.
21652 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
21654 setDefaultSort : function(field, dir){
21655 this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
21659 * Sort the Records.
21660 * If remote sorting is used, the sort is performed on the server, and the cache is
21661 * reloaded. If local sorting is used, the cache is sorted internally.
21662 * @param {String} fieldName The name of the field to sort by.
21663 * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
21665 sort : function(fieldName, dir){
21666 var f = this.fields.get(fieldName);
21668 this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
21670 if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
21671 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
21676 this.sortToggle[f.name] = dir;
21677 this.sortInfo = {field: f.name, direction: dir};
21678 if(!this.remoteSort){
21680 this.fireEvent("datachanged", this);
21682 this.load(this.lastOptions);
21687 * Calls the specified function for each of the Records in the cache.
21688 * @param {Function} fn The function to call. The Record is passed as the first parameter.
21689 * Returning <em>false</em> aborts and exits the iteration.
21690 * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
21692 each : function(fn, scope){
21693 this.data.each(fn, scope);
21697 * Gets all records modified since the last commit. Modified records are persisted across load operations
21698 * (e.g., during paging).
21699 * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
21701 getModifiedRecords : function(){
21702 return this.modified;
21706 createFilterFn : function(property, value, anyMatch){
21707 if(!value.exec){ // not a regex
21708 value = String(value);
21709 if(value.length == 0){
21712 value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
21714 return function(r){
21715 return value.test(r.data[property]);
21720 * Sums the value of <i>property</i> for each record between start and end and returns the result.
21721 * @param {String} property A field on your records
21722 * @param {Number} start The record index to start at (defaults to 0)
21723 * @param {Number} end The last record index to include (defaults to length - 1)
21724 * @return {Number} The sum
21726 sum : function(property, start, end){
21727 var rs = this.data.items, v = 0;
21728 start = start || 0;
21729 end = (end || end === 0) ? end : rs.length-1;
21731 for(var i = start; i <= end; i++){
21732 v += (rs[i].data[property] || 0);
21738 * Filter the records by a specified property.
21739 * @param {String} field A field on your records
21740 * @param {String/RegExp} value Either a string that the field
21741 * should start with or a RegExp to test against the field
21742 * @param {Boolean} anyMatch True to match any part not just the beginning
21744 filter : function(property, value, anyMatch){
21745 var fn = this.createFilterFn(property, value, anyMatch);
21746 return fn ? this.filterBy(fn) : this.clearFilter();
21750 * Filter by a function. The specified function will be called with each
21751 * record in this data source. If the function returns true the record is included,
21752 * otherwise it is filtered.
21753 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
21754 * @param {Object} scope (optional) The scope of the function (defaults to this)
21756 filterBy : function(fn, scope){
21757 this.snapshot = this.snapshot || this.data;
21758 this.data = this.queryBy(fn, scope||this);
21759 this.fireEvent("datachanged", this);
21763 * Query the records by a specified property.
21764 * @param {String} field A field on your records
21765 * @param {String/RegExp} value Either a string that the field
21766 * should start with or a RegExp to test against the field
21767 * @param {Boolean} anyMatch True to match any part not just the beginning
21768 * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
21770 query : function(property, value, anyMatch){
21771 var fn = this.createFilterFn(property, value, anyMatch);
21772 return fn ? this.queryBy(fn) : this.data.clone();
21776 * Query by a function. The specified function will be called with each
21777 * record in this data source. If the function returns true the record is included
21779 * @param {Function} fn The function to be called, it will receive 2 args (record, id)
21780 * @param {Object} scope (optional) The scope of the function (defaults to this)
21781 @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
21783 queryBy : function(fn, scope){
21784 var data = this.snapshot || this.data;
21785 return data.filterBy(fn, scope||this);
21789 * Collects unique values for a particular dataIndex from this store.
21790 * @param {String} dataIndex The property to collect
21791 * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
21792 * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
21793 * @return {Array} An array of the unique values
21795 collect : function(dataIndex, allowNull, bypassFilter){
21796 var d = (bypassFilter === true && this.snapshot) ?
21797 this.snapshot.items : this.data.items;
21798 var v, sv, r = [], l = {};
21799 for(var i = 0, len = d.length; i < len; i++){
21800 v = d[i].data[dataIndex];
21802 if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
21811 * Revert to a view of the Record cache with no filtering applied.
21812 * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
21814 clearFilter : function(suppressEvent){
21815 if(this.snapshot && this.snapshot != this.data){
21816 this.data = this.snapshot;
21817 delete this.snapshot;
21818 if(suppressEvent !== true){
21819 this.fireEvent("datachanged", this);
21825 afterEdit : function(record){
21826 if(this.modified.indexOf(record) == -1){
21827 this.modified.push(record);
21829 this.fireEvent("update", this, record, Roo.data.Record.EDIT);
21833 afterReject : function(record){
21834 this.modified.remove(record);
21835 this.fireEvent("update", this, record, Roo.data.Record.REJECT);
21839 afterCommit : function(record){
21840 this.modified.remove(record);
21841 this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
21845 * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
21846 * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
21848 commitChanges : function(){
21849 var m = this.modified.slice(0);
21850 this.modified = [];
21851 for(var i = 0, len = m.length; i < len; i++){
21857 * Cancel outstanding changes on all changed records.
21859 rejectChanges : function(){
21860 var m = this.modified.slice(0);
21861 this.modified = [];
21862 for(var i = 0, len = m.length; i < len; i++){
21867 onMetaChange : function(meta, rtype, o){
21868 this.recordType = rtype;
21869 this.fields = rtype.prototype.fields;
21870 delete this.snapshot;
21871 this.sortInfo = meta.sortInfo || this.sortInfo;
21872 this.modified = [];
21873 this.fireEvent('metachange', this, this.reader.meta);
21876 moveIndex : function(data, type)
21878 var index = this.indexOf(data);
21880 var newIndex = index + type;
21884 this.insert(newIndex, data);
21889 * Ext JS Library 1.1.1
21890 * Copyright(c) 2006-2007, Ext JS, LLC.
21892 * Originally Released Under LGPL - original licence link has changed is not relivant.
21895 * <script type="text/javascript">
21899 * @class Roo.data.SimpleStore
21900 * @extends Roo.data.Store
21901 * Small helper class to make creating Stores from Array data easier.
21902 * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
21903 * @cfg {Array} fields An array of field definition objects, or field name strings.
21904 * @cfg {Array} data The multi-dimensional array of data
21906 * @param {Object} config
21908 Roo.data.SimpleStore = function(config){
21909 Roo.data.SimpleStore.superclass.constructor.call(this, {
21911 reader: new Roo.data.ArrayReader({
21914 Roo.data.Record.create(config.fields)
21916 proxy : new Roo.data.MemoryProxy(config.data)
21920 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
21922 * Ext JS Library 1.1.1
21923 * Copyright(c) 2006-2007, Ext JS, LLC.
21925 * Originally Released Under LGPL - original licence link has changed is not relivant.
21928 * <script type="text/javascript">
21933 * @extends Roo.data.Store
21934 * @class Roo.data.JsonStore
21935 * Small helper class to make creating Stores for JSON data easier. <br/>
21937 var store = new Roo.data.JsonStore({
21938 url: 'get-images.php',
21940 fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
21943 * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
21944 * JsonReader and HttpProxy (unless inline data is provided).</b>
21945 * @cfg {Array} fields An array of field definition objects, or field name strings.
21947 * @param {Object} config
21949 Roo.data.JsonStore = function(c){
21950 Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
21951 proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
21952 reader: new Roo.data.JsonReader(c, c.fields)
21955 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
21957 * Ext JS Library 1.1.1
21958 * Copyright(c) 2006-2007, Ext JS, LLC.
21960 * Originally Released Under LGPL - original licence link has changed is not relivant.
21963 * <script type="text/javascript">
21967 Roo.data.Field = function(config){
21968 if(typeof config == "string"){
21969 config = {name: config};
21971 Roo.apply(this, config);
21974 this.type = "auto";
21977 var st = Roo.data.SortTypes;
21978 // named sortTypes are supported, here we look them up
21979 if(typeof this.sortType == "string"){
21980 this.sortType = st[this.sortType];
21983 // set default sortType for strings and dates
21984 if(!this.sortType){
21987 this.sortType = st.asUCString;
21990 this.sortType = st.asDate;
21993 this.sortType = st.none;
21998 var stripRe = /[\$,%]/g;
22000 // prebuilt conversion function for this field, instead of
22001 // switching every time we're reading a value
22003 var cv, dateFormat = this.dateFormat;
22008 cv = function(v){ return v; };
22011 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
22015 return v !== undefined && v !== null && v !== '' ?
22016 parseInt(String(v).replace(stripRe, ""), 10) : '';
22021 return v !== undefined && v !== null && v !== '' ?
22022 parseFloat(String(v).replace(stripRe, ""), 10) : '';
22027 cv = function(v){ return v === true || v === "true" || v == 1; };
22034 if(v instanceof Date){
22038 if(dateFormat == "timestamp"){
22039 return new Date(v*1000);
22041 return Date.parseDate(v, dateFormat);
22043 var parsed = Date.parse(v);
22044 return parsed ? new Date(parsed) : null;
22053 Roo.data.Field.prototype = {
22061 * Ext JS Library 1.1.1
22062 * Copyright(c) 2006-2007, Ext JS, LLC.
22064 * Originally Released Under LGPL - original licence link has changed is not relivant.
22067 * <script type="text/javascript">
22070 // Base class for reading structured data from a data source. This class is intended to be
22071 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
22074 * @class Roo.data.DataReader
22075 * Base class for reading structured data from a data source. This class is intended to be
22076 * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
22079 Roo.data.DataReader = function(meta, recordType){
22083 this.recordType = recordType instanceof Array ?
22084 Roo.data.Record.create(recordType) : recordType;
22087 Roo.data.DataReader.prototype = {
22089 * Create an empty record
22090 * @param {Object} data (optional) - overlay some values
22091 * @return {Roo.data.Record} record created.
22093 newRow : function(d) {
22095 this.recordType.prototype.fields.each(function(c) {
22097 case 'int' : da[c.name] = 0; break;
22098 case 'date' : da[c.name] = new Date(); break;
22099 case 'float' : da[c.name] = 0.0; break;
22100 case 'boolean' : da[c.name] = false; break;
22101 default : da[c.name] = ""; break;
22105 return new this.recordType(Roo.apply(da, d));
22110 * Ext JS Library 1.1.1
22111 * Copyright(c) 2006-2007, Ext JS, LLC.
22113 * Originally Released Under LGPL - original licence link has changed is not relivant.
22116 * <script type="text/javascript">
22120 * @class Roo.data.DataProxy
22121 * @extends Roo.data.Observable
22122 * This class is an abstract base class for implementations which provide retrieval of
22123 * unformatted data objects.<br>
22125 * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
22126 * (of the appropriate type which knows how to parse the data object) to provide a block of
22127 * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
22129 * Custom implementations must implement the load method as described in
22130 * {@link Roo.data.HttpProxy#load}.
22132 Roo.data.DataProxy = function(){
22135 * @event beforeload
22136 * Fires before a network request is made to retrieve a data object.
22137 * @param {Object} This DataProxy object.
22138 * @param {Object} params The params parameter to the load function.
22143 * Fires before the load method's callback is called.
22144 * @param {Object} This DataProxy object.
22145 * @param {Object} o The data object.
22146 * @param {Object} arg The callback argument object passed to the load function.
22150 * @event loadexception
22151 * Fires if an Exception occurs during data retrieval.
22152 * @param {Object} This DataProxy object.
22153 * @param {Object} o The data object.
22154 * @param {Object} arg The callback argument object passed to the load function.
22155 * @param {Object} e The Exception.
22157 loadexception : true
22159 Roo.data.DataProxy.superclass.constructor.call(this);
22162 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
22165 * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
22169 * Ext JS Library 1.1.1
22170 * Copyright(c) 2006-2007, Ext JS, LLC.
22172 * Originally Released Under LGPL - original licence link has changed is not relivant.
22175 * <script type="text/javascript">
22178 * @class Roo.data.MemoryProxy
22179 * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
22180 * to the Reader when its load method is called.
22182 * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
22184 Roo.data.MemoryProxy = function(data){
22188 Roo.data.MemoryProxy.superclass.constructor.call(this);
22192 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
22194 * Load data from the requested source (in this case an in-memory
22195 * data object passed to the constructor), read the data object into
22196 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
22197 * process that block using the passed callback.
22198 * @param {Object} params This parameter is not used by the MemoryProxy class.
22199 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22200 * object into a block of Roo.data.Records.
22201 * @param {Function} callback The function into which to pass the block of Roo.data.records.
22202 * The function must be passed <ul>
22203 * <li>The Record block object</li>
22204 * <li>The "arg" argument from the load function</li>
22205 * <li>A boolean success indicator</li>
22207 * @param {Object} scope The scope in which to call the callback
22208 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22210 load : function(params, reader, callback, scope, arg){
22211 params = params || {};
22214 result = reader.readRecords(this.data);
22216 this.fireEvent("loadexception", this, arg, null, e);
22217 callback.call(scope, null, arg, false);
22220 callback.call(scope, result, arg, true);
22224 update : function(params, records){
22229 * Ext JS Library 1.1.1
22230 * Copyright(c) 2006-2007, Ext JS, LLC.
22232 * Originally Released Under LGPL - original licence link has changed is not relivant.
22235 * <script type="text/javascript">
22238 * @class Roo.data.HttpProxy
22239 * @extends Roo.data.DataProxy
22240 * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
22241 * configured to reference a certain URL.<br><br>
22243 * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
22244 * from which the running page was served.<br><br>
22246 * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
22248 * Be aware that to enable the browser to parse an XML document, the server must set
22249 * the Content-Type header in the HTTP response to "text/xml".
22251 * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
22252 * an {@link Roo.data.Connection} object. If a Connection config is passed, the singleton {@link Roo.Ajax} object
22253 * will be used to make the request.
22255 Roo.data.HttpProxy = function(conn){
22256 Roo.data.HttpProxy.superclass.constructor.call(this);
22257 // is conn a conn config or a real conn?
22259 this.useAjax = !conn || !conn.events;
22263 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
22264 // thse are take from connection...
22267 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
22270 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
22271 * extra parameters to each request made by this object. (defaults to undefined)
22274 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
22275 * to each request made by this object. (defaults to undefined)
22278 * @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)
22281 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
22284 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
22290 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
22294 * Return the {@link Roo.data.Connection} object being used by this Proxy.
22295 * @return {Connection} The Connection object. This object may be used to subscribe to events on
22296 * a finer-grained basis than the DataProxy events.
22298 getConnection : function(){
22299 return this.useAjax ? Roo.Ajax : this.conn;
22303 * Load data from the configured {@link Roo.data.Connection}, read the data object into
22304 * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
22305 * process that block using the passed callback.
22306 * @param {Object} params An object containing properties which are to be used as HTTP parameters
22307 * for the request to the remote server.
22308 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22309 * object into a block of Roo.data.Records.
22310 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
22311 * The function must be passed <ul>
22312 * <li>The Record block object</li>
22313 * <li>The "arg" argument from the load function</li>
22314 * <li>A boolean success indicator</li>
22316 * @param {Object} scope The scope in which to call the callback
22317 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22319 load : function(params, reader, callback, scope, arg){
22320 if(this.fireEvent("beforeload", this, params) !== false){
22322 params : params || {},
22324 callback : callback,
22329 callback : this.loadResponse,
22333 Roo.applyIf(o, this.conn);
22334 if(this.activeRequest){
22335 Roo.Ajax.abort(this.activeRequest);
22337 this.activeRequest = Roo.Ajax.request(o);
22339 this.conn.request(o);
22342 callback.call(scope||this, null, arg, false);
22347 loadResponse : function(o, success, response){
22348 delete this.activeRequest;
22350 this.fireEvent("loadexception", this, o, response);
22351 o.request.callback.call(o.request.scope, null, o.request.arg, false);
22356 result = o.reader.read(response);
22358 this.fireEvent("loadexception", this, o, response, e);
22359 o.request.callback.call(o.request.scope, null, o.request.arg, false);
22363 this.fireEvent("load", this, o, o.request.arg);
22364 o.request.callback.call(o.request.scope, result, o.request.arg, true);
22368 update : function(dataSet){
22373 updateResponse : function(dataSet){
22378 * Ext JS Library 1.1.1
22379 * Copyright(c) 2006-2007, Ext JS, LLC.
22381 * Originally Released Under LGPL - original licence link has changed is not relivant.
22384 * <script type="text/javascript">
22388 * @class Roo.data.ScriptTagProxy
22389 * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
22390 * other than the originating domain of the running page.<br><br>
22392 * <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
22393 * of the running page, you must use this class, rather than DataProxy.</em><br><br>
22395 * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
22396 * source code that is used as the source inside a <script> tag.<br><br>
22398 * In order for the browser to process the returned data, the server must wrap the data object
22399 * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
22400 * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
22401 * depending on whether the callback name was passed:
22404 boolean scriptTag = false;
22405 String cb = request.getParameter("callback");
22408 response.setContentType("text/javascript");
22410 response.setContentType("application/x-json");
22412 Writer out = response.getWriter();
22414 out.write(cb + "(");
22416 out.print(dataBlock.toJsonString());
22423 * @param {Object} config A configuration object.
22425 Roo.data.ScriptTagProxy = function(config){
22426 Roo.data.ScriptTagProxy.superclass.constructor.call(this);
22427 Roo.apply(this, config);
22428 this.head = document.getElementsByTagName("head")[0];
22431 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
22433 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
22435 * @cfg {String} url The URL from which to request the data object.
22438 * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
22442 * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
22443 * the server the name of the callback function set up by the load call to process the returned data object.
22444 * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
22445 * javascript output which calls this named function passing the data object as its only parameter.
22447 callbackParam : "callback",
22449 * @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
22450 * name to the request.
22455 * Load data from the configured URL, read the data object into
22456 * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
22457 * process that block using the passed callback.
22458 * @param {Object} params An object containing properties which are to be used as HTTP parameters
22459 * for the request to the remote server.
22460 * @param {Roo.data.DataReader} reader The Reader object which converts the data
22461 * object into a block of Roo.data.Records.
22462 * @param {Function} callback The function into which to pass the block of Roo.data.Records.
22463 * The function must be passed <ul>
22464 * <li>The Record block object</li>
22465 * <li>The "arg" argument from the load function</li>
22466 * <li>A boolean success indicator</li>
22468 * @param {Object} scope The scope in which to call the callback
22469 * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
22471 load : function(params, reader, callback, scope, arg){
22472 if(this.fireEvent("beforeload", this, params) !== false){
22474 var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
22476 var url = this.url;
22477 url += (url.indexOf("?") != -1 ? "&" : "?") + p;
22479 url += "&_dc=" + (new Date().getTime());
22481 var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
22484 cb : "stcCallback"+transId,
22485 scriptId : "stcScript"+transId,
22489 callback : callback,
22495 window[trans.cb] = function(o){
22496 conn.handleResponse(o, trans);
22499 url += String.format("&{0}={1}", this.callbackParam, trans.cb);
22501 if(this.autoAbort !== false){
22505 trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
22507 var script = document.createElement("script");
22508 script.setAttribute("src", url);
22509 script.setAttribute("type", "text/javascript");
22510 script.setAttribute("id", trans.scriptId);
22511 this.head.appendChild(script);
22513 this.trans = trans;
22515 callback.call(scope||this, null, arg, false);
22520 isLoading : function(){
22521 return this.trans ? true : false;
22525 * Abort the current server request.
22527 abort : function(){
22528 if(this.isLoading()){
22529 this.destroyTrans(this.trans);
22534 destroyTrans : function(trans, isLoaded){
22535 this.head.removeChild(document.getElementById(trans.scriptId));
22536 clearTimeout(trans.timeoutId);
22538 window[trans.cb] = undefined;
22540 delete window[trans.cb];
22543 // if hasn't been loaded, wait for load to remove it to prevent script error
22544 window[trans.cb] = function(){
22545 window[trans.cb] = undefined;
22547 delete window[trans.cb];
22554 handleResponse : function(o, trans){
22555 this.trans = false;
22556 this.destroyTrans(trans, true);
22559 result = trans.reader.readRecords(o);
22561 this.fireEvent("loadexception", this, o, trans.arg, e);
22562 trans.callback.call(trans.scope||window, null, trans.arg, false);
22565 this.fireEvent("load", this, o, trans.arg);
22566 trans.callback.call(trans.scope||window, result, trans.arg, true);
22570 handleFailure : function(trans){
22571 this.trans = false;
22572 this.destroyTrans(trans, false);
22573 this.fireEvent("loadexception", this, null, trans.arg);
22574 trans.callback.call(trans.scope||window, null, trans.arg, false);
22578 * Ext JS Library 1.1.1
22579 * Copyright(c) 2006-2007, Ext JS, LLC.
22581 * Originally Released Under LGPL - original licence link has changed is not relivant.
22584 * <script type="text/javascript">
22588 * @class Roo.data.JsonReader
22589 * @extends Roo.data.DataReader
22590 * Data reader class to create an Array of Roo.data.Record objects from a JSON response
22591 * based on mappings in a provided Roo.data.Record constructor.
22593 * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
22594 * in the reply previously.
22599 var RecordDef = Roo.data.Record.create([
22600 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
22601 {name: 'occupation'} // This field will use "occupation" as the mapping.
22603 var myReader = new Roo.data.JsonReader({
22604 totalProperty: "results", // The property which contains the total dataset size (optional)
22605 root: "rows", // The property which contains an Array of row objects
22606 id: "id" // The property within each row object that provides an ID for the record (optional)
22610 * This would consume a JSON file like this:
22612 { 'results': 2, 'rows': [
22613 { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
22614 { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
22617 * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
22618 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
22619 * paged from the remote server.
22620 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
22621 * @cfg {String} root name of the property which contains the Array of row objects.
22622 * @cfg {String} id Name of the property within a row object that contains a record identifier value.
22623 * @cfg {Array} fields Array of field definition objects
22625 * Create a new JsonReader
22626 * @param {Object} meta Metadata configuration options
22627 * @param {Object} recordType Either an Array of field definition objects,
22628 * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
22630 Roo.data.JsonReader = function(meta, recordType){
22633 // set some defaults:
22634 Roo.applyIf(meta, {
22635 totalProperty: 'total',
22636 successProperty : 'success',
22641 Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
22643 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
22646 * @prop {Boolean} metaFromRemote - if the meta data was loaded from the remote source.
22647 * Used by Store query builder to append _requestMeta to params.
22650 metaFromRemote : false,
22652 * This method is only used by a DataProxy which has retrieved data from a remote server.
22653 * @param {Object} response The XHR object which contains the JSON data in its responseText.
22654 * @return {Object} data A data block which is used by an Roo.data.Store object as
22655 * a cache of Roo.data.Records.
22657 read : function(response){
22658 var json = response.responseText;
22660 var o = /* eval:var:o */ eval("("+json+")");
22662 throw {message: "JsonReader.read: Json object not found"};
22668 this.metaFromRemote = true;
22669 this.meta = o.metaData;
22670 this.recordType = Roo.data.Record.create(o.metaData.fields);
22671 this.onMetaChange(this.meta, this.recordType, o);
22673 return this.readRecords(o);
22676 // private function a store will implement
22677 onMetaChange : function(meta, recordType, o){
22684 simpleAccess: function(obj, subsc) {
22691 getJsonAccessor: function(){
22693 return function(expr) {
22695 return(re.test(expr))
22696 ? new Function("obj", "return obj." + expr)
22701 return Roo.emptyFn;
22706 * Create a data block containing Roo.data.Records from an XML document.
22707 * @param {Object} o An object which contains an Array of row objects in the property specified
22708 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
22709 * which contains the total size of the dataset.
22710 * @return {Object} data A data block which is used by an Roo.data.Store object as
22711 * a cache of Roo.data.Records.
22713 readRecords : function(o){
22715 * After any data loads, the raw JSON data is available for further custom processing.
22719 var s = this.meta, Record = this.recordType,
22720 f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
22722 // Generate extraction functions for the totalProperty, the root, the id, and for each field
22724 if(s.totalProperty) {
22725 this.getTotal = this.getJsonAccessor(s.totalProperty);
22727 if(s.successProperty) {
22728 this.getSuccess = this.getJsonAccessor(s.successProperty);
22730 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
22732 var g = this.getJsonAccessor(s.id);
22733 this.getId = function(rec) {
22735 return (r === undefined || r === "") ? null : r;
22738 this.getId = function(){return null;};
22741 for(var jj = 0; jj < fl; jj++){
22743 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
22744 this.ef[jj] = this.getJsonAccessor(map);
22748 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
22749 if(s.totalProperty){
22750 var vt = parseInt(this.getTotal(o), 10);
22755 if(s.successProperty){
22756 var vs = this.getSuccess(o);
22757 if(vs === false || vs === 'false'){
22762 for(var i = 0; i < c; i++){
22765 var id = this.getId(n);
22766 for(var j = 0; j < fl; j++){
22768 var v = this.ef[j](n);
22770 Roo.log('missing convert for ' + f.name);
22774 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
22776 var record = new Record(values, id);
22778 records[i] = record;
22784 totalRecords : totalRecords
22789 * Ext JS Library 1.1.1
22790 * Copyright(c) 2006-2007, Ext JS, LLC.
22792 * Originally Released Under LGPL - original licence link has changed is not relivant.
22795 * <script type="text/javascript">
22799 * @class Roo.data.XmlReader
22800 * @extends Roo.data.DataReader
22801 * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
22802 * based on mappings in a provided Roo.data.Record constructor.<br><br>
22804 * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
22805 * header in the HTTP response must be set to "text/xml".</em>
22809 var RecordDef = Roo.data.Record.create([
22810 {name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
22811 {name: 'occupation'} // This field will use "occupation" as the mapping.
22813 var myReader = new Roo.data.XmlReader({
22814 totalRecords: "results", // The element which contains the total dataset size (optional)
22815 record: "row", // The repeated element which contains row information
22816 id: "id" // The element within the row that provides an ID for the record (optional)
22820 * This would consume an XML file like this:
22824 <results>2</results>
22827 <name>Bill</name>
22828 <occupation>Gardener</occupation>
22832 <name>Ben</name>
22833 <occupation>Horticulturalist</occupation>
22837 * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
22838 * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
22839 * paged from the remote server.
22840 * @cfg {String} record The DomQuery path to the repeated element which contains record information.
22841 * @cfg {String} success The DomQuery path to the success attribute used by forms.
22842 * @cfg {String} id The DomQuery path relative from the record element to the element that contains
22843 * a record identifier value.
22845 * Create a new XmlReader
22846 * @param {Object} meta Metadata configuration options
22847 * @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
22848 * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
22849 * Roo.data.Record.create. See the {@link Roo.data.Record} class for more details.
22851 Roo.data.XmlReader = function(meta, recordType){
22853 Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
22855 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
22857 * This method is only used by a DataProxy which has retrieved data from a remote server.
22858 * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
22859 * to contain a method called 'responseXML' that returns an XML document object.
22860 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
22861 * a cache of Roo.data.Records.
22863 read : function(response){
22864 var doc = response.responseXML;
22866 throw {message: "XmlReader.read: XML Document not available"};
22868 return this.readRecords(doc);
22872 * Create a data block containing Roo.data.Records from an XML document.
22873 * @param {Object} doc A parsed XML document.
22874 * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
22875 * a cache of Roo.data.Records.
22877 readRecords : function(doc){
22879 * After any data loads/reads, the raw XML Document is available for further custom processing.
22880 * @type XMLDocument
22882 this.xmlData = doc;
22883 var root = doc.documentElement || doc;
22884 var q = Roo.DomQuery;
22885 var recordType = this.recordType, fields = recordType.prototype.fields;
22886 var sid = this.meta.id;
22887 var totalRecords = 0, success = true;
22888 if(this.meta.totalRecords){
22889 totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
22892 if(this.meta.success){
22893 var sv = q.selectValue(this.meta.success, root, true);
22894 success = sv !== false && sv !== 'false';
22897 var ns = q.select(this.meta.record, root);
22898 for(var i = 0, len = ns.length; i < len; i++) {
22901 var id = sid ? q.selectValue(sid, n) : undefined;
22902 for(var j = 0, jlen = fields.length; j < jlen; j++){
22903 var f = fields.items[j];
22904 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
22906 values[f.name] = v;
22908 var record = new recordType(values, id);
22910 records[records.length] = record;
22916 totalRecords : totalRecords || records.length
22921 * Ext JS Library 1.1.1
22922 * Copyright(c) 2006-2007, Ext JS, LLC.
22924 * Originally Released Under LGPL - original licence link has changed is not relivant.
22927 * <script type="text/javascript">
22931 * @class Roo.data.ArrayReader
22932 * @extends Roo.data.DataReader
22933 * Data reader class to create an Array of Roo.data.Record objects from an Array.
22934 * Each element of that Array represents a row of data fields. The
22935 * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
22936 * of the field definition if it exists, or the field's ordinal position in the definition.<br>
22940 var RecordDef = Roo.data.Record.create([
22941 {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
22942 {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
22944 var myReader = new Roo.data.ArrayReader({
22945 id: 0 // The subscript within row Array that provides an ID for the Record (optional)
22949 * This would consume an Array like this:
22951 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
22953 * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
22955 * Create a new JsonReader
22956 * @param {Object} meta Metadata configuration options.
22957 * @param {Object} recordType Either an Array of field definition objects
22958 * as specified to {@link Roo.data.Record#create},
22959 * or an {@link Roo.data.Record} object
22960 * created using {@link Roo.data.Record#create}.
22962 Roo.data.ArrayReader = function(meta, recordType){
22963 Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
22966 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
22968 * Create a data block containing Roo.data.Records from an XML document.
22969 * @param {Object} o An Array of row objects which represents the dataset.
22970 * @return {Object} data A data block which is used by an Roo.data.Store object as
22971 * a cache of Roo.data.Records.
22973 readRecords : function(o){
22974 var sid = this.meta ? this.meta.id : null;
22975 var recordType = this.recordType, fields = recordType.prototype.fields;
22978 for(var i = 0; i < root.length; i++){
22981 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
22982 for(var j = 0, jlen = fields.length; j < jlen; j++){
22983 var f = fields.items[j];
22984 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
22985 var v = n[k] !== undefined ? n[k] : f.defaultValue;
22987 values[f.name] = v;
22989 var record = new recordType(values, id);
22991 records[records.length] = record;
22995 totalRecords : records.length
23000 * Ext JS Library 1.1.1
23001 * Copyright(c) 2006-2007, Ext JS, LLC.
23003 * Originally Released Under LGPL - original licence link has changed is not relivant.
23006 * <script type="text/javascript">
23011 * @class Roo.data.Tree
23012 * @extends Roo.util.Observable
23013 * Represents a tree data structure and bubbles all the events for its nodes. The nodes
23014 * in the tree have most standard DOM functionality.
23016 * @param {Node} root (optional) The root node
23018 Roo.data.Tree = function(root){
23019 this.nodeHash = {};
23021 * The root node for this tree
23026 this.setRootNode(root);
23031 * Fires when a new child node is appended to a node in this tree.
23032 * @param {Tree} tree The owner tree
23033 * @param {Node} parent The parent node
23034 * @param {Node} node The newly appended node
23035 * @param {Number} index The index of the newly appended node
23040 * Fires when a child node is removed from a node in this tree.
23041 * @param {Tree} tree The owner tree
23042 * @param {Node} parent The parent node
23043 * @param {Node} node The child node removed
23048 * Fires when a node is moved to a new location in the tree
23049 * @param {Tree} tree The owner tree
23050 * @param {Node} node The node moved
23051 * @param {Node} oldParent The old parent of this node
23052 * @param {Node} newParent The new parent of this node
23053 * @param {Number} index The index it was moved to
23058 * Fires when a new child node is inserted in a node in this tree.
23059 * @param {Tree} tree The owner tree
23060 * @param {Node} parent The parent node
23061 * @param {Node} node The child node inserted
23062 * @param {Node} refNode The child node the node was inserted before
23066 * @event beforeappend
23067 * Fires before a new child is appended to a node in this tree, return false to cancel the append.
23068 * @param {Tree} tree The owner tree
23069 * @param {Node} parent The parent node
23070 * @param {Node} node The child node to be appended
23072 "beforeappend" : true,
23074 * @event beforeremove
23075 * Fires before a child is removed from a node in this tree, return false to cancel the remove.
23076 * @param {Tree} tree The owner tree
23077 * @param {Node} parent The parent node
23078 * @param {Node} node The child node to be removed
23080 "beforeremove" : true,
23082 * @event beforemove
23083 * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
23084 * @param {Tree} tree The owner tree
23085 * @param {Node} node The node being moved
23086 * @param {Node} oldParent The parent of the node
23087 * @param {Node} newParent The new parent the node is moving to
23088 * @param {Number} index The index it is being moved to
23090 "beforemove" : true,
23092 * @event beforeinsert
23093 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
23094 * @param {Tree} tree The owner tree
23095 * @param {Node} parent The parent node
23096 * @param {Node} node The child node to be inserted
23097 * @param {Node} refNode The child node the node is being inserted before
23099 "beforeinsert" : true
23102 Roo.data.Tree.superclass.constructor.call(this);
23105 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
23106 pathSeparator: "/",
23108 proxyNodeEvent : function(){
23109 return this.fireEvent.apply(this, arguments);
23113 * Returns the root node for this tree.
23116 getRootNode : function(){
23121 * Sets the root node for this tree.
23122 * @param {Node} node
23125 setRootNode : function(node){
23127 node.ownerTree = this;
23128 node.isRoot = true;
23129 this.registerNode(node);
23134 * Gets a node in this tree by its id.
23135 * @param {String} id
23138 getNodeById : function(id){
23139 return this.nodeHash[id];
23142 registerNode : function(node){
23143 this.nodeHash[node.id] = node;
23146 unregisterNode : function(node){
23147 delete this.nodeHash[node.id];
23150 toString : function(){
23151 return "[Tree"+(this.id?" "+this.id:"")+"]";
23156 * @class Roo.data.Node
23157 * @extends Roo.util.Observable
23158 * @cfg {Boolean} leaf true if this node is a leaf and does not have children
23159 * @cfg {String} id The id for this node. If one is not specified, one is generated.
23161 * @param {Object} attributes The attributes/config for the node
23163 Roo.data.Node = function(attributes){
23165 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
23168 this.attributes = attributes || {};
23169 this.leaf = this.attributes.leaf;
23171 * The node id. @type String
23173 this.id = this.attributes.id;
23175 this.id = Roo.id(null, "ynode-");
23176 this.attributes.id = this.id;
23181 * All child nodes of this node. @type Array
23183 this.childNodes = [];
23184 if(!this.childNodes.indexOf){ // indexOf is a must
23185 this.childNodes.indexOf = function(o){
23186 for(var i = 0, len = this.length; i < len; i++){
23195 * The parent node for this node. @type Node
23197 this.parentNode = null;
23199 * The first direct child node of this node, or null if this node has no child nodes. @type Node
23201 this.firstChild = null;
23203 * The last direct child node of this node, or null if this node has no child nodes. @type Node
23205 this.lastChild = null;
23207 * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
23209 this.previousSibling = null;
23211 * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
23213 this.nextSibling = null;
23218 * Fires when a new child node is appended
23219 * @param {Tree} tree The owner tree
23220 * @param {Node} this This node
23221 * @param {Node} node The newly appended node
23222 * @param {Number} index The index of the newly appended node
23227 * Fires when a child node is removed
23228 * @param {Tree} tree The owner tree
23229 * @param {Node} this This node
23230 * @param {Node} node The removed node
23235 * Fires when this node is moved to a new location in the tree
23236 * @param {Tree} tree The owner tree
23237 * @param {Node} this This node
23238 * @param {Node} oldParent The old parent of this node
23239 * @param {Node} newParent The new parent of this node
23240 * @param {Number} index The index it was moved to
23245 * Fires when a new child node is inserted.
23246 * @param {Tree} tree The owner tree
23247 * @param {Node} this This node
23248 * @param {Node} node The child node inserted
23249 * @param {Node} refNode The child node the node was inserted before
23253 * @event beforeappend
23254 * Fires before a new child is appended, return false to cancel the append.
23255 * @param {Tree} tree The owner tree
23256 * @param {Node} this This node
23257 * @param {Node} node The child node to be appended
23259 "beforeappend" : true,
23261 * @event beforeremove
23262 * Fires before a child is removed, return false to cancel the remove.
23263 * @param {Tree} tree The owner tree
23264 * @param {Node} this This node
23265 * @param {Node} node The child node to be removed
23267 "beforeremove" : true,
23269 * @event beforemove
23270 * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
23271 * @param {Tree} tree The owner tree
23272 * @param {Node} this This node
23273 * @param {Node} oldParent The parent of this node
23274 * @param {Node} newParent The new parent this node is moving to
23275 * @param {Number} index The index it is being moved to
23277 "beforemove" : true,
23279 * @event beforeinsert
23280 * Fires before a new child is inserted, return false to cancel the insert.
23281 * @param {Tree} tree The owner tree
23282 * @param {Node} this This node
23283 * @param {Node} node The child node to be inserted
23284 * @param {Node} refNode The child node the node is being inserted before
23286 "beforeinsert" : true
23288 this.listeners = this.attributes.listeners;
23289 Roo.data.Node.superclass.constructor.call(this);
23292 Roo.extend(Roo.data.Node, Roo.util.Observable, {
23293 fireEvent : function(evtName){
23294 // first do standard event for this node
23295 if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
23298 // then bubble it up to the tree if the event wasn't cancelled
23299 var ot = this.getOwnerTree();
23301 if(ot.proxyNodeEvent.apply(ot, arguments) === false){
23309 * Returns true if this node is a leaf
23310 * @return {Boolean}
23312 isLeaf : function(){
23313 return this.leaf === true;
23317 setFirstChild : function(node){
23318 this.firstChild = node;
23322 setLastChild : function(node){
23323 this.lastChild = node;
23328 * Returns true if this node is the last child of its parent
23329 * @return {Boolean}
23331 isLast : function(){
23332 return (!this.parentNode ? true : this.parentNode.lastChild == this);
23336 * Returns true if this node is the first child of its parent
23337 * @return {Boolean}
23339 isFirst : function(){
23340 return (!this.parentNode ? true : this.parentNode.firstChild == this);
23343 hasChildNodes : function(){
23344 return !this.isLeaf() && this.childNodes.length > 0;
23348 * Insert node(s) as the last child node of this node.
23349 * @param {Node/Array} node The node or Array of nodes to append
23350 * @return {Node} The appended node if single append, or null if an array was passed
23352 appendChild : function(node){
23354 if(node instanceof Array){
23356 }else if(arguments.length > 1){
23359 // if passed an array or multiple args do them one by one
23361 for(var i = 0, len = multi.length; i < len; i++) {
23362 this.appendChild(multi[i]);
23365 if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
23368 var index = this.childNodes.length;
23369 var oldParent = node.parentNode;
23370 // it's a move, make sure we move it cleanly
23372 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
23375 oldParent.removeChild(node);
23377 index = this.childNodes.length;
23379 this.setFirstChild(node);
23381 this.childNodes.push(node);
23382 node.parentNode = this;
23383 var ps = this.childNodes[index-1];
23385 node.previousSibling = ps;
23386 ps.nextSibling = node;
23388 node.previousSibling = null;
23390 node.nextSibling = null;
23391 this.setLastChild(node);
23392 node.setOwnerTree(this.getOwnerTree());
23393 this.fireEvent("append", this.ownerTree, this, node, index);
23395 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
23402 * Removes a child node from this node.
23403 * @param {Node} node The node to remove
23404 * @return {Node} The removed node
23406 removeChild : function(node){
23407 var index = this.childNodes.indexOf(node);
23411 if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
23415 // remove it from childNodes collection
23416 this.childNodes.splice(index, 1);
23419 if(node.previousSibling){
23420 node.previousSibling.nextSibling = node.nextSibling;
23422 if(node.nextSibling){
23423 node.nextSibling.previousSibling = node.previousSibling;
23426 // update child refs
23427 if(this.firstChild == node){
23428 this.setFirstChild(node.nextSibling);
23430 if(this.lastChild == node){
23431 this.setLastChild(node.previousSibling);
23434 node.setOwnerTree(null);
23435 // clear any references from the node
23436 node.parentNode = null;
23437 node.previousSibling = null;
23438 node.nextSibling = null;
23439 this.fireEvent("remove", this.ownerTree, this, node);
23444 * Inserts the first node before the second node in this nodes childNodes collection.
23445 * @param {Node} node The node to insert
23446 * @param {Node} refNode The node to insert before (if null the node is appended)
23447 * @return {Node} The inserted node
23449 insertBefore : function(node, refNode){
23450 if(!refNode){ // like standard Dom, refNode can be null for append
23451 return this.appendChild(node);
23454 if(node == refNode){
23458 if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
23461 var index = this.childNodes.indexOf(refNode);
23462 var oldParent = node.parentNode;
23463 var refIndex = index;
23465 // when moving internally, indexes will change after remove
23466 if(oldParent == this && this.childNodes.indexOf(node) < index){
23470 // it's a move, make sure we move it cleanly
23472 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
23475 oldParent.removeChild(node);
23478 this.setFirstChild(node);
23480 this.childNodes.splice(refIndex, 0, node);
23481 node.parentNode = this;
23482 var ps = this.childNodes[refIndex-1];
23484 node.previousSibling = ps;
23485 ps.nextSibling = node;
23487 node.previousSibling = null;
23489 node.nextSibling = refNode;
23490 refNode.previousSibling = node;
23491 node.setOwnerTree(this.getOwnerTree());
23492 this.fireEvent("insert", this.ownerTree, this, node, refNode);
23494 node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
23500 * Returns the child node at the specified index.
23501 * @param {Number} index
23504 item : function(index){
23505 return this.childNodes[index];
23509 * Replaces one child node in this node with another.
23510 * @param {Node} newChild The replacement node
23511 * @param {Node} oldChild The node to replace
23512 * @return {Node} The replaced node
23514 replaceChild : function(newChild, oldChild){
23515 this.insertBefore(newChild, oldChild);
23516 this.removeChild(oldChild);
23521 * Returns the index of a child node
23522 * @param {Node} node
23523 * @return {Number} The index of the node or -1 if it was not found
23525 indexOf : function(child){
23526 return this.childNodes.indexOf(child);
23530 * Returns the tree this node is in.
23533 getOwnerTree : function(){
23534 // if it doesn't have one, look for one
23535 if(!this.ownerTree){
23539 this.ownerTree = p.ownerTree;
23545 return this.ownerTree;
23549 * Returns depth of this node (the root node has a depth of 0)
23552 getDepth : function(){
23555 while(p.parentNode){
23563 setOwnerTree : function(tree){
23564 // if it's move, we need to update everyone
23565 if(tree != this.ownerTree){
23566 if(this.ownerTree){
23567 this.ownerTree.unregisterNode(this);
23569 this.ownerTree = tree;
23570 var cs = this.childNodes;
23571 for(var i = 0, len = cs.length; i < len; i++) {
23572 cs[i].setOwnerTree(tree);
23575 tree.registerNode(this);
23581 * Returns the path for this node. The path can be used to expand or select this node programmatically.
23582 * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
23583 * @return {String} The path
23585 getPath : function(attr){
23586 attr = attr || "id";
23587 var p = this.parentNode;
23588 var b = [this.attributes[attr]];
23590 b.unshift(p.attributes[attr]);
23593 var sep = this.getOwnerTree().pathSeparator;
23594 return sep + b.join(sep);
23598 * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
23599 * function call will be the scope provided or the current node. The arguments to the function
23600 * will be the args provided or the current node. If the function returns false at any point,
23601 * the bubble is stopped.
23602 * @param {Function} fn The function to call
23603 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23604 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23606 bubble : function(fn, scope, args){
23609 if(fn.call(scope || p, args || p) === false){
23617 * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
23618 * function call will be the scope provided or the current node. The arguments to the function
23619 * will be the args provided or the current node. If the function returns false at any point,
23620 * the cascade is stopped on that branch.
23621 * @param {Function} fn The function to call
23622 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23623 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23625 cascade : function(fn, scope, args){
23626 if(fn.call(scope || this, args || this) !== false){
23627 var cs = this.childNodes;
23628 for(var i = 0, len = cs.length; i < len; i++) {
23629 cs[i].cascade(fn, scope, args);
23635 * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
23636 * function call will be the scope provided or the current node. The arguments to the function
23637 * will be the args provided or the current node. If the function returns false at any point,
23638 * the iteration stops.
23639 * @param {Function} fn The function to call
23640 * @param {Object} scope (optional) The scope of the function (defaults to current node)
23641 * @param {Array} args (optional) The args to call the function with (default to passing the current node)
23643 eachChild : function(fn, scope, args){
23644 var cs = this.childNodes;
23645 for(var i = 0, len = cs.length; i < len; i++) {
23646 if(fn.call(scope || this, args || cs[i]) === false){
23653 * Finds the first child that has the attribute with the specified value.
23654 * @param {String} attribute The attribute name
23655 * @param {Mixed} value The value to search for
23656 * @return {Node} The found child or null if none was found
23658 findChild : function(attribute, value){
23659 var cs = this.childNodes;
23660 for(var i = 0, len = cs.length; i < len; i++) {
23661 if(cs[i].attributes[attribute] == value){
23669 * Finds the first child by a custom function. The child matches if the function passed
23671 * @param {Function} fn
23672 * @param {Object} scope (optional)
23673 * @return {Node} The found child or null if none was found
23675 findChildBy : function(fn, scope){
23676 var cs = this.childNodes;
23677 for(var i = 0, len = cs.length; i < len; i++) {
23678 if(fn.call(scope||cs[i], cs[i]) === true){
23686 * Sorts this nodes children using the supplied sort function
23687 * @param {Function} fn
23688 * @param {Object} scope (optional)
23690 sort : function(fn, scope){
23691 var cs = this.childNodes;
23692 var len = cs.length;
23694 var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
23696 for(var i = 0; i < len; i++){
23698 n.previousSibling = cs[i-1];
23699 n.nextSibling = cs[i+1];
23701 this.setFirstChild(n);
23704 this.setLastChild(n);
23711 * Returns true if this node is an ancestor (at any point) of the passed node.
23712 * @param {Node} node
23713 * @return {Boolean}
23715 contains : function(node){
23716 return node.isAncestor(this);
23720 * Returns true if the passed node is an ancestor (at any point) of this node.
23721 * @param {Node} node
23722 * @return {Boolean}
23724 isAncestor : function(node){
23725 var p = this.parentNode;
23735 toString : function(){
23736 return "[Node"+(this.id?" "+this.id:"")+"]";
23740 * Ext JS Library 1.1.1
23741 * Copyright(c) 2006-2007, Ext JS, LLC.
23743 * Originally Released Under LGPL - original licence link has changed is not relivant.
23746 * <script type="text/javascript">
23751 * @extends Roo.Element
23752 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
23753 * automatic maintaining of shadow/shim positions.
23754 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
23755 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
23756 * you can pass a string with a CSS class name. False turns off the shadow.
23757 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
23758 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
23759 * @cfg {String} cls CSS class to add to the element
23760 * @cfg {Number} zindex Starting z-index (defaults to 11000)
23761 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
23763 * @param {Object} config An object with config options.
23764 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
23767 Roo.Layer = function(config, existingEl){
23768 config = config || {};
23769 var dh = Roo.DomHelper;
23770 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
23772 this.dom = Roo.getDom(existingEl);
23775 var o = config.dh || {tag: "div", cls: "x-layer"};
23776 this.dom = dh.append(pel, o);
23779 this.addClass(config.cls);
23781 this.constrain = config.constrain !== false;
23782 this.visibilityMode = Roo.Element.VISIBILITY;
23784 this.id = this.dom.id = config.id;
23786 this.id = Roo.id(this.dom);
23788 this.zindex = config.zindex || this.getZIndex();
23789 this.position("absolute", this.zindex);
23791 this.shadowOffset = config.shadowOffset || 4;
23792 this.shadow = new Roo.Shadow({
23793 offset : this.shadowOffset,
23794 mode : config.shadow
23797 this.shadowOffset = 0;
23799 this.useShim = config.shim !== false && Roo.useShims;
23800 this.useDisplay = config.useDisplay;
23804 var supr = Roo.Element.prototype;
23806 // shims are shared among layer to keep from having 100 iframes
23809 Roo.extend(Roo.Layer, Roo.Element, {
23811 getZIndex : function(){
23812 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
23815 getShim : function(){
23822 var shim = shims.shift();
23824 shim = this.createShim();
23825 shim.enableDisplayMode('block');
23826 shim.dom.style.display = 'none';
23827 shim.dom.style.visibility = 'visible';
23829 var pn = this.dom.parentNode;
23830 if(shim.dom.parentNode != pn){
23831 pn.insertBefore(shim.dom, this.dom);
23833 shim.setStyle('z-index', this.getZIndex()-2);
23838 hideShim : function(){
23840 this.shim.setDisplayed(false);
23841 shims.push(this.shim);
23846 disableShadow : function(){
23848 this.shadowDisabled = true;
23849 this.shadow.hide();
23850 this.lastShadowOffset = this.shadowOffset;
23851 this.shadowOffset = 0;
23855 enableShadow : function(show){
23857 this.shadowDisabled = false;
23858 this.shadowOffset = this.lastShadowOffset;
23859 delete this.lastShadowOffset;
23867 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
23868 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
23869 sync : function(doShow){
23870 var sw = this.shadow;
23871 if(!this.updating && this.isVisible() && (sw || this.useShim)){
23872 var sh = this.getShim();
23874 var w = this.getWidth(),
23875 h = this.getHeight();
23877 var l = this.getLeft(true),
23878 t = this.getTop(true);
23880 if(sw && !this.shadowDisabled){
23881 if(doShow && !sw.isVisible()){
23884 sw.realign(l, t, w, h);
23890 // fit the shim behind the shadow, so it is shimmed too
23891 var a = sw.adjusts, s = sh.dom.style;
23892 s.left = (Math.min(l, l+a.l))+"px";
23893 s.top = (Math.min(t, t+a.t))+"px";
23894 s.width = (w+a.w)+"px";
23895 s.height = (h+a.h)+"px";
23902 sh.setLeftTop(l, t);
23909 destroy : function(){
23912 this.shadow.hide();
23914 this.removeAllListeners();
23915 var pn = this.dom.parentNode;
23917 pn.removeChild(this.dom);
23919 Roo.Element.uncache(this.id);
23922 remove : function(){
23927 beginUpdate : function(){
23928 this.updating = true;
23932 endUpdate : function(){
23933 this.updating = false;
23938 hideUnders : function(negOffset){
23940 this.shadow.hide();
23946 constrainXY : function(){
23947 if(this.constrain){
23948 var vw = Roo.lib.Dom.getViewWidth(),
23949 vh = Roo.lib.Dom.getViewHeight();
23950 var s = Roo.get(document).getScroll();
23952 var xy = this.getXY();
23953 var x = xy[0], y = xy[1];
23954 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
23955 // only move it if it needs it
23957 // first validate right/bottom
23958 if((x + w) > vw+s.left){
23959 x = vw - w - this.shadowOffset;
23962 if((y + h) > vh+s.top){
23963 y = vh - h - this.shadowOffset;
23966 // then make sure top/left isn't negative
23977 var ay = this.avoidY;
23978 if(y <= ay && (y+h) >= ay){
23984 supr.setXY.call(this, xy);
23990 isVisible : function(){
23991 return this.visible;
23995 showAction : function(){
23996 this.visible = true; // track visibility to prevent getStyle calls
23997 if(this.useDisplay === true){
23998 this.setDisplayed("");
23999 }else if(this.lastXY){
24000 supr.setXY.call(this, this.lastXY);
24001 }else if(this.lastLT){
24002 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
24007 hideAction : function(){
24008 this.visible = false;
24009 if(this.useDisplay === true){
24010 this.setDisplayed(false);
24012 this.setLeftTop(-10000,-10000);
24016 // overridden Element method
24017 setVisible : function(v, a, d, c, e){
24022 var cb = function(){
24027 }.createDelegate(this);
24028 supr.setVisible.call(this, true, true, d, cb, e);
24031 this.hideUnders(true);
24040 }.createDelegate(this);
24042 supr.setVisible.call(this, v, a, d, cb, e);
24051 storeXY : function(xy){
24052 delete this.lastLT;
24056 storeLeftTop : function(left, top){
24057 delete this.lastXY;
24058 this.lastLT = [left, top];
24062 beforeFx : function(){
24063 this.beforeAction();
24064 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
24068 afterFx : function(){
24069 Roo.Layer.superclass.afterFx.apply(this, arguments);
24070 this.sync(this.isVisible());
24074 beforeAction : function(){
24075 if(!this.updating && this.shadow){
24076 this.shadow.hide();
24080 // overridden Element method
24081 setLeft : function(left){
24082 this.storeLeftTop(left, this.getTop(true));
24083 supr.setLeft.apply(this, arguments);
24087 setTop : function(top){
24088 this.storeLeftTop(this.getLeft(true), top);
24089 supr.setTop.apply(this, arguments);
24093 setLeftTop : function(left, top){
24094 this.storeLeftTop(left, top);
24095 supr.setLeftTop.apply(this, arguments);
24099 setXY : function(xy, a, d, c, e){
24101 this.beforeAction();
24103 var cb = this.createCB(c);
24104 supr.setXY.call(this, xy, a, d, cb, e);
24111 createCB : function(c){
24122 // overridden Element method
24123 setX : function(x, a, d, c, e){
24124 this.setXY([x, this.getY()], a, d, c, e);
24127 // overridden Element method
24128 setY : function(y, a, d, c, e){
24129 this.setXY([this.getX(), y], a, d, c, e);
24132 // overridden Element method
24133 setSize : function(w, h, a, d, c, e){
24134 this.beforeAction();
24135 var cb = this.createCB(c);
24136 supr.setSize.call(this, w, h, a, d, cb, e);
24142 // overridden Element method
24143 setWidth : function(w, a, d, c, e){
24144 this.beforeAction();
24145 var cb = this.createCB(c);
24146 supr.setWidth.call(this, w, a, d, cb, e);
24152 // overridden Element method
24153 setHeight : function(h, a, d, c, e){
24154 this.beforeAction();
24155 var cb = this.createCB(c);
24156 supr.setHeight.call(this, h, a, d, cb, e);
24162 // overridden Element method
24163 setBounds : function(x, y, w, h, a, d, c, e){
24164 this.beforeAction();
24165 var cb = this.createCB(c);
24167 this.storeXY([x, y]);
24168 supr.setXY.call(this, [x, y]);
24169 supr.setSize.call(this, w, h, a, d, cb, e);
24172 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
24178 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
24179 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
24180 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
24181 * @param {Number} zindex The new z-index to set
24182 * @return {this} The Layer
24184 setZIndex : function(zindex){
24185 this.zindex = zindex;
24186 this.setStyle("z-index", zindex + 2);
24188 this.shadow.setZIndex(zindex + 1);
24191 this.shim.setStyle("z-index", zindex);
24197 * Ext JS Library 1.1.1
24198 * Copyright(c) 2006-2007, Ext JS, LLC.
24200 * Originally Released Under LGPL - original licence link has changed is not relivant.
24203 * <script type="text/javascript">
24208 * @class Roo.Shadow
24209 * Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
24210 * and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
24211 * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
24213 * Create a new Shadow
24214 * @param {Object} config The config object
24216 Roo.Shadow = function(config){
24217 Roo.apply(this, config);
24218 if(typeof this.mode != "string"){
24219 this.mode = this.defaultMode;
24221 var o = this.offset, a = {h: 0};
24222 var rad = Math.floor(this.offset/2);
24223 switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
24229 a.l -= this.offset + rad;
24230 a.t -= this.offset + rad;
24241 a.l -= (this.offset - rad);
24242 a.t -= this.offset + rad;
24244 a.w -= (this.offset - rad)*2;
24255 a.l -= (this.offset - rad);
24256 a.t -= (this.offset - rad);
24258 a.w -= (this.offset + rad + 1);
24259 a.h -= (this.offset + rad);
24268 Roo.Shadow.prototype = {
24270 * @cfg {String} mode
24271 * The shadow display mode. Supports the following options:<br />
24272 * sides: Shadow displays on both sides and bottom only<br />
24273 * frame: Shadow displays equally on all four sides<br />
24274 * drop: Traditional bottom-right drop shadow (default)
24277 * @cfg {String} offset
24278 * The number of pixels to offset the shadow from the element (defaults to 4)
24283 defaultMode: "drop",
24286 * Displays the shadow under the target element
24287 * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
24289 show : function(target){
24290 target = Roo.get(target);
24292 this.el = Roo.Shadow.Pool.pull();
24293 if(this.el.dom.nextSibling != target.dom){
24294 this.el.insertBefore(target);
24297 this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
24299 this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
24302 target.getLeft(true),
24303 target.getTop(true),
24307 this.el.dom.style.display = "block";
24311 * Returns true if the shadow is visible, else false
24313 isVisible : function(){
24314 return this.el ? true : false;
24318 * Direct alignment when values are already available. Show must be called at least once before
24319 * calling this method to ensure it is initialized.
24320 * @param {Number} left The target element left position
24321 * @param {Number} top The target element top position
24322 * @param {Number} width The target element width
24323 * @param {Number} height The target element height
24325 realign : function(l, t, w, h){
24329 var a = this.adjusts, d = this.el.dom, s = d.style;
24331 s.left = (l+a.l)+"px";
24332 s.top = (t+a.t)+"px";
24333 var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
24335 if(s.width != sws || s.height != shs){
24339 var cn = d.childNodes;
24340 var sww = Math.max(0, (sw-12))+"px";
24341 cn[0].childNodes[1].style.width = sww;
24342 cn[1].childNodes[1].style.width = sww;
24343 cn[2].childNodes[1].style.width = sww;
24344 cn[1].style.height = Math.max(0, (sh-12))+"px";
24350 * Hides this shadow
24354 this.el.dom.style.display = "none";
24355 Roo.Shadow.Pool.push(this.el);
24361 * Adjust the z-index of this shadow
24362 * @param {Number} zindex The new z-index
24364 setZIndex : function(z){
24367 this.el.setStyle("z-index", z);
24372 // Private utility class that manages the internal Shadow cache
24373 Roo.Shadow.Pool = function(){
24375 var markup = Roo.isIE ?
24376 '<div class="x-ie-shadow"></div>' :
24377 '<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>';
24380 var sh = p.shift();
24382 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
24383 sh.autoBoxAdjust = false;
24388 push : function(sh){
24394 * Ext JS Library 1.1.1
24395 * Copyright(c) 2006-2007, Ext JS, LLC.
24397 * Originally Released Under LGPL - original licence link has changed is not relivant.
24400 * <script type="text/javascript">
24405 * @class Roo.SplitBar
24406 * @extends Roo.util.Observable
24407 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
24411 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
24412 Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
24413 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
24414 split.minSize = 100;
24415 split.maxSize = 600;
24416 split.animate = true;
24417 split.on('moved', splitterMoved);
24420 * Create a new SplitBar
24421 * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar.
24422 * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged
24423 * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
24424 * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or
24425 Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
24426 position of the SplitBar).
24428 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
24431 this.el = Roo.get(dragElement, true);
24432 this.el.dom.unselectable = "on";
24434 this.resizingEl = Roo.get(resizingElement, true);
24438 * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
24439 * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
24442 this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
24445 * The minimum size of the resizing element. (Defaults to 0)
24451 * The maximum size of the resizing element. (Defaults to 2000)
24454 this.maxSize = 2000;
24457 * Whether to animate the transition to the new size
24460 this.animate = false;
24463 * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
24466 this.useShim = false;
24471 if(!existingProxy){
24473 this.proxy = Roo.SplitBar.createProxy(this.orientation);
24475 this.proxy = Roo.get(existingProxy).dom;
24478 this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
24481 this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
24484 this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
24487 this.dragSpecs = {};
24490 * @private The adapter to use to positon and resize elements
24492 this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
24493 this.adapter.init(this);
24495 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24497 this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
24498 this.el.addClass("x-splitbar-h");
24501 this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
24502 this.el.addClass("x-splitbar-v");
24508 * Fires when the splitter is moved (alias for {@link #event-moved})
24509 * @param {Roo.SplitBar} this
24510 * @param {Number} newSize the new width or height
24515 * Fires when the splitter is moved
24516 * @param {Roo.SplitBar} this
24517 * @param {Number} newSize the new width or height
24521 * @event beforeresize
24522 * Fires before the splitter is dragged
24523 * @param {Roo.SplitBar} this
24525 "beforeresize" : true,
24527 "beforeapply" : true
24530 Roo.util.Observable.call(this);
24533 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
24534 onStartProxyDrag : function(x, y){
24535 this.fireEvent("beforeresize", this);
24537 var o = Roo.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: " "}, true);
24539 o.enableDisplayMode("block");
24540 // all splitbars share the same overlay
24541 Roo.SplitBar.prototype.overlay = o;
24543 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
24544 this.overlay.show();
24545 Roo.get(this.proxy).setDisplayed("block");
24546 var size = this.adapter.getElementSize(this);
24547 this.activeMinSize = this.getMinimumSize();;
24548 this.activeMaxSize = this.getMaximumSize();;
24549 var c1 = size - this.activeMinSize;
24550 var c2 = Math.max(this.activeMaxSize - size, 0);
24551 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24552 this.dd.resetConstraints();
24553 this.dd.setXConstraint(
24554 this.placement == Roo.SplitBar.LEFT ? c1 : c2,
24555 this.placement == Roo.SplitBar.LEFT ? c2 : c1
24557 this.dd.setYConstraint(0, 0);
24559 this.dd.resetConstraints();
24560 this.dd.setXConstraint(0, 0);
24561 this.dd.setYConstraint(
24562 this.placement == Roo.SplitBar.TOP ? c1 : c2,
24563 this.placement == Roo.SplitBar.TOP ? c2 : c1
24566 this.dragSpecs.startSize = size;
24567 this.dragSpecs.startPoint = [x, y];
24568 Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
24572 * @private Called after the drag operation by the DDProxy
24574 onEndProxyDrag : function(e){
24575 Roo.get(this.proxy).setDisplayed(false);
24576 var endPoint = Roo.lib.Event.getXY(e);
24578 this.overlay.hide();
24581 if(this.orientation == Roo.SplitBar.HORIZONTAL){
24582 newSize = this.dragSpecs.startSize +
24583 (this.placement == Roo.SplitBar.LEFT ?
24584 endPoint[0] - this.dragSpecs.startPoint[0] :
24585 this.dragSpecs.startPoint[0] - endPoint[0]
24588 newSize = this.dragSpecs.startSize +
24589 (this.placement == Roo.SplitBar.TOP ?
24590 endPoint[1] - this.dragSpecs.startPoint[1] :
24591 this.dragSpecs.startPoint[1] - endPoint[1]
24594 newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
24595 if(newSize != this.dragSpecs.startSize){
24596 if(this.fireEvent('beforeapply', this, newSize) !== false){
24597 this.adapter.setElementSize(this, newSize);
24598 this.fireEvent("moved", this, newSize);
24599 this.fireEvent("resize", this, newSize);
24605 * Get the adapter this SplitBar uses
24606 * @return The adapter object
24608 getAdapter : function(){
24609 return this.adapter;
24613 * Set the adapter this SplitBar uses
24614 * @param {Object} adapter A SplitBar adapter object
24616 setAdapter : function(adapter){
24617 this.adapter = adapter;
24618 this.adapter.init(this);
24622 * Gets the minimum size for the resizing element
24623 * @return {Number} The minimum size
24625 getMinimumSize : function(){
24626 return this.minSize;
24630 * Sets the minimum size for the resizing element
24631 * @param {Number} minSize The minimum size
24633 setMinimumSize : function(minSize){
24634 this.minSize = minSize;
24638 * Gets the maximum size for the resizing element
24639 * @return {Number} The maximum size
24641 getMaximumSize : function(){
24642 return this.maxSize;
24646 * Sets the maximum size for the resizing element
24647 * @param {Number} maxSize The maximum size
24649 setMaximumSize : function(maxSize){
24650 this.maxSize = maxSize;
24654 * Sets the initialize size for the resizing element
24655 * @param {Number} size The initial size
24657 setCurrentSize : function(size){
24658 var oldAnimate = this.animate;
24659 this.animate = false;
24660 this.adapter.setElementSize(this, size);
24661 this.animate = oldAnimate;
24665 * Destroy this splitbar.
24666 * @param {Boolean} removeEl True to remove the element
24668 destroy : function(removeEl){
24670 this.shim.remove();
24673 this.proxy.parentNode.removeChild(this.proxy);
24681 * @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.
24683 Roo.SplitBar.createProxy = function(dir){
24684 var proxy = new Roo.Element(document.createElement("div"));
24685 proxy.unselectable();
24686 var cls = 'x-splitbar-proxy';
24687 proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
24688 document.body.appendChild(proxy.dom);
24693 * @class Roo.SplitBar.BasicLayoutAdapter
24694 * Default Adapter. It assumes the splitter and resizing element are not positioned
24695 * elements and only gets/sets the width of the element. Generally used for table based layouts.
24697 Roo.SplitBar.BasicLayoutAdapter = function(){
24700 Roo.SplitBar.BasicLayoutAdapter.prototype = {
24701 // do nothing for now
24702 init : function(s){
24706 * Called before drag operations to get the current size of the resizing element.
24707 * @param {Roo.SplitBar} s The SplitBar using this adapter
24709 getElementSize : function(s){
24710 if(s.orientation == Roo.SplitBar.HORIZONTAL){
24711 return s.resizingEl.getWidth();
24713 return s.resizingEl.getHeight();
24718 * Called after drag operations to set the size of the resizing element.
24719 * @param {Roo.SplitBar} s The SplitBar using this adapter
24720 * @param {Number} newSize The new size to set
24721 * @param {Function} onComplete A function to be invoked when resizing is complete
24723 setElementSize : function(s, newSize, onComplete){
24724 if(s.orientation == Roo.SplitBar.HORIZONTAL){
24726 s.resizingEl.setWidth(newSize);
24728 onComplete(s, newSize);
24731 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
24736 s.resizingEl.setHeight(newSize);
24738 onComplete(s, newSize);
24741 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
24748 *@class Roo.SplitBar.AbsoluteLayoutAdapter
24749 * @extends Roo.SplitBar.BasicLayoutAdapter
24750 * Adapter that moves the splitter element to align with the resized sizing element.
24751 * Used with an absolute positioned SplitBar.
24752 * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
24753 * document.body, make sure you assign an id to the body element.
24755 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
24756 this.basic = new Roo.SplitBar.BasicLayoutAdapter();
24757 this.container = Roo.get(container);
24760 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
24761 init : function(s){
24762 this.basic.init(s);
24765 getElementSize : function(s){
24766 return this.basic.getElementSize(s);
24769 setElementSize : function(s, newSize, onComplete){
24770 this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
24773 moveSplitter : function(s){
24774 var yes = Roo.SplitBar;
24775 switch(s.placement){
24777 s.el.setX(s.resizingEl.getRight());
24780 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
24783 s.el.setY(s.resizingEl.getBottom());
24786 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
24793 * Orientation constant - Create a vertical SplitBar
24797 Roo.SplitBar.VERTICAL = 1;
24800 * Orientation constant - Create a horizontal SplitBar
24804 Roo.SplitBar.HORIZONTAL = 2;
24807 * Placement constant - The resizing element is to the left of the splitter element
24811 Roo.SplitBar.LEFT = 1;
24814 * Placement constant - The resizing element is to the right of the splitter element
24818 Roo.SplitBar.RIGHT = 2;
24821 * Placement constant - The resizing element is positioned above the splitter element
24825 Roo.SplitBar.TOP = 3;
24828 * Placement constant - The resizing element is positioned under splitter element
24832 Roo.SplitBar.BOTTOM = 4;
24835 * Ext JS Library 1.1.1
24836 * Copyright(c) 2006-2007, Ext JS, LLC.
24838 * Originally Released Under LGPL - original licence link has changed is not relivant.
24841 * <script type="text/javascript">
24846 * @extends Roo.util.Observable
24847 * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template.
24848 * This class also supports single and multi selection modes. <br>
24849 * Create a data model bound view:
24851 var store = new Roo.data.Store(...);
24853 var view = new Roo.View({
24855 tpl : '<div id="{0}">{2} - {1}</div>', // auto create template
24857 singleSelect: true,
24858 selectedClass: "ydataview-selected",
24862 // listen for node click?
24863 view.on("click", function(vw, index, node, e){
24864 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
24868 dataModel.load("foobar.xml");
24870 For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
24872 * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
24873 * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
24875 * Note: old style constructor is still suported (container, template, config)
24878 * Create a new View
24879 * @param {Object} config The config object
24882 Roo.View = function(config, depreciated_tpl, depreciated_config){
24884 this.parent = false;
24886 if (typeof(depreciated_tpl) == 'undefined') {
24887 // new way.. - universal constructor.
24888 Roo.apply(this, config);
24889 this.el = Roo.get(this.el);
24892 this.el = Roo.get(config);
24893 this.tpl = depreciated_tpl;
24894 Roo.apply(this, depreciated_config);
24896 this.wrapEl = this.el.wrap().wrap();
24897 ///this.el = this.wrapEla.appendChild(document.createElement("div"));
24900 if(typeof(this.tpl) == "string"){
24901 this.tpl = new Roo.Template(this.tpl);
24903 // support xtype ctors..
24904 this.tpl = new Roo.factory(this.tpl, Roo);
24908 this.tpl.compile();
24913 * @event beforeclick
24914 * Fires before a click is processed. Returns false to cancel the default action.
24915 * @param {Roo.View} this
24916 * @param {Number} index The index of the target node
24917 * @param {HTMLElement} node The target node
24918 * @param {Roo.EventObject} e The raw event object
24920 "beforeclick" : true,
24923 * Fires when a template node is clicked.
24924 * @param {Roo.View} this
24925 * @param {Number} index The index of the target node
24926 * @param {HTMLElement} node The target node
24927 * @param {Roo.EventObject} e The raw event object
24932 * Fires when a template node is double clicked.
24933 * @param {Roo.View} this
24934 * @param {Number} index The index of the target node
24935 * @param {HTMLElement} node The target node
24936 * @param {Roo.EventObject} e The raw event object
24940 * @event contextmenu
24941 * Fires when a template node is right clicked.
24942 * @param {Roo.View} this
24943 * @param {Number} index The index of the target node
24944 * @param {HTMLElement} node The target node
24945 * @param {Roo.EventObject} e The raw event object
24947 "contextmenu" : true,
24949 * @event selectionchange
24950 * Fires when the selected nodes change.
24951 * @param {Roo.View} this
24952 * @param {Array} selections Array of the selected nodes
24954 "selectionchange" : true,
24957 * @event beforeselect
24958 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
24959 * @param {Roo.View} this
24960 * @param {HTMLElement} node The node to be selected
24961 * @param {Array} selections Array of currently selected nodes
24963 "beforeselect" : true,
24965 * @event preparedata
24966 * Fires on every row to render, to allow you to change the data.
24967 * @param {Roo.View} this
24968 * @param {Object} data to be rendered (change this)
24970 "preparedata" : true
24978 "click": this.onClick,
24979 "dblclick": this.onDblClick,
24980 "contextmenu": this.onContextMenu,
24984 this.selections = [];
24986 this.cmp = new Roo.CompositeElementLite([]);
24988 this.store = Roo.factory(this.store, Roo.data);
24989 this.setStore(this.store, true);
24992 if ( this.footer && this.footer.xtype) {
24994 var fctr = this.wrapEl.appendChild(document.createElement("div"));
24996 this.footer.dataSource = this.store
24997 this.footer.container = fctr;
24998 this.footer = Roo.factory(this.footer, Roo);
24999 fctr.insertFirst(this.el);
25001 // this is a bit insane - as the paging toolbar seems to detach the el..
25002 // dom.parentNode.parentNode.parentNode
25003 // they get detached?
25007 Roo.View.superclass.constructor.call(this);
25012 Roo.extend(Roo.View, Roo.util.Observable, {
25015 * @cfg {Roo.data.Store} store Data store to load data from.
25020 * @cfg {String|Roo.Element} el The container element.
25025 * @cfg {String|Roo.Template} tpl The template used by this View
25029 * @cfg {String} dataName the named area of the template to use as the data area
25030 * Works with domtemplates roo-name="name"
25034 * @cfg {String} selectedClass The css class to add to selected nodes
25036 selectedClass : "x-view-selected",
25038 * @cfg {String} emptyText The empty text to show when nothing is loaded.
25043 * @cfg {String} text to display on mask (default Loading)
25047 * @cfg {Boolean} multiSelect Allow multiple selection
25049 multiSelect : false,
25051 * @cfg {Boolean} singleSelect Allow single selection
25053 singleSelect: false,
25056 * @cfg {Boolean} toggleSelect - selecting
25058 toggleSelect : false,
25061 * @cfg {Boolean} tickable - selecting
25066 * Returns the element this view is bound to.
25067 * @return {Roo.Element}
25069 getEl : function(){
25070 return this.wrapEl;
25076 * Refreshes the view. - called by datachanged on the store. - do not call directly.
25078 refresh : function(){
25079 //Roo.log('refresh');
25082 // if we are using something like 'domtemplate', then
25083 // the what gets used is:
25084 // t.applySubtemplate(NAME, data, wrapping data..)
25085 // the outer template then get' applied with
25086 // the store 'extra data'
25087 // and the body get's added to the
25088 // roo-name="data" node?
25089 // <span class='roo-tpl-{name}'></span> ?????
25093 this.clearSelections();
25094 this.el.update("");
25096 var records = this.store.getRange();
25097 if(records.length < 1) {
25099 // is this valid?? = should it render a template??
25101 this.el.update(this.emptyText);
25105 if (this.dataName) {
25106 this.el.update(t.apply(this.store.meta)); //????
25107 el = this.el.child('.roo-tpl-' + this.dataName);
25110 for(var i = 0, len = records.length; i < len; i++){
25111 var data = this.prepareData(records[i].data, i, records[i]);
25112 this.fireEvent("preparedata", this, data, i, records[i]);
25114 var d = Roo.apply({}, data);
25117 Roo.apply(d, {'roo-id' : Roo.id()});
25121 Roo.each(this.parent.item, function(item){
25122 if(item[_this.parent.valueField] != data[_this.parent.valueField]){
25125 Roo.apply(d, {'roo-data-checked' : 'checked'});
25129 html[html.length] = Roo.util.Format.trim(
25131 t.applySubtemplate(this.dataName, d, this.store.meta) :
25138 el.update(html.join(""));
25139 this.nodes = el.dom.childNodes;
25140 this.updateIndexes(0);
25145 * Function to override to reformat the data that is sent to
25146 * the template for each node.
25147 * DEPRICATED - use the preparedata event handler.
25148 * @param {Array/Object} data The raw data (array of colData for a data model bound view or
25149 * a JSON object for an UpdateManager bound view).
25151 prepareData : function(data, index, record)
25153 this.fireEvent("preparedata", this, data, index, record);
25157 onUpdate : function(ds, record){
25158 // Roo.log('on update');
25159 this.clearSelections();
25160 var index = this.store.indexOf(record);
25161 var n = this.nodes[index];
25162 this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
25163 n.parentNode.removeChild(n);
25164 this.updateIndexes(index, index);
25170 onAdd : function(ds, records, index)
25172 //Roo.log(['on Add', ds, records, index] );
25173 this.clearSelections();
25174 if(this.nodes.length == 0){
25178 var n = this.nodes[index];
25179 for(var i = 0, len = records.length; i < len; i++){
25180 var d = this.prepareData(records[i].data, i, records[i]);
25182 this.tpl.insertBefore(n, d);
25185 this.tpl.append(this.el, d);
25188 this.updateIndexes(index);
25191 onRemove : function(ds, record, index){
25192 // Roo.log('onRemove');
25193 this.clearSelections();
25194 var el = this.dataName ?
25195 this.el.child('.roo-tpl-' + this.dataName) :
25198 el.dom.removeChild(this.nodes[index]);
25199 this.updateIndexes(index);
25203 * Refresh an individual node.
25204 * @param {Number} index
25206 refreshNode : function(index){
25207 this.onUpdate(this.store, this.store.getAt(index));
25210 updateIndexes : function(startIndex, endIndex){
25211 var ns = this.nodes;
25212 startIndex = startIndex || 0;
25213 endIndex = endIndex || ns.length - 1;
25214 for(var i = startIndex; i <= endIndex; i++){
25215 ns[i].nodeIndex = i;
25220 * Changes the data store this view uses and refresh the view.
25221 * @param {Store} store
25223 setStore : function(store, initial){
25224 if(!initial && this.store){
25225 this.store.un("datachanged", this.refresh);
25226 this.store.un("add", this.onAdd);
25227 this.store.un("remove", this.onRemove);
25228 this.store.un("update", this.onUpdate);
25229 this.store.un("clear", this.refresh);
25230 this.store.un("beforeload", this.onBeforeLoad);
25231 this.store.un("load", this.onLoad);
25232 this.store.un("loadexception", this.onLoad);
25236 store.on("datachanged", this.refresh, this);
25237 store.on("add", this.onAdd, this);
25238 store.on("remove", this.onRemove, this);
25239 store.on("update", this.onUpdate, this);
25240 store.on("clear", this.refresh, this);
25241 store.on("beforeload", this.onBeforeLoad, this);
25242 store.on("load", this.onLoad, this);
25243 store.on("loadexception", this.onLoad, this);
25251 * onbeforeLoad - masks the loading area.
25254 onBeforeLoad : function(store,opts)
25256 //Roo.log('onBeforeLoad');
25258 this.el.update("");
25260 this.el.mask(this.mask ? this.mask : "Loading" );
25262 onLoad : function ()
25269 * Returns the template node the passed child belongs to or null if it doesn't belong to one.
25270 * @param {HTMLElement} node
25271 * @return {HTMLElement} The template node
25273 findItemFromChild : function(node){
25274 var el = this.dataName ?
25275 this.el.child('.roo-tpl-' + this.dataName,true) :
25278 if(!node || node.parentNode == el){
25281 var p = node.parentNode;
25282 while(p && p != el){
25283 if(p.parentNode == el){
25292 onClick : function(e){
25293 var item = this.findItemFromChild(e.getTarget());
25295 var index = this.indexOf(item);
25296 if(this.onItemClick(item, index, e) !== false){
25297 this.fireEvent("click", this, index, item, e);
25300 this.clearSelections();
25305 onContextMenu : function(e){
25306 var item = this.findItemFromChild(e.getTarget());
25308 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
25313 onDblClick : function(e){
25314 var item = this.findItemFromChild(e.getTarget());
25316 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
25320 onItemClick : function(item, index, e)
25322 if(this.fireEvent("beforeclick", this, index, item, e) === false){
25325 if (this.toggleSelect) {
25326 var m = this.isSelected(item) ? 'unselect' : 'select';
25329 _t[m](item, true, false);
25332 if(this.multiSelect || this.singleSelect){
25333 if(this.multiSelect && e.shiftKey && this.lastSelection){
25334 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
25336 this.select(item, this.multiSelect && e.ctrlKey);
25337 this.lastSelection = item;
25340 if(!this.tickable){
25341 e.preventDefault();
25349 * Get the number of selected nodes.
25352 getSelectionCount : function(){
25353 return this.selections.length;
25357 * Get the currently selected nodes.
25358 * @return {Array} An array of HTMLElements
25360 getSelectedNodes : function(){
25361 return this.selections;
25365 * Get the indexes of the selected nodes.
25368 getSelectedIndexes : function(){
25369 var indexes = [], s = this.selections;
25370 for(var i = 0, len = s.length; i < len; i++){
25371 indexes.push(s[i].nodeIndex);
25377 * Clear all selections
25378 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
25380 clearSelections : function(suppressEvent){
25381 if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
25382 this.cmp.elements = this.selections;
25383 this.cmp.removeClass(this.selectedClass);
25384 this.selections = [];
25385 if(!suppressEvent){
25386 this.fireEvent("selectionchange", this, this.selections);
25392 * Returns true if the passed node is selected
25393 * @param {HTMLElement/Number} node The node or node index
25394 * @return {Boolean}
25396 isSelected : function(node){
25397 var s = this.selections;
25401 node = this.getNode(node);
25402 return s.indexOf(node) !== -1;
25407 * @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
25408 * @param {Boolean} keepExisting (optional) true to keep existing selections
25409 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
25411 select : function(nodeInfo, keepExisting, suppressEvent){
25412 if(nodeInfo instanceof Array){
25414 this.clearSelections(true);
25416 for(var i = 0, len = nodeInfo.length; i < len; i++){
25417 this.select(nodeInfo[i], true, true);
25421 var node = this.getNode(nodeInfo);
25422 if(!node || this.isSelected(node)){
25423 return; // already selected.
25426 this.clearSelections(true);
25429 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
25430 Roo.fly(node).addClass(this.selectedClass);
25431 this.selections.push(node);
25432 if(!suppressEvent){
25433 this.fireEvent("selectionchange", this, this.selections);
25441 * @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
25442 * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
25443 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
25445 unselect : function(nodeInfo, keepExisting, suppressEvent)
25447 if(nodeInfo instanceof Array){
25448 Roo.each(this.selections, function(s) {
25449 this.unselect(s, nodeInfo);
25453 var node = this.getNode(nodeInfo);
25454 if(!node || !this.isSelected(node)){
25455 //Roo.log("not selected");
25456 return; // not selected.
25460 Roo.each(this.selections, function(s) {
25462 Roo.fly(node).removeClass(this.selectedClass);
25469 this.selections= ns;
25470 this.fireEvent("selectionchange", this, this.selections);
25474 * Gets a template node.
25475 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
25476 * @return {HTMLElement} The node or null if it wasn't found
25478 getNode : function(nodeInfo){
25479 if(typeof nodeInfo == "string"){
25480 return document.getElementById(nodeInfo);
25481 }else if(typeof nodeInfo == "number"){
25482 return this.nodes[nodeInfo];
25488 * Gets a range template nodes.
25489 * @param {Number} startIndex
25490 * @param {Number} endIndex
25491 * @return {Array} An array of nodes
25493 getNodes : function(start, end){
25494 var ns = this.nodes;
25495 start = start || 0;
25496 end = typeof end == "undefined" ? ns.length - 1 : end;
25499 for(var i = start; i <= end; i++){
25503 for(var i = start; i >= end; i--){
25511 * Finds the index of the passed node
25512 * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
25513 * @return {Number} The index of the node or -1
25515 indexOf : function(node){
25516 node = this.getNode(node);
25517 if(typeof node.nodeIndex == "number"){
25518 return node.nodeIndex;
25520 var ns = this.nodes;
25521 for(var i = 0, len = ns.length; i < len; i++){
25531 * Ext JS Library 1.1.1
25532 * Copyright(c) 2006-2007, Ext JS, LLC.
25534 * Originally Released Under LGPL - original licence link has changed is not relivant.
25537 * <script type="text/javascript">
25541 * @class Roo.JsonView
25542 * @extends Roo.View
25543 * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
25545 var view = new Roo.JsonView({
25546 container: "my-element",
25547 tpl: '<div id="{id}">{foo} - {bar}</div>', // auto create template
25552 // listen for node click?
25553 view.on("click", function(vw, index, node, e){
25554 alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
25557 // direct load of JSON data
25558 view.load("foobar.php");
25560 // Example from my blog list
25561 var tpl = new Roo.Template(
25562 '<div class="entry">' +
25563 '<a class="entry-title" href="{link}">{title}</a>' +
25564 "<h4>{date} by {author} | {comments} Comments</h4>{description}" +
25565 "</div><hr />"
25568 var moreView = new Roo.JsonView({
25569 container : "entry-list",
25573 moreView.on("beforerender", this.sortEntries, this);
25575 url: "/blog/get-posts.php",
25576 params: "allposts=true",
25577 text: "Loading Blog Entries..."
25581 * Note: old code is supported with arguments : (container, template, config)
25585 * Create a new JsonView
25587 * @param {Object} config The config object
25590 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
25593 Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
25595 var um = this.el.getUpdateManager();
25596 um.setRenderer(this);
25597 um.on("update", this.onLoad, this);
25598 um.on("failure", this.onLoadException, this);
25601 * @event beforerender
25602 * Fires before rendering of the downloaded JSON data.
25603 * @param {Roo.JsonView} this
25604 * @param {Object} data The JSON data loaded
25608 * Fires when data is loaded.
25609 * @param {Roo.JsonView} this
25610 * @param {Object} data The JSON data loaded
25611 * @param {Object} response The raw Connect response object
25614 * @event loadexception
25615 * Fires when loading fails.
25616 * @param {Roo.JsonView} this
25617 * @param {Object} response The raw Connect response object
25620 'beforerender' : true,
25622 'loadexception' : true
25625 Roo.extend(Roo.JsonView, Roo.View, {
25627 * @type {String} The root property in the loaded JSON object that contains the data
25632 * Refreshes the view.
25634 refresh : function(){
25635 this.clearSelections();
25636 this.el.update("");
25638 var o = this.jsonData;
25639 if(o && o.length > 0){
25640 for(var i = 0, len = o.length; i < len; i++){
25641 var data = this.prepareData(o[i], i, o);
25642 html[html.length] = this.tpl.apply(data);
25645 html.push(this.emptyText);
25647 this.el.update(html.join(""));
25648 this.nodes = this.el.dom.childNodes;
25649 this.updateIndexes(0);
25653 * 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.
25654 * @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:
25657 url: "your-url.php",
25658 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
25659 callback: yourFunction,
25660 scope: yourObject, //(optional scope)
25663 text: "Loading...",
25668 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
25669 * 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.
25670 * @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}
25671 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
25672 * @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.
25675 var um = this.el.getUpdateManager();
25676 um.update.apply(um, arguments);
25679 render : function(el, response){
25680 this.clearSelections();
25681 this.el.update("");
25684 o = Roo.util.JSON.decode(response.responseText);
25687 o = o[this.jsonRoot];
25692 * The current JSON data or null
25695 this.beforeRender();
25700 * Get the number of records in the current JSON dataset
25703 getCount : function(){
25704 return this.jsonData ? this.jsonData.length : 0;
25708 * Returns the JSON object for the specified node(s)
25709 * @param {HTMLElement/Array} node The node or an array of nodes
25710 * @return {Object/Array} If you pass in an array, you get an array back, otherwise
25711 * you get the JSON object for the node
25713 getNodeData : function(node){
25714 if(node instanceof Array){
25716 for(var i = 0, len = node.length; i < len; i++){
25717 data.push(this.getNodeData(node[i]));
25721 return this.jsonData[this.indexOf(node)] || null;
25724 beforeRender : function(){
25725 this.snapshot = this.jsonData;
25727 this.sort.apply(this, this.sortInfo);
25729 this.fireEvent("beforerender", this, this.jsonData);
25732 onLoad : function(el, o){
25733 this.fireEvent("load", this, this.jsonData, o);
25736 onLoadException : function(el, o){
25737 this.fireEvent("loadexception", this, o);
25741 * Filter the data by a specific property.
25742 * @param {String} property A property on your JSON objects
25743 * @param {String/RegExp} value Either string that the property values
25744 * should start with, or a RegExp to test against the property
25746 filter : function(property, value){
25749 var ss = this.snapshot;
25750 if(typeof value == "string"){
25751 var vlen = value.length;
25753 this.clearFilter();
25756 value = value.toLowerCase();
25757 for(var i = 0, len = ss.length; i < len; i++){
25759 if(o[property].substr(0, vlen).toLowerCase() == value){
25763 } else if(value.exec){ // regex?
25764 for(var i = 0, len = ss.length; i < len; i++){
25766 if(value.test(o[property])){
25773 this.jsonData = data;
25779 * Filter by a function. The passed function will be called with each
25780 * object in the current dataset. If the function returns true the value is kept,
25781 * otherwise it is filtered.
25782 * @param {Function} fn
25783 * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
25785 filterBy : function(fn, scope){
25788 var ss = this.snapshot;
25789 for(var i = 0, len = ss.length; i < len; i++){
25791 if(fn.call(scope || this, o)){
25795 this.jsonData = data;
25801 * Clears the current filter.
25803 clearFilter : function(){
25804 if(this.snapshot && this.jsonData != this.snapshot){
25805 this.jsonData = this.snapshot;
25812 * Sorts the data for this view and refreshes it.
25813 * @param {String} property A property on your JSON objects to sort on
25814 * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
25815 * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
25817 sort : function(property, dir, sortType){
25818 this.sortInfo = Array.prototype.slice.call(arguments, 0);
25821 var dsc = dir && dir.toLowerCase() == "desc";
25822 var f = function(o1, o2){
25823 var v1 = sortType ? sortType(o1[p]) : o1[p];
25824 var v2 = sortType ? sortType(o2[p]) : o2[p];
25827 return dsc ? +1 : -1;
25828 } else if(v1 > v2){
25829 return dsc ? -1 : +1;
25834 this.jsonData.sort(f);
25836 if(this.jsonData != this.snapshot){
25837 this.snapshot.sort(f);
25843 * Ext JS Library 1.1.1
25844 * Copyright(c) 2006-2007, Ext JS, LLC.
25846 * Originally Released Under LGPL - original licence link has changed is not relivant.
25849 * <script type="text/javascript">
25854 * @class Roo.ColorPalette
25855 * @extends Roo.Component
25856 * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
25857 * Here's an example of typical usage:
25859 var cp = new Roo.ColorPalette({value:'993300'}); // initial selected color
25860 cp.render('my-div');
25862 cp.on('select', function(palette, selColor){
25863 // do something with selColor
25867 * Create a new ColorPalette
25868 * @param {Object} config The config object
25870 Roo.ColorPalette = function(config){
25871 Roo.ColorPalette.superclass.constructor.call(this, config);
25875 * Fires when a color is selected
25876 * @param {ColorPalette} this
25877 * @param {String} color The 6-digit color hex code (without the # symbol)
25883 this.on("select", this.handler, this.scope, true);
25886 Roo.extend(Roo.ColorPalette, Roo.Component, {
25888 * @cfg {String} itemCls
25889 * The CSS class to apply to the containing element (defaults to "x-color-palette")
25891 itemCls : "x-color-palette",
25893 * @cfg {String} value
25894 * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
25895 * the hex codes are case-sensitive.
25898 clickEvent:'click',
25900 ctype: "Roo.ColorPalette",
25903 * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
25905 allowReselect : false,
25908 * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
25909 * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
25910 * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
25911 * of colors with the width setting until the box is symmetrical.</p>
25912 * <p>You can override individual colors if needed:</p>
25914 var cp = new Roo.ColorPalette();
25915 cp.colors[0] = "FF0000"; // change the first box to red
25918 Or you can provide a custom array of your own for complete control:
25920 var cp = new Roo.ColorPalette();
25921 cp.colors = ["000000", "993300", "333300"];
25926 "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
25927 "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
25928 "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
25929 "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
25930 "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
25934 onRender : function(container, position){
25935 var t = new Roo.MasterTemplate(
25936 '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on"> </span></em></a></tpl>'
25938 var c = this.colors;
25939 for(var i = 0, len = c.length; i < len; i++){
25942 var el = document.createElement("div");
25943 el.className = this.itemCls;
25945 container.dom.insertBefore(el, position);
25946 this.el = Roo.get(el);
25947 this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"});
25948 if(this.clickEvent != 'click'){
25949 this.el.on('click', Roo.emptyFn, this, {delegate: "a", preventDefault:true});
25954 afterRender : function(){
25955 Roo.ColorPalette.superclass.afterRender.call(this);
25957 var s = this.value;
25964 handleClick : function(e, t){
25965 e.preventDefault();
25966 if(!this.disabled){
25967 var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
25968 this.select(c.toUpperCase());
25973 * Selects the specified color in the palette (fires the select event)
25974 * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
25976 select : function(color){
25977 color = color.replace("#", "");
25978 if(color != this.value || this.allowReselect){
25981 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
25983 el.child("a.color-"+color).addClass("x-color-palette-sel");
25984 this.value = color;
25985 this.fireEvent("select", this, color);
25990 * Ext JS Library 1.1.1
25991 * Copyright(c) 2006-2007, Ext JS, LLC.
25993 * Originally Released Under LGPL - original licence link has changed is not relivant.
25996 * <script type="text/javascript">
26000 * @class Roo.DatePicker
26001 * @extends Roo.Component
26002 * Simple date picker class.
26004 * Create a new DatePicker
26005 * @param {Object} config The config object
26007 Roo.DatePicker = function(config){
26008 Roo.DatePicker.superclass.constructor.call(this, config);
26010 this.value = config && config.value ?
26011 config.value.clearTime() : new Date().clearTime();
26016 * Fires when a date is selected
26017 * @param {DatePicker} this
26018 * @param {Date} date The selected date
26022 * @event monthchange
26023 * Fires when the displayed month changes
26024 * @param {DatePicker} this
26025 * @param {Date} date The selected month
26027 'monthchange': true
26031 this.on("select", this.handler, this.scope || this);
26033 // build the disabledDatesRE
26034 if(!this.disabledDatesRE && this.disabledDates){
26035 var dd = this.disabledDates;
26037 for(var i = 0; i < dd.length; i++){
26039 if(i != dd.length-1) re += "|";
26041 this.disabledDatesRE = new RegExp(re + ")");
26045 Roo.extend(Roo.DatePicker, Roo.Component, {
26047 * @cfg {String} todayText
26048 * The text to display on the button that selects the current date (defaults to "Today")
26050 todayText : "Today",
26052 * @cfg {String} okText
26053 * The text to display on the ok button
26055 okText : " OK ", //   to give the user extra clicking room
26057 * @cfg {String} cancelText
26058 * The text to display on the cancel button
26060 cancelText : "Cancel",
26062 * @cfg {String} todayTip
26063 * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
26065 todayTip : "{0} (Spacebar)",
26067 * @cfg {Date} minDate
26068 * Minimum allowable date (JavaScript date object, defaults to null)
26072 * @cfg {Date} maxDate
26073 * Maximum allowable date (JavaScript date object, defaults to null)
26077 * @cfg {String} minText
26078 * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
26080 minText : "This date is before the minimum date",
26082 * @cfg {String} maxText
26083 * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
26085 maxText : "This date is after the maximum date",
26087 * @cfg {String} format
26088 * The default date format string which can be overriden for localization support. The format must be
26089 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
26093 * @cfg {Array} disabledDays
26094 * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
26096 disabledDays : null,
26098 * @cfg {String} disabledDaysText
26099 * The tooltip to display when the date falls on a disabled day (defaults to "")
26101 disabledDaysText : "",
26103 * @cfg {RegExp} disabledDatesRE
26104 * JavaScript regular expression used to disable a pattern of dates (defaults to null)
26106 disabledDatesRE : null,
26108 * @cfg {String} disabledDatesText
26109 * The tooltip text to display when the date falls on a disabled date (defaults to "")
26111 disabledDatesText : "",
26113 * @cfg {Boolean} constrainToViewport
26114 * True to constrain the date picker to the viewport (defaults to true)
26116 constrainToViewport : true,
26118 * @cfg {Array} monthNames
26119 * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
26121 monthNames : Date.monthNames,
26123 * @cfg {Array} dayNames
26124 * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
26126 dayNames : Date.dayNames,
26128 * @cfg {String} nextText
26129 * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
26131 nextText: 'Next Month (Control+Right)',
26133 * @cfg {String} prevText
26134 * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
26136 prevText: 'Previous Month (Control+Left)',
26138 * @cfg {String} monthYearText
26139 * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
26141 monthYearText: 'Choose a month (Control+Up/Down to move years)',
26143 * @cfg {Number} startDay
26144 * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
26148 * @cfg {Bool} showClear
26149 * Show a clear button (usefull for date form elements that can be blank.)
26155 * Sets the value of the date field
26156 * @param {Date} value The date to set
26158 setValue : function(value){
26159 var old = this.value;
26161 if (typeof(value) == 'string') {
26163 value = Date.parseDate(value, this.format);
26166 value = new Date();
26169 this.value = value.clearTime(true);
26171 this.update(this.value);
26176 * Gets the current selected value of the date field
26177 * @return {Date} The selected date
26179 getValue : function(){
26184 focus : function(){
26186 this.update(this.activeDate);
26191 onRender : function(container, position){
26194 '<table cellspacing="0">',
26195 '<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>',
26196 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
26197 var dn = this.dayNames;
26198 for(var i = 0; i < 7; i++){
26199 var d = this.startDay+i;
26203 m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
26205 m[m.length] = "</tr></thead><tbody><tr>";
26206 for(var i = 0; i < 42; i++) {
26207 if(i % 7 == 0 && i != 0){
26208 m[m.length] = "</tr><tr>";
26210 m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
26212 m[m.length] = '</tr></tbody></table></td></tr><tr>'+
26213 '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
26215 var el = document.createElement("div");
26216 el.className = "x-date-picker";
26217 el.innerHTML = m.join("");
26219 container.dom.insertBefore(el, position);
26221 this.el = Roo.get(el);
26222 this.eventEl = Roo.get(el.firstChild);
26224 new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
26225 handler: this.showPrevMonth,
26227 preventDefault:true,
26231 new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
26232 handler: this.showNextMonth,
26234 preventDefault:true,
26238 this.eventEl.on("mousewheel", this.handleMouseWheel, this);
26240 this.monthPicker = this.el.down('div.x-date-mp');
26241 this.monthPicker.enableDisplayMode('block');
26243 var kn = new Roo.KeyNav(this.eventEl, {
26244 "left" : function(e){
26246 this.showPrevMonth() :
26247 this.update(this.activeDate.add("d", -1));
26250 "right" : function(e){
26252 this.showNextMonth() :
26253 this.update(this.activeDate.add("d", 1));
26256 "up" : function(e){
26258 this.showNextYear() :
26259 this.update(this.activeDate.add("d", -7));
26262 "down" : function(e){
26264 this.showPrevYear() :
26265 this.update(this.activeDate.add("d", 7));
26268 "pageUp" : function(e){
26269 this.showNextMonth();
26272 "pageDown" : function(e){
26273 this.showPrevMonth();
26276 "enter" : function(e){
26277 e.stopPropagation();
26284 this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
26286 this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday, this);
26288 this.el.unselectable();
26290 this.cells = this.el.select("table.x-date-inner tbody td");
26291 this.textNodes = this.el.query("table.x-date-inner tbody span");
26293 this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
26295 tooltip: this.monthYearText
26298 this.mbtn.on('click', this.showMonthPicker, this);
26299 this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
26302 var today = (new Date()).dateFormat(this.format);
26304 var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
26305 if (this.showClear) {
26306 baseTb.add( new Roo.Toolbar.Fill());
26309 text: String.format(this.todayText, today),
26310 tooltip: String.format(this.todayTip, today),
26311 handler: this.selectToday,
26315 //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
26318 if (this.showClear) {
26320 baseTb.add( new Roo.Toolbar.Fill());
26323 cls: 'x-btn-icon x-btn-clear',
26324 handler: function() {
26326 this.fireEvent("select", this, '');
26336 this.update(this.value);
26339 createMonthPicker : function(){
26340 if(!this.monthPicker.dom.firstChild){
26341 var buf = ['<table border="0" cellspacing="0">'];
26342 for(var i = 0; i < 6; i++){
26344 '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
26345 '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
26347 '<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>' :
26348 '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
26352 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
26354 '</button><button type="button" class="x-date-mp-cancel">',
26356 '</button></td></tr>',
26359 this.monthPicker.update(buf.join(''));
26360 this.monthPicker.on('click', this.onMonthClick, this);
26361 this.monthPicker.on('dblclick', this.onMonthDblClick, this);
26363 this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
26364 this.mpYears = this.monthPicker.select('td.x-date-mp-year');
26366 this.mpMonths.each(function(m, a, i){
26369 m.dom.xmonth = 5 + Math.round(i * .5);
26371 m.dom.xmonth = Math.round((i-1) * .5);
26377 showMonthPicker : function(){
26378 this.createMonthPicker();
26379 var size = this.el.getSize();
26380 this.monthPicker.setSize(size);
26381 this.monthPicker.child('table').setSize(size);
26383 this.mpSelMonth = (this.activeDate || this.value).getMonth();
26384 this.updateMPMonth(this.mpSelMonth);
26385 this.mpSelYear = (this.activeDate || this.value).getFullYear();
26386 this.updateMPYear(this.mpSelYear);
26388 this.monthPicker.slideIn('t', {duration:.2});
26391 updateMPYear : function(y){
26393 var ys = this.mpYears.elements;
26394 for(var i = 1; i <= 10; i++){
26395 var td = ys[i-1], y2;
26397 y2 = y + Math.round(i * .5);
26398 td.firstChild.innerHTML = y2;
26401 y2 = y - (5-Math.round(i * .5));
26402 td.firstChild.innerHTML = y2;
26405 this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
26409 updateMPMonth : function(sm){
26410 this.mpMonths.each(function(m, a, i){
26411 m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
26415 selectMPMonth: function(m){
26419 onMonthClick : function(e, t){
26421 var el = new Roo.Element(t), pn;
26422 if(el.is('button.x-date-mp-cancel')){
26423 this.hideMonthPicker();
26425 else if(el.is('button.x-date-mp-ok')){
26426 this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
26427 this.hideMonthPicker();
26429 else if(pn = el.up('td.x-date-mp-month', 2)){
26430 this.mpMonths.removeClass('x-date-mp-sel');
26431 pn.addClass('x-date-mp-sel');
26432 this.mpSelMonth = pn.dom.xmonth;
26434 else if(pn = el.up('td.x-date-mp-year', 2)){
26435 this.mpYears.removeClass('x-date-mp-sel');
26436 pn.addClass('x-date-mp-sel');
26437 this.mpSelYear = pn.dom.xyear;
26439 else if(el.is('a.x-date-mp-prev')){
26440 this.updateMPYear(this.mpyear-10);
26442 else if(el.is('a.x-date-mp-next')){
26443 this.updateMPYear(this.mpyear+10);
26447 onMonthDblClick : function(e, t){
26449 var el = new Roo.Element(t), pn;
26450 if(pn = el.up('td.x-date-mp-month', 2)){
26451 this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
26452 this.hideMonthPicker();
26454 else if(pn = el.up('td.x-date-mp-year', 2)){
26455 this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
26456 this.hideMonthPicker();
26460 hideMonthPicker : function(disableAnim){
26461 if(this.monthPicker){
26462 if(disableAnim === true){
26463 this.monthPicker.hide();
26465 this.monthPicker.slideOut('t', {duration:.2});
26471 showPrevMonth : function(e){
26472 this.update(this.activeDate.add("mo", -1));
26476 showNextMonth : function(e){
26477 this.update(this.activeDate.add("mo", 1));
26481 showPrevYear : function(){
26482 this.update(this.activeDate.add("y", -1));
26486 showNextYear : function(){
26487 this.update(this.activeDate.add("y", 1));
26491 handleMouseWheel : function(e){
26492 var delta = e.getWheelDelta();
26494 this.showPrevMonth();
26496 } else if(delta < 0){
26497 this.showNextMonth();
26503 handleDateClick : function(e, t){
26505 if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
26506 this.setValue(new Date(t.dateValue));
26507 this.fireEvent("select", this, this.value);
26512 selectToday : function(){
26513 this.setValue(new Date().clearTime());
26514 this.fireEvent("select", this, this.value);
26518 update : function(date)
26520 var vd = this.activeDate;
26521 this.activeDate = date;
26523 var t = date.getTime();
26524 if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
26525 this.cells.removeClass("x-date-selected");
26526 this.cells.each(function(c){
26527 if(c.dom.firstChild.dateValue == t){
26528 c.addClass("x-date-selected");
26529 setTimeout(function(){
26530 try{c.dom.firstChild.focus();}catch(e){}
26539 var days = date.getDaysInMonth();
26540 var firstOfMonth = date.getFirstDateOfMonth();
26541 var startingPos = firstOfMonth.getDay()-this.startDay;
26543 if(startingPos <= this.startDay){
26547 var pm = date.add("mo", -1);
26548 var prevStart = pm.getDaysInMonth()-startingPos;
26550 var cells = this.cells.elements;
26551 var textEls = this.textNodes;
26552 days += startingPos;
26554 // convert everything to numbers so it's fast
26555 var day = 86400000;
26556 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
26557 var today = new Date().clearTime().getTime();
26558 var sel = date.clearTime().getTime();
26559 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
26560 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
26561 var ddMatch = this.disabledDatesRE;
26562 var ddText = this.disabledDatesText;
26563 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
26564 var ddaysText = this.disabledDaysText;
26565 var format = this.format;
26567 var setCellClass = function(cal, cell){
26569 var t = d.getTime();
26570 cell.firstChild.dateValue = t;
26572 cell.className += " x-date-today";
26573 cell.title = cal.todayText;
26576 cell.className += " x-date-selected";
26577 setTimeout(function(){
26578 try{cell.firstChild.focus();}catch(e){}
26583 cell.className = " x-date-disabled";
26584 cell.title = cal.minText;
26588 cell.className = " x-date-disabled";
26589 cell.title = cal.maxText;
26593 if(ddays.indexOf(d.getDay()) != -1){
26594 cell.title = ddaysText;
26595 cell.className = " x-date-disabled";
26598 if(ddMatch && format){
26599 var fvalue = d.dateFormat(format);
26600 if(ddMatch.test(fvalue)){
26601 cell.title = ddText.replace("%0", fvalue);
26602 cell.className = " x-date-disabled";
26608 for(; i < startingPos; i++) {
26609 textEls[i].innerHTML = (++prevStart);
26610 d.setDate(d.getDate()+1);
26611 cells[i].className = "x-date-prevday";
26612 setCellClass(this, cells[i]);
26614 for(; i < days; i++){
26615 intDay = i - startingPos + 1;
26616 textEls[i].innerHTML = (intDay);
26617 d.setDate(d.getDate()+1);
26618 cells[i].className = "x-date-active";
26619 setCellClass(this, cells[i]);
26622 for(; i < 42; i++) {
26623 textEls[i].innerHTML = (++extraDays);
26624 d.setDate(d.getDate()+1);
26625 cells[i].className = "x-date-nextday";
26626 setCellClass(this, cells[i]);
26629 this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
26630 this.fireEvent('monthchange', this, date);
26632 if(!this.internalRender){
26633 var main = this.el.dom.firstChild;
26634 var w = main.offsetWidth;
26635 this.el.setWidth(w + this.el.getBorderWidth("lr"));
26636 Roo.fly(main).setWidth(w);
26637 this.internalRender = true;
26638 // opera does not respect the auto grow header center column
26639 // then, after it gets a width opera refuses to recalculate
26640 // without a second pass
26641 if(Roo.isOpera && !this.secondPass){
26642 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
26643 this.secondPass = true;
26644 this.update.defer(10, this, [date]);
26652 * Ext JS Library 1.1.1
26653 * Copyright(c) 2006-2007, Ext JS, LLC.
26655 * Originally Released Under LGPL - original licence link has changed is not relivant.
26658 * <script type="text/javascript">
26661 * @class Roo.TabPanel
26662 * @extends Roo.util.Observable
26663 * A lightweight tab container.
26667 // basic tabs 1, built from existing content
26668 var tabs = new Roo.TabPanel("tabs1");
26669 tabs.addTab("script", "View Script");
26670 tabs.addTab("markup", "View Markup");
26671 tabs.activate("script");
26673 // more advanced tabs, built from javascript
26674 var jtabs = new Roo.TabPanel("jtabs");
26675 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
26677 // set up the UpdateManager
26678 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
26679 var updater = tab2.getUpdateManager();
26680 updater.setDefaultUrl("ajax1.htm");
26681 tab2.on('activate', updater.refresh, updater, true);
26683 // Use setUrl for Ajax loading
26684 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
26685 tab3.setUrl("ajax2.htm", null, true);
26688 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
26691 jtabs.activate("jtabs-1");
26694 * Create a new TabPanel.
26695 * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
26696 * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
26698 Roo.TabPanel = function(container, config){
26700 * The container element for this TabPanel.
26701 * @type Roo.Element
26703 this.el = Roo.get(container, true);
26705 if(typeof config == "boolean"){
26706 this.tabPosition = config ? "bottom" : "top";
26708 Roo.apply(this, config);
26711 if(this.tabPosition == "bottom"){
26712 this.bodyEl = Roo.get(this.createBody(this.el.dom));
26713 this.el.addClass("x-tabs-bottom");
26715 this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
26716 this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
26717 this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
26719 Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
26721 if(this.tabPosition != "bottom"){
26722 /** The body element that contains {@link Roo.TabPanelItem} bodies. +
26723 * @type Roo.Element
26725 this.bodyEl = Roo.get(this.createBody(this.el.dom));
26726 this.el.addClass("x-tabs-top");
26730 this.bodyEl.setStyle("position", "relative");
26732 this.active = null;
26733 this.activateDelegate = this.activate.createDelegate(this);
26738 * Fires when the active tab changes
26739 * @param {Roo.TabPanel} this
26740 * @param {Roo.TabPanelItem} activePanel The new active tab
26744 * @event beforetabchange
26745 * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
26746 * @param {Roo.TabPanel} this
26747 * @param {Object} e Set cancel to true on this object to cancel the tab change
26748 * @param {Roo.TabPanelItem} tab The tab being changed to
26750 "beforetabchange" : true
26753 Roo.EventManager.onWindowResize(this.onResize, this);
26754 this.cpad = this.el.getPadding("lr");
26755 this.hiddenCount = 0;
26758 // toolbar on the tabbar support...
26759 if (this.toolbar) {
26760 var tcfg = this.toolbar;
26761 tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');
26762 this.toolbar = new Roo.Toolbar(tcfg);
26763 if (Roo.isSafari) {
26764 var tbl = tcfg.container.child('table', true);
26765 tbl.setAttribute('width', '100%');
26772 Roo.TabPanel.superclass.constructor.call(this);
26775 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
26777 *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
26779 tabPosition : "top",
26781 *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
26783 currentTabWidth : 0,
26785 *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
26789 *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
26793 *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
26795 preferredTabWidth : 175,
26797 *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
26799 resizeTabs : false,
26801 *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
26803 monitorResize : true,
26805 *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar.
26810 * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
26811 * @param {String} id The id of the div to use <b>or create</b>
26812 * @param {String} text The text for the tab
26813 * @param {String} content (optional) Content to put in the TabPanelItem body
26814 * @param {Boolean} closable (optional) True to create a close icon on the tab
26815 * @return {Roo.TabPanelItem} The created TabPanelItem
26817 addTab : function(id, text, content, closable){
26818 var item = new Roo.TabPanelItem(this, id, text, closable);
26819 this.addTabItem(item);
26821 item.setContent(content);
26827 * Returns the {@link Roo.TabPanelItem} with the specified id/index
26828 * @param {String/Number} id The id or index of the TabPanelItem to fetch.
26829 * @return {Roo.TabPanelItem}
26831 getTab : function(id){
26832 return this.items[id];
26836 * Hides the {@link Roo.TabPanelItem} with the specified id/index
26837 * @param {String/Number} id The id or index of the TabPanelItem to hide.
26839 hideTab : function(id){
26840 var t = this.items[id];
26843 this.hiddenCount++;
26844 this.autoSizeTabs();
26849 * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
26850 * @param {String/Number} id The id or index of the TabPanelItem to unhide.
26852 unhideTab : function(id){
26853 var t = this.items[id];
26855 t.setHidden(false);
26856 this.hiddenCount--;
26857 this.autoSizeTabs();
26862 * Adds an existing {@link Roo.TabPanelItem}.
26863 * @param {Roo.TabPanelItem} item The TabPanelItem to add
26865 addTabItem : function(item){
26866 this.items[item.id] = item;
26867 this.items.push(item);
26868 if(this.resizeTabs){
26869 item.setWidth(this.currentTabWidth || this.preferredTabWidth);
26870 this.autoSizeTabs();
26877 * Removes a {@link Roo.TabPanelItem}.
26878 * @param {String/Number} id The id or index of the TabPanelItem to remove.
26880 removeTab : function(id){
26881 var items = this.items;
26882 var tab = items[id];
26883 if(!tab) { return; }
26884 var index = items.indexOf(tab);
26885 if(this.active == tab && items.length > 1){
26886 var newTab = this.getNextAvailable(index);
26891 this.stripEl.dom.removeChild(tab.pnode.dom);
26892 if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
26893 this.bodyEl.dom.removeChild(tab.bodyEl.dom);
26895 items.splice(index, 1);
26896 delete this.items[tab.id];
26897 tab.fireEvent("close", tab);
26898 tab.purgeListeners();
26899 this.autoSizeTabs();
26902 getNextAvailable : function(start){
26903 var items = this.items;
26905 // look for a next tab that will slide over to
26906 // replace the one being removed
26907 while(index < items.length){
26908 var item = items[++index];
26909 if(item && !item.isHidden()){
26913 // if one isn't found select the previous tab (on the left)
26916 var item = items[--index];
26917 if(item && !item.isHidden()){
26925 * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
26926 * @param {String/Number} id The id or index of the TabPanelItem to disable.
26928 disableTab : function(id){
26929 var tab = this.items[id];
26930 if(tab && this.active != tab){
26936 * Enables a {@link Roo.TabPanelItem} that is disabled.
26937 * @param {String/Number} id The id or index of the TabPanelItem to enable.
26939 enableTab : function(id){
26940 var tab = this.items[id];
26945 * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
26946 * @param {String/Number} id The id or index of the TabPanelItem to activate.
26947 * @return {Roo.TabPanelItem} The TabPanelItem.
26949 activate : function(id){
26950 var tab = this.items[id];
26954 if(tab == this.active || tab.disabled){
26958 this.fireEvent("beforetabchange", this, e, tab);
26959 if(e.cancel !== true && !tab.disabled){
26961 this.active.hide();
26963 this.active = this.items[id];
26964 this.active.show();
26965 this.fireEvent("tabchange", this, this.active);
26971 * Gets the active {@link Roo.TabPanelItem}.
26972 * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
26974 getActiveTab : function(){
26975 return this.active;
26979 * Updates the tab body element to fit the height of the container element
26980 * for overflow scrolling
26981 * @param {Number} targetHeight (optional) Override the starting height from the elements height
26983 syncHeight : function(targetHeight){
26984 var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
26985 var bm = this.bodyEl.getMargins();
26986 var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
26987 this.bodyEl.setHeight(newHeight);
26991 onResize : function(){
26992 if(this.monitorResize){
26993 this.autoSizeTabs();
26998 * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
27000 beginUpdate : function(){
27001 this.updating = true;
27005 * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
27007 endUpdate : function(){
27008 this.updating = false;
27009 this.autoSizeTabs();
27013 * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
27015 autoSizeTabs : function(){
27016 var count = this.items.length;
27017 var vcount = count - this.hiddenCount;
27018 if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
27019 var w = Math.max(this.el.getWidth() - this.cpad, 10);
27020 var availWidth = Math.floor(w / vcount);
27021 var b = this.stripBody;
27022 if(b.getWidth() > w){
27023 var tabs = this.items;
27024 this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
27025 if(availWidth < this.minTabWidth){
27026 /*if(!this.sleft){ // incomplete scrolling code
27027 this.createScrollButtons();
27030 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
27033 if(this.currentTabWidth < this.preferredTabWidth){
27034 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
27040 * Returns the number of tabs in this TabPanel.
27043 getCount : function(){
27044 return this.items.length;
27048 * Resizes all the tabs to the passed width
27049 * @param {Number} The new width
27051 setTabWidth : function(width){
27052 this.currentTabWidth = width;
27053 for(var i = 0, len = this.items.length; i < len; i++) {
27054 if(!this.items[i].isHidden())this.items[i].setWidth(width);
27059 * Destroys this TabPanel
27060 * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
27062 destroy : function(removeEl){
27063 Roo.EventManager.removeResizeListener(this.onResize, this);
27064 for(var i = 0, len = this.items.length; i < len; i++){
27065 this.items[i].purgeListeners();
27067 if(removeEl === true){
27068 this.el.update("");
27075 * @class Roo.TabPanelItem
27076 * @extends Roo.util.Observable
27077 * Represents an individual item (tab plus body) in a TabPanel.
27078 * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
27079 * @param {String} id The id of this TabPanelItem
27080 * @param {String} text The text for the tab of this TabPanelItem
27081 * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
27083 Roo.TabPanelItem = function(tabPanel, id, text, closable){
27085 * The {@link Roo.TabPanel} this TabPanelItem belongs to
27086 * @type Roo.TabPanel
27088 this.tabPanel = tabPanel;
27090 * The id for this TabPanelItem
27095 this.disabled = false;
27099 this.loaded = false;
27100 this.closable = closable;
27103 * The body element for this TabPanelItem.
27104 * @type Roo.Element
27106 this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
27107 this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
27108 this.bodyEl.setStyle("display", "block");
27109 this.bodyEl.setStyle("zoom", "1");
27112 var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
27114 this.el = Roo.get(els.el, true);
27115 this.inner = Roo.get(els.inner, true);
27116 this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
27117 this.pnode = Roo.get(els.el.parentNode, true);
27118 this.el.on("mousedown", this.onTabMouseDown, this);
27119 this.el.on("click", this.onTabClick, this);
27122 var c = Roo.get(els.close, true);
27123 c.dom.title = this.closeText;
27124 c.addClassOnOver("close-over");
27125 c.on("click", this.closeClick, this);
27131 * Fires when this tab becomes the active tab.
27132 * @param {Roo.TabPanel} tabPanel The parent TabPanel
27133 * @param {Roo.TabPanelItem} this
27137 * @event beforeclose
27138 * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
27139 * @param {Roo.TabPanelItem} this
27140 * @param {Object} e Set cancel to true on this object to cancel the close.
27142 "beforeclose": true,
27145 * Fires when this tab is closed.
27146 * @param {Roo.TabPanelItem} this
27150 * @event deactivate
27151 * Fires when this tab is no longer the active tab.
27152 * @param {Roo.TabPanel} tabPanel The parent TabPanel
27153 * @param {Roo.TabPanelItem} this
27155 "deactivate" : true
27157 this.hidden = false;
27159 Roo.TabPanelItem.superclass.constructor.call(this);
27162 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
27163 purgeListeners : function(){
27164 Roo.util.Observable.prototype.purgeListeners.call(this);
27165 this.el.removeAllListeners();
27168 * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
27171 this.pnode.addClass("on");
27174 this.tabPanel.stripWrap.repaint();
27176 this.fireEvent("activate", this.tabPanel, this);
27180 * Returns true if this tab is the active tab.
27181 * @return {Boolean}
27183 isActive : function(){
27184 return this.tabPanel.getActiveTab() == this;
27188 * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
27191 this.pnode.removeClass("on");
27193 this.fireEvent("deactivate", this.tabPanel, this);
27196 hideAction : function(){
27197 this.bodyEl.hide();
27198 this.bodyEl.setStyle("position", "absolute");
27199 this.bodyEl.setLeft("-20000px");
27200 this.bodyEl.setTop("-20000px");
27203 showAction : function(){
27204 this.bodyEl.setStyle("position", "relative");
27205 this.bodyEl.setTop("");
27206 this.bodyEl.setLeft("");
27207 this.bodyEl.show();
27211 * Set the tooltip for the tab.
27212 * @param {String} tooltip The tab's tooltip
27214 setTooltip : function(text){
27215 if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
27216 this.textEl.dom.qtip = text;
27217 this.textEl.dom.removeAttribute('title');
27219 this.textEl.dom.title = text;
27223 onTabClick : function(e){
27224 e.preventDefault();
27225 this.tabPanel.activate(this.id);
27228 onTabMouseDown : function(e){
27229 e.preventDefault();
27230 this.tabPanel.activate(this.id);
27233 getWidth : function(){
27234 return this.inner.getWidth();
27237 setWidth : function(width){
27238 var iwidth = width - this.pnode.getPadding("lr");
27239 this.inner.setWidth(iwidth);
27240 this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
27241 this.pnode.setWidth(width);
27245 * Show or hide the tab
27246 * @param {Boolean} hidden True to hide or false to show.
27248 setHidden : function(hidden){
27249 this.hidden = hidden;
27250 this.pnode.setStyle("display", hidden ? "none" : "");
27254 * Returns true if this tab is "hidden"
27255 * @return {Boolean}
27257 isHidden : function(){
27258 return this.hidden;
27262 * Returns the text for this tab
27265 getText : function(){
27269 autoSize : function(){
27270 //this.el.beginMeasure();
27271 this.textEl.setWidth(1);
27273 * #2804 [new] Tabs in Roojs
27274 * increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
27276 this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
27277 //this.el.endMeasure();
27281 * Sets the text for the tab (Note: this also sets the tooltip text)
27282 * @param {String} text The tab's text and tooltip
27284 setText : function(text){
27286 this.textEl.update(text);
27287 this.setTooltip(text);
27288 if(!this.tabPanel.resizeTabs){
27293 * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
27295 activate : function(){
27296 this.tabPanel.activate(this.id);
27300 * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
27302 disable : function(){
27303 if(this.tabPanel.active != this){
27304 this.disabled = true;
27305 this.pnode.addClass("disabled");
27310 * Enables this TabPanelItem if it was previously disabled.
27312 enable : function(){
27313 this.disabled = false;
27314 this.pnode.removeClass("disabled");
27318 * Sets the content for this TabPanelItem.
27319 * @param {String} content The content
27320 * @param {Boolean} loadScripts true to look for and load scripts
27322 setContent : function(content, loadScripts){
27323 this.bodyEl.update(content, loadScripts);
27327 * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
27328 * @return {Roo.UpdateManager} The UpdateManager
27330 getUpdateManager : function(){
27331 return this.bodyEl.getUpdateManager();
27335 * Set a URL to be used to load the content for this TabPanelItem.
27336 * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
27337 * @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)
27338 * @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)
27339 * @return {Roo.UpdateManager} The UpdateManager
27341 setUrl : function(url, params, loadOnce){
27342 if(this.refreshDelegate){
27343 this.un('activate', this.refreshDelegate);
27345 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
27346 this.on("activate", this.refreshDelegate);
27347 return this.bodyEl.getUpdateManager();
27351 _handleRefresh : function(url, params, loadOnce){
27352 if(!loadOnce || !this.loaded){
27353 var updater = this.bodyEl.getUpdateManager();
27354 updater.update(url, params, this._setLoaded.createDelegate(this));
27359 * Forces a content refresh from the URL specified in the {@link #setUrl} method.
27360 * Will fail silently if the setUrl method has not been called.
27361 * This does not activate the panel, just updates its content.
27363 refresh : function(){
27364 if(this.refreshDelegate){
27365 this.loaded = false;
27366 this.refreshDelegate();
27371 _setLoaded : function(){
27372 this.loaded = true;
27376 closeClick : function(e){
27379 this.fireEvent("beforeclose", this, o);
27380 if(o.cancel !== true){
27381 this.tabPanel.removeTab(this.id);
27385 * The text displayed in the tooltip for the close icon.
27388 closeText : "Close this tab"
27392 Roo.TabPanel.prototype.createStrip = function(container){
27393 var strip = document.createElement("div");
27394 strip.className = "x-tabs-wrap";
27395 container.appendChild(strip);
27399 Roo.TabPanel.prototype.createStripList = function(strip){
27400 // div wrapper for retard IE
27401 // returns the "tr" element.
27402 strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
27403 '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
27404 '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
27405 return strip.firstChild.firstChild.firstChild.firstChild;
27408 Roo.TabPanel.prototype.createBody = function(container){
27409 var body = document.createElement("div");
27410 Roo.id(body, "tab-body");
27411 Roo.fly(body).addClass("x-tabs-body");
27412 container.appendChild(body);
27416 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
27417 var body = Roo.getDom(id);
27419 body = document.createElement("div");
27422 Roo.fly(body).addClass("x-tabs-item-body");
27423 bodyEl.insertBefore(body, bodyEl.firstChild);
27427 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
27428 var td = document.createElement("td");
27429 stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
27430 //stripEl.appendChild(td);
27432 td.className = "x-tabs-closable";
27433 if(!this.closeTpl){
27434 this.closeTpl = new Roo.Template(
27435 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
27436 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
27437 '<div unselectable="on" class="close-icon"> </div></em></span></a>'
27440 var el = this.closeTpl.overwrite(td, {"text": text});
27441 var close = el.getElementsByTagName("div")[0];
27442 var inner = el.getElementsByTagName("em")[0];
27443 return {"el": el, "close": close, "inner": inner};
27446 this.tabTpl = new Roo.Template(
27447 '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
27448 '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
27451 var el = this.tabTpl.overwrite(td, {"text": text});
27452 var inner = el.getElementsByTagName("em")[0];
27453 return {"el": el, "inner": inner};
27457 * Ext JS Library 1.1.1
27458 * Copyright(c) 2006-2007, Ext JS, LLC.
27460 * Originally Released Under LGPL - original licence link has changed is not relivant.
27463 * <script type="text/javascript">
27467 * @class Roo.Button
27468 * @extends Roo.util.Observable
27469 * Simple Button class
27470 * @cfg {String} text The button text
27471 * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
27472 * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
27473 * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
27474 * @cfg {Object} scope The scope of the handler
27475 * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
27476 * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
27477 * @cfg {Boolean} hidden True to start hidden (defaults to false)
27478 * @cfg {Boolean} disabled True to start disabled (defaults to false)
27479 * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
27480 * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
27481 applies if enableToggle = true)
27482 * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
27483 * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
27484 an {@link Roo.util.ClickRepeater} config object (defaults to false).
27486 * Create a new button
27487 * @param {Object} config The config object
27489 Roo.Button = function(renderTo, config)
27493 renderTo = config.renderTo || false;
27496 Roo.apply(this, config);
27500 * Fires when this button is clicked
27501 * @param {Button} this
27502 * @param {EventObject} e The click event
27507 * Fires when the "pressed" state of this button changes (only if enableToggle = true)
27508 * @param {Button} this
27509 * @param {Boolean} pressed
27514 * Fires when the mouse hovers over the button
27515 * @param {Button} this
27516 * @param {Event} e The event object
27518 'mouseover' : true,
27521 * Fires when the mouse exits the button
27522 * @param {Button} this
27523 * @param {Event} e The event object
27528 * Fires when the button is rendered
27529 * @param {Button} this
27534 this.menu = Roo.menu.MenuMgr.get(this.menu);
27536 // register listeners first!! - so render can be captured..
27537 Roo.util.Observable.call(this);
27539 this.render(renderTo);
27545 Roo.extend(Roo.Button, Roo.util.Observable, {
27551 * Read-only. True if this button is hidden
27556 * Read-only. True if this button is disabled
27561 * Read-only. True if this button is pressed (only if enableToggle = true)
27567 * @cfg {Number} tabIndex
27568 * The DOM tabIndex for this button (defaults to undefined)
27570 tabIndex : undefined,
27573 * @cfg {Boolean} enableToggle
27574 * True to enable pressed/not pressed toggling (defaults to false)
27576 enableToggle: false,
27578 * @cfg {Mixed} menu
27579 * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
27583 * @cfg {String} menuAlign
27584 * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
27586 menuAlign : "tl-bl?",
27589 * @cfg {String} iconCls
27590 * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
27592 iconCls : undefined,
27594 * @cfg {String} type
27595 * The button's type, corresponding to the DOM input element type attribute. Either "submit," "reset" or "button" (default).
27600 menuClassTarget: 'tr',
27603 * @cfg {String} clickEvent
27604 * The type of event to map to the button's event handler (defaults to 'click')
27606 clickEvent : 'click',
27609 * @cfg {Boolean} handleMouseEvents
27610 * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
27612 handleMouseEvents : true,
27615 * @cfg {String} tooltipType
27616 * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
27618 tooltipType : 'qtip',
27621 * @cfg {String} cls
27622 * A CSS class to apply to the button's main element.
27626 * @cfg {Roo.Template} template (Optional)
27627 * An {@link Roo.Template} with which to create the Button's main element. This Template must
27628 * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
27629 * require code modifications if required elements (e.g. a button) aren't present.
27633 render : function(renderTo){
27635 if(this.hideParent){
27636 this.parentEl = Roo.get(renderTo);
27638 if(!this.dhconfig){
27639 if(!this.template){
27640 if(!Roo.Button.buttonTemplate){
27641 // hideous table template
27642 Roo.Button.buttonTemplate = new Roo.Template(
27643 '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
27644 '<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>',
27645 "</tr></tbody></table>");
27647 this.template = Roo.Button.buttonTemplate;
27649 btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
27650 var btnEl = btn.child("button:first");
27651 btnEl.on('focus', this.onFocus, this);
27652 btnEl.on('blur', this.onBlur, this);
27654 btn.addClass(this.cls);
27657 btnEl.setStyle('background-image', 'url(' +this.icon +')');
27660 btnEl.addClass(this.iconCls);
27662 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
27665 if(this.tabIndex !== undefined){
27666 btnEl.dom.tabIndex = this.tabIndex;
27669 if(typeof this.tooltip == 'object'){
27670 Roo.QuickTips.tips(Roo.apply({
27674 btnEl.dom[this.tooltipType] = this.tooltip;
27678 btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
27682 this.el.dom.id = this.el.id = this.id;
27685 this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
27686 this.menu.on("show", this.onMenuShow, this);
27687 this.menu.on("hide", this.onMenuHide, this);
27689 btn.addClass("x-btn");
27690 if(Roo.isIE && !Roo.isIE7){
27691 this.autoWidth.defer(1, this);
27695 if(this.handleMouseEvents){
27696 btn.on("mouseover", this.onMouseOver, this);
27697 btn.on("mouseout", this.onMouseOut, this);
27698 btn.on("mousedown", this.onMouseDown, this);
27700 btn.on(this.clickEvent, this.onClick, this);
27701 //btn.on("mouseup", this.onMouseUp, this);
27708 Roo.ButtonToggleMgr.register(this);
27710 this.el.addClass("x-btn-pressed");
27713 var repeater = new Roo.util.ClickRepeater(btn,
27714 typeof this.repeat == "object" ? this.repeat : {}
27716 repeater.on("click", this.onClick, this);
27719 this.fireEvent('render', this);
27723 * Returns the button's underlying element
27724 * @return {Roo.Element} The element
27726 getEl : function(){
27731 * Destroys this Button and removes any listeners.
27733 destroy : function(){
27734 Roo.ButtonToggleMgr.unregister(this);
27735 this.el.removeAllListeners();
27736 this.purgeListeners();
27741 autoWidth : function(){
27743 this.el.setWidth("auto");
27744 if(Roo.isIE7 && Roo.isStrict){
27745 var ib = this.el.child('button');
27746 if(ib && ib.getWidth() > 20){
27748 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
27753 this.el.beginMeasure();
27755 if(this.el.getWidth() < this.minWidth){
27756 this.el.setWidth(this.minWidth);
27759 this.el.endMeasure();
27766 * Assigns this button's click handler
27767 * @param {Function} handler The function to call when the button is clicked
27768 * @param {Object} scope (optional) Scope for the function passed in
27770 setHandler : function(handler, scope){
27771 this.handler = handler;
27772 this.scope = scope;
27776 * Sets this button's text
27777 * @param {String} text The button text
27779 setText : function(text){
27782 this.el.child("td.x-btn-center button.x-btn-text").update(text);
27788 * Gets the text for this button
27789 * @return {String} The button text
27791 getText : function(){
27799 this.hidden = false;
27801 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
27809 this.hidden = true;
27811 this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
27816 * Convenience function for boolean show/hide
27817 * @param {Boolean} visible True to show, false to hide
27819 setVisible: function(visible){
27828 * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
27829 * @param {Boolean} state (optional) Force a particular state
27831 toggle : function(state){
27832 state = state === undefined ? !this.pressed : state;
27833 if(state != this.pressed){
27835 this.el.addClass("x-btn-pressed");
27836 this.pressed = true;
27837 this.fireEvent("toggle", this, true);
27839 this.el.removeClass("x-btn-pressed");
27840 this.pressed = false;
27841 this.fireEvent("toggle", this, false);
27843 if(this.toggleHandler){
27844 this.toggleHandler.call(this.scope || this, this, state);
27852 focus : function(){
27853 this.el.child('button:first').focus();
27857 * Disable this button
27859 disable : function(){
27861 this.el.addClass("x-btn-disabled");
27863 this.disabled = true;
27867 * Enable this button
27869 enable : function(){
27871 this.el.removeClass("x-btn-disabled");
27873 this.disabled = false;
27877 * Convenience function for boolean enable/disable
27878 * @param {Boolean} enabled True to enable, false to disable
27880 setDisabled : function(v){
27881 this[v !== true ? "enable" : "disable"]();
27885 onClick : function(e)
27888 e.preventDefault();
27893 if(!this.disabled){
27894 if(this.enableToggle){
27897 if(this.menu && !this.menu.isVisible()){
27898 this.menu.show(this.el, this.menuAlign);
27900 this.fireEvent("click", this, e);
27902 this.el.removeClass("x-btn-over");
27903 this.handler.call(this.scope || this, this, e);
27908 onMouseOver : function(e){
27909 if(!this.disabled){
27910 this.el.addClass("x-btn-over");
27911 this.fireEvent('mouseover', this, e);
27915 onMouseOut : function(e){
27916 if(!e.within(this.el, true)){
27917 this.el.removeClass("x-btn-over");
27918 this.fireEvent('mouseout', this, e);
27922 onFocus : function(e){
27923 if(!this.disabled){
27924 this.el.addClass("x-btn-focus");
27928 onBlur : function(e){
27929 this.el.removeClass("x-btn-focus");
27932 onMouseDown : function(e){
27933 if(!this.disabled && e.button == 0){
27934 this.el.addClass("x-btn-click");
27935 Roo.get(document).on('mouseup', this.onMouseUp, this);
27939 onMouseUp : function(e){
27941 this.el.removeClass("x-btn-click");
27942 Roo.get(document).un('mouseup', this.onMouseUp, this);
27946 onMenuShow : function(e){
27947 this.el.addClass("x-btn-menu-active");
27950 onMenuHide : function(e){
27951 this.el.removeClass("x-btn-menu-active");
27955 // Private utility class used by Button
27956 Roo.ButtonToggleMgr = function(){
27959 function toggleGroup(btn, state){
27961 var g = groups[btn.toggleGroup];
27962 for(var i = 0, l = g.length; i < l; i++){
27964 g[i].toggle(false);
27971 register : function(btn){
27972 if(!btn.toggleGroup){
27975 var g = groups[btn.toggleGroup];
27977 g = groups[btn.toggleGroup] = [];
27980 btn.on("toggle", toggleGroup);
27983 unregister : function(btn){
27984 if(!btn.toggleGroup){
27987 var g = groups[btn.toggleGroup];
27990 btn.un("toggle", toggleGroup);
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.SplitButton
28007 * @extends Roo.Button
28008 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
28009 * click event of the button. Typically this would be used to display a dropdown menu that provides additional
28010 * options to the primary button action, but any custom handler can provide the arrowclick implementation.
28011 * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
28012 * @cfg {String} arrowTooltip The title attribute of the arrow
28014 * Create a new menu button
28015 * @param {String/HTMLElement/Element} renderTo The element to append the button to
28016 * @param {Object} config The config object
28018 Roo.SplitButton = function(renderTo, config){
28019 Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
28021 * @event arrowclick
28022 * Fires when this button's arrow is clicked
28023 * @param {SplitButton} this
28024 * @param {EventObject} e The click event
28026 this.addEvents({"arrowclick":true});
28029 Roo.extend(Roo.SplitButton, Roo.Button, {
28030 render : function(renderTo){
28031 // this is one sweet looking template!
28032 var tpl = new Roo.Template(
28033 '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
28034 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
28035 '<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>',
28036 "</tbody></table></td><td>",
28037 '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
28038 '<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>',
28039 "</tbody></table></td></tr></table>"
28041 var btn = tpl.append(renderTo, [this.text, this.type], true);
28042 var btnEl = btn.child("button");
28044 btn.addClass(this.cls);
28047 btnEl.setStyle('background-image', 'url(' +this.icon +')');
28050 btnEl.addClass(this.iconCls);
28052 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
28056 if(this.handleMouseEvents){
28057 btn.on("mouseover", this.onMouseOver, this);
28058 btn.on("mouseout", this.onMouseOut, this);
28059 btn.on("mousedown", this.onMouseDown, this);
28060 btn.on("mouseup", this.onMouseUp, this);
28062 btn.on(this.clickEvent, this.onClick, this);
28064 if(typeof this.tooltip == 'object'){
28065 Roo.QuickTips.tips(Roo.apply({
28069 btnEl.dom[this.tooltipType] = this.tooltip;
28072 if(this.arrowTooltip){
28073 btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
28082 this.el.addClass("x-btn-pressed");
28084 if(Roo.isIE && !Roo.isIE7){
28085 this.autoWidth.defer(1, this);
28090 this.menu.on("show", this.onMenuShow, this);
28091 this.menu.on("hide", this.onMenuHide, this);
28093 this.fireEvent('render', this);
28097 autoWidth : function(){
28099 var tbl = this.el.child("table:first");
28100 var tbl2 = this.el.child("table:last");
28101 this.el.setWidth("auto");
28102 tbl.setWidth("auto");
28103 if(Roo.isIE7 && Roo.isStrict){
28104 var ib = this.el.child('button:first');
28105 if(ib && ib.getWidth() > 20){
28107 ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
28112 this.el.beginMeasure();
28114 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
28115 tbl.setWidth(this.minWidth-tbl2.getWidth());
28118 this.el.endMeasure();
28121 this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
28125 * Sets this button's click handler
28126 * @param {Function} handler The function to call when the button is clicked
28127 * @param {Object} scope (optional) Scope for the function passed above
28129 setHandler : function(handler, scope){
28130 this.handler = handler;
28131 this.scope = scope;
28135 * Sets this button's arrow click handler
28136 * @param {Function} handler The function to call when the arrow is clicked
28137 * @param {Object} scope (optional) Scope for the function passed above
28139 setArrowHandler : function(handler, scope){
28140 this.arrowHandler = handler;
28141 this.scope = scope;
28147 focus : function(){
28149 this.el.child("button:first").focus();
28154 onClick : function(e){
28155 e.preventDefault();
28156 if(!this.disabled){
28157 if(e.getTarget(".x-btn-menu-arrow-wrap")){
28158 if(this.menu && !this.menu.isVisible()){
28159 this.menu.show(this.el, this.menuAlign);
28161 this.fireEvent("arrowclick", this, e);
28162 if(this.arrowHandler){
28163 this.arrowHandler.call(this.scope || this, this, e);
28166 this.fireEvent("click", this, e);
28168 this.handler.call(this.scope || this, this, e);
28174 onMouseDown : function(e){
28175 if(!this.disabled){
28176 Roo.fly(e.getTarget("table")).addClass("x-btn-click");
28180 onMouseUp : function(e){
28181 Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
28186 // backwards compat
28187 Roo.MenuButton = Roo.SplitButton;/*
28189 * Ext JS Library 1.1.1
28190 * Copyright(c) 2006-2007, Ext JS, LLC.
28192 * Originally Released Under LGPL - original licence link has changed is not relivant.
28195 * <script type="text/javascript">
28199 * @class Roo.Toolbar
28200 * Basic Toolbar class.
28202 * Creates a new Toolbar
28203 * @param {Object} container The config object
28205 Roo.Toolbar = function(container, buttons, config)
28207 /// old consturctor format still supported..
28208 if(container instanceof Array){ // omit the container for later rendering
28209 buttons = container;
28213 if (typeof(container) == 'object' && container.xtype) {
28214 config = container;
28215 container = config.container;
28216 buttons = config.buttons || []; // not really - use items!!
28219 if (config && config.items) {
28220 xitems = config.items;
28221 delete config.items;
28223 Roo.apply(this, config);
28224 this.buttons = buttons;
28227 this.render(container);
28229 this.xitems = xitems;
28230 Roo.each(xitems, function(b) {
28236 Roo.Toolbar.prototype = {
28238 * @cfg {Array} items
28239 * array of button configs or elements to add (will be converted to a MixedCollection)
28243 * @cfg {String/HTMLElement/Element} container
28244 * The id or element that will contain the toolbar
28247 render : function(ct){
28248 this.el = Roo.get(ct);
28250 this.el.addClass(this.cls);
28252 // using a table allows for vertical alignment
28253 // 100% width is needed by Safari...
28254 this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
28255 this.tr = this.el.child("tr", true);
28257 this.items = new Roo.util.MixedCollection(false, function(o){
28258 return o.id || ("item" + (++autoId));
28261 this.add.apply(this, this.buttons);
28262 delete this.buttons;
28267 * Adds element(s) to the toolbar -- this function takes a variable number of
28268 * arguments of mixed type and adds them to the toolbar.
28269 * @param {Mixed} arg1 The following types of arguments are all valid:<br />
28271 * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
28272 * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
28273 * <li>Field: Any form field (equivalent to {@link #addField})</li>
28274 * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
28275 * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
28276 * Note that there are a few special strings that are treated differently as explained nRoo.</li>
28277 * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
28278 * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
28279 * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
28281 * @param {Mixed} arg2
28282 * @param {Mixed} etc.
28285 var a = arguments, l = a.length;
28286 for(var i = 0; i < l; i++){
28291 _add : function(el) {
28294 el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
28297 if (el.applyTo){ // some kind of form field
28298 return this.addField(el);
28300 if (el.render){ // some kind of Toolbar.Item
28301 return this.addItem(el);
28303 if (typeof el == "string"){ // string
28304 if(el == "separator" || el == "-"){
28305 return this.addSeparator();
28308 return this.addSpacer();
28311 return this.addFill();
28313 return this.addText(el);
28316 if(el.tagName){ // element
28317 return this.addElement(el);
28319 if(typeof el == "object"){ // must be button config?
28320 return this.addButton(el);
28322 // and now what?!?!
28328 * Add an Xtype element
28329 * @param {Object} xtype Xtype Object
28330 * @return {Object} created Object
28332 addxtype : function(e){
28333 return this.add(e);
28337 * Returns the Element for this toolbar.
28338 * @return {Roo.Element}
28340 getEl : function(){
28346 * @return {Roo.Toolbar.Item} The separator item
28348 addSeparator : function(){
28349 return this.addItem(new Roo.Toolbar.Separator());
28353 * Adds a spacer element
28354 * @return {Roo.Toolbar.Spacer} The spacer item
28356 addSpacer : function(){
28357 return this.addItem(new Roo.Toolbar.Spacer());
28361 * Adds a fill element that forces subsequent additions to the right side of the toolbar
28362 * @return {Roo.Toolbar.Fill} The fill item
28364 addFill : function(){
28365 return this.addItem(new Roo.Toolbar.Fill());
28369 * Adds any standard HTML element to the toolbar
28370 * @param {String/HTMLElement/Element} el The element or id of the element to add
28371 * @return {Roo.Toolbar.Item} The element's item
28373 addElement : function(el){
28374 return this.addItem(new Roo.Toolbar.Item(el));
28377 * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
28378 * @type Roo.util.MixedCollection
28383 * Adds any Toolbar.Item or subclass
28384 * @param {Roo.Toolbar.Item} item
28385 * @return {Roo.Toolbar.Item} The item
28387 addItem : function(item){
28388 var td = this.nextBlock();
28390 this.items.add(item);
28395 * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
28396 * @param {Object/Array} config A button config or array of configs
28397 * @return {Roo.Toolbar.Button/Array}
28399 addButton : function(config){
28400 if(config instanceof Array){
28402 for(var i = 0, len = config.length; i < len; i++) {
28403 buttons.push(this.addButton(config[i]));
28408 if(!(config instanceof Roo.Toolbar.Button)){
28410 new Roo.Toolbar.SplitButton(config) :
28411 new Roo.Toolbar.Button(config);
28413 var td = this.nextBlock();
28420 * Adds text to the toolbar
28421 * @param {String} text The text to add
28422 * @return {Roo.Toolbar.Item} The element's item
28424 addText : function(text){
28425 return this.addItem(new Roo.Toolbar.TextItem(text));
28429 * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
28430 * @param {Number} index The index where the item is to be inserted
28431 * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
28432 * @return {Roo.Toolbar.Button/Item}
28434 insertButton : function(index, item){
28435 if(item instanceof Array){
28437 for(var i = 0, len = item.length; i < len; i++) {
28438 buttons.push(this.insertButton(index + i, item[i]));
28442 if (!(item instanceof Roo.Toolbar.Button)){
28443 item = new Roo.Toolbar.Button(item);
28445 var td = document.createElement("td");
28446 this.tr.insertBefore(td, this.tr.childNodes[index]);
28448 this.items.insert(index, item);
28453 * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
28454 * @param {Object} config
28455 * @return {Roo.Toolbar.Item} The element's item
28457 addDom : function(config, returnEl){
28458 var td = this.nextBlock();
28459 Roo.DomHelper.overwrite(td, config);
28460 var ti = new Roo.Toolbar.Item(td.firstChild);
28462 this.items.add(ti);
28467 * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
28468 * @type Roo.util.MixedCollection
28473 * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
28474 * Note: the field should not have been rendered yet. For a field that has already been
28475 * rendered, use {@link #addElement}.
28476 * @param {Roo.form.Field} field
28477 * @return {Roo.ToolbarItem}
28481 addField : function(field) {
28482 if (!this.fields) {
28484 this.fields = new Roo.util.MixedCollection(false, function(o){
28485 return o.id || ("item" + (++autoId));
28490 var td = this.nextBlock();
28492 var ti = new Roo.Toolbar.Item(td.firstChild);
28494 this.items.add(ti);
28495 this.fields.add(field);
28506 this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
28507 this.el.child('div').hide();
28515 this.el.child('div').show();
28519 nextBlock : function(){
28520 var td = document.createElement("td");
28521 this.tr.appendChild(td);
28526 destroy : function(){
28527 if(this.items){ // rendered?
28528 Roo.destroy.apply(Roo, this.items.items);
28530 if(this.fields){ // rendered?
28531 Roo.destroy.apply(Roo, this.fields.items);
28533 Roo.Element.uncache(this.el, this.tr);
28538 * @class Roo.Toolbar.Item
28539 * The base class that other classes should extend in order to get some basic common toolbar item functionality.
28541 * Creates a new Item
28542 * @param {HTMLElement} el
28544 Roo.Toolbar.Item = function(el){
28546 if (typeof (el.xtype) != 'undefined') {
28551 this.el = Roo.getDom(el);
28552 this.id = Roo.id(this.el);
28553 this.hidden = false;
28558 * Fires when the button is rendered
28559 * @param {Button} this
28563 Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
28565 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
28566 //Roo.Toolbar.Item.prototype = {
28569 * Get this item's HTML Element
28570 * @return {HTMLElement}
28572 getEl : function(){
28577 render : function(td){
28580 td.appendChild(this.el);
28582 this.fireEvent('render', this);
28586 * Removes and destroys this item.
28588 destroy : function(){
28589 this.td.parentNode.removeChild(this.td);
28596 this.hidden = false;
28597 this.td.style.display = "";
28604 this.hidden = true;
28605 this.td.style.display = "none";
28609 * Convenience function for boolean show/hide.
28610 * @param {Boolean} visible true to show/false to hide
28612 setVisible: function(visible){
28621 * Try to focus this item.
28623 focus : function(){
28624 Roo.fly(this.el).focus();
28628 * Disables this item.
28630 disable : function(){
28631 Roo.fly(this.td).addClass("x-item-disabled");
28632 this.disabled = true;
28633 this.el.disabled = true;
28637 * Enables this item.
28639 enable : function(){
28640 Roo.fly(this.td).removeClass("x-item-disabled");
28641 this.disabled = false;
28642 this.el.disabled = false;
28648 * @class Roo.Toolbar.Separator
28649 * @extends Roo.Toolbar.Item
28650 * A simple toolbar separator class
28652 * Creates a new Separator
28654 Roo.Toolbar.Separator = function(cfg){
28656 var s = document.createElement("span");
28657 s.className = "ytb-sep";
28662 Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
28664 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
28665 enable:Roo.emptyFn,
28666 disable:Roo.emptyFn,
28671 * @class Roo.Toolbar.Spacer
28672 * @extends Roo.Toolbar.Item
28673 * A simple element that adds extra horizontal space to a toolbar.
28675 * Creates a new Spacer
28677 Roo.Toolbar.Spacer = function(cfg){
28678 var s = document.createElement("div");
28679 s.className = "ytb-spacer";
28683 Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
28685 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
28686 enable:Roo.emptyFn,
28687 disable:Roo.emptyFn,
28692 * @class Roo.Toolbar.Fill
28693 * @extends Roo.Toolbar.Spacer
28694 * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
28696 * Creates a new Spacer
28698 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
28700 render : function(td){
28701 td.style.width = '100%';
28702 Roo.Toolbar.Fill.superclass.render.call(this, td);
28707 * @class Roo.Toolbar.TextItem
28708 * @extends Roo.Toolbar.Item
28709 * A simple class that renders text directly into a toolbar.
28711 * Creates a new TextItem
28712 * @param {String} text
28714 Roo.Toolbar.TextItem = function(cfg){
28715 var text = cfg || "";
28716 if (typeof(cfg) == 'object') {
28717 text = cfg.text || "";
28721 var s = document.createElement("span");
28722 s.className = "ytb-text";
28723 s.innerHTML = text;
28728 Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg || s);
28730 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
28733 enable:Roo.emptyFn,
28734 disable:Roo.emptyFn,
28739 * @class Roo.Toolbar.Button
28740 * @extends Roo.Button
28741 * A button that renders into a toolbar.
28743 * Creates a new Button
28744 * @param {Object} config A standard {@link Roo.Button} config object
28746 Roo.Toolbar.Button = function(config){
28747 Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
28749 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
28750 render : function(td){
28752 Roo.Toolbar.Button.superclass.render.call(this, td);
28756 * Removes and destroys this button
28758 destroy : function(){
28759 Roo.Toolbar.Button.superclass.destroy.call(this);
28760 this.td.parentNode.removeChild(this.td);
28764 * Shows this button
28767 this.hidden = false;
28768 this.td.style.display = "";
28772 * Hides this button
28775 this.hidden = true;
28776 this.td.style.display = "none";
28780 * Disables this item
28782 disable : function(){
28783 Roo.fly(this.td).addClass("x-item-disabled");
28784 this.disabled = true;
28788 * Enables this item
28790 enable : function(){
28791 Roo.fly(this.td).removeClass("x-item-disabled");
28792 this.disabled = false;
28795 // backwards compat
28796 Roo.ToolbarButton = Roo.Toolbar.Button;
28799 * @class Roo.Toolbar.SplitButton
28800 * @extends Roo.SplitButton
28801 * A menu button that renders into a toolbar.
28803 * Creates a new SplitButton
28804 * @param {Object} config A standard {@link Roo.SplitButton} config object
28806 Roo.Toolbar.SplitButton = function(config){
28807 Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
28809 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
28810 render : function(td){
28812 Roo.Toolbar.SplitButton.superclass.render.call(this, td);
28816 * Removes and destroys this button
28818 destroy : function(){
28819 Roo.Toolbar.SplitButton.superclass.destroy.call(this);
28820 this.td.parentNode.removeChild(this.td);
28824 * Shows this button
28827 this.hidden = false;
28828 this.td.style.display = "";
28832 * Hides this button
28835 this.hidden = true;
28836 this.td.style.display = "none";
28840 // backwards compat
28841 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
28843 * Ext JS Library 1.1.1
28844 * Copyright(c) 2006-2007, Ext JS, LLC.
28846 * Originally Released Under LGPL - original licence link has changed is not relivant.
28849 * <script type="text/javascript">
28853 * @class Roo.PagingToolbar
28854 * @extends Roo.Toolbar
28855 * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
28857 * Create a new PagingToolbar
28858 * @param {Object} config The config object
28860 Roo.PagingToolbar = function(el, ds, config)
28862 // old args format still supported... - xtype is prefered..
28863 if (typeof(el) == 'object' && el.xtype) {
28864 // created from xtype...
28866 ds = el.dataSource;
28867 el = config.container;
28870 if (config.items) {
28871 items = config.items;
28875 Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
28878 this.renderButtons(this.el);
28881 // supprot items array.
28883 Roo.each(items, function(e) {
28884 this.add(Roo.factory(e));
28889 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
28891 * @cfg {Roo.data.Store} dataSource
28892 * The underlying data store providing the paged data
28895 * @cfg {String/HTMLElement/Element} container
28896 * container The id or element that will contain the toolbar
28899 * @cfg {Boolean} displayInfo
28900 * True to display the displayMsg (defaults to false)
28903 * @cfg {Number} pageSize
28904 * The number of records to display per page (defaults to 20)
28908 * @cfg {String} displayMsg
28909 * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
28911 displayMsg : 'Displaying {0} - {1} of {2}',
28913 * @cfg {String} emptyMsg
28914 * The message to display when no records are found (defaults to "No data to display")
28916 emptyMsg : 'No data to display',
28918 * Customizable piece of the default paging text (defaults to "Page")
28921 beforePageText : "Page",
28923 * Customizable piece of the default paging text (defaults to "of %0")
28926 afterPageText : "of {0}",
28928 * Customizable piece of the default paging text (defaults to "First Page")
28931 firstText : "First Page",
28933 * Customizable piece of the default paging text (defaults to "Previous Page")
28936 prevText : "Previous Page",
28938 * Customizable piece of the default paging text (defaults to "Next Page")
28941 nextText : "Next Page",
28943 * Customizable piece of the default paging text (defaults to "Last Page")
28946 lastText : "Last Page",
28948 * Customizable piece of the default paging text (defaults to "Refresh")
28951 refreshText : "Refresh",
28954 renderButtons : function(el){
28955 Roo.PagingToolbar.superclass.render.call(this, el);
28956 this.first = this.addButton({
28957 tooltip: this.firstText,
28958 cls: "x-btn-icon x-grid-page-first",
28960 handler: this.onClick.createDelegate(this, ["first"])
28962 this.prev = this.addButton({
28963 tooltip: this.prevText,
28964 cls: "x-btn-icon x-grid-page-prev",
28966 handler: this.onClick.createDelegate(this, ["prev"])
28968 //this.addSeparator();
28969 this.add(this.beforePageText);
28970 this.field = Roo.get(this.addDom({
28975 cls: "x-grid-page-number"
28977 this.field.on("keydown", this.onPagingKeydown, this);
28978 this.field.on("focus", function(){this.dom.select();});
28979 this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
28980 this.field.setHeight(18);
28981 //this.addSeparator();
28982 this.next = this.addButton({
28983 tooltip: this.nextText,
28984 cls: "x-btn-icon x-grid-page-next",
28986 handler: this.onClick.createDelegate(this, ["next"])
28988 this.last = this.addButton({
28989 tooltip: this.lastText,
28990 cls: "x-btn-icon x-grid-page-last",
28992 handler: this.onClick.createDelegate(this, ["last"])
28994 //this.addSeparator();
28995 this.loading = this.addButton({
28996 tooltip: this.refreshText,
28997 cls: "x-btn-icon x-grid-loading",
28998 handler: this.onClick.createDelegate(this, ["refresh"])
29001 if(this.displayInfo){
29002 this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
29007 updateInfo : function(){
29008 if(this.displayEl){
29009 var count = this.ds.getCount();
29010 var msg = count == 0 ?
29014 this.cursor+1, this.cursor+count, this.ds.getTotalCount()
29016 this.displayEl.update(msg);
29021 onLoad : function(ds, r, o){
29022 this.cursor = o.params ? o.params.start : 0;
29023 var d = this.getPageData(), ap = d.activePage, ps = d.pages;
29025 this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
29026 this.field.dom.value = ap;
29027 this.first.setDisabled(ap == 1);
29028 this.prev.setDisabled(ap == 1);
29029 this.next.setDisabled(ap == ps);
29030 this.last.setDisabled(ap == ps);
29031 this.loading.enable();
29036 getPageData : function(){
29037 var total = this.ds.getTotalCount();
29040 activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
29041 pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
29046 onLoadError : function(){
29047 this.loading.enable();
29051 onPagingKeydown : function(e){
29052 var k = e.getKey();
29053 var d = this.getPageData();
29055 var v = this.field.dom.value, pageNum;
29056 if(!v || isNaN(pageNum = parseInt(v, 10))){
29057 this.field.dom.value = d.activePage;
29060 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
29061 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
29064 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))
29066 var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
29067 this.field.dom.value = pageNum;
29068 this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
29071 else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
29073 var v = this.field.dom.value, pageNum;
29074 var increment = (e.shiftKey) ? 10 : 1;
29075 if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
29077 if(!v || isNaN(pageNum = parseInt(v, 10))) {
29078 this.field.dom.value = d.activePage;
29081 else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
29083 this.field.dom.value = parseInt(v, 10) + increment;
29084 pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
29085 this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
29092 beforeLoad : function(){
29094 this.loading.disable();
29099 onClick : function(which){
29103 ds.load({params:{start: 0, limit: this.pageSize}});
29106 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
29109 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
29112 var total = ds.getTotalCount();
29113 var extra = total % this.pageSize;
29114 var lastStart = extra ? (total - extra) : total-this.pageSize;
29115 ds.load({params:{start: lastStart, limit: this.pageSize}});
29118 ds.load({params:{start: this.cursor, limit: this.pageSize}});
29124 * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
29125 * @param {Roo.data.Store} store The data store to unbind
29127 unbind : function(ds){
29128 ds.un("beforeload", this.beforeLoad, this);
29129 ds.un("load", this.onLoad, this);
29130 ds.un("loadexception", this.onLoadError, this);
29131 ds.un("remove", this.updateInfo, this);
29132 ds.un("add", this.updateInfo, this);
29133 this.ds = undefined;
29137 * Binds the paging toolbar to the specified {@link Roo.data.Store}
29138 * @param {Roo.data.Store} store The data store to bind
29140 bind : function(ds){
29141 ds.on("beforeload", this.beforeLoad, this);
29142 ds.on("load", this.onLoad, this);
29143 ds.on("loadexception", this.onLoadError, this);
29144 ds.on("remove", this.updateInfo, this);
29145 ds.on("add", this.updateInfo, this);
29150 * Ext JS Library 1.1.1
29151 * Copyright(c) 2006-2007, Ext JS, LLC.
29153 * Originally Released Under LGPL - original licence link has changed is not relivant.
29156 * <script type="text/javascript">
29160 * @class Roo.Resizable
29161 * @extends Roo.util.Observable
29162 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
29163 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
29164 * 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
29165 * the element will be wrapped for you automatically.</p>
29166 * <p>Here is the list of valid resize handles:</p>
29169 ------ -------------------
29178 'hd' horizontal drag
29181 * <p>Here's an example showing the creation of a typical Resizable:</p>
29183 var resizer = new Roo.Resizable("element-id", {
29191 resizer.on("resize", myHandler);
29193 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
29194 * resizer.east.setDisplayed(false);</p>
29195 * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
29196 * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
29197 * resize operation's new size (defaults to [0, 0])
29198 * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
29199 * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
29200 * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
29201 * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
29202 * @cfg {Boolean} enabled False to disable resizing (defaults to true)
29203 * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
29204 * @cfg {Number} width The width of the element in pixels (defaults to null)
29205 * @cfg {Number} height The height of the element in pixels (defaults to null)
29206 * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
29207 * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
29208 * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
29209 * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
29210 * @cfg {Boolean} multiDirectional <b>Deprecated</b>. The old style of adding multi-direction resize handles, deprecated
29211 * in favor of the handles config option (defaults to false)
29212 * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
29213 * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
29214 * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
29215 * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
29216 * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
29217 * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
29218 * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
29219 * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
29220 * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
29221 * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
29222 * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
29224 * Create a new resizable component
29225 * @param {String/HTMLElement/Roo.Element} el The id or element to resize
29226 * @param {Object} config configuration options
29228 Roo.Resizable = function(el, config)
29230 this.el = Roo.get(el);
29232 if(config && config.wrap){
29233 config.resizeChild = this.el;
29234 this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
29235 this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
29236 this.el.setStyle("overflow", "hidden");
29237 this.el.setPositioning(config.resizeChild.getPositioning());
29238 config.resizeChild.clearPositioning();
29239 if(!config.width || !config.height){
29240 var csize = config.resizeChild.getSize();
29241 this.el.setSize(csize.width, csize.height);
29243 if(config.pinned && !config.adjustments){
29244 config.adjustments = "auto";
29248 this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
29249 this.proxy.unselectable();
29250 this.proxy.enableDisplayMode('block');
29252 Roo.apply(this, config);
29255 this.disableTrackOver = true;
29256 this.el.addClass("x-resizable-pinned");
29258 // if the element isn't positioned, make it relative
29259 var position = this.el.getStyle("position");
29260 if(position != "absolute" && position != "fixed"){
29261 this.el.setStyle("position", "relative");
29263 if(!this.handles){ // no handles passed, must be legacy style
29264 this.handles = 's,e,se';
29265 if(this.multiDirectional){
29266 this.handles += ',n,w';
29269 if(this.handles == "all"){
29270 this.handles = "n s e w ne nw se sw";
29272 var hs = this.handles.split(/\s*?[,;]\s*?| /);
29273 var ps = Roo.Resizable.positions;
29274 for(var i = 0, len = hs.length; i < len; i++){
29275 if(hs[i] && ps[hs[i]]){
29276 var pos = ps[hs[i]];
29277 this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
29281 this.corner = this.southeast;
29283 // updateBox = the box can move..
29284 if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
29285 this.updateBox = true;
29288 this.activeHandle = null;
29290 if(this.resizeChild){
29291 if(typeof this.resizeChild == "boolean"){
29292 this.resizeChild = Roo.get(this.el.dom.firstChild, true);
29294 this.resizeChild = Roo.get(this.resizeChild, true);
29298 if(this.adjustments == "auto"){
29299 var rc = this.resizeChild;
29300 var hw = this.west, he = this.east, hn = this.north, hs = this.south;
29301 if(rc && (hw || hn)){
29302 rc.position("relative");
29303 rc.setLeft(hw ? hw.el.getWidth() : 0);
29304 rc.setTop(hn ? hn.el.getHeight() : 0);
29306 this.adjustments = [
29307 (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
29308 (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
29312 if(this.draggable){
29313 this.dd = this.dynamic ?
29314 this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
29315 this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
29321 * @event beforeresize
29322 * Fired before resize is allowed. Set enabled to false to cancel resize.
29323 * @param {Roo.Resizable} this
29324 * @param {Roo.EventObject} e The mousedown event
29326 "beforeresize" : true,
29329 * Fired a resizing.
29330 * @param {Roo.Resizable} this
29331 * @param {Number} x The new x position
29332 * @param {Number} y The new y position
29333 * @param {Number} w The new w width
29334 * @param {Number} h The new h hight
29335 * @param {Roo.EventObject} e The mouseup event
29340 * Fired after a resize.
29341 * @param {Roo.Resizable} this
29342 * @param {Number} width The new width
29343 * @param {Number} height The new height
29344 * @param {Roo.EventObject} e The mouseup event
29349 if(this.width !== null && this.height !== null){
29350 this.resizeTo(this.width, this.height);
29352 this.updateChildSize();
29355 this.el.dom.style.zoom = 1;
29357 Roo.Resizable.superclass.constructor.call(this);
29360 Roo.extend(Roo.Resizable, Roo.util.Observable, {
29361 resizeChild : false,
29362 adjustments : [0, 0],
29372 multiDirectional : false,
29373 disableTrackOver : false,
29374 easing : 'easeOutStrong',
29375 widthIncrement : 0,
29376 heightIncrement : 0,
29380 preserveRatio : false,
29381 transparent: false,
29387 * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
29389 constrainTo: undefined,
29391 * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
29393 resizeRegion: undefined,
29397 * Perform a manual resize
29398 * @param {Number} width
29399 * @param {Number} height
29401 resizeTo : function(width, height){
29402 this.el.setSize(width, height);
29403 this.updateChildSize();
29404 this.fireEvent("resize", this, width, height, null);
29408 startSizing : function(e, handle){
29409 this.fireEvent("beforeresize", this, e);
29410 if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
29413 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "});
29414 this.overlay.unselectable();
29415 this.overlay.enableDisplayMode("block");
29416 this.overlay.on("mousemove", this.onMouseMove, this);
29417 this.overlay.on("mouseup", this.onMouseUp, this);
29419 this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
29421 this.resizing = true;
29422 this.startBox = this.el.getBox();
29423 this.startPoint = e.getXY();
29424 this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
29425 (this.startBox.y + this.startBox.height) - this.startPoint[1]];
29427 this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
29428 this.overlay.show();
29430 if(this.constrainTo) {
29431 var ct = Roo.get(this.constrainTo);
29432 this.resizeRegion = ct.getRegion().adjust(
29433 ct.getFrameWidth('t'),
29434 ct.getFrameWidth('l'),
29435 -ct.getFrameWidth('b'),
29436 -ct.getFrameWidth('r')
29440 this.proxy.setStyle('visibility', 'hidden'); // workaround display none
29442 this.proxy.setBox(this.startBox);
29444 this.proxy.setStyle('visibility', 'visible');
29450 onMouseDown : function(handle, e){
29453 this.activeHandle = handle;
29454 this.startSizing(e, handle);
29459 onMouseUp : function(e){
29460 var size = this.resizeElement();
29461 this.resizing = false;
29463 this.overlay.hide();
29465 this.fireEvent("resize", this, size.width, size.height, e);
29469 updateChildSize : function(){
29471 if(this.resizeChild){
29473 var child = this.resizeChild;
29474 var adj = this.adjustments;
29475 if(el.dom.offsetWidth){
29476 var b = el.getSize(true);
29477 child.setSize(b.width+adj[0], b.height+adj[1]);
29479 // Second call here for IE
29480 // The first call enables instant resizing and
29481 // the second call corrects scroll bars if they
29484 setTimeout(function(){
29485 if(el.dom.offsetWidth){
29486 var b = el.getSize(true);
29487 child.setSize(b.width+adj[0], b.height+adj[1]);
29495 snap : function(value, inc, min){
29496 if(!inc || !value) return value;
29497 var newValue = value;
29498 var m = value % inc;
29501 newValue = value + (inc-m);
29503 newValue = value - m;
29506 return Math.max(min, newValue);
29510 resizeElement : function(){
29511 var box = this.proxy.getBox();
29512 if(this.updateBox){
29513 this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
29515 this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
29517 this.updateChildSize();
29525 constrain : function(v, diff, m, mx){
29528 }else if(v - diff > mx){
29535 onMouseMove : function(e){
29538 try{// try catch so if something goes wrong the user doesn't get hung
29540 if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
29544 //var curXY = this.startPoint;
29545 var curSize = this.curSize || this.startBox;
29546 var x = this.startBox.x, y = this.startBox.y;
29547 var ox = x, oy = y;
29548 var w = curSize.width, h = curSize.height;
29549 var ow = w, oh = h;
29550 var mw = this.minWidth, mh = this.minHeight;
29551 var mxw = this.maxWidth, mxh = this.maxHeight;
29552 var wi = this.widthIncrement;
29553 var hi = this.heightIncrement;
29555 var eventXY = e.getXY();
29556 var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
29557 var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
29559 var pos = this.activeHandle.position;
29564 w = Math.min(Math.max(mw, w), mxw);
29569 h = Math.min(Math.max(mh, h), mxh);
29574 w = Math.min(Math.max(mw, w), mxw);
29575 h = Math.min(Math.max(mh, h), mxh);
29578 diffY = this.constrain(h, diffY, mh, mxh);
29585 var adiffX = Math.abs(diffX);
29586 var sub = (adiffX % wi); // how much
29587 if (sub > (wi/2)) { // far enough to snap
29588 diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
29590 // remove difference..
29591 diffX = (diffX > 0) ? diffX-sub : diffX+sub;
29595 x = Math.max(this.minX, x);
29598 diffX = this.constrain(w, diffX, mw, mxw);
29604 w = Math.min(Math.max(mw, w), mxw);
29605 diffY = this.constrain(h, diffY, mh, mxh);
29610 diffX = this.constrain(w, diffX, mw, mxw);
29611 diffY = this.constrain(h, diffY, mh, mxh);
29618 diffX = this.constrain(w, diffX, mw, mxw);
29620 h = Math.min(Math.max(mh, h), mxh);
29626 var sw = this.snap(w, wi, mw);
29627 var sh = this.snap(h, hi, mh);
29628 if(sw != w || sh != h){
29651 if(this.preserveRatio){
29656 h = Math.min(Math.max(mh, h), mxh);
29661 w = Math.min(Math.max(mw, w), mxw);
29666 w = Math.min(Math.max(mw, w), mxw);
29672 w = Math.min(Math.max(mw, w), mxw);
29678 h = Math.min(Math.max(mh, h), mxh);
29686 h = Math.min(Math.max(mh, h), mxh);
29696 h = Math.min(Math.max(mh, h), mxh);
29704 if (pos == 'hdrag') {
29707 this.proxy.setBounds(x, y, w, h);
29709 this.resizeElement();
29713 this.fireEvent("resizing", this, x, y, w, h, e);
29717 handleOver : function(){
29719 this.el.addClass("x-resizable-over");
29724 handleOut : function(){
29725 if(!this.resizing){
29726 this.el.removeClass("x-resizable-over");
29731 * Returns the element this component is bound to.
29732 * @return {Roo.Element}
29734 getEl : function(){
29739 * Returns the resizeChild element (or null).
29740 * @return {Roo.Element}
29742 getResizeChild : function(){
29743 return this.resizeChild;
29745 groupHandler : function()
29750 * Destroys this resizable. If the element was wrapped and
29751 * removeEl is not true then the element remains.
29752 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
29754 destroy : function(removeEl){
29755 this.proxy.remove();
29757 this.overlay.removeAllListeners();
29758 this.overlay.remove();
29760 var ps = Roo.Resizable.positions;
29762 if(typeof ps[k] != "function" && this[ps[k]]){
29763 var h = this[ps[k]];
29764 h.el.removeAllListeners();
29769 this.el.update("");
29776 // hash to map config positions to true positions
29777 Roo.Resizable.positions = {
29778 n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast",
29783 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
29785 // only initialize the template if resizable is used
29786 var tpl = Roo.DomHelper.createTemplate(
29787 {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
29790 Roo.Resizable.Handle.prototype.tpl = tpl;
29792 this.position = pos;
29794 // show north drag fro topdra
29795 var handlepos = pos == 'hdrag' ? 'north' : pos;
29797 this.el = this.tpl.append(rz.el.dom, [handlepos], true);
29798 if (pos == 'hdrag') {
29799 this.el.setStyle('cursor', 'pointer');
29801 this.el.unselectable();
29803 this.el.setOpacity(0);
29805 this.el.on("mousedown", this.onMouseDown, this);
29806 if(!disableTrackOver){
29807 this.el.on("mouseover", this.onMouseOver, this);
29808 this.el.on("mouseout", this.onMouseOut, this);
29813 Roo.Resizable.Handle.prototype = {
29814 afterResize : function(rz){
29819 onMouseDown : function(e){
29820 this.rz.onMouseDown(this, e);
29823 onMouseOver : function(e){
29824 this.rz.handleOver(this, e);
29827 onMouseOut : function(e){
29828 this.rz.handleOut(this, e);
29832 * Ext JS Library 1.1.1
29833 * Copyright(c) 2006-2007, Ext JS, LLC.
29835 * Originally Released Under LGPL - original licence link has changed is not relivant.
29838 * <script type="text/javascript">
29842 * @class Roo.Editor
29843 * @extends Roo.Component
29844 * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
29846 * Create a new Editor
29847 * @param {Roo.form.Field} field The Field object (or descendant)
29848 * @param {Object} config The config object
29850 Roo.Editor = function(field, config){
29851 Roo.Editor.superclass.constructor.call(this, config);
29852 this.field = field;
29855 * @event beforestartedit
29856 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
29857 * false from the handler of this event.
29858 * @param {Editor} this
29859 * @param {Roo.Element} boundEl The underlying element bound to this editor
29860 * @param {Mixed} value The field value being set
29862 "beforestartedit" : true,
29865 * Fires when this editor is displayed
29866 * @param {Roo.Element} boundEl The underlying element bound to this editor
29867 * @param {Mixed} value The starting field value
29869 "startedit" : true,
29871 * @event beforecomplete
29872 * Fires after a change has been made to the field, but before the change is reflected in the underlying
29873 * field. Saving the change to the field can be canceled by returning false from the handler of this event.
29874 * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
29875 * event will not fire since no edit actually occurred.
29876 * @param {Editor} this
29877 * @param {Mixed} value The current field value
29878 * @param {Mixed} startValue The original field value
29880 "beforecomplete" : true,
29883 * Fires after editing is complete and any changed value has been written to the underlying field.
29884 * @param {Editor} this
29885 * @param {Mixed} value The current field value
29886 * @param {Mixed} startValue The original field value
29890 * @event specialkey
29891 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
29892 * {@link Roo.EventObject#getKey} to determine which key was pressed.
29893 * @param {Roo.form.Field} this
29894 * @param {Roo.EventObject} e The event object
29896 "specialkey" : true
29900 Roo.extend(Roo.Editor, Roo.Component, {
29902 * @cfg {Boolean/String} autosize
29903 * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
29904 * or "height" to adopt the height only (defaults to false)
29907 * @cfg {Boolean} revertInvalid
29908 * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
29909 * validation fails (defaults to true)
29912 * @cfg {Boolean} ignoreNoChange
29913 * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
29914 * the value has not changed (defaults to false). Applies only to string values - edits for other data types
29915 * will never be ignored.
29918 * @cfg {Boolean} hideEl
29919 * False to keep the bound element visible while the editor is displayed (defaults to true)
29922 * @cfg {Mixed} value
29923 * The data value of the underlying field (defaults to "")
29927 * @cfg {String} alignment
29928 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
29932 * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
29933 * for bottom-right shadow (defaults to "frame")
29937 * @cfg {Boolean} constrain True to constrain the editor to the viewport
29941 * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
29943 completeOnEnter : false,
29945 * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
29947 cancelOnEsc : false,
29949 * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
29954 onRender : function(ct, position){
29955 this.el = new Roo.Layer({
29956 shadow: this.shadow,
29962 constrain: this.constrain
29964 this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
29965 if(this.field.msgTarget != 'title'){
29966 this.field.msgTarget = 'qtip';
29968 this.field.render(this.el);
29970 this.field.el.dom.setAttribute('autocomplete', 'off');
29972 this.field.on("specialkey", this.onSpecialKey, this);
29973 if(this.swallowKeys){
29974 this.field.el.swallowEvent(['keydown','keypress']);
29977 this.field.on("blur", this.onBlur, this);
29978 if(this.field.grow){
29979 this.field.on("autosize", this.el.sync, this.el, {delay:1});
29983 onSpecialKey : function(field, e)
29985 //Roo.log('editor onSpecialKey');
29986 if(this.completeOnEnter && e.getKey() == e.ENTER){
29988 this.completeEdit();
29991 // do not fire special key otherwise it might hide close the editor...
29992 if(e.getKey() == e.ENTER){
29995 if(this.cancelOnEsc && e.getKey() == e.ESC){
29999 this.fireEvent('specialkey', field, e);
30004 * Starts the editing process and shows the editor.
30005 * @param {String/HTMLElement/Element} el The element to edit
30006 * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
30007 * to the innerHTML of el.
30009 startEdit : function(el, value){
30011 this.completeEdit();
30013 this.boundEl = Roo.get(el);
30014 var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
30015 if(!this.rendered){
30016 this.render(this.parentEl || document.body);
30018 if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
30021 this.startValue = v;
30022 this.field.setValue(v);
30024 var sz = this.boundEl.getSize();
30025 switch(this.autoSize){
30027 this.setSize(sz.width, "");
30030 this.setSize("", sz.height);
30033 this.setSize(sz.width, sz.height);
30036 this.el.alignTo(this.boundEl, this.alignment);
30037 this.editing = true;
30039 Roo.QuickTips.disable();
30045 * Sets the height and width of this editor.
30046 * @param {Number} width The new width
30047 * @param {Number} height The new height
30049 setSize : function(w, h){
30050 this.field.setSize(w, h);
30057 * Realigns the editor to the bound field based on the current alignment config value.
30059 realign : function(){
30060 this.el.alignTo(this.boundEl, this.alignment);
30064 * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
30065 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
30067 completeEdit : function(remainVisible){
30071 var v = this.getValue();
30072 if(this.revertInvalid !== false && !this.field.isValid()){
30073 v = this.startValue;
30074 this.cancelEdit(true);
30076 if(String(v) === String(this.startValue) && this.ignoreNoChange){
30077 this.editing = false;
30081 if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
30082 this.editing = false;
30083 if(this.updateEl && this.boundEl){
30084 this.boundEl.update(v);
30086 if(remainVisible !== true){
30089 this.fireEvent("complete", this, v, this.startValue);
30094 onShow : function(){
30096 if(this.hideEl !== false){
30097 this.boundEl.hide();
30100 if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
30101 this.fixIEFocus = true;
30102 this.deferredFocus.defer(50, this);
30104 this.field.focus();
30106 this.fireEvent("startedit", this.boundEl, this.startValue);
30109 deferredFocus : function(){
30111 this.field.focus();
30116 * Cancels the editing process and hides the editor without persisting any changes. The field value will be
30117 * reverted to the original starting value.
30118 * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
30119 * cancel (defaults to false)
30121 cancelEdit : function(remainVisible){
30123 this.setValue(this.startValue);
30124 if(remainVisible !== true){
30131 onBlur : function(){
30132 if(this.allowBlur !== true && this.editing){
30133 this.completeEdit();
30138 onHide : function(){
30140 this.completeEdit();
30144 if(this.field.collapse){
30145 this.field.collapse();
30148 if(this.hideEl !== false){
30149 this.boundEl.show();
30152 Roo.QuickTips.enable();
30157 * Sets the data value of the editor
30158 * @param {Mixed} value Any valid value supported by the underlying field
30160 setValue : function(v){
30161 this.field.setValue(v);
30165 * Gets the data value of the editor
30166 * @return {Mixed} The data value
30168 getValue : function(){
30169 return this.field.getValue();
30173 * Ext JS Library 1.1.1
30174 * Copyright(c) 2006-2007, Ext JS, LLC.
30176 * Originally Released Under LGPL - original licence link has changed is not relivant.
30179 * <script type="text/javascript">
30183 * @class Roo.BasicDialog
30184 * @extends Roo.util.Observable
30185 * Lightweight Dialog Class. The code below shows the creation of a typical dialog using existing HTML markup:
30187 var dlg = new Roo.BasicDialog("my-dlg", {
30196 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
30197 dlg.addButton('OK', dlg.hide, dlg); // Could call a save function instead of hiding
30198 dlg.addButton('Cancel', dlg.hide, dlg);
30201 <b>A Dialog should always be a direct child of the body element.</b>
30202 * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
30203 * @cfg {String} title Default text to display in the title bar (defaults to null)
30204 * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
30205 * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS). Determined by browser if unspecified.
30206 * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
30207 * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
30208 * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
30209 * (defaults to null with no animation)
30210 * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
30211 * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
30212 * property for valid values (defaults to 'all')
30213 * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
30214 * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
30215 * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
30216 * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
30217 * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
30218 * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
30219 * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
30220 * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
30221 * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
30222 * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
30223 * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
30224 * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
30225 * draggable = true (defaults to false)
30226 * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
30227 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
30228 * shadow (defaults to false)
30229 * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
30230 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
30231 * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
30232 * @cfg {Array} buttons Array of buttons
30233 * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
30235 * Create a new BasicDialog.
30236 * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
30237 * @param {Object} config Configuration options
30239 Roo.BasicDialog = function(el, config){
30240 this.el = Roo.get(el);
30241 var dh = Roo.DomHelper;
30242 if(!this.el && config && config.autoCreate){
30243 if(typeof config.autoCreate == "object"){
30244 if(!config.autoCreate.id){
30245 config.autoCreate.id = el;
30247 this.el = dh.append(document.body,
30248 config.autoCreate, true);
30250 this.el = dh.append(document.body,
30251 {tag: "div", id: el, style:'visibility:hidden;'}, true);
30255 el.setDisplayed(true);
30256 el.hide = this.hideAction;
30258 el.addClass("x-dlg");
30260 Roo.apply(this, config);
30262 this.proxy = el.createProxy("x-dlg-proxy");
30263 this.proxy.hide = this.hideAction;
30264 this.proxy.setOpacity(.5);
30268 el.setWidth(config.width);
30271 el.setHeight(config.height);
30273 this.size = el.getSize();
30274 if(typeof config.x != "undefined" && typeof config.y != "undefined"){
30275 this.xy = [config.x,config.y];
30277 this.xy = el.getCenterXY(true);
30279 /** The header element @type Roo.Element */
30280 this.header = el.child("> .x-dlg-hd");
30281 /** The body element @type Roo.Element */
30282 this.body = el.child("> .x-dlg-bd");
30283 /** The footer element @type Roo.Element */
30284 this.footer = el.child("> .x-dlg-ft");
30287 this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
30290 this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
30293 this.header.unselectable();
30295 this.header.update(this.title);
30297 // this element allows the dialog to be focused for keyboard event
30298 this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
30299 this.focusEl.swallowEvent("click", true);
30301 this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
30303 // wrap the body and footer for special rendering
30304 this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
30306 this.bwrap.dom.appendChild(this.footer.dom);
30309 this.bg = this.el.createChild({
30310 tag: "div", cls:"x-dlg-bg",
30311 html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
30313 this.centerBg = this.bg.child("div.x-dlg-bg-center");
30316 if(this.autoScroll !== false && !this.autoTabs){
30317 this.body.setStyle("overflow", "auto");
30320 this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
30322 if(this.closable !== false){
30323 this.el.addClass("x-dlg-closable");
30324 this.close = this.toolbox.createChild({cls:"x-dlg-close"});
30325 this.close.on("click", this.closeClick, this);
30326 this.close.addClassOnOver("x-dlg-close-over");
30328 if(this.collapsible !== false){
30329 this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
30330 this.collapseBtn.on("click", this.collapseClick, this);
30331 this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
30332 this.header.on("dblclick", this.collapseClick, this);
30334 if(this.resizable !== false){
30335 this.el.addClass("x-dlg-resizable");
30336 this.resizer = new Roo.Resizable(el, {
30337 minWidth: this.minWidth || 80,
30338 minHeight:this.minHeight || 80,
30339 handles: this.resizeHandles || "all",
30342 this.resizer.on("beforeresize", this.beforeResize, this);
30343 this.resizer.on("resize", this.onResize, this);
30345 if(this.draggable !== false){
30346 el.addClass("x-dlg-draggable");
30347 if (!this.proxyDrag) {
30348 var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
30351 var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
30353 dd.setHandleElId(this.header.id);
30354 dd.endDrag = this.endMove.createDelegate(this);
30355 dd.startDrag = this.startMove.createDelegate(this);
30356 dd.onDrag = this.onDrag.createDelegate(this);
30361 this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
30362 this.mask.enableDisplayMode("block");
30364 this.el.addClass("x-dlg-modal");
30367 this.shadow = new Roo.Shadow({
30368 mode : typeof this.shadow == "string" ? this.shadow : "sides",
30369 offset : this.shadowOffset
30372 this.shadowOffset = 0;
30374 if(Roo.useShims && this.shim !== false){
30375 this.shim = this.el.createShim();
30376 this.shim.hide = this.hideAction;
30384 if (this.buttons) {
30385 var bts= this.buttons;
30387 Roo.each(bts, function(b) {
30396 * Fires when a key is pressed
30397 * @param {Roo.BasicDialog} this
30398 * @param {Roo.EventObject} e
30403 * Fires when this dialog is moved by the user.
30404 * @param {Roo.BasicDialog} this
30405 * @param {Number} x The new page X
30406 * @param {Number} y The new page Y
30411 * Fires when this dialog is resized by the user.
30412 * @param {Roo.BasicDialog} this
30413 * @param {Number} width The new width
30414 * @param {Number} height The new height
30418 * @event beforehide
30419 * Fires before this dialog is hidden.
30420 * @param {Roo.BasicDialog} this
30422 "beforehide" : true,
30425 * Fires when this dialog is hidden.
30426 * @param {Roo.BasicDialog} this
30430 * @event beforeshow
30431 * Fires before this dialog is shown.
30432 * @param {Roo.BasicDialog} this
30434 "beforeshow" : true,
30437 * Fires when this dialog is shown.
30438 * @param {Roo.BasicDialog} this
30442 el.on("keydown", this.onKeyDown, this);
30443 el.on("mousedown", this.toFront, this);
30444 Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
30446 Roo.DialogManager.register(this);
30447 Roo.BasicDialog.superclass.constructor.call(this);
30450 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
30451 shadowOffset: Roo.isIE ? 6 : 5,
30454 minButtonWidth: 75,
30455 defaultButton: null,
30456 buttonAlign: "right",
30461 * Sets the dialog title text
30462 * @param {String} text The title text to display
30463 * @return {Roo.BasicDialog} this
30465 setTitle : function(text){
30466 this.header.update(text);
30471 closeClick : function(){
30476 collapseClick : function(){
30477 this[this.collapsed ? "expand" : "collapse"]();
30481 * Collapses the dialog to its minimized state (only the title bar is visible).
30482 * Equivalent to the user clicking the collapse dialog button.
30484 collapse : function(){
30485 if(!this.collapsed){
30486 this.collapsed = true;
30487 this.el.addClass("x-dlg-collapsed");
30488 this.restoreHeight = this.el.getHeight();
30489 this.resizeTo(this.el.getWidth(), this.header.getHeight());
30494 * Expands a collapsed dialog back to its normal state. Equivalent to the user
30495 * clicking the expand dialog button.
30497 expand : function(){
30498 if(this.collapsed){
30499 this.collapsed = false;
30500 this.el.removeClass("x-dlg-collapsed");
30501 this.resizeTo(this.el.getWidth(), this.restoreHeight);
30506 * Reinitializes the tabs component, clearing out old tabs and finding new ones.
30507 * @return {Roo.TabPanel} The tabs component
30509 initTabs : function(){
30510 var tabs = this.getTabs();
30511 while(tabs.getTab(0)){
30514 this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
30516 tabs.addTab(Roo.id(dom), dom.title);
30524 beforeResize : function(){
30525 this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
30529 onResize : function(){
30530 this.refreshSize();
30531 this.syncBodyHeight();
30532 this.adjustAssets();
30534 this.fireEvent("resize", this, this.size.width, this.size.height);
30538 onKeyDown : function(e){
30539 if(this.isVisible()){
30540 this.fireEvent("keydown", this, e);
30545 * Resizes the dialog.
30546 * @param {Number} width
30547 * @param {Number} height
30548 * @return {Roo.BasicDialog} this
30550 resizeTo : function(width, height){
30551 this.el.setSize(width, height);
30552 this.size = {width: width, height: height};
30553 this.syncBodyHeight();
30554 if(this.fixedcenter){
30557 if(this.isVisible()){
30558 this.constrainXY();
30559 this.adjustAssets();
30561 this.fireEvent("resize", this, width, height);
30567 * Resizes the dialog to fit the specified content size.
30568 * @param {Number} width
30569 * @param {Number} height
30570 * @return {Roo.BasicDialog} this
30572 setContentSize : function(w, h){
30573 h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
30574 w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
30575 //if(!this.el.isBorderBox()){
30576 h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
30577 w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
30580 h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
30581 w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
30583 this.resizeTo(w, h);
30588 * Adds a key listener for when this dialog is displayed. This allows you to hook in a function that will be
30589 * executed in response to a particular key being pressed while the dialog is active.
30590 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
30591 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
30592 * @param {Function} fn The function to call
30593 * @param {Object} scope (optional) The scope of the function
30594 * @return {Roo.BasicDialog} this
30596 addKeyListener : function(key, fn, scope){
30597 var keyCode, shift, ctrl, alt;
30598 if(typeof key == "object" && !(key instanceof Array)){
30599 keyCode = key["key"];
30600 shift = key["shift"];
30601 ctrl = key["ctrl"];
30606 var handler = function(dlg, e){
30607 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
30608 var k = e.getKey();
30609 if(keyCode instanceof Array){
30610 for(var i = 0, len = keyCode.length; i < len; i++){
30611 if(keyCode[i] == k){
30612 fn.call(scope || window, dlg, k, e);
30618 fn.call(scope || window, dlg, k, e);
30623 this.on("keydown", handler);
30628 * Returns the TabPanel component (creates it if it doesn't exist).
30629 * Note: If you wish to simply check for the existence of tabs without creating them,
30630 * check for a null 'tabs' property.
30631 * @return {Roo.TabPanel} The tabs component
30633 getTabs : function(){
30635 this.el.addClass("x-dlg-auto-tabs");
30636 this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
30637 this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
30643 * Adds a button to the footer section of the dialog.
30644 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
30645 * object or a valid Roo.DomHelper element config
30646 * @param {Function} handler The function called when the button is clicked
30647 * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
30648 * @return {Roo.Button} The new button
30650 addButton : function(config, handler, scope){
30651 var dh = Roo.DomHelper;
30653 this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
30655 if(!this.btnContainer){
30656 var tb = this.footer.createChild({
30658 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
30659 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
30661 this.btnContainer = tb.firstChild.firstChild.firstChild;
30666 minWidth: this.minButtonWidth,
30669 if(typeof config == "string"){
30670 bconfig.text = config;
30673 bconfig.dhconfig = config;
30675 Roo.apply(bconfig, config);
30679 if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
30680 bconfig.position = Math.max(0, bconfig.position);
30681 fc = this.btnContainer.childNodes[bconfig.position];
30684 var btn = new Roo.Button(
30686 this.btnContainer.insertBefore(document.createElement("td"),fc)
30687 : this.btnContainer.appendChild(document.createElement("td")),
30688 //Roo.get(this.btnContainer).createChild( { tag: 'td'}, fc ),
30691 this.syncBodyHeight();
30694 * Array of all the buttons that have been added to this dialog via addButton
30699 this.buttons.push(btn);
30704 * Sets the default button to be focused when the dialog is displayed.
30705 * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
30706 * @return {Roo.BasicDialog} this
30708 setDefaultButton : function(btn){
30709 this.defaultButton = btn;
30714 getHeaderFooterHeight : function(safe){
30717 height += this.header.getHeight();
30720 var fm = this.footer.getMargins();
30721 height += (this.footer.getHeight()+fm.top+fm.bottom);
30723 height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
30724 height += this.centerBg.getPadding("tb");
30729 syncBodyHeight : function()
30731 var bd = this.body, // the text
30732 cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
30734 var height = this.size.height - this.getHeaderFooterHeight(false);
30735 bd.setHeight(height-bd.getMargins("tb"));
30736 var hh = this.header.getHeight();
30737 var h = this.size.height-hh;
30740 bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
30741 bw.setHeight(h-cb.getPadding("tb"));
30743 bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
30744 bd.setWidth(bw.getWidth(true));
30746 this.tabs.syncHeight();
30748 this.tabs.el.repaint();
30754 * Restores the previous state of the dialog if Roo.state is configured.
30755 * @return {Roo.BasicDialog} this
30757 restoreState : function(){
30758 var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
30759 if(box && box.width){
30760 this.xy = [box.x, box.y];
30761 this.resizeTo(box.width, box.height);
30767 beforeShow : function(){
30769 if(this.fixedcenter){
30770 this.xy = this.el.getCenterXY(true);
30773 Roo.get(document.body).addClass("x-body-masked");
30774 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
30777 this.constrainXY();
30781 animShow : function(){
30782 var b = Roo.get(this.animateTarget).getBox();
30783 this.proxy.setSize(b.width, b.height);
30784 this.proxy.setLocation(b.x, b.y);
30786 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
30787 true, .35, this.showEl.createDelegate(this));
30791 * Shows the dialog.
30792 * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
30793 * @return {Roo.BasicDialog} this
30795 show : function(animateTarget){
30796 if (this.fireEvent("beforeshow", this) === false){
30799 if(this.syncHeightBeforeShow){
30800 this.syncBodyHeight();
30801 }else if(this.firstShow){
30802 this.firstShow = false;
30803 this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
30805 this.animateTarget = animateTarget || this.animateTarget;
30806 if(!this.el.isVisible()){
30808 if(this.animateTarget && Roo.get(this.animateTarget)){
30818 showEl : function(){
30820 this.el.setXY(this.xy);
30822 this.adjustAssets(true);
30825 // IE peekaboo bug - fix found by Dave Fenwick
30829 this.fireEvent("show", this);
30833 * Focuses the dialog. If a defaultButton is set, it will receive focus, otherwise the
30834 * dialog itself will receive focus.
30836 focus : function(){
30837 if(this.defaultButton){
30838 this.defaultButton.focus();
30840 this.focusEl.focus();
30845 constrainXY : function(){
30846 if(this.constraintoviewport !== false){
30847 if(!this.viewSize){
30848 if(this.container){
30849 var s = this.container.getSize();
30850 this.viewSize = [s.width, s.height];
30852 this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
30855 var s = Roo.get(this.container||document).getScroll();
30857 var x = this.xy[0], y = this.xy[1];
30858 var w = this.size.width, h = this.size.height;
30859 var vw = this.viewSize[0], vh = this.viewSize[1];
30860 // only move it if it needs it
30862 // first validate right/bottom
30863 if(x + w > vw+s.left){
30867 if(y + h > vh+s.top){
30871 // then make sure top/left isn't negative
30883 if(this.isVisible()){
30884 this.el.setLocation(x, y);
30885 this.adjustAssets();
30892 onDrag : function(){
30893 if(!this.proxyDrag){
30894 this.xy = this.el.getXY();
30895 this.adjustAssets();
30900 adjustAssets : function(doShow){
30901 var x = this.xy[0], y = this.xy[1];
30902 var w = this.size.width, h = this.size.height;
30903 if(doShow === true){
30905 this.shadow.show(this.el);
30911 if(this.shadow && this.shadow.isVisible()){
30912 this.shadow.show(this.el);
30914 if(this.shim && this.shim.isVisible()){
30915 this.shim.setBounds(x, y, w, h);
30920 adjustViewport : function(w, h){
30922 w = Roo.lib.Dom.getViewWidth();
30923 h = Roo.lib.Dom.getViewHeight();
30926 this.viewSize = [w, h];
30927 if(this.modal && this.mask.isVisible()){
30928 this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
30929 this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
30931 if(this.isVisible()){
30932 this.constrainXY();
30937 * Destroys this dialog and all its supporting elements (including any tabs, shim,
30938 * shadow, proxy, mask, etc.) Also removes all event listeners.
30939 * @param {Boolean} removeEl (optional) true to remove the element from the DOM
30941 destroy : function(removeEl){
30942 if(this.isVisible()){
30943 this.animateTarget = null;
30946 Roo.EventManager.removeResizeListener(this.adjustViewport, this);
30948 this.tabs.destroy(removeEl);
30961 for(var i = 0, len = this.buttons.length; i < len; i++){
30962 this.buttons[i].destroy();
30965 this.el.removeAllListeners();
30966 if(removeEl === true){
30967 this.el.update("");
30970 Roo.DialogManager.unregister(this);
30974 startMove : function(){
30975 if(this.proxyDrag){
30978 if(this.constraintoviewport !== false){
30979 this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
30984 endMove : function(){
30985 if(!this.proxyDrag){
30986 Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
30988 Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
30991 this.refreshSize();
30992 this.adjustAssets();
30994 this.fireEvent("move", this, this.xy[0], this.xy[1]);
30998 * Brings this dialog to the front of any other visible dialogs
30999 * @return {Roo.BasicDialog} this
31001 toFront : function(){
31002 Roo.DialogManager.bringToFront(this);
31007 * Sends this dialog to the back (under) of any other visible dialogs
31008 * @return {Roo.BasicDialog} this
31010 toBack : function(){
31011 Roo.DialogManager.sendToBack(this);
31016 * Centers this dialog in the viewport
31017 * @return {Roo.BasicDialog} this
31019 center : function(){
31020 var xy = this.el.getCenterXY(true);
31021 this.moveTo(xy[0], xy[1]);
31026 * Moves the dialog's top-left corner to the specified point
31027 * @param {Number} x
31028 * @param {Number} y
31029 * @return {Roo.BasicDialog} this
31031 moveTo : function(x, y){
31033 if(this.isVisible()){
31034 this.el.setXY(this.xy);
31035 this.adjustAssets();
31041 * Aligns the dialog to the specified element
31042 * @param {String/HTMLElement/Roo.Element} element The element to align to.
31043 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
31044 * @param {Array} offsets (optional) Offset the positioning by [x, y]
31045 * @return {Roo.BasicDialog} this
31047 alignTo : function(element, position, offsets){
31048 this.xy = this.el.getAlignToXY(element, position, offsets);
31049 if(this.isVisible()){
31050 this.el.setXY(this.xy);
31051 this.adjustAssets();
31057 * Anchors an element to another element and realigns it when the window is resized.
31058 * @param {String/HTMLElement/Roo.Element} element The element to align to.
31059 * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
31060 * @param {Array} offsets (optional) Offset the positioning by [x, y]
31061 * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
31062 * is a number, it is used as the buffer delay (defaults to 50ms).
31063 * @return {Roo.BasicDialog} this
31065 anchorTo : function(el, alignment, offsets, monitorScroll){
31066 var action = function(){
31067 this.alignTo(el, alignment, offsets);
31069 Roo.EventManager.onWindowResize(action, this);
31070 var tm = typeof monitorScroll;
31071 if(tm != 'undefined'){
31072 Roo.EventManager.on(window, 'scroll', action, this,
31073 {buffer: tm == 'number' ? monitorScroll : 50});
31080 * Returns true if the dialog is visible
31081 * @return {Boolean}
31083 isVisible : function(){
31084 return this.el.isVisible();
31088 animHide : function(callback){
31089 var b = Roo.get(this.animateTarget).getBox();
31091 this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
31093 this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
31094 this.hideEl.createDelegate(this, [callback]));
31098 * Hides the dialog.
31099 * @param {Function} callback (optional) Function to call when the dialog is hidden
31100 * @return {Roo.BasicDialog} this
31102 hide : function(callback){
31103 if (this.fireEvent("beforehide", this) === false){
31107 this.shadow.hide();
31112 // sometimes animateTarget seems to get set.. causing problems...
31113 // this just double checks..
31114 if(this.animateTarget && Roo.get(this.animateTarget)) {
31115 this.animHide(callback);
31118 this.hideEl(callback);
31124 hideEl : function(callback){
31128 Roo.get(document.body).removeClass("x-body-masked");
31130 this.fireEvent("hide", this);
31131 if(typeof callback == "function"){
31137 hideAction : function(){
31138 this.setLeft("-10000px");
31139 this.setTop("-10000px");
31140 this.setStyle("visibility", "hidden");
31144 refreshSize : function(){
31145 this.size = this.el.getSize();
31146 this.xy = this.el.getXY();
31147 Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
31151 // z-index is managed by the DialogManager and may be overwritten at any time
31152 setZIndex : function(index){
31154 this.mask.setStyle("z-index", index);
31157 this.shim.setStyle("z-index", ++index);
31160 this.shadow.setZIndex(++index);
31162 this.el.setStyle("z-index", ++index);
31164 this.proxy.setStyle("z-index", ++index);
31167 this.resizer.proxy.setStyle("z-index", ++index);
31170 this.lastZIndex = index;
31174 * Returns the element for this dialog
31175 * @return {Roo.Element} The underlying dialog Element
31177 getEl : function(){
31183 * @class Roo.DialogManager
31184 * Provides global access to BasicDialogs that have been created and
31185 * support for z-indexing (layering) multiple open dialogs.
31187 Roo.DialogManager = function(){
31189 var accessList = [];
31193 var sortDialogs = function(d1, d2){
31194 return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
31198 var orderDialogs = function(){
31199 accessList.sort(sortDialogs);
31200 var seed = Roo.DialogManager.zseed;
31201 for(var i = 0, len = accessList.length; i < len; i++){
31202 var dlg = accessList[i];
31204 dlg.setZIndex(seed + (i*10));
31211 * The starting z-index for BasicDialogs (defaults to 9000)
31212 * @type Number The z-index value
31217 register : function(dlg){
31218 list[dlg.id] = dlg;
31219 accessList.push(dlg);
31223 unregister : function(dlg){
31224 delete list[dlg.id];
31227 if(!accessList.indexOf){
31228 for( i = 0, len = accessList.length; i < len; i++){
31229 if(accessList[i] == dlg){
31230 accessList.splice(i, 1);
31235 i = accessList.indexOf(dlg);
31237 accessList.splice(i, 1);
31243 * Gets a registered dialog by id
31244 * @param {String/Object} id The id of the dialog or a dialog
31245 * @return {Roo.BasicDialog} this
31247 get : function(id){
31248 return typeof id == "object" ? id : list[id];
31252 * Brings the specified dialog to the front
31253 * @param {String/Object} dlg The id of the dialog or a dialog
31254 * @return {Roo.BasicDialog} this
31256 bringToFront : function(dlg){
31257 dlg = this.get(dlg);
31260 dlg._lastAccess = new Date().getTime();
31267 * Sends the specified dialog to the back
31268 * @param {String/Object} dlg The id of the dialog or a dialog
31269 * @return {Roo.BasicDialog} this
31271 sendToBack : function(dlg){
31272 dlg = this.get(dlg);
31273 dlg._lastAccess = -(new Date().getTime());
31279 * Hides all dialogs
31281 hideAll : function(){
31282 for(var id in list){
31283 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
31292 * @class Roo.LayoutDialog
31293 * @extends Roo.BasicDialog
31294 * Dialog which provides adjustments for working with a layout in a Dialog.
31295 * Add your necessary layout config options to the dialog's config.<br>
31296 * Example usage (including a nested layout):
31299 dialog = new Roo.LayoutDialog("download-dlg", {
31308 // layout config merges with the dialog config
31310 tabPosition: "top",
31311 alwaysShowTabs: true
31314 dialog.addKeyListener(27, dialog.hide, dialog);
31315 dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
31316 dialog.addButton("Build It!", this.getDownload, this);
31318 // we can even add nested layouts
31319 var innerLayout = new Roo.BorderLayout("dl-inner", {
31329 innerLayout.beginUpdate();
31330 innerLayout.add("east", new Roo.ContentPanel("dl-details"));
31331 innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
31332 innerLayout.endUpdate(true);
31334 var layout = dialog.getLayout();
31335 layout.beginUpdate();
31336 layout.add("center", new Roo.ContentPanel("standard-panel",
31337 {title: "Download the Source", fitToFrame:true}));
31338 layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
31339 {title: "Build your own roo.js"}));
31340 layout.getRegion("center").showPanel(sp);
31341 layout.endUpdate();
31345 * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
31346 * @param {Object} config configuration options
31348 Roo.LayoutDialog = function(el, cfg){
31351 if (typeof(cfg) == 'undefined') {
31352 config = Roo.apply({}, el);
31353 // not sure why we use documentElement here.. - it should always be body.
31354 // IE7 borks horribly if we use documentElement.
31355 // webkit also does not like documentElement - it creates a body element...
31356 el = Roo.get( document.body || document.documentElement ).createChild();
31357 //config.autoCreate = true;
31361 config.autoTabs = false;
31362 Roo.LayoutDialog.superclass.constructor.call(this, el, config);
31363 this.body.setStyle({overflow:"hidden", position:"relative"});
31364 this.layout = new Roo.BorderLayout(this.body.dom, config);
31365 this.layout.monitorWindowResize = false;
31366 this.el.addClass("x-dlg-auto-layout");
31367 // fix case when center region overwrites center function
31368 this.center = Roo.BasicDialog.prototype.center;
31369 this.on("show", this.layout.layout, this.layout, true);
31370 if (config.items) {
31371 var xitems = config.items;
31372 delete config.items;
31373 Roo.each(xitems, this.addxtype, this);
31378 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
31380 * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
31383 endUpdate : function(){
31384 this.layout.endUpdate();
31388 * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
31391 beginUpdate : function(){
31392 this.layout.beginUpdate();
31396 * Get the BorderLayout for this dialog
31397 * @return {Roo.BorderLayout}
31399 getLayout : function(){
31400 return this.layout;
31403 showEl : function(){
31404 Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
31406 this.layout.layout();
31411 // Use the syncHeightBeforeShow config option to control this automatically
31412 syncBodyHeight : function(){
31413 Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
31414 if(this.layout){this.layout.layout();}
31418 * Add an xtype element (actually adds to the layout.)
31419 * @return {Object} xdata xtype object data.
31422 addxtype : function(c) {
31423 return this.layout.addxtype(c);
31427 * Ext JS Library 1.1.1
31428 * Copyright(c) 2006-2007, Ext JS, LLC.
31430 * Originally Released Under LGPL - original licence link has changed is not relivant.
31433 * <script type="text/javascript">
31437 * @class Roo.MessageBox
31438 * Utility class for generating different styles of message boxes. The alias Roo.Msg can also be used.
31442 Roo.Msg.alert('Status', 'Changes saved successfully.');
31444 // Prompt for user data:
31445 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
31447 // process text value...
31451 // Show a dialog using config options:
31453 title:'Save Changes?',
31454 msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
31455 buttons: Roo.Msg.YESNOCANCEL,
31462 Roo.MessageBox = function(){
31463 var dlg, opt, mask, waitTimer;
31464 var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
31465 var buttons, activeTextEl, bwidth;
31468 var handleButton = function(button){
31470 Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
31474 var handleHide = function(){
31475 if(opt && opt.cls){
31476 dlg.el.removeClass(opt.cls);
31479 Roo.TaskMgr.stop(waitTimer);
31485 var updateButtons = function(b){
31488 buttons["ok"].hide();
31489 buttons["cancel"].hide();
31490 buttons["yes"].hide();
31491 buttons["no"].hide();
31492 dlg.footer.dom.style.display = 'none';
31495 dlg.footer.dom.style.display = '';
31496 for(var k in buttons){
31497 if(typeof buttons[k] != "function"){
31500 buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
31501 width += buttons[k].el.getWidth()+15;
31511 var handleEsc = function(d, k, e){
31512 if(opt && opt.closable !== false){
31522 * Returns a reference to the underlying {@link Roo.BasicDialog} element
31523 * @return {Roo.BasicDialog} The BasicDialog element
31525 getDialog : function(){
31527 dlg = new Roo.BasicDialog("x-msg-box", {
31532 constraintoviewport:false,
31534 collapsible : false,
31537 width:400, height:100,
31538 buttonAlign:"center",
31539 closeClick : function(){
31540 if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
31541 handleButton("no");
31543 handleButton("cancel");
31547 dlg.on("hide", handleHide);
31549 dlg.addKeyListener(27, handleEsc);
31551 var bt = this.buttonText;
31552 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
31553 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
31554 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
31555 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
31556 bodyEl = dlg.body.createChild({
31558 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>'
31560 msgEl = bodyEl.dom.firstChild;
31561 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
31562 textboxEl.enableDisplayMode();
31563 textboxEl.addKeyListener([10,13], function(){
31564 if(dlg.isVisible() && opt && opt.buttons){
31565 if(opt.buttons.ok){
31566 handleButton("ok");
31567 }else if(opt.buttons.yes){
31568 handleButton("yes");
31572 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
31573 textareaEl.enableDisplayMode();
31574 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
31575 progressEl.enableDisplayMode();
31576 var pf = progressEl.dom.firstChild;
31578 pp = Roo.get(pf.firstChild);
31579 pp.setHeight(pf.offsetHeight);
31587 * Updates the message box body text
31588 * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
31589 * the XHTML-compliant non-breaking space character '&#160;')
31590 * @return {Roo.MessageBox} This message box
31592 updateText : function(text){
31593 if(!dlg.isVisible() && !opt.width){
31594 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
31596 msgEl.innerHTML = text || ' ';
31598 var cw = Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
31599 //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
31601 Math.min(opt.width || cw , this.maxWidth),
31602 Math.max(opt.minWidth || this.minWidth, bwidth)
31605 activeTextEl.setWidth(w);
31607 if(dlg.isVisible()){
31608 dlg.fixedcenter = false;
31610 // to big, make it scroll. = But as usual stupid IE does not support
31613 if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
31614 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
31615 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
31617 bodyEl.dom.style.height = '';
31618 bodyEl.dom.style.overflowY = '';
31621 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
31623 bodyEl.dom.style.overflowX = '';
31626 dlg.setContentSize(w, bodyEl.getHeight());
31627 if(dlg.isVisible()){
31628 dlg.fixedcenter = true;
31634 * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
31635 * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
31636 * @param {Number} value Any number between 0 and 1 (e.g., .5)
31637 * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
31638 * @return {Roo.MessageBox} This message box
31640 updateProgress : function(value, text){
31642 this.updateText(text);
31644 if (pp) { // weird bug on my firefox - for some reason this is not defined
31645 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
31651 * Returns true if the message box is currently displayed
31652 * @return {Boolean} True if the message box is visible, else false
31654 isVisible : function(){
31655 return dlg && dlg.isVisible();
31659 * Hides the message box if it is displayed
31662 if(this.isVisible()){
31668 * Displays a new message box, or reinitializes an existing message box, based on the config options
31669 * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
31670 * The following config object properties are supported:
31672 Property Type Description
31673 ---------- --------------- ------------------------------------------------------------------------------------
31674 animEl String/Element An id or Element from which the message box should animate as it opens and
31675 closes (defaults to undefined)
31676 buttons Object/Boolean A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
31677 cancel:'Bar'}), or false to not show any buttons (defaults to false)
31678 closable Boolean False to hide the top-right close button (defaults to true). Note that
31679 progress and wait dialogs will ignore this property and always hide the
31680 close button as they can only be closed programmatically.
31681 cls String A custom CSS class to apply to the message box element
31682 defaultTextHeight Number The default height in pixels of the message box's multiline textarea if
31683 displayed (defaults to 75)
31684 fn Function A callback function to execute after closing the dialog. The arguments to the
31685 function will be btn (the name of the button that was clicked, if applicable,
31686 e.g. "ok"), and text (the value of the active text field, if applicable).
31687 Progress and wait dialogs will ignore this option since they do not respond to
31688 user actions and can only be closed programmatically, so any required function
31689 should be called by the same code after it closes the dialog.
31690 icon String A CSS class that provides a background image to be used as an icon for
31691 the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
31692 maxWidth Number The maximum width in pixels of the message box (defaults to 600)
31693 minWidth Number The minimum width in pixels of the message box (defaults to 100)
31694 modal Boolean False to allow user interaction with the page while the message box is
31695 displayed (defaults to true)
31696 msg String A string that will replace the existing message box body text (defaults
31697 to the XHTML-compliant non-breaking space character ' ')
31698 multiline Boolean True to prompt the user to enter multi-line text (defaults to false)
31699 progress Boolean True to display a progress bar (defaults to false)
31700 progressText String The text to display inside the progress bar if progress = true (defaults to '')
31701 prompt Boolean True to prompt the user to enter single-line text (defaults to false)
31702 proxyDrag Boolean True to display a lightweight proxy while dragging (defaults to false)
31703 title String The title text
31704 value String The string value to set into the active textbox element if displayed
31705 wait Boolean True to display a progress bar (defaults to false)
31706 width Number The width of the dialog in pixels
31713 msg: 'Please enter your address:',
31715 buttons: Roo.MessageBox.OKCANCEL,
31718 animEl: 'addAddressBtn'
31721 * @param {Object} config Configuration options
31722 * @return {Roo.MessageBox} This message box
31724 show : function(options)
31727 // this causes nightmares if you show one dialog after another
31728 // especially on callbacks..
31730 if(this.isVisible()){
31733 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
31734 Roo.log("Old Dialog Message:" + msgEl.innerHTML );
31735 Roo.log("New Dialog Message:" + options.msg )
31736 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
31737 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
31740 var d = this.getDialog();
31742 d.setTitle(opt.title || " ");
31743 d.close.setDisplayed(opt.closable !== false);
31744 activeTextEl = textboxEl;
31745 opt.prompt = opt.prompt || (opt.multiline ? true : false);
31750 textareaEl.setHeight(typeof opt.multiline == "number" ?
31751 opt.multiline : this.defaultTextHeight);
31752 activeTextEl = textareaEl;
31761 progressEl.setDisplayed(opt.progress === true);
31762 this.updateProgress(0);
31763 activeTextEl.dom.value = opt.value || "";
31765 dlg.setDefaultButton(activeTextEl);
31767 var bs = opt.buttons;
31770 db = buttons["ok"];
31771 }else if(bs && bs.yes){
31772 db = buttons["yes"];
31774 dlg.setDefaultButton(db);
31776 bwidth = updateButtons(opt.buttons);
31777 this.updateText(opt.msg);
31779 d.el.addClass(opt.cls);
31781 d.proxyDrag = opt.proxyDrag === true;
31782 d.modal = opt.modal !== false;
31783 d.mask = opt.modal !== false ? mask : false;
31784 if(!d.isVisible()){
31785 // force it to the end of the z-index stack so it gets a cursor in FF
31786 document.body.appendChild(dlg.el.dom);
31787 d.animateTarget = null;
31788 d.show(options.animEl);
31794 * Displays a message box with a progress bar. This message box has no buttons and is not closeable by
31795 * the user. You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
31796 * and closing the message box when the process is complete.
31797 * @param {String} title The title bar text
31798 * @param {String} msg The message box body text
31799 * @return {Roo.MessageBox} This message box
31801 progress : function(title, msg){
31808 minWidth: this.minProgressWidth,
31815 * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
31816 * If a callback function is passed it will be called after the user clicks the button, and the
31817 * id of the button that was clicked will be passed as the only parameter to the callback
31818 * (could also be the top-right close button).
31819 * @param {String} title The title bar text
31820 * @param {String} msg The message box body text
31821 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31822 * @param {Object} scope (optional) The scope of the callback function
31823 * @return {Roo.MessageBox} This message box
31825 alert : function(title, msg, fn, scope){
31838 * Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
31839 * interaction while waiting for a long-running process to complete that does not have defined intervals.
31840 * You are responsible for closing the message box when the process is complete.
31841 * @param {String} msg The message box body text
31842 * @param {String} title (optional) The title bar text
31843 * @return {Roo.MessageBox} This message box
31845 wait : function(msg, title){
31856 waitTimer = Roo.TaskMgr.start({
31858 Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
31866 * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
31867 * If a callback function is passed it will be called after the user clicks either button, and the id of the
31868 * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
31869 * @param {String} title The title bar text
31870 * @param {String} msg The message box body text
31871 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31872 * @param {Object} scope (optional) The scope of the callback function
31873 * @return {Roo.MessageBox} This message box
31875 confirm : function(title, msg, fn, scope){
31879 buttons: this.YESNO,
31888 * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
31889 * JavaScript's Window.prompt). The prompt can be a single-line or multi-line textbox. If a callback function
31890 * is passed it will be called after the user clicks either button, and the id of the button that was clicked
31891 * (could also be the top-right close button) and the text that was entered will be passed as the two
31892 * parameters to the callback.
31893 * @param {String} title The title bar text
31894 * @param {String} msg The message box body text
31895 * @param {Function} fn (optional) The callback function invoked after the message box is closed
31896 * @param {Object} scope (optional) The scope of the callback function
31897 * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
31898 * property, or the height in pixels to create the textbox (defaults to false / single-line)
31899 * @return {Roo.MessageBox} This message box
31901 prompt : function(title, msg, fn, scope, multiline){
31905 buttons: this.OKCANCEL,
31910 multiline: multiline,
31917 * Button config that displays a single OK button
31922 * Button config that displays Yes and No buttons
31925 YESNO : {yes:true, no:true},
31927 * Button config that displays OK and Cancel buttons
31930 OKCANCEL : {ok:true, cancel:true},
31932 * Button config that displays Yes, No and Cancel buttons
31935 YESNOCANCEL : {yes:true, no:true, cancel:true},
31938 * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
31941 defaultTextHeight : 75,
31943 * The maximum width in pixels of the message box (defaults to 600)
31948 * The minimum width in pixels of the message box (defaults to 100)
31953 * The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
31954 * for setting a different minimum width than text-only dialogs may need (defaults to 250)
31957 minProgressWidth : 250,
31959 * An object containing the default button text strings that can be overriden for localized language support.
31960 * Supported properties are: ok, cancel, yes and no.
31961 * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
31974 * Shorthand for {@link Roo.MessageBox}
31976 Roo.Msg = Roo.MessageBox;/*
31978 * Ext JS Library 1.1.1
31979 * Copyright(c) 2006-2007, Ext JS, LLC.
31981 * Originally Released Under LGPL - original licence link has changed is not relivant.
31984 * <script type="text/javascript">
31987 * @class Roo.QuickTips
31988 * Provides attractive and customizable tooltips for any element.
31991 Roo.QuickTips = function(){
31992 var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
31993 var ce, bd, xy, dd;
31994 var visible = false, disabled = true, inited = false;
31995 var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
31997 var onOver = function(e){
32001 var t = e.getTarget();
32002 if(!t || t.nodeType !== 1 || t == document || t == document.body){
32005 if(ce && t == ce.el){
32006 clearTimeout(hideProc);
32009 if(t && tagEls[t.id]){
32010 tagEls[t.id].el = t;
32011 showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
32014 var ttp, et = Roo.fly(t);
32015 var ns = cfg.namespace;
32016 if(tm.interceptTitles && t.title){
32019 t.removeAttribute("title");
32020 e.preventDefault();
32022 ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
32025 showProc = show.defer(tm.showDelay, tm, [{
32028 width: et.getAttributeNS(ns, cfg.width),
32029 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
32030 title: et.getAttributeNS(ns, cfg.title),
32031 cls: et.getAttributeNS(ns, cfg.cls)
32036 var onOut = function(e){
32037 clearTimeout(showProc);
32038 var t = e.getTarget();
32039 if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
32040 hideProc = setTimeout(hide, tm.hideDelay);
32044 var onMove = function(e){
32050 if(tm.trackMouse && ce){
32055 var onDown = function(e){
32056 clearTimeout(showProc);
32057 clearTimeout(hideProc);
32059 if(tm.hideOnClick){
32062 tm.enable.defer(100, tm);
32067 var getPad = function(){
32068 return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
32071 var show = function(o){
32075 clearTimeout(dismissProc);
32077 if(removeCls){ // in case manually hidden
32078 el.removeClass(removeCls);
32082 el.addClass(ce.cls);
32083 removeCls = ce.cls;
32086 tipTitle.update(ce.title);
32089 tipTitle.update('');
32092 el.dom.style.width = tm.maxWidth+'px';
32093 //tipBody.dom.style.width = '';
32094 tipBodyText.update(o.text);
32095 var p = getPad(), w = ce.width;
32097 var td = tipBodyText.dom;
32098 var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
32099 if(aw > tm.maxWidth){
32101 }else if(aw < tm.minWidth){
32107 //tipBody.setWidth(w);
32108 el.setWidth(parseInt(w, 10) + p);
32109 if(ce.autoHide === false){
32110 close.setDisplayed(true);
32115 close.setDisplayed(false);
32121 el.avoidY = xy[1]-18;
32126 el.setStyle("visibility", "visible");
32127 el.fadeIn({callback: afterShow});
32133 var afterShow = function(){
32137 if(tm.autoDismiss && ce.autoHide !== false){
32138 dismissProc = setTimeout(hide, tm.autoDismissDelay);
32143 var hide = function(noanim){
32144 clearTimeout(dismissProc);
32145 clearTimeout(hideProc);
32147 if(el.isVisible()){
32149 if(noanim !== true && tm.animate){
32150 el.fadeOut({callback: afterHide});
32157 var afterHide = function(){
32160 el.removeClass(removeCls);
32167 * @cfg {Number} minWidth
32168 * The minimum width of the quick tip (defaults to 40)
32172 * @cfg {Number} maxWidth
32173 * The maximum width of the quick tip (defaults to 300)
32177 * @cfg {Boolean} interceptTitles
32178 * True to automatically use the element's DOM title value if available (defaults to false)
32180 interceptTitles : false,
32182 * @cfg {Boolean} trackMouse
32183 * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
32185 trackMouse : false,
32187 * @cfg {Boolean} hideOnClick
32188 * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
32190 hideOnClick : true,
32192 * @cfg {Number} showDelay
32193 * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
32197 * @cfg {Number} hideDelay
32198 * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
32202 * @cfg {Boolean} autoHide
32203 * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
32204 * Used in conjunction with hideDelay.
32209 * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
32210 * (defaults to true). Used in conjunction with autoDismissDelay.
32212 autoDismiss : true,
32215 * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
32217 autoDismissDelay : 5000,
32219 * @cfg {Boolean} animate
32220 * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
32225 * @cfg {String} title
32226 * Title text to display (defaults to ''). This can be any valid HTML markup.
32230 * @cfg {String} text
32231 * Body text to display (defaults to ''). This can be any valid HTML markup.
32235 * @cfg {String} cls
32236 * A CSS class to apply to the base quick tip element (defaults to '').
32240 * @cfg {Number} width
32241 * Width in pixels of the quick tip (defaults to auto). Width will be ignored if it exceeds the bounds of
32242 * minWidth or maxWidth.
32247 * Initialize and enable QuickTips for first use. This should be called once before the first attempt to access
32248 * or display QuickTips in a page.
32251 tm = Roo.QuickTips;
32252 cfg = tm.tagConfig;
32254 if(!Roo.isReady){ // allow calling of init() before onReady
32255 Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
32258 el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
32259 el.fxDefaults = {stopFx: true};
32260 // maximum custom styling
32261 //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>');
32262 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>');
32263 tipTitle = el.child('h3');
32264 tipTitle.enableDisplayMode("block");
32265 tipBody = el.child('div.x-tip-bd');
32266 tipBodyText = el.child('div.x-tip-bd-inner');
32267 //bdLeft = el.child('div.x-tip-bd-left');
32268 //bdRight = el.child('div.x-tip-bd-right');
32269 close = el.child('div.x-tip-close');
32270 close.enableDisplayMode("block");
32271 close.on("click", hide);
32272 var d = Roo.get(document);
32273 d.on("mousedown", onDown);
32274 d.on("mouseover", onOver);
32275 d.on("mouseout", onOut);
32276 d.on("mousemove", onMove);
32277 esc = d.addKeyListener(27, hide);
32280 dd = el.initDD("default", null, {
32281 onDrag : function(){
32285 dd.setHandleElId(tipTitle.id);
32294 * Configures a new quick tip instance and assigns it to a target element. The following config options
32297 Property Type Description
32298 ---------- --------------------- ------------------------------------------------------------------------
32299 target Element/String/Array An Element, id or array of ids that this quick tip should be tied to
32301 * @param {Object} config The config object
32303 register : function(config){
32304 var cs = config instanceof Array ? config : arguments;
32305 for(var i = 0, len = cs.length; i < len; i++) {
32307 var target = c.target;
32309 if(target instanceof Array){
32310 for(var j = 0, jlen = target.length; j < jlen; j++){
32311 tagEls[target[j]] = c;
32314 tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
32321 * Removes this quick tip from its element and destroys it.
32322 * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
32324 unregister : function(el){
32325 delete tagEls[Roo.id(el)];
32329 * Enable this quick tip.
32331 enable : function(){
32332 if(inited && disabled){
32334 if(locks.length < 1){
32341 * Disable this quick tip.
32343 disable : function(){
32345 clearTimeout(showProc);
32346 clearTimeout(hideProc);
32347 clearTimeout(dismissProc);
32355 * Returns true if the quick tip is enabled, else false.
32357 isEnabled : function(){
32364 attribute : "qtip",
32374 // backwards compat
32375 Roo.QuickTips.tips = Roo.QuickTips.register;/*
32377 * Ext JS Library 1.1.1
32378 * Copyright(c) 2006-2007, Ext JS, LLC.
32380 * Originally Released Under LGPL - original licence link has changed is not relivant.
32383 * <script type="text/javascript">
32388 * @class Roo.tree.TreePanel
32389 * @extends Roo.data.Tree
32391 * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
32392 * @cfg {Boolean} lines false to disable tree lines (defaults to true)
32393 * @cfg {Boolean} enableDD true to enable drag and drop
32394 * @cfg {Boolean} enableDrag true to enable just drag
32395 * @cfg {Boolean} enableDrop true to enable just drop
32396 * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
32397 * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
32398 * @cfg {String} ddGroup The DD group this TreePanel belongs to
32399 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
32400 * @cfg {Boolean} ddScroll true to enable YUI body scrolling
32401 * @cfg {Boolean} containerScroll true to register this container with ScrollManager
32402 * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
32403 * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
32404 * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
32405 * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
32406 * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
32407 * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
32408 * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
32409 * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
32410 * @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>
32411 * @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>
32414 * @param {String/HTMLElement/Element} el The container element
32415 * @param {Object} config
32417 Roo.tree.TreePanel = function(el, config){
32419 var loader = false;
32421 root = config.root;
32422 delete config.root;
32424 if (config.loader) {
32425 loader = config.loader;
32426 delete config.loader;
32429 Roo.apply(this, config);
32430 Roo.tree.TreePanel.superclass.constructor.call(this);
32431 this.el = Roo.get(el);
32432 this.el.addClass('x-tree');
32433 //console.log(root);
32435 this.setRootNode( Roo.factory(root, Roo.tree));
32438 this.loader = Roo.factory(loader, Roo.tree);
32441 * Read-only. The id of the container element becomes this TreePanel's id.
32443 this.id = this.el.id;
32446 * @event beforeload
32447 * Fires before a node is loaded, return false to cancel
32448 * @param {Node} node The node being loaded
32450 "beforeload" : true,
32453 * Fires when a node is loaded
32454 * @param {Node} node The node that was loaded
32458 * @event textchange
32459 * Fires when the text for a node is changed
32460 * @param {Node} node The node
32461 * @param {String} text The new text
32462 * @param {String} oldText The old text
32464 "textchange" : true,
32466 * @event beforeexpand
32467 * Fires before a node is expanded, return false to cancel.
32468 * @param {Node} node The node
32469 * @param {Boolean} deep
32470 * @param {Boolean} anim
32472 "beforeexpand" : true,
32474 * @event beforecollapse
32475 * Fires before a node is collapsed, return false to cancel.
32476 * @param {Node} node The node
32477 * @param {Boolean} deep
32478 * @param {Boolean} anim
32480 "beforecollapse" : true,
32483 * Fires when a node is expanded
32484 * @param {Node} node The node
32488 * @event disabledchange
32489 * Fires when the disabled status of a node changes
32490 * @param {Node} node The node
32491 * @param {Boolean} disabled
32493 "disabledchange" : true,
32496 * Fires when a node is collapsed
32497 * @param {Node} node The node
32501 * @event beforeclick
32502 * Fires before click processing on a node. Return false to cancel the default action.
32503 * @param {Node} node The node
32504 * @param {Roo.EventObject} e The event object
32506 "beforeclick":true,
32508 * @event checkchange
32509 * Fires when a node with a checkbox's checked property changes
32510 * @param {Node} this This node
32511 * @param {Boolean} checked
32513 "checkchange":true,
32516 * Fires when a node is clicked
32517 * @param {Node} node The node
32518 * @param {Roo.EventObject} e The event object
32523 * Fires when a node is double clicked
32524 * @param {Node} node The node
32525 * @param {Roo.EventObject} e The event object
32529 * @event contextmenu
32530 * Fires when a node is right clicked
32531 * @param {Node} node The node
32532 * @param {Roo.EventObject} e The event object
32534 "contextmenu":true,
32536 * @event beforechildrenrendered
32537 * Fires right before the child nodes for a node are rendered
32538 * @param {Node} node The node
32540 "beforechildrenrendered":true,
32543 * Fires when a node starts being dragged
32544 * @param {Roo.tree.TreePanel} this
32545 * @param {Roo.tree.TreeNode} node
32546 * @param {event} e The raw browser event
32548 "startdrag" : true,
32551 * Fires when a drag operation is complete
32552 * @param {Roo.tree.TreePanel} this
32553 * @param {Roo.tree.TreeNode} node
32554 * @param {event} e The raw browser event
32559 * Fires when a dragged node is dropped on a valid DD target
32560 * @param {Roo.tree.TreePanel} this
32561 * @param {Roo.tree.TreeNode} node
32562 * @param {DD} dd The dd it was dropped on
32563 * @param {event} e The raw browser event
32567 * @event beforenodedrop
32568 * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
32569 * passed to handlers has the following properties:<br />
32570 * <ul style="padding:5px;padding-left:16px;">
32571 * <li>tree - The TreePanel</li>
32572 * <li>target - The node being targeted for the drop</li>
32573 * <li>data - The drag data from the drag source</li>
32574 * <li>point - The point of the drop - append, above or below</li>
32575 * <li>source - The drag source</li>
32576 * <li>rawEvent - Raw mouse event</li>
32577 * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
32578 * to be inserted by setting them on this object.</li>
32579 * <li>cancel - Set this to true to cancel the drop.</li>
32581 * @param {Object} dropEvent
32583 "beforenodedrop" : true,
32586 * Fires after a DD object is dropped on a node in this tree. The dropEvent
32587 * passed to handlers has the following properties:<br />
32588 * <ul style="padding:5px;padding-left:16px;">
32589 * <li>tree - The TreePanel</li>
32590 * <li>target - The node being targeted for the drop</li>
32591 * <li>data - The drag data from the drag source</li>
32592 * <li>point - The point of the drop - append, above or below</li>
32593 * <li>source - The drag source</li>
32594 * <li>rawEvent - Raw mouse event</li>
32595 * <li>dropNode - Dropped node(s).</li>
32597 * @param {Object} dropEvent
32601 * @event nodedragover
32602 * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
32603 * passed to handlers has the following properties:<br />
32604 * <ul style="padding:5px;padding-left:16px;">
32605 * <li>tree - The TreePanel</li>
32606 * <li>target - The node being targeted for the drop</li>
32607 * <li>data - The drag data from the drag source</li>
32608 * <li>point - The point of the drop - append, above or below</li>
32609 * <li>source - The drag source</li>
32610 * <li>rawEvent - Raw mouse event</li>
32611 * <li>dropNode - Drop node(s) provided by the source.</li>
32612 * <li>cancel - Set this to true to signal drop not allowed.</li>
32614 * @param {Object} dragOverEvent
32616 "nodedragover" : true
32619 if(this.singleExpand){
32620 this.on("beforeexpand", this.restrictExpand, this);
32623 this.editor.tree = this;
32624 this.editor = Roo.factory(this.editor, Roo.tree);
32627 if (this.selModel) {
32628 this.selModel = Roo.factory(this.selModel, Roo.tree);
32632 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
32633 rootVisible : true,
32634 animate: Roo.enableFx,
32637 hlDrop : Roo.enableFx,
32641 rendererTip: false,
32643 restrictExpand : function(node){
32644 var p = node.parentNode;
32646 if(p.expandedChild && p.expandedChild.parentNode == p){
32647 p.expandedChild.collapse();
32649 p.expandedChild = node;
32653 // private override
32654 setRootNode : function(node){
32655 Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
32656 if(!this.rootVisible){
32657 node.ui = new Roo.tree.RootTreeNodeUI(node);
32663 * Returns the container element for this TreePanel
32665 getEl : function(){
32670 * Returns the default TreeLoader for this TreePanel
32672 getLoader : function(){
32673 return this.loader;
32679 expandAll : function(){
32680 this.root.expand(true);
32684 * Collapse all nodes
32686 collapseAll : function(){
32687 this.root.collapse(true);
32691 * Returns the selection model used by this TreePanel
32693 getSelectionModel : function(){
32694 if(!this.selModel){
32695 this.selModel = new Roo.tree.DefaultSelectionModel();
32697 return this.selModel;
32701 * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
32702 * @param {String} attribute (optional) Defaults to null (return the actual nodes)
32703 * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
32706 getChecked : function(a, startNode){
32707 startNode = startNode || this.root;
32709 var f = function(){
32710 if(this.attributes.checked){
32711 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
32714 startNode.cascade(f);
32719 * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
32720 * @param {String} path
32721 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
32722 * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
32723 * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
32725 expandPath : function(path, attr, callback){
32726 attr = attr || "id";
32727 var keys = path.split(this.pathSeparator);
32728 var curNode = this.root;
32729 if(curNode.attributes[attr] != keys[1]){ // invalid root
32731 callback(false, null);
32736 var f = function(){
32737 if(++index == keys.length){
32739 callback(true, curNode);
32743 var c = curNode.findChild(attr, keys[index]);
32746 callback(false, curNode);
32751 c.expand(false, false, f);
32753 curNode.expand(false, false, f);
32757 * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
32758 * @param {String} path
32759 * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
32760 * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
32761 * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
32763 selectPath : function(path, attr, callback){
32764 attr = attr || "id";
32765 var keys = path.split(this.pathSeparator);
32766 var v = keys.pop();
32767 if(keys.length > 0){
32768 var f = function(success, node){
32769 if(success && node){
32770 var n = node.findChild(attr, v);
32776 }else if(callback){
32777 callback(false, n);
32781 callback(false, n);
32785 this.expandPath(keys.join(this.pathSeparator), attr, f);
32787 this.root.select();
32789 callback(true, this.root);
32794 getTreeEl : function(){
32799 * Trigger rendering of this TreePanel
32801 render : function(){
32802 if (this.innerCt) {
32803 return this; // stop it rendering more than once!!
32806 this.innerCt = this.el.createChild({tag:"ul",
32807 cls:"x-tree-root-ct " +
32808 (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
32810 if(this.containerScroll){
32811 Roo.dd.ScrollManager.register(this.el);
32813 if((this.enableDD || this.enableDrop) && !this.dropZone){
32815 * The dropZone used by this tree if drop is enabled
32816 * @type Roo.tree.TreeDropZone
32818 this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
32819 ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
32822 if((this.enableDD || this.enableDrag) && !this.dragZone){
32824 * The dragZone used by this tree if drag is enabled
32825 * @type Roo.tree.TreeDragZone
32827 this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
32828 ddGroup: this.ddGroup || "TreeDD",
32829 scroll: this.ddScroll
32832 this.getSelectionModel().init(this);
32834 Roo.log("ROOT not set in tree");
32837 this.root.render();
32838 if(!this.rootVisible){
32839 this.root.renderChildren();
32845 * Ext JS Library 1.1.1
32846 * Copyright(c) 2006-2007, Ext JS, LLC.
32848 * Originally Released Under LGPL - original licence link has changed is not relivant.
32851 * <script type="text/javascript">
32856 * @class Roo.tree.DefaultSelectionModel
32857 * @extends Roo.util.Observable
32858 * The default single selection for a TreePanel.
32859 * @param {Object} cfg Configuration
32861 Roo.tree.DefaultSelectionModel = function(cfg){
32862 this.selNode = null;
32868 * @event selectionchange
32869 * Fires when the selected node changes
32870 * @param {DefaultSelectionModel} this
32871 * @param {TreeNode} node the new selection
32873 "selectionchange" : true,
32876 * @event beforeselect
32877 * Fires before the selected node changes, return false to cancel the change
32878 * @param {DefaultSelectionModel} this
32879 * @param {TreeNode} node the new selection
32880 * @param {TreeNode} node the old selection
32882 "beforeselect" : true
32885 Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
32888 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
32889 init : function(tree){
32891 tree.getTreeEl().on("keydown", this.onKeyDown, this);
32892 tree.on("click", this.onNodeClick, this);
32895 onNodeClick : function(node, e){
32896 if (e.ctrlKey && this.selNode == node) {
32897 this.unselect(node);
32905 * @param {TreeNode} node The node to select
32906 * @return {TreeNode} The selected node
32908 select : function(node){
32909 var last = this.selNode;
32910 if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
32912 last.ui.onSelectedChange(false);
32914 this.selNode = node;
32915 node.ui.onSelectedChange(true);
32916 this.fireEvent("selectionchange", this, node, last);
32923 * @param {TreeNode} node The node to unselect
32925 unselect : function(node){
32926 if(this.selNode == node){
32927 this.clearSelections();
32932 * Clear all selections
32934 clearSelections : function(){
32935 var n = this.selNode;
32937 n.ui.onSelectedChange(false);
32938 this.selNode = null;
32939 this.fireEvent("selectionchange", this, null);
32945 * Get the selected node
32946 * @return {TreeNode} The selected node
32948 getSelectedNode : function(){
32949 return this.selNode;
32953 * Returns true if the node is selected
32954 * @param {TreeNode} node The node to check
32955 * @return {Boolean}
32957 isSelected : function(node){
32958 return this.selNode == node;
32962 * Selects the node above the selected node in the tree, intelligently walking the nodes
32963 * @return TreeNode The new selection
32965 selectPrevious : function(){
32966 var s = this.selNode || this.lastSelNode;
32970 var ps = s.previousSibling;
32972 if(!ps.isExpanded() || ps.childNodes.length < 1){
32973 return this.select(ps);
32975 var lc = ps.lastChild;
32976 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
32979 return this.select(lc);
32981 } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
32982 return this.select(s.parentNode);
32988 * Selects the node above the selected node in the tree, intelligently walking the nodes
32989 * @return TreeNode The new selection
32991 selectNext : function(){
32992 var s = this.selNode || this.lastSelNode;
32996 if(s.firstChild && s.isExpanded()){
32997 return this.select(s.firstChild);
32998 }else if(s.nextSibling){
32999 return this.select(s.nextSibling);
33000 }else if(s.parentNode){
33002 s.parentNode.bubble(function(){
33003 if(this.nextSibling){
33004 newS = this.getOwnerTree().selModel.select(this.nextSibling);
33013 onKeyDown : function(e){
33014 var s = this.selNode || this.lastSelNode;
33015 // undesirable, but required
33020 var k = e.getKey();
33028 this.selectPrevious();
33031 e.preventDefault();
33032 if(s.hasChildNodes()){
33033 if(!s.isExpanded()){
33035 }else if(s.firstChild){
33036 this.select(s.firstChild, e);
33041 e.preventDefault();
33042 if(s.hasChildNodes() && s.isExpanded()){
33044 }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
33045 this.select(s.parentNode, e);
33053 * @class Roo.tree.MultiSelectionModel
33054 * @extends Roo.util.Observable
33055 * Multi selection for a TreePanel.
33056 * @param {Object} cfg Configuration
33058 Roo.tree.MultiSelectionModel = function(){
33059 this.selNodes = [];
33063 * @event selectionchange
33064 * Fires when the selected nodes change
33065 * @param {MultiSelectionModel} this
33066 * @param {Array} nodes Array of the selected nodes
33068 "selectionchange" : true
33070 Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
33074 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
33075 init : function(tree){
33077 tree.getTreeEl().on("keydown", this.onKeyDown, this);
33078 tree.on("click", this.onNodeClick, this);
33081 onNodeClick : function(node, e){
33082 this.select(node, e, e.ctrlKey);
33087 * @param {TreeNode} node The node to select
33088 * @param {EventObject} e (optional) An event associated with the selection
33089 * @param {Boolean} keepExisting True to retain existing selections
33090 * @return {TreeNode} The selected node
33092 select : function(node, e, keepExisting){
33093 if(keepExisting !== true){
33094 this.clearSelections(true);
33096 if(this.isSelected(node)){
33097 this.lastSelNode = node;
33100 this.selNodes.push(node);
33101 this.selMap[node.id] = node;
33102 this.lastSelNode = node;
33103 node.ui.onSelectedChange(true);
33104 this.fireEvent("selectionchange", this, this.selNodes);
33110 * @param {TreeNode} node The node to unselect
33112 unselect : function(node){
33113 if(this.selMap[node.id]){
33114 node.ui.onSelectedChange(false);
33115 var sn = this.selNodes;
33118 index = sn.indexOf(node);
33120 for(var i = 0, len = sn.length; i < len; i++){
33128 this.selNodes.splice(index, 1);
33130 delete this.selMap[node.id];
33131 this.fireEvent("selectionchange", this, this.selNodes);
33136 * Clear all selections
33138 clearSelections : function(suppressEvent){
33139 var sn = this.selNodes;
33141 for(var i = 0, len = sn.length; i < len; i++){
33142 sn[i].ui.onSelectedChange(false);
33144 this.selNodes = [];
33146 if(suppressEvent !== true){
33147 this.fireEvent("selectionchange", this, this.selNodes);
33153 * Returns true if the node is selected
33154 * @param {TreeNode} node The node to check
33155 * @return {Boolean}
33157 isSelected : function(node){
33158 return this.selMap[node.id] ? true : false;
33162 * Returns an array of the selected nodes
33165 getSelectedNodes : function(){
33166 return this.selNodes;
33169 onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
33171 selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
33173 selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
33176 * Ext JS Library 1.1.1
33177 * Copyright(c) 2006-2007, Ext JS, LLC.
33179 * Originally Released Under LGPL - original licence link has changed is not relivant.
33182 * <script type="text/javascript">
33186 * @class Roo.tree.TreeNode
33187 * @extends Roo.data.Node
33188 * @cfg {String} text The text for this node
33189 * @cfg {Boolean} expanded true to start the node expanded
33190 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
33191 * @cfg {Boolean} allowDrop false if this node cannot be drop on
33192 * @cfg {Boolean} disabled true to start the node disabled
33193 * @cfg {String} icon The path to an icon for the node. The preferred way to do this
33194 * is to use the cls or iconCls attributes and add the icon via a CSS background image.
33195 * @cfg {String} cls A css class to be added to the node
33196 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
33197 * @cfg {String} href URL of the link used for the node (defaults to #)
33198 * @cfg {String} hrefTarget target frame for the link
33199 * @cfg {String} qtip An Ext QuickTip for the node
33200 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
33201 * @cfg {Boolean} singleClickExpand True for single click expand on this node
33202 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
33203 * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
33204 * (defaults to undefined with no checkbox rendered)
33206 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
33208 Roo.tree.TreeNode = function(attributes){
33209 attributes = attributes || {};
33210 if(typeof attributes == "string"){
33211 attributes = {text: attributes};
33213 this.childrenRendered = false;
33214 this.rendered = false;
33215 Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
33216 this.expanded = attributes.expanded === true;
33217 this.isTarget = attributes.isTarget !== false;
33218 this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
33219 this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
33222 * Read-only. The text for this node. To change it use setText().
33225 this.text = attributes.text;
33227 * True if this node is disabled.
33230 this.disabled = attributes.disabled === true;
33234 * @event textchange
33235 * Fires when the text for this node is changed
33236 * @param {Node} this This node
33237 * @param {String} text The new text
33238 * @param {String} oldText The old text
33240 "textchange" : true,
33242 * @event beforeexpand
33243 * Fires before this node is expanded, return false to cancel.
33244 * @param {Node} this This node
33245 * @param {Boolean} deep
33246 * @param {Boolean} anim
33248 "beforeexpand" : true,
33250 * @event beforecollapse
33251 * Fires before this node is collapsed, return false to cancel.
33252 * @param {Node} this This node
33253 * @param {Boolean} deep
33254 * @param {Boolean} anim
33256 "beforecollapse" : true,
33259 * Fires when this node is expanded
33260 * @param {Node} this This node
33264 * @event disabledchange
33265 * Fires when the disabled status of this node changes
33266 * @param {Node} this This node
33267 * @param {Boolean} disabled
33269 "disabledchange" : true,
33272 * Fires when this node is collapsed
33273 * @param {Node} this This node
33277 * @event beforeclick
33278 * Fires before click processing. Return false to cancel the default action.
33279 * @param {Node} this This node
33280 * @param {Roo.EventObject} e The event object
33282 "beforeclick":true,
33284 * @event checkchange
33285 * Fires when a node with a checkbox's checked property changes
33286 * @param {Node} this This node
33287 * @param {Boolean} checked
33289 "checkchange":true,
33292 * Fires when this node is clicked
33293 * @param {Node} this This node
33294 * @param {Roo.EventObject} e The event object
33299 * Fires when this node is double clicked
33300 * @param {Node} this This node
33301 * @param {Roo.EventObject} e The event object
33305 * @event contextmenu
33306 * Fires when this node is right clicked
33307 * @param {Node} this This node
33308 * @param {Roo.EventObject} e The event object
33310 "contextmenu":true,
33312 * @event beforechildrenrendered
33313 * Fires right before the child nodes for this node are rendered
33314 * @param {Node} this This node
33316 "beforechildrenrendered":true
33319 var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
33322 * Read-only. The UI for this node
33325 this.ui = new uiClass(this);
33327 // finally support items[]
33328 if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
33333 Roo.each(this.attributes.items, function(c) {
33334 this.appendChild(Roo.factory(c,Roo.Tree));
33336 delete this.attributes.items;
33341 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
33342 preventHScroll: true,
33344 * Returns true if this node is expanded
33345 * @return {Boolean}
33347 isExpanded : function(){
33348 return this.expanded;
33352 * Returns the UI object for this node
33353 * @return {TreeNodeUI}
33355 getUI : function(){
33359 // private override
33360 setFirstChild : function(node){
33361 var of = this.firstChild;
33362 Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
33363 if(this.childrenRendered && of && node != of){
33364 of.renderIndent(true, true);
33367 this.renderIndent(true, true);
33371 // private override
33372 setLastChild : function(node){
33373 var ol = this.lastChild;
33374 Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
33375 if(this.childrenRendered && ol && node != ol){
33376 ol.renderIndent(true, true);
33379 this.renderIndent(true, true);
33383 // these methods are overridden to provide lazy rendering support
33384 // private override
33385 appendChild : function()
33387 var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
33388 if(node && this.childrenRendered){
33391 this.ui.updateExpandIcon();
33395 // private override
33396 removeChild : function(node){
33397 this.ownerTree.getSelectionModel().unselect(node);
33398 Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
33399 // if it's been rendered remove dom node
33400 if(this.childrenRendered){
33403 if(this.childNodes.length < 1){
33404 this.collapse(false, false);
33406 this.ui.updateExpandIcon();
33408 if(!this.firstChild) {
33409 this.childrenRendered = false;
33414 // private override
33415 insertBefore : function(node, refNode){
33416 var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
33417 if(newNode && refNode && this.childrenRendered){
33420 this.ui.updateExpandIcon();
33425 * Sets the text for this node
33426 * @param {String} text
33428 setText : function(text){
33429 var oldText = this.text;
33431 this.attributes.text = text;
33432 if(this.rendered){ // event without subscribing
33433 this.ui.onTextChange(this, text, oldText);
33435 this.fireEvent("textchange", this, text, oldText);
33439 * Triggers selection of this node
33441 select : function(){
33442 this.getOwnerTree().getSelectionModel().select(this);
33446 * Triggers deselection of this node
33448 unselect : function(){
33449 this.getOwnerTree().getSelectionModel().unselect(this);
33453 * Returns true if this node is selected
33454 * @return {Boolean}
33456 isSelected : function(){
33457 return this.getOwnerTree().getSelectionModel().isSelected(this);
33461 * Expand this node.
33462 * @param {Boolean} deep (optional) True to expand all children as well
33463 * @param {Boolean} anim (optional) false to cancel the default animation
33464 * @param {Function} callback (optional) A callback to be called when
33465 * expanding this node completes (does not wait for deep expand to complete).
33466 * Called with 1 parameter, this node.
33468 expand : function(deep, anim, callback){
33469 if(!this.expanded){
33470 if(this.fireEvent("beforeexpand", this, deep, anim) === false){
33473 if(!this.childrenRendered){
33474 this.renderChildren();
33476 this.expanded = true;
33477 if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
33478 this.ui.animExpand(function(){
33479 this.fireEvent("expand", this);
33480 if(typeof callback == "function"){
33484 this.expandChildNodes(true);
33486 }.createDelegate(this));
33490 this.fireEvent("expand", this);
33491 if(typeof callback == "function"){
33496 if(typeof callback == "function"){
33501 this.expandChildNodes(true);
33505 isHiddenRoot : function(){
33506 return this.isRoot && !this.getOwnerTree().rootVisible;
33510 * Collapse this node.
33511 * @param {Boolean} deep (optional) True to collapse all children as well
33512 * @param {Boolean} anim (optional) false to cancel the default animation
33514 collapse : function(deep, anim){
33515 if(this.expanded && !this.isHiddenRoot()){
33516 if(this.fireEvent("beforecollapse", this, deep, anim) === false){
33519 this.expanded = false;
33520 if((this.getOwnerTree().animate && anim !== false) || anim){
33521 this.ui.animCollapse(function(){
33522 this.fireEvent("collapse", this);
33524 this.collapseChildNodes(true);
33526 }.createDelegate(this));
33529 this.ui.collapse();
33530 this.fireEvent("collapse", this);
33534 var cs = this.childNodes;
33535 for(var i = 0, len = cs.length; i < len; i++) {
33536 cs[i].collapse(true, false);
33542 delayedExpand : function(delay){
33543 if(!this.expandProcId){
33544 this.expandProcId = this.expand.defer(delay, this);
33549 cancelExpand : function(){
33550 if(this.expandProcId){
33551 clearTimeout(this.expandProcId);
33553 this.expandProcId = false;
33557 * Toggles expanded/collapsed state of the node
33559 toggle : function(){
33568 * Ensures all parent nodes are expanded
33570 ensureVisible : function(callback){
33571 var tree = this.getOwnerTree();
33572 tree.expandPath(this.parentNode.getPath(), false, function(){
33573 tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
33574 Roo.callback(callback);
33575 }.createDelegate(this));
33579 * Expand all child nodes
33580 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
33582 expandChildNodes : function(deep){
33583 var cs = this.childNodes;
33584 for(var i = 0, len = cs.length; i < len; i++) {
33585 cs[i].expand(deep);
33590 * Collapse all child nodes
33591 * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
33593 collapseChildNodes : function(deep){
33594 var cs = this.childNodes;
33595 for(var i = 0, len = cs.length; i < len; i++) {
33596 cs[i].collapse(deep);
33601 * Disables this node
33603 disable : function(){
33604 this.disabled = true;
33606 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
33607 this.ui.onDisableChange(this, true);
33609 this.fireEvent("disabledchange", this, true);
33613 * Enables this node
33615 enable : function(){
33616 this.disabled = false;
33617 if(this.rendered && this.ui.onDisableChange){ // event without subscribing
33618 this.ui.onDisableChange(this, false);
33620 this.fireEvent("disabledchange", this, false);
33624 renderChildren : function(suppressEvent){
33625 if(suppressEvent !== false){
33626 this.fireEvent("beforechildrenrendered", this);
33628 var cs = this.childNodes;
33629 for(var i = 0, len = cs.length; i < len; i++){
33630 cs[i].render(true);
33632 this.childrenRendered = true;
33636 sort : function(fn, scope){
33637 Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
33638 if(this.childrenRendered){
33639 var cs = this.childNodes;
33640 for(var i = 0, len = cs.length; i < len; i++){
33641 cs[i].render(true);
33647 render : function(bulkRender){
33648 this.ui.render(bulkRender);
33649 if(!this.rendered){
33650 this.rendered = true;
33652 this.expanded = false;
33653 this.expand(false, false);
33659 renderIndent : function(deep, refresh){
33661 this.ui.childIndent = null;
33663 this.ui.renderIndent();
33664 if(deep === true && this.childrenRendered){
33665 var cs = this.childNodes;
33666 for(var i = 0, len = cs.length; i < len; i++){
33667 cs[i].renderIndent(true, refresh);
33673 * Ext JS Library 1.1.1
33674 * Copyright(c) 2006-2007, Ext JS, LLC.
33676 * Originally Released Under LGPL - original licence link has changed is not relivant.
33679 * <script type="text/javascript">
33683 * @class Roo.tree.AsyncTreeNode
33684 * @extends Roo.tree.TreeNode
33685 * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
33687 * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
33689 Roo.tree.AsyncTreeNode = function(config){
33690 this.loaded = false;
33691 this.loading = false;
33692 Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
33694 * @event beforeload
33695 * Fires before this node is loaded, return false to cancel
33696 * @param {Node} this This node
33698 this.addEvents({'beforeload':true, 'load': true});
33701 * Fires when this node is loaded
33702 * @param {Node} this This node
33705 * The loader used by this node (defaults to using the tree's defined loader)
33710 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
33711 expand : function(deep, anim, callback){
33712 if(this.loading){ // if an async load is already running, waiting til it's done
33714 var f = function(){
33715 if(!this.loading){ // done loading
33716 clearInterval(timer);
33717 this.expand(deep, anim, callback);
33719 }.createDelegate(this);
33720 timer = setInterval(f, 200);
33724 if(this.fireEvent("beforeload", this) === false){
33727 this.loading = true;
33728 this.ui.beforeLoad(this);
33729 var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
33731 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
33735 Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
33739 * Returns true if this node is currently loading
33740 * @return {Boolean}
33742 isLoading : function(){
33743 return this.loading;
33746 loadComplete : function(deep, anim, callback){
33747 this.loading = false;
33748 this.loaded = true;
33749 this.ui.afterLoad(this);
33750 this.fireEvent("load", this);
33751 this.expand(deep, anim, callback);
33755 * Returns true if this node has been loaded
33756 * @return {Boolean}
33758 isLoaded : function(){
33759 return this.loaded;
33762 hasChildNodes : function(){
33763 if(!this.isLeaf() && !this.loaded){
33766 return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
33771 * Trigger a reload for this node
33772 * @param {Function} callback
33774 reload : function(callback){
33775 this.collapse(false, false);
33776 while(this.firstChild){
33777 this.removeChild(this.firstChild);
33779 this.childrenRendered = false;
33780 this.loaded = false;
33781 if(this.isHiddenRoot()){
33782 this.expanded = false;
33784 this.expand(false, false, callback);
33788 * Ext JS Library 1.1.1
33789 * Copyright(c) 2006-2007, Ext JS, LLC.
33791 * Originally Released Under LGPL - original licence link has changed is not relivant.
33794 * <script type="text/javascript">
33798 * @class Roo.tree.TreeNodeUI
33800 * @param {Object} node The node to render
33801 * The TreeNode UI implementation is separate from the
33802 * tree implementation. Unless you are customizing the tree UI,
33803 * you should never have to use this directly.
33805 Roo.tree.TreeNodeUI = function(node){
33807 this.rendered = false;
33808 this.animating = false;
33809 this.emptyIcon = Roo.BLANK_IMAGE_URL;
33812 Roo.tree.TreeNodeUI.prototype = {
33813 removeChild : function(node){
33815 this.ctNode.removeChild(node.ui.getEl());
33819 beforeLoad : function(){
33820 this.addClass("x-tree-node-loading");
33823 afterLoad : function(){
33824 this.removeClass("x-tree-node-loading");
33827 onTextChange : function(node, text, oldText){
33829 this.textNode.innerHTML = text;
33833 onDisableChange : function(node, state){
33834 this.disabled = state;
33836 this.addClass("x-tree-node-disabled");
33838 this.removeClass("x-tree-node-disabled");
33842 onSelectedChange : function(state){
33845 this.addClass("x-tree-selected");
33848 this.removeClass("x-tree-selected");
33852 onMove : function(tree, node, oldParent, newParent, index, refNode){
33853 this.childIndent = null;
33855 var targetNode = newParent.ui.getContainer();
33856 if(!targetNode){//target not rendered
33857 this.holder = document.createElement("div");
33858 this.holder.appendChild(this.wrap);
33861 var insertBefore = refNode ? refNode.ui.getEl() : null;
33863 targetNode.insertBefore(this.wrap, insertBefore);
33865 targetNode.appendChild(this.wrap);
33867 this.node.renderIndent(true);
33871 addClass : function(cls){
33873 Roo.fly(this.elNode).addClass(cls);
33877 removeClass : function(cls){
33879 Roo.fly(this.elNode).removeClass(cls);
33883 remove : function(){
33885 this.holder = document.createElement("div");
33886 this.holder.appendChild(this.wrap);
33890 fireEvent : function(){
33891 return this.node.fireEvent.apply(this.node, arguments);
33894 initEvents : function(){
33895 this.node.on("move", this.onMove, this);
33896 var E = Roo.EventManager;
33897 var a = this.anchor;
33899 var el = Roo.fly(a, '_treeui');
33901 if(Roo.isOpera){ // opera render bug ignores the CSS
33902 el.setStyle("text-decoration", "none");
33905 el.on("click", this.onClick, this);
33906 el.on("dblclick", this.onDblClick, this);
33909 Roo.EventManager.on(this.checkbox,
33910 Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
33913 el.on("contextmenu", this.onContextMenu, this);
33915 var icon = Roo.fly(this.iconNode);
33916 icon.on("click", this.onClick, this);
33917 icon.on("dblclick", this.onDblClick, this);
33918 icon.on("contextmenu", this.onContextMenu, this);
33919 E.on(this.ecNode, "click", this.ecClick, this, true);
33921 if(this.node.disabled){
33922 this.addClass("x-tree-node-disabled");
33924 if(this.node.hidden){
33925 this.addClass("x-tree-node-disabled");
33927 var ot = this.node.getOwnerTree();
33928 var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
33929 if(dd && (!this.node.isRoot || ot.rootVisible)){
33930 Roo.dd.Registry.register(this.elNode, {
33932 handles: this.getDDHandles(),
33938 getDDHandles : function(){
33939 return [this.iconNode, this.textNode];
33944 this.wrap.style.display = "none";
33950 this.wrap.style.display = "";
33954 onContextMenu : function(e){
33955 if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
33956 e.preventDefault();
33958 this.fireEvent("contextmenu", this.node, e);
33962 onClick : function(e){
33967 if(this.fireEvent("beforeclick", this.node, e) !== false){
33968 if(!this.disabled && this.node.attributes.href){
33969 this.fireEvent("click", this.node, e);
33972 e.preventDefault();
33977 if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
33978 this.node.toggle();
33981 this.fireEvent("click", this.node, e);
33987 onDblClick : function(e){
33988 e.preventDefault();
33993 this.toggleCheck();
33995 if(!this.animating && this.node.hasChildNodes()){
33996 this.node.toggle();
33998 this.fireEvent("dblclick", this.node, e);
34001 onCheckChange : function(){
34002 var checked = this.checkbox.checked;
34003 this.node.attributes.checked = checked;
34004 this.fireEvent('checkchange', this.node, checked);
34007 ecClick : function(e){
34008 if(!this.animating && this.node.hasChildNodes()){
34009 this.node.toggle();
34013 startDrop : function(){
34014 this.dropping = true;
34017 // delayed drop so the click event doesn't get fired on a drop
34018 endDrop : function(){
34019 setTimeout(function(){
34020 this.dropping = false;
34021 }.createDelegate(this), 50);
34024 expand : function(){
34025 this.updateExpandIcon();
34026 this.ctNode.style.display = "";
34029 focus : function(){
34030 if(!this.node.preventHScroll){
34031 try{this.anchor.focus();
34033 }else if(!Roo.isIE){
34035 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
34036 var l = noscroll.scrollLeft;
34037 this.anchor.focus();
34038 noscroll.scrollLeft = l;
34043 toggleCheck : function(value){
34044 var cb = this.checkbox;
34046 cb.checked = (value === undefined ? !cb.checked : value);
34052 this.anchor.blur();
34056 animExpand : function(callback){
34057 var ct = Roo.get(this.ctNode);
34059 if(!this.node.hasChildNodes()){
34060 this.updateExpandIcon();
34061 this.ctNode.style.display = "";
34062 Roo.callback(callback);
34065 this.animating = true;
34066 this.updateExpandIcon();
34069 callback : function(){
34070 this.animating = false;
34071 Roo.callback(callback);
34074 duration: this.node.ownerTree.duration || .25
34078 highlight : function(){
34079 var tree = this.node.getOwnerTree();
34080 Roo.fly(this.wrap).highlight(
34081 tree.hlColor || "C3DAF9",
34082 {endColor: tree.hlBaseColor}
34086 collapse : function(){
34087 this.updateExpandIcon();
34088 this.ctNode.style.display = "none";
34091 animCollapse : function(callback){
34092 var ct = Roo.get(this.ctNode);
34093 ct.enableDisplayMode('block');
34096 this.animating = true;
34097 this.updateExpandIcon();
34100 callback : function(){
34101 this.animating = false;
34102 Roo.callback(callback);
34105 duration: this.node.ownerTree.duration || .25
34109 getContainer : function(){
34110 return this.ctNode;
34113 getEl : function(){
34117 appendDDGhost : function(ghostNode){
34118 ghostNode.appendChild(this.elNode.cloneNode(true));
34121 getDDRepairXY : function(){
34122 return Roo.lib.Dom.getXY(this.iconNode);
34125 onRender : function(){
34129 render : function(bulkRender){
34130 var n = this.node, a = n.attributes;
34131 var targetNode = n.parentNode ?
34132 n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
34134 if(!this.rendered){
34135 this.rendered = true;
34137 this.renderElements(n, a, targetNode, bulkRender);
34140 if(this.textNode.setAttributeNS){
34141 this.textNode.setAttributeNS("ext", "qtip", a.qtip);
34143 this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
34146 this.textNode.setAttribute("ext:qtip", a.qtip);
34148 this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
34151 }else if(a.qtipCfg){
34152 a.qtipCfg.target = Roo.id(this.textNode);
34153 Roo.QuickTips.register(a.qtipCfg);
34156 if(!this.node.expanded){
34157 this.updateExpandIcon();
34160 if(bulkRender === true) {
34161 targetNode.appendChild(this.wrap);
34166 renderElements : function(n, a, targetNode, bulkRender)
34168 // add some indent caching, this helps performance when rendering a large tree
34169 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
34170 var t = n.getOwnerTree();
34171 var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
34172 if (typeof(n.attributes.html) != 'undefined') {
34173 txt = n.attributes.html;
34175 var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
34176 var cb = typeof a.checked == 'boolean';
34177 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
34178 var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
34179 '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
34180 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
34181 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
34182 cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
34183 '<a hidefocus="on" href="',href,'" tabIndex="1" ',
34184 a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "",
34185 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
34186 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
34189 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
34190 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
34191 n.nextSibling.ui.getEl(), buf.join(""));
34193 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
34196 this.elNode = this.wrap.childNodes[0];
34197 this.ctNode = this.wrap.childNodes[1];
34198 var cs = this.elNode.childNodes;
34199 this.indentNode = cs[0];
34200 this.ecNode = cs[1];
34201 this.iconNode = cs[2];
34204 this.checkbox = cs[3];
34207 this.anchor = cs[index];
34208 this.textNode = cs[index].firstChild;
34211 getAnchor : function(){
34212 return this.anchor;
34215 getTextEl : function(){
34216 return this.textNode;
34219 getIconEl : function(){
34220 return this.iconNode;
34223 isChecked : function(){
34224 return this.checkbox ? this.checkbox.checked : false;
34227 updateExpandIcon : function(){
34229 var n = this.node, c1, c2;
34230 var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
34231 var hasChild = n.hasChildNodes();
34235 c1 = "x-tree-node-collapsed";
34236 c2 = "x-tree-node-expanded";
34239 c1 = "x-tree-node-expanded";
34240 c2 = "x-tree-node-collapsed";
34243 this.removeClass("x-tree-node-leaf");
34244 this.wasLeaf = false;
34246 if(this.c1 != c1 || this.c2 != c2){
34247 Roo.fly(this.elNode).replaceClass(c1, c2);
34248 this.c1 = c1; this.c2 = c2;
34251 // this changes non-leafs into leafs if they have no children.
34252 // it's not very rational behaviour..
34254 if(!this.wasLeaf && this.node.leaf){
34255 Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
34258 this.wasLeaf = true;
34261 var ecc = "x-tree-ec-icon "+cls;
34262 if(this.ecc != ecc){
34263 this.ecNode.className = ecc;
34269 getChildIndent : function(){
34270 if(!this.childIndent){
34274 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
34276 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
34278 buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
34283 this.childIndent = buf.join("");
34285 return this.childIndent;
34288 renderIndent : function(){
34291 var p = this.node.parentNode;
34293 indent = p.ui.getChildIndent();
34295 if(this.indentMarkup != indent){ // don't rerender if not required
34296 this.indentNode.innerHTML = indent;
34297 this.indentMarkup = indent;
34299 this.updateExpandIcon();
34304 Roo.tree.RootTreeNodeUI = function(){
34305 Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
34307 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
34308 render : function(){
34309 if(!this.rendered){
34310 var targetNode = this.node.ownerTree.innerCt.dom;
34311 this.node.expanded = true;
34312 targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
34313 this.wrap = this.ctNode = targetNode.firstChild;
34316 collapse : function(){
34318 expand : function(){
34322 * Ext JS Library 1.1.1
34323 * Copyright(c) 2006-2007, Ext JS, LLC.
34325 * Originally Released Under LGPL - original licence link has changed is not relivant.
34328 * <script type="text/javascript">
34331 * @class Roo.tree.TreeLoader
34332 * @extends Roo.util.Observable
34333 * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
34334 * nodes from a specified URL. The response must be a javascript Array definition
34335 * who's elements are node definition objects. eg:
34340 { 'id': 1, 'text': 'A folder Node', 'leaf': false },
34341 { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
34348 * The old style respose with just an array is still supported, but not recommended.
34351 * A server request is sent, and child nodes are loaded only when a node is expanded.
34352 * The loading node's id is passed to the server under the parameter name "node" to
34353 * enable the server to produce the correct child nodes.
34355 * To pass extra parameters, an event handler may be attached to the "beforeload"
34356 * event, and the parameters specified in the TreeLoader's baseParams property:
34358 myTreeLoader.on("beforeload", function(treeLoader, node) {
34359 this.baseParams.category = node.attributes.category;
34362 * This would pass an HTTP parameter called "category" to the server containing
34363 * the value of the Node's "category" attribute.
34365 * Creates a new Treeloader.
34366 * @param {Object} config A config object containing config properties.
34368 Roo.tree.TreeLoader = function(config){
34369 this.baseParams = {};
34370 this.requestMethod = "POST";
34371 Roo.apply(this, config);
34376 * @event beforeload
34377 * Fires before a network request is made to retrieve the Json text which specifies a node's children.
34378 * @param {Object} This TreeLoader object.
34379 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34380 * @param {Object} callback The callback function specified in the {@link #load} call.
34385 * Fires when the node has been successfuly loaded.
34386 * @param {Object} This TreeLoader object.
34387 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34388 * @param {Object} response The response object containing the data from the server.
34392 * @event loadexception
34393 * Fires if the network request failed.
34394 * @param {Object} This TreeLoader object.
34395 * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
34396 * @param {Object} response The response object containing the data from the server.
34398 loadexception : true,
34401 * Fires before a node is created, enabling you to return custom Node types
34402 * @param {Object} This TreeLoader object.
34403 * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
34408 Roo.tree.TreeLoader.superclass.constructor.call(this);
34411 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
34413 * @cfg {String} dataUrl The URL from which to request a Json string which
34414 * specifies an array of node definition object representing the child nodes
34418 * @cfg {String} requestMethod either GET or POST
34419 * defaults to POST (due to BC)
34423 * @cfg {Object} baseParams (optional) An object containing properties which
34424 * specify HTTP parameters to be passed to each request for child nodes.
34427 * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
34428 * created by this loader. If the attributes sent by the server have an attribute in this object,
34429 * they take priority.
34432 * @cfg {Object} uiProviders (optional) An object containing properties which
34434 * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
34435 * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
34436 * <i>uiProvider</i> attribute of a returned child node is a string rather
34437 * than a reference to a TreeNodeUI implementation, this that string value
34438 * is used as a property name in the uiProviders object. You can define the provider named
34439 * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
34444 * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
34445 * child nodes before loading.
34447 clearOnLoad : true,
34450 * @cfg {String} root (optional) Default to false. Use this to read data from an object
34451 * property on loading, rather than expecting an array. (eg. more compatible to a standard
34452 * Grid query { data : [ .....] }
34457 * @cfg {String} queryParam (optional)
34458 * Name of the query as it will be passed on the querystring (defaults to 'node')
34459 * eg. the request will be ?node=[id]
34466 * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
34467 * This is called automatically when a node is expanded, but may be used to reload
34468 * a node (or append new children if the {@link #clearOnLoad} option is false.)
34469 * @param {Roo.tree.TreeNode} node
34470 * @param {Function} callback
34472 load : function(node, callback){
34473 if(this.clearOnLoad){
34474 while(node.firstChild){
34475 node.removeChild(node.firstChild);
34478 if(node.attributes.children){ // preloaded json children
34479 var cs = node.attributes.children;
34480 for(var i = 0, len = cs.length; i < len; i++){
34481 node.appendChild(this.createNode(cs[i]));
34483 if(typeof callback == "function"){
34486 }else if(this.dataUrl){
34487 this.requestData(node, callback);
34491 getParams: function(node){
34492 var buf = [], bp = this.baseParams;
34493 for(var key in bp){
34494 if(typeof bp[key] != "function"){
34495 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
34498 var n = this.queryParam === false ? 'node' : this.queryParam;
34499 buf.push(n + "=", encodeURIComponent(node.id));
34500 return buf.join("");
34503 requestData : function(node, callback){
34504 if(this.fireEvent("beforeload", this, node, callback) !== false){
34505 this.transId = Roo.Ajax.request({
34506 method:this.requestMethod,
34507 url: this.dataUrl||this.url,
34508 success: this.handleResponse,
34509 failure: this.handleFailure,
34511 argument: {callback: callback, node: node},
34512 params: this.getParams(node)
34515 // if the load is cancelled, make sure we notify
34516 // the node that we are done
34517 if(typeof callback == "function"){
34523 isLoading : function(){
34524 return this.transId ? true : false;
34527 abort : function(){
34528 if(this.isLoading()){
34529 Roo.Ajax.abort(this.transId);
34534 createNode : function(attr)
34536 // apply baseAttrs, nice idea Corey!
34537 if(this.baseAttrs){
34538 Roo.applyIf(attr, this.baseAttrs);
34540 if(this.applyLoader !== false){
34541 attr.loader = this;
34543 // uiProvider = depreciated..
34545 if(typeof(attr.uiProvider) == 'string'){
34546 attr.uiProvider = this.uiProviders[attr.uiProvider] ||
34547 /** eval:var:attr */ eval(attr.uiProvider);
34549 if(typeof(this.uiProviders['default']) != 'undefined') {
34550 attr.uiProvider = this.uiProviders['default'];
34553 this.fireEvent('create', this, attr);
34555 attr.leaf = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
34557 new Roo.tree.TreeNode(attr) :
34558 new Roo.tree.AsyncTreeNode(attr));
34561 processResponse : function(response, node, callback)
34563 var json = response.responseText;
34566 var o = Roo.decode(json);
34568 if (this.root === false && typeof(o.success) != undefined) {
34569 this.root = 'data'; // the default behaviour for list like data..
34572 if (this.root !== false && !o.success) {
34573 // it's a failure condition.
34574 var a = response.argument;
34575 this.fireEvent("loadexception", this, a.node, response);
34576 Roo.log("Load failed - should have a handler really");
34582 if (this.root !== false) {
34586 for(var i = 0, len = o.length; i < len; i++){
34587 var n = this.createNode(o[i]);
34589 node.appendChild(n);
34592 if(typeof callback == "function"){
34593 callback(this, node);
34596 this.handleFailure(response);
34600 handleResponse : function(response){
34601 this.transId = false;
34602 var a = response.argument;
34603 this.processResponse(response, a.node, a.callback);
34604 this.fireEvent("load", this, a.node, response);
34607 handleFailure : function(response)
34609 // should handle failure better..
34610 this.transId = false;
34611 var a = response.argument;
34612 this.fireEvent("loadexception", this, a.node, response);
34613 if(typeof a.callback == "function"){
34614 a.callback(this, a.node);
34619 * Ext JS Library 1.1.1
34620 * Copyright(c) 2006-2007, Ext JS, LLC.
34622 * Originally Released Under LGPL - original licence link has changed is not relivant.
34625 * <script type="text/javascript">
34629 * @class Roo.tree.TreeFilter
34630 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
34631 * @param {TreePanel} tree
34632 * @param {Object} config (optional)
34634 Roo.tree.TreeFilter = function(tree, config){
34636 this.filtered = {};
34637 Roo.apply(this, config);
34640 Roo.tree.TreeFilter.prototype = {
34647 * Filter the data by a specific attribute.
34648 * @param {String/RegExp} value Either string that the attribute value
34649 * should start with or a RegExp to test against the attribute
34650 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
34651 * @param {TreeNode} startNode (optional) The node to start the filter at.
34653 filter : function(value, attr, startNode){
34654 attr = attr || "text";
34656 if(typeof value == "string"){
34657 var vlen = value.length;
34658 // auto clear empty filter
34659 if(vlen == 0 && this.clearBlank){
34663 value = value.toLowerCase();
34665 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
34667 }else if(value.exec){ // regex?
34669 return value.test(n.attributes[attr]);
34672 throw 'Illegal filter type, must be string or regex';
34674 this.filterBy(f, null, startNode);
34678 * Filter by a function. The passed function will be called with each
34679 * node in the tree (or from the startNode). If the function returns true, the node is kept
34680 * otherwise it is filtered. If a node is filtered, its children are also filtered.
34681 * @param {Function} fn The filter function
34682 * @param {Object} scope (optional) The scope of the function (defaults to the current node)
34684 filterBy : function(fn, scope, startNode){
34685 startNode = startNode || this.tree.root;
34686 if(this.autoClear){
34689 var af = this.filtered, rv = this.reverse;
34690 var f = function(n){
34691 if(n == startNode){
34697 var m = fn.call(scope || n, n);
34705 startNode.cascade(f);
34708 if(typeof id != "function"){
34710 if(n && n.parentNode){
34711 n.parentNode.removeChild(n);
34719 * Clears the current filter. Note: with the "remove" option
34720 * set a filter cannot be cleared.
34722 clear : function(){
34724 var af = this.filtered;
34726 if(typeof id != "function"){
34733 this.filtered = {};
34738 * Ext JS Library 1.1.1
34739 * Copyright(c) 2006-2007, Ext JS, LLC.
34741 * Originally Released Under LGPL - original licence link has changed is not relivant.
34744 * <script type="text/javascript">
34749 * @class Roo.tree.TreeSorter
34750 * Provides sorting of nodes in a TreePanel
34752 * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
34753 * @cfg {String} property The named attribute on the node to sort by (defaults to text)
34754 * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
34755 * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
34756 * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
34757 * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
34759 * @param {TreePanel} tree
34760 * @param {Object} config
34762 Roo.tree.TreeSorter = function(tree, config){
34763 Roo.apply(this, config);
34764 tree.on("beforechildrenrendered", this.doSort, this);
34765 tree.on("append", this.updateSort, this);
34766 tree.on("insert", this.updateSort, this);
34768 var dsc = this.dir && this.dir.toLowerCase() == "desc";
34769 var p = this.property || "text";
34770 var sortType = this.sortType;
34771 var fs = this.folderSort;
34772 var cs = this.caseSensitive === true;
34773 var leafAttr = this.leafAttr || 'leaf';
34775 this.sortFn = function(n1, n2){
34777 if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
34780 if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
34784 var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
34785 var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
34787 return dsc ? +1 : -1;
34789 return dsc ? -1 : +1;
34796 Roo.tree.TreeSorter.prototype = {
34797 doSort : function(node){
34798 node.sort(this.sortFn);
34801 compareNodes : function(n1, n2){
34802 return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
34805 updateSort : function(tree, node){
34806 if(node.childrenRendered){
34807 this.doSort.defer(1, this, [node]);
34812 * Ext JS Library 1.1.1
34813 * Copyright(c) 2006-2007, Ext JS, LLC.
34815 * Originally Released Under LGPL - original licence link has changed is not relivant.
34818 * <script type="text/javascript">
34821 if(Roo.dd.DropZone){
34823 Roo.tree.TreeDropZone = function(tree, config){
34824 this.allowParentInsert = false;
34825 this.allowContainerDrop = false;
34826 this.appendOnly = false;
34827 Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
34829 this.lastInsertClass = "x-tree-no-status";
34830 this.dragOverData = {};
34833 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
34834 ddGroup : "TreeDD",
34837 expandDelay : 1000,
34839 expandNode : function(node){
34840 if(node.hasChildNodes() && !node.isExpanded()){
34841 node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
34845 queueExpand : function(node){
34846 this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
34849 cancelExpand : function(){
34850 if(this.expandProcId){
34851 clearTimeout(this.expandProcId);
34852 this.expandProcId = false;
34856 isValidDropPoint : function(n, pt, dd, e, data){
34857 if(!n || !data){ return false; }
34858 var targetNode = n.node;
34859 var dropNode = data.node;
34860 // default drop rules
34861 if(!(targetNode && targetNode.isTarget && pt)){
34864 if(pt == "append" && targetNode.allowChildren === false){
34867 if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
34870 if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
34873 // reuse the object
34874 var overEvent = this.dragOverData;
34875 overEvent.tree = this.tree;
34876 overEvent.target = targetNode;
34877 overEvent.data = data;
34878 overEvent.point = pt;
34879 overEvent.source = dd;
34880 overEvent.rawEvent = e;
34881 overEvent.dropNode = dropNode;
34882 overEvent.cancel = false;
34883 var result = this.tree.fireEvent("nodedragover", overEvent);
34884 return overEvent.cancel === false && result !== false;
34887 getDropPoint : function(e, n, dd)
34891 return tn.allowChildren !== false ? "append" : false; // always append for root
34893 var dragEl = n.ddel;
34894 var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
34895 var y = Roo.lib.Event.getPageY(e);
34896 //var noAppend = tn.allowChildren === false || tn.isLeaf();
34898 // we may drop nodes anywhere, as long as allowChildren has not been set to false..
34899 var noAppend = tn.allowChildren === false;
34900 if(this.appendOnly || tn.parentNode.allowChildren === false){
34901 return noAppend ? false : "append";
34903 var noBelow = false;
34904 if(!this.allowParentInsert){
34905 noBelow = tn.hasChildNodes() && tn.isExpanded();
34907 var q = (b - t) / (noAppend ? 2 : 3);
34908 if(y >= t && y < (t + q)){
34910 }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
34917 onNodeEnter : function(n, dd, e, data)
34919 this.cancelExpand();
34922 onNodeOver : function(n, dd, e, data)
34925 var pt = this.getDropPoint(e, n, dd);
34928 // auto node expand check
34929 if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
34930 this.queueExpand(node);
34931 }else if(pt != "append"){
34932 this.cancelExpand();
34935 // set the insert point style on the target node
34936 var returnCls = this.dropNotAllowed;
34937 if(this.isValidDropPoint(n, pt, dd, e, data)){
34942 returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
34943 cls = "x-tree-drag-insert-above";
34944 }else if(pt == "below"){
34945 returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
34946 cls = "x-tree-drag-insert-below";
34948 returnCls = "x-tree-drop-ok-append";
34949 cls = "x-tree-drag-append";
34951 if(this.lastInsertClass != cls){
34952 Roo.fly(el).replaceClass(this.lastInsertClass, cls);
34953 this.lastInsertClass = cls;
34960 onNodeOut : function(n, dd, e, data){
34962 this.cancelExpand();
34963 this.removeDropIndicators(n);
34966 onNodeDrop : function(n, dd, e, data){
34967 var point = this.getDropPoint(e, n, dd);
34968 var targetNode = n.node;
34969 targetNode.ui.startDrop();
34970 if(!this.isValidDropPoint(n, point, dd, e, data)){
34971 targetNode.ui.endDrop();
34974 // first try to find the drop node
34975 var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
34978 target: targetNode,
34983 dropNode: dropNode,
34986 var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
34987 if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
34988 targetNode.ui.endDrop();
34991 // allow target changing
34992 targetNode = dropEvent.target;
34993 if(point == "append" && !targetNode.isExpanded()){
34994 targetNode.expand(false, null, function(){
34995 this.completeDrop(dropEvent);
34996 }.createDelegate(this));
34998 this.completeDrop(dropEvent);
35003 completeDrop : function(de){
35004 var ns = de.dropNode, p = de.point, t = de.target;
35005 if(!(ns instanceof Array)){
35009 for(var i = 0, len = ns.length; i < len; i++){
35012 t.parentNode.insertBefore(n, t);
35013 }else if(p == "below"){
35014 t.parentNode.insertBefore(n, t.nextSibling);
35020 if(this.tree.hlDrop){
35024 this.tree.fireEvent("nodedrop", de);
35027 afterNodeMoved : function(dd, data, e, targetNode, dropNode){
35028 if(this.tree.hlDrop){
35029 dropNode.ui.focus();
35030 dropNode.ui.highlight();
35032 this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
35035 getTree : function(){
35039 removeDropIndicators : function(n){
35042 Roo.fly(el).removeClass([
35043 "x-tree-drag-insert-above",
35044 "x-tree-drag-insert-below",
35045 "x-tree-drag-append"]);
35046 this.lastInsertClass = "_noclass";
35050 beforeDragDrop : function(target, e, id){
35051 this.cancelExpand();
35055 afterRepair : function(data){
35056 if(data && Roo.enableFx){
35057 data.node.ui.highlight();
35067 * Ext JS Library 1.1.1
35068 * Copyright(c) 2006-2007, Ext JS, LLC.
35070 * Originally Released Under LGPL - original licence link has changed is not relivant.
35073 * <script type="text/javascript">
35077 if(Roo.dd.DragZone){
35078 Roo.tree.TreeDragZone = function(tree, config){
35079 Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
35083 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
35084 ddGroup : "TreeDD",
35086 onBeforeDrag : function(data, e){
35088 return n && n.draggable && !n.disabled;
35092 onInitDrag : function(e){
35093 var data = this.dragData;
35094 this.tree.getSelectionModel().select(data.node);
35095 this.proxy.update("");
35096 data.node.ui.appendDDGhost(this.proxy.ghost.dom);
35097 this.tree.fireEvent("startdrag", this.tree, data.node, e);
35100 getRepairXY : function(e, data){
35101 return data.node.ui.getDDRepairXY();
35104 onEndDrag : function(data, e){
35105 this.tree.fireEvent("enddrag", this.tree, data.node, e);
35110 onValidDrop : function(dd, e, id){
35111 this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
35115 beforeInvalidDrop : function(e, id){
35116 // this scrolls the original position back into view
35117 var sm = this.tree.getSelectionModel();
35118 sm.clearSelections();
35119 sm.select(this.dragData.node);
35124 * Ext JS Library 1.1.1
35125 * Copyright(c) 2006-2007, Ext JS, LLC.
35127 * Originally Released Under LGPL - original licence link has changed is not relivant.
35130 * <script type="text/javascript">
35133 * @class Roo.tree.TreeEditor
35134 * @extends Roo.Editor
35135 * Provides editor functionality for inline tree node editing. Any valid {@link Roo.form.Field} can be used
35136 * as the editor field.
35138 * @param {Object} config (used to be the tree panel.)
35139 * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
35141 * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
35142 * @cfg {Roo.form.TextField|Object} field The field configuration
35146 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
35149 if (oldconfig) { // old style..
35150 field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
35153 tree = config.tree;
35154 config.field = config.field || {};
35155 config.field.xtype = 'TextField';
35156 field = Roo.factory(config.field, Roo.form);
35158 config = config || {};
35163 * @event beforenodeedit
35164 * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
35165 * false from the handler of this event.
35166 * @param {Editor} this
35167 * @param {Roo.tree.Node} node
35169 "beforenodeedit" : true
35173 Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
35177 tree.on('beforeclick', this.beforeNodeClick, this);
35178 tree.getTreeEl().on('mousedown', this.hide, this);
35179 this.on('complete', this.updateNode, this);
35180 this.on('beforestartedit', this.fitToTree, this);
35181 this.on('startedit', this.bindScroll, this, {delay:10});
35182 this.on('specialkey', this.onSpecialKey, this);
35185 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
35187 * @cfg {String} alignment
35188 * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
35194 * @cfg {Boolean} hideEl
35195 * True to hide the bound element while the editor is displayed (defaults to false)
35199 * @cfg {String} cls
35200 * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
35202 cls: "x-small-editor x-tree-editor",
35204 * @cfg {Boolean} shim
35205 * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
35211 * @cfg {Number} maxWidth
35212 * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
35213 * the containing tree element's size, it will be automatically limited for you to the container width, taking
35214 * scroll and client offsets into account prior to each edit.
35221 fitToTree : function(ed, el){
35222 var td = this.tree.getTreeEl().dom, nd = el.dom;
35223 if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
35224 td.scrollLeft = nd.offsetLeft;
35228 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
35229 this.setSize(w, '');
35231 return this.fireEvent('beforenodeedit', this, this.editNode);
35236 triggerEdit : function(node){
35237 this.completeEdit();
35238 this.editNode = node;
35239 this.startEdit(node.ui.textNode, node.text);
35243 bindScroll : function(){
35244 this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
35248 beforeNodeClick : function(node, e){
35249 var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
35250 this.lastClick = new Date();
35251 if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
35253 this.triggerEdit(node);
35260 updateNode : function(ed, value){
35261 this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
35262 this.editNode.setText(value);
35266 onHide : function(){
35267 Roo.tree.TreeEditor.superclass.onHide.call(this);
35269 this.editNode.ui.focus();
35274 onSpecialKey : function(field, e){
35275 var k = e.getKey();
35279 }else if(k == e.ENTER && !e.hasModifier()){
35281 this.completeEdit();
35284 });//<Script type="text/javascript">
35287 * Ext JS Library 1.1.1
35288 * Copyright(c) 2006-2007, Ext JS, LLC.
35290 * Originally Released Under LGPL - original licence link has changed is not relivant.
35293 * <script type="text/javascript">
35297 * Not documented??? - probably should be...
35300 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
35301 //focus: Roo.emptyFn, // prevent odd scrolling behavior
35303 renderElements : function(n, a, targetNode, bulkRender){
35304 //consel.log("renderElements?");
35305 this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
35307 var t = n.getOwnerTree();
35308 var tid = Pman.Tab.Document_TypesTree.tree.el.id;
35310 var cols = t.columns;
35311 var bw = t.borderWidth;
35313 var href = a.href ? a.href : Roo.isGecko ? "" : "#";
35314 var cb = typeof a.checked == "boolean";
35315 var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
35316 var colcls = 'x-t-' + tid + '-c0';
35318 '<li class="x-tree-node">',
35321 '<div class="x-tree-node-el ', a.cls,'">',
35323 '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
35326 '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
35327 '<img src="', this.emptyIcon, '" class="x-tree-ec-icon " />',
35328 '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
35329 (a.icon ? ' x-tree-node-inline-icon' : ''),
35330 (a.iconCls ? ' '+a.iconCls : ''),
35331 '" unselectable="on" />',
35332 (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' +
35333 (a.checked ? 'checked="checked" />' : ' />')) : ''),
35335 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
35336 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
35337 '<span unselectable="on" qtip="' + tx + '">',
35341 '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
35342 (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
35344 for(var i = 1, len = cols.length; i < len; i++){
35346 colcls = 'x-t-' + tid + '-c' +i;
35347 tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
35348 buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
35349 '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
35355 '<div class="x-clear"></div></div>',
35356 '<ul class="x-tree-node-ct" style="display:none;"></ul>',
35359 if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
35360 this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
35361 n.nextSibling.ui.getEl(), buf.join(""));
35363 this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
35365 var el = this.wrap.firstChild;
35367 this.elNode = el.firstChild;
35368 this.ranchor = el.childNodes[1];
35369 this.ctNode = this.wrap.childNodes[1];
35370 var cs = el.firstChild.childNodes;
35371 this.indentNode = cs[0];
35372 this.ecNode = cs[1];
35373 this.iconNode = cs[2];
35376 this.checkbox = cs[3];
35379 this.anchor = cs[index];
35381 this.textNode = cs[index].firstChild;
35383 //el.on("click", this.onClick, this);
35384 //el.on("dblclick", this.onDblClick, this);
35387 // console.log(this);
35389 initEvents : function(){
35390 Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
35393 var a = this.ranchor;
35395 var el = Roo.get(a);
35397 if(Roo.isOpera){ // opera render bug ignores the CSS
35398 el.setStyle("text-decoration", "none");
35401 el.on("click", this.onClick, this);
35402 el.on("dblclick", this.onDblClick, this);
35403 el.on("contextmenu", this.onContextMenu, this);
35407 /*onSelectedChange : function(state){
35410 this.addClass("x-tree-selected");
35413 this.removeClass("x-tree-selected");
35416 addClass : function(cls){
35418 Roo.fly(this.elRow).addClass(cls);
35424 removeClass : function(cls){
35426 Roo.fly(this.elRow).removeClass(cls);
35432 });//<Script type="text/javascript">
35436 * Ext JS Library 1.1.1
35437 * Copyright(c) 2006-2007, Ext JS, LLC.
35439 * Originally Released Under LGPL - original licence link has changed is not relivant.
35442 * <script type="text/javascript">
35447 * @class Roo.tree.ColumnTree
35448 * @extends Roo.data.TreePanel
35449 * @cfg {Object} columns Including width, header, renderer, cls, dataIndex
35450 * @cfg {int} borderWidth compined right/left border allowance
35452 * @param {String/HTMLElement/Element} el The container element
35453 * @param {Object} config
35455 Roo.tree.ColumnTree = function(el, config)
35457 Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
35461 * Fire this event on a container when it resizes
35462 * @param {int} w Width
35463 * @param {int} h Height
35467 this.on('resize', this.onResize, this);
35470 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
35474 borderWidth: Roo.isBorderBox ? 0 : 2,
35477 render : function(){
35478 // add the header.....
35480 Roo.tree.ColumnTree.superclass.render.apply(this);
35482 this.el.addClass('x-column-tree');
35484 this.headers = this.el.createChild(
35485 {cls:'x-tree-headers'},this.innerCt.dom);
35487 var cols = this.columns, c;
35488 var totalWidth = 0;
35490 var len = cols.length;
35491 for(var i = 0; i < len; i++){
35493 totalWidth += c.width;
35494 this.headEls.push(this.headers.createChild({
35495 cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
35497 cls:'x-tree-hd-text',
35500 style:'width:'+(c.width-this.borderWidth)+'px;'
35503 this.headers.createChild({cls:'x-clear'});
35504 // prevent floats from wrapping when clipped
35505 this.headers.setWidth(totalWidth);
35506 //this.innerCt.setWidth(totalWidth);
35507 this.innerCt.setStyle({ overflow: 'auto' });
35508 this.onResize(this.width, this.height);
35512 onResize : function(w,h)
35517 this.innerCt.setWidth(this.width);
35518 this.innerCt.setHeight(this.height-20);
35521 var cols = this.columns, c;
35522 var totalWidth = 0;
35524 var len = cols.length;
35525 for(var i = 0; i < len; i++){
35527 if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
35528 // it's the expander..
35529 expEl = this.headEls[i];
35532 totalWidth += c.width;
35536 expEl.setWidth( ((w - totalWidth)-this.borderWidth - 20));
35538 this.headers.setWidth(w-20);
35547 * Ext JS Library 1.1.1
35548 * Copyright(c) 2006-2007, Ext JS, LLC.
35550 * Originally Released Under LGPL - original licence link has changed is not relivant.
35553 * <script type="text/javascript">
35557 * @class Roo.menu.Menu
35558 * @extends Roo.util.Observable
35559 * A menu object. This is the container to which you add all other menu items. Menu can also serve a as a base class
35560 * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
35562 * Creates a new Menu
35563 * @param {Object} config Configuration options
35565 Roo.menu.Menu = function(config){
35566 Roo.apply(this, config);
35567 this.id = this.id || Roo.id();
35570 * @event beforeshow
35571 * Fires before this menu is displayed
35572 * @param {Roo.menu.Menu} this
35576 * @event beforehide
35577 * Fires before this menu is hidden
35578 * @param {Roo.menu.Menu} this
35583 * Fires after this menu is displayed
35584 * @param {Roo.menu.Menu} this
35589 * Fires after this menu is hidden
35590 * @param {Roo.menu.Menu} this
35595 * Fires when this menu is clicked (or when the enter key is pressed while it is active)
35596 * @param {Roo.menu.Menu} this
35597 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35598 * @param {Roo.EventObject} e
35603 * Fires when the mouse is hovering over this menu
35604 * @param {Roo.menu.Menu} this
35605 * @param {Roo.EventObject} e
35606 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35611 * Fires when the mouse exits this menu
35612 * @param {Roo.menu.Menu} this
35613 * @param {Roo.EventObject} e
35614 * @param {Roo.menu.Item} menuItem The menu item that was clicked
35619 * Fires when a menu item contained in this menu is clicked
35620 * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
35621 * @param {Roo.EventObject} e
35625 if (this.registerMenu) {
35626 Roo.menu.MenuMgr.register(this);
35629 var mis = this.items;
35630 this.items = new Roo.util.MixedCollection();
35632 this.add.apply(this, mis);
35636 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
35638 * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
35642 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
35643 * for bottom-right shadow (defaults to "sides")
35647 * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
35648 * this menu (defaults to "tl-tr?")
35650 subMenuAlign : "tl-tr?",
35652 * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
35653 * relative to its element of origin (defaults to "tl-bl?")
35655 defaultAlign : "tl-bl?",
35657 * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
35659 allowOtherMenus : false,
35661 * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
35663 registerMenu : true,
35668 render : function(){
35672 var el = this.el = new Roo.Layer({
35674 shadow:this.shadow,
35676 parentEl: this.parentEl || document.body,
35680 this.keyNav = new Roo.menu.MenuNav(this);
35683 el.addClass("x-menu-plain");
35686 el.addClass(this.cls);
35688 // generic focus element
35689 this.focusEl = el.createChild({
35690 tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
35692 var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
35693 ul.on(Roo.isTouch ? 'touchstart' : 'click' , this.onClick, this);
35695 ul.on("mouseover", this.onMouseOver, this);
35696 ul.on("mouseout", this.onMouseOut, this);
35697 this.items.each(function(item){
35702 var li = document.createElement("li");
35703 li.className = "x-menu-list-item";
35704 ul.dom.appendChild(li);
35705 item.render(li, this);
35712 autoWidth : function(){
35713 var el = this.el, ul = this.ul;
35717 var w = this.width;
35720 }else if(Roo.isIE){
35721 el.setWidth(this.minWidth);
35722 var t = el.dom.offsetWidth; // force recalc
35723 el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
35728 delayAutoWidth : function(){
35731 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
35733 this.awTask.delay(20);
35738 findTargetItem : function(e){
35739 var t = e.getTarget(".x-menu-list-item", this.ul, true);
35740 if(t && t.menuItemId){
35741 return this.items.get(t.menuItemId);
35746 onClick : function(e){
35747 Roo.log("menu.onClick");
35748 var t = this.findTargetItem(e);
35753 if (Roo.isTouch && e.type == 'touchstart' && t.menu && !t.disabled) {
35754 if(t == this.activeItem && t.shouldDeactivate(e)){
35755 this.activeItem.deactivate();
35756 delete this.activeItem;
35760 this.setActiveItem(t, true);
35768 this.fireEvent("click", this, t, e);
35772 setActiveItem : function(item, autoExpand){
35773 if(item != this.activeItem){
35774 if(this.activeItem){
35775 this.activeItem.deactivate();
35777 this.activeItem = item;
35778 item.activate(autoExpand);
35779 }else if(autoExpand){
35785 tryActivate : function(start, step){
35786 var items = this.items;
35787 for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
35788 var item = items.get(i);
35789 if(!item.disabled && item.canActivate){
35790 this.setActiveItem(item, false);
35798 onMouseOver : function(e){
35800 if(t = this.findTargetItem(e)){
35801 if(t.canActivate && !t.disabled){
35802 this.setActiveItem(t, true);
35805 this.fireEvent("mouseover", this, e, t);
35809 onMouseOut : function(e){
35811 if(t = this.findTargetItem(e)){
35812 if(t == this.activeItem && t.shouldDeactivate(e)){
35813 this.activeItem.deactivate();
35814 delete this.activeItem;
35817 this.fireEvent("mouseout", this, e, t);
35821 * Read-only. Returns true if the menu is currently displayed, else false.
35824 isVisible : function(){
35825 return this.el && !this.hidden;
35829 * Displays this menu relative to another element
35830 * @param {String/HTMLElement/Roo.Element} element The element to align to
35831 * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
35832 * the element (defaults to this.defaultAlign)
35833 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
35835 show : function(el, pos, parentMenu){
35836 this.parentMenu = parentMenu;
35840 this.fireEvent("beforeshow", this);
35841 this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
35845 * Displays this menu at a specific xy position
35846 * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
35847 * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
35849 showAt : function(xy, parentMenu, /* private: */_e){
35850 this.parentMenu = parentMenu;
35855 this.fireEvent("beforeshow", this);
35856 xy = this.el.adjustForConstraints(xy);
35860 this.hidden = false;
35862 this.fireEvent("show", this);
35865 focus : function(){
35867 this.doFocus.defer(50, this);
35871 doFocus : function(){
35873 this.focusEl.focus();
35878 * Hides this menu and optionally all parent menus
35879 * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
35881 hide : function(deep){
35882 if(this.el && this.isVisible()){
35883 this.fireEvent("beforehide", this);
35884 if(this.activeItem){
35885 this.activeItem.deactivate();
35886 this.activeItem = null;
35889 this.hidden = true;
35890 this.fireEvent("hide", this);
35892 if(deep === true && this.parentMenu){
35893 this.parentMenu.hide(true);
35898 * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
35899 * Any of the following are valid:
35901 * <li>Any menu item object based on {@link Roo.menu.Item}</li>
35902 * <li>An HTMLElement object which will be converted to a menu item</li>
35903 * <li>A menu item config object that will be created as a new menu item</li>
35904 * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
35905 * it will be converted into a {@link Roo.menu.TextItem} and added</li>
35910 var menu = new Roo.menu.Menu();
35912 // Create a menu item to add by reference
35913 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
35915 // Add a bunch of items at once using different methods.
35916 // Only the last item added will be returned.
35917 var item = menu.add(
35918 menuItem, // add existing item by ref
35919 'Dynamic Item', // new TextItem
35920 '-', // new separator
35921 { text: 'Config Item' } // new item by config
35924 * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
35925 * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
35928 var a = arguments, l = a.length, item;
35929 for(var i = 0; i < l; i++){
35931 if ((typeof(el) == "object") && el.xtype && el.xns) {
35932 el = Roo.factory(el, Roo.menu);
35935 if(el.render){ // some kind of Item
35936 item = this.addItem(el);
35937 }else if(typeof el == "string"){ // string
35938 if(el == "separator" || el == "-"){
35939 item = this.addSeparator();
35941 item = this.addText(el);
35943 }else if(el.tagName || el.el){ // element
35944 item = this.addElement(el);
35945 }else if(typeof el == "object"){ // must be menu item config?
35946 item = this.addMenuItem(el);
35953 * Returns this menu's underlying {@link Roo.Element} object
35954 * @return {Roo.Element} The element
35956 getEl : function(){
35964 * Adds a separator bar to the menu
35965 * @return {Roo.menu.Item} The menu item that was added
35967 addSeparator : function(){
35968 return this.addItem(new Roo.menu.Separator());
35972 * Adds an {@link Roo.Element} object to the menu
35973 * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
35974 * @return {Roo.menu.Item} The menu item that was added
35976 addElement : function(el){
35977 return this.addItem(new Roo.menu.BaseItem(el));
35981 * Adds an existing object based on {@link Roo.menu.Item} to the menu
35982 * @param {Roo.menu.Item} item The menu item to add
35983 * @return {Roo.menu.Item} The menu item that was added
35985 addItem : function(item){
35986 this.items.add(item);
35988 var li = document.createElement("li");
35989 li.className = "x-menu-list-item";
35990 this.ul.dom.appendChild(li);
35991 item.render(li, this);
35992 this.delayAutoWidth();
35998 * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
35999 * @param {Object} config A MenuItem config object
36000 * @return {Roo.menu.Item} The menu item that was added
36002 addMenuItem : function(config){
36003 if(!(config instanceof Roo.menu.Item)){
36004 if(typeof config.checked == "boolean"){ // must be check menu item config?
36005 config = new Roo.menu.CheckItem(config);
36007 config = new Roo.menu.Item(config);
36010 return this.addItem(config);
36014 * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
36015 * @param {String} text The text to display in the menu item
36016 * @return {Roo.menu.Item} The menu item that was added
36018 addText : function(text){
36019 return this.addItem(new Roo.menu.TextItem({ text : text }));
36023 * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
36024 * @param {Number} index The index in the menu's list of current items where the new item should be inserted
36025 * @param {Roo.menu.Item} item The menu item to add
36026 * @return {Roo.menu.Item} The menu item that was added
36028 insert : function(index, item){
36029 this.items.insert(index, item);
36031 var li = document.createElement("li");
36032 li.className = "x-menu-list-item";
36033 this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
36034 item.render(li, this);
36035 this.delayAutoWidth();
36041 * Removes an {@link Roo.menu.Item} from the menu and destroys the object
36042 * @param {Roo.menu.Item} item The menu item to remove
36044 remove : function(item){
36045 this.items.removeKey(item.id);
36050 * Removes and destroys all items in the menu
36052 removeAll : function(){
36054 while(f = this.items.first()){
36060 // MenuNav is a private utility class used internally by the Menu
36061 Roo.menu.MenuNav = function(menu){
36062 Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
36063 this.scope = this.menu = menu;
36066 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
36067 doRelay : function(e, h){
36068 var k = e.getKey();
36069 if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
36070 this.menu.tryActivate(0, 1);
36073 return h.call(this.scope || this, e, this.menu);
36076 up : function(e, m){
36077 if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
36078 m.tryActivate(m.items.length-1, -1);
36082 down : function(e, m){
36083 if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
36084 m.tryActivate(0, 1);
36088 right : function(e, m){
36090 m.activeItem.expandMenu(true);
36094 left : function(e, m){
36096 if(m.parentMenu && m.parentMenu.activeItem){
36097 m.parentMenu.activeItem.activate();
36101 enter : function(e, m){
36103 e.stopPropagation();
36104 m.activeItem.onClick(e);
36105 m.fireEvent("click", this, m.activeItem);
36111 * Ext JS Library 1.1.1
36112 * Copyright(c) 2006-2007, Ext JS, LLC.
36114 * Originally Released Under LGPL - original licence link has changed is not relivant.
36117 * <script type="text/javascript">
36121 * @class Roo.menu.MenuMgr
36122 * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
36125 Roo.menu.MenuMgr = function(){
36126 var menus, active, groups = {}, attached = false, lastShow = new Date();
36128 // private - called when first menu is created
36131 active = new Roo.util.MixedCollection();
36132 Roo.get(document).addKeyListener(27, function(){
36133 if(active.length > 0){
36140 function hideAll(){
36141 if(active && active.length > 0){
36142 var c = active.clone();
36143 c.each(function(m){
36150 function onHide(m){
36152 if(active.length < 1){
36153 Roo.get(document).un("mousedown", onMouseDown);
36159 function onShow(m){
36160 var last = active.last();
36161 lastShow = new Date();
36164 Roo.get(document).on("mousedown", onMouseDown);
36168 m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
36169 m.parentMenu.activeChild = m;
36170 }else if(last && last.isVisible()){
36171 m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
36176 function onBeforeHide(m){
36178 m.activeChild.hide();
36180 if(m.autoHideTimer){
36181 clearTimeout(m.autoHideTimer);
36182 delete m.autoHideTimer;
36187 function onBeforeShow(m){
36188 var pm = m.parentMenu;
36189 if(!pm && !m.allowOtherMenus){
36191 }else if(pm && pm.activeChild && active != m){
36192 pm.activeChild.hide();
36197 function onMouseDown(e){
36198 if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
36204 function onBeforeCheck(mi, state){
36206 var g = groups[mi.group];
36207 for(var i = 0, l = g.length; i < l; i++){
36209 g[i].setChecked(false);
36218 * Hides all menus that are currently visible
36220 hideAll : function(){
36225 register : function(menu){
36229 menus[menu.id] = menu;
36230 menu.on("beforehide", onBeforeHide);
36231 menu.on("hide", onHide);
36232 menu.on("beforeshow", onBeforeShow);
36233 menu.on("show", onShow);
36234 var g = menu.group;
36235 if(g && menu.events["checkchange"]){
36239 groups[g].push(menu);
36240 menu.on("checkchange", onCheck);
36245 * Returns a {@link Roo.menu.Menu} object
36246 * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
36247 * be used to generate and return a new Menu instance.
36249 get : function(menu){
36250 if(typeof menu == "string"){ // menu id
36251 return menus[menu];
36252 }else if(menu.events){ // menu instance
36254 }else if(typeof menu.length == 'number'){ // array of menu items?
36255 return new Roo.menu.Menu({items:menu});
36256 }else{ // otherwise, must be a config
36257 return new Roo.menu.Menu(menu);
36262 unregister : function(menu){
36263 delete menus[menu.id];
36264 menu.un("beforehide", onBeforeHide);
36265 menu.un("hide", onHide);
36266 menu.un("beforeshow", onBeforeShow);
36267 menu.un("show", onShow);
36268 var g = menu.group;
36269 if(g && menu.events["checkchange"]){
36270 groups[g].remove(menu);
36271 menu.un("checkchange", onCheck);
36276 registerCheckable : function(menuItem){
36277 var g = menuItem.group;
36282 groups[g].push(menuItem);
36283 menuItem.on("beforecheckchange", onBeforeCheck);
36288 unregisterCheckable : function(menuItem){
36289 var g = menuItem.group;
36291 groups[g].remove(menuItem);
36292 menuItem.un("beforecheckchange", onBeforeCheck);
36298 * Ext JS Library 1.1.1
36299 * Copyright(c) 2006-2007, Ext JS, LLC.
36301 * Originally Released Under LGPL - original licence link has changed is not relivant.
36304 * <script type="text/javascript">
36309 * @class Roo.menu.BaseItem
36310 * @extends Roo.Component
36311 * The base class for all items that render into menus. BaseItem provides default rendering, activated state
36312 * management and base configuration options shared by all menu components.
36314 * Creates a new BaseItem
36315 * @param {Object} config Configuration options
36317 Roo.menu.BaseItem = function(config){
36318 Roo.menu.BaseItem.superclass.constructor.call(this, config);
36323 * Fires when this item is clicked
36324 * @param {Roo.menu.BaseItem} this
36325 * @param {Roo.EventObject} e
36330 * Fires when this item is activated
36331 * @param {Roo.menu.BaseItem} this
36335 * @event deactivate
36336 * Fires when this item is deactivated
36337 * @param {Roo.menu.BaseItem} this
36343 this.on("click", this.handler, this.scope, true);
36347 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
36349 * @cfg {Function} handler
36350 * A function that will handle the click event of this menu item (defaults to undefined)
36353 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
36355 canActivate : false,
36358 * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
36363 * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
36365 activeClass : "x-menu-item-active",
36367 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
36369 hideOnClick : true,
36371 * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
36376 ctype: "Roo.menu.BaseItem",
36379 actionMode : "container",
36382 render : function(container, parentMenu){
36383 this.parentMenu = parentMenu;
36384 Roo.menu.BaseItem.superclass.render.call(this, container);
36385 this.container.menuItemId = this.id;
36389 onRender : function(container, position){
36390 this.el = Roo.get(this.el);
36391 container.dom.appendChild(this.el.dom);
36395 onClick : function(e){
36396 if(!this.disabled && this.fireEvent("click", this, e) !== false
36397 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
36398 this.handleClick(e);
36405 activate : function(){
36409 var li = this.container;
36410 li.addClass(this.activeClass);
36411 this.region = li.getRegion().adjust(2, 2, -2, -2);
36412 this.fireEvent("activate", this);
36417 deactivate : function(){
36418 this.container.removeClass(this.activeClass);
36419 this.fireEvent("deactivate", this);
36423 shouldDeactivate : function(e){
36424 return !this.region || !this.region.contains(e.getPoint());
36428 handleClick : function(e){
36429 if(this.hideOnClick){
36430 this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
36435 expandMenu : function(autoActivate){
36440 hideMenu : function(){
36445 * Ext JS Library 1.1.1
36446 * Copyright(c) 2006-2007, Ext JS, LLC.
36448 * Originally Released Under LGPL - original licence link has changed is not relivant.
36451 * <script type="text/javascript">
36455 * @class Roo.menu.Adapter
36456 * @extends Roo.menu.BaseItem
36457 * 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.
36458 * It provides basic rendering, activation management and enable/disable logic required to work in menus.
36460 * Creates a new Adapter
36461 * @param {Object} config Configuration options
36463 Roo.menu.Adapter = function(component, config){
36464 Roo.menu.Adapter.superclass.constructor.call(this, config);
36465 this.component = component;
36467 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
36469 canActivate : true,
36472 onRender : function(container, position){
36473 this.component.render(container);
36474 this.el = this.component.getEl();
36478 activate : function(){
36482 this.component.focus();
36483 this.fireEvent("activate", this);
36488 deactivate : function(){
36489 this.fireEvent("deactivate", this);
36493 disable : function(){
36494 this.component.disable();
36495 Roo.menu.Adapter.superclass.disable.call(this);
36499 enable : function(){
36500 this.component.enable();
36501 Roo.menu.Adapter.superclass.enable.call(this);
36505 * Ext JS Library 1.1.1
36506 * Copyright(c) 2006-2007, Ext JS, LLC.
36508 * Originally Released Under LGPL - original licence link has changed is not relivant.
36511 * <script type="text/javascript">
36515 * @class Roo.menu.TextItem
36516 * @extends Roo.menu.BaseItem
36517 * Adds a static text string to a menu, usually used as either a heading or group separator.
36518 * Note: old style constructor with text is still supported.
36521 * Creates a new TextItem
36522 * @param {Object} cfg Configuration
36524 Roo.menu.TextItem = function(cfg){
36525 if (typeof(cfg) == 'string') {
36528 Roo.apply(this,cfg);
36531 Roo.menu.TextItem.superclass.constructor.call(this);
36534 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
36536 * @cfg {Boolean} text Text to show on item.
36541 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
36543 hideOnClick : false,
36545 * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
36547 itemCls : "x-menu-text",
36550 onRender : function(){
36551 var s = document.createElement("span");
36552 s.className = this.itemCls;
36553 s.innerHTML = this.text;
36555 Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
36559 * Ext JS Library 1.1.1
36560 * Copyright(c) 2006-2007, Ext JS, LLC.
36562 * Originally Released Under LGPL - original licence link has changed is not relivant.
36565 * <script type="text/javascript">
36569 * @class Roo.menu.Separator
36570 * @extends Roo.menu.BaseItem
36571 * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
36572 * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
36574 * @param {Object} config Configuration options
36576 Roo.menu.Separator = function(config){
36577 Roo.menu.Separator.superclass.constructor.call(this, config);
36580 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
36582 * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
36584 itemCls : "x-menu-sep",
36586 * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
36588 hideOnClick : false,
36591 onRender : function(li){
36592 var s = document.createElement("span");
36593 s.className = this.itemCls;
36594 s.innerHTML = " ";
36596 li.addClass("x-menu-sep-li");
36597 Roo.menu.Separator.superclass.onRender.apply(this, arguments);
36601 * Ext JS Library 1.1.1
36602 * Copyright(c) 2006-2007, Ext JS, LLC.
36604 * Originally Released Under LGPL - original licence link has changed is not relivant.
36607 * <script type="text/javascript">
36610 * @class Roo.menu.Item
36611 * @extends Roo.menu.BaseItem
36612 * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
36613 * display items. Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
36614 * activation and click handling.
36616 * Creates a new Item
36617 * @param {Object} config Configuration options
36619 Roo.menu.Item = function(config){
36620 Roo.menu.Item.superclass.constructor.call(this, config);
36622 this.menu = Roo.menu.MenuMgr.get(this.menu);
36625 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
36628 * @cfg {String} text
36629 * The text to show on the menu item.
36633 * @cfg {String} HTML to render in menu
36634 * The text to show on the menu item (HTML version).
36638 * @cfg {String} icon
36639 * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
36643 * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
36645 itemCls : "x-menu-item",
36647 * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
36649 canActivate : true,
36651 * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
36654 // doc'd in BaseItem
36658 ctype: "Roo.menu.Item",
36661 onRender : function(container, position){
36662 var el = document.createElement("a");
36663 el.hideFocus = true;
36664 el.unselectable = "on";
36665 el.href = this.href || "#";
36666 if(this.hrefTarget){
36667 el.target = this.hrefTarget;
36669 el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
36671 var html = this.html.length ? this.html : String.format('{0}',this.text);
36673 el.innerHTML = String.format(
36674 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
36675 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
36677 Roo.menu.Item.superclass.onRender.call(this, container, position);
36681 * Sets the text to display in this menu item
36682 * @param {String} text The text to display
36683 * @param {Boolean} isHTML true to indicate text is pure html.
36685 setText : function(text, isHTML){
36693 var html = this.html.length ? this.html : String.format('{0}',this.text);
36695 this.el.update(String.format(
36696 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
36697 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
36698 this.parentMenu.autoWidth();
36703 handleClick : function(e){
36704 if(!this.href){ // if no link defined, stop the event automatically
36707 Roo.menu.Item.superclass.handleClick.apply(this, arguments);
36711 activate : function(autoExpand){
36712 if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
36722 shouldDeactivate : function(e){
36723 if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
36724 if(this.menu && this.menu.isVisible()){
36725 return !this.menu.getEl().getRegion().contains(e.getPoint());
36733 deactivate : function(){
36734 Roo.menu.Item.superclass.deactivate.apply(this, arguments);
36739 expandMenu : function(autoActivate){
36740 if(!this.disabled && this.menu){
36741 clearTimeout(this.hideTimer);
36742 delete this.hideTimer;
36743 if(!this.menu.isVisible() && !this.showTimer){
36744 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
36745 }else if (this.menu.isVisible() && autoActivate){
36746 this.menu.tryActivate(0, 1);
36752 deferExpand : function(autoActivate){
36753 delete this.showTimer;
36754 this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
36756 this.menu.tryActivate(0, 1);
36761 hideMenu : function(){
36762 clearTimeout(this.showTimer);
36763 delete this.showTimer;
36764 if(!this.hideTimer && this.menu && this.menu.isVisible()){
36765 this.hideTimer = this.deferHide.defer(this.hideDelay, this);
36770 deferHide : function(){
36771 delete this.hideTimer;
36776 * Ext JS Library 1.1.1
36777 * Copyright(c) 2006-2007, Ext JS, LLC.
36779 * Originally Released Under LGPL - original licence link has changed is not relivant.
36782 * <script type="text/javascript">
36786 * @class Roo.menu.CheckItem
36787 * @extends Roo.menu.Item
36788 * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
36790 * Creates a new CheckItem
36791 * @param {Object} config Configuration options
36793 Roo.menu.CheckItem = function(config){
36794 Roo.menu.CheckItem.superclass.constructor.call(this, config);
36797 * @event beforecheckchange
36798 * Fires before the checked value is set, providing an opportunity to cancel if needed
36799 * @param {Roo.menu.CheckItem} this
36800 * @param {Boolean} checked The new checked value that will be set
36802 "beforecheckchange" : true,
36804 * @event checkchange
36805 * Fires after the checked value has been set
36806 * @param {Roo.menu.CheckItem} this
36807 * @param {Boolean} checked The checked value that was set
36809 "checkchange" : true
36811 if(this.checkHandler){
36812 this.on('checkchange', this.checkHandler, this.scope);
36815 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
36817 * @cfg {String} group
36818 * All check items with the same group name will automatically be grouped into a single-select
36819 * radio button group (defaults to '')
36822 * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
36824 itemCls : "x-menu-item x-menu-check-item",
36826 * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
36828 groupClass : "x-menu-group-item",
36831 * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false). Note that
36832 * if this checkbox is part of a radio group (group = true) only the last item in the group that is
36833 * initialized with checked = true will be rendered as checked.
36838 ctype: "Roo.menu.CheckItem",
36841 onRender : function(c){
36842 Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
36844 this.el.addClass(this.groupClass);
36846 Roo.menu.MenuMgr.registerCheckable(this);
36848 this.checked = false;
36849 this.setChecked(true, true);
36854 destroy : function(){
36856 Roo.menu.MenuMgr.unregisterCheckable(this);
36858 Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
36862 * Set the checked state of this item
36863 * @param {Boolean} checked The new checked value
36864 * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
36866 setChecked : function(state, suppressEvent){
36867 if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
36868 if(this.container){
36869 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
36871 this.checked = state;
36872 if(suppressEvent !== true){
36873 this.fireEvent("checkchange", this, state);
36879 handleClick : function(e){
36880 if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
36881 this.setChecked(!this.checked);
36883 Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
36887 * Ext JS Library 1.1.1
36888 * Copyright(c) 2006-2007, Ext JS, LLC.
36890 * Originally Released Under LGPL - original licence link has changed is not relivant.
36893 * <script type="text/javascript">
36897 * @class Roo.menu.DateItem
36898 * @extends Roo.menu.Adapter
36899 * A menu item that wraps the {@link Roo.DatPicker} component.
36901 * Creates a new DateItem
36902 * @param {Object} config Configuration options
36904 Roo.menu.DateItem = function(config){
36905 Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
36906 /** The Roo.DatePicker object @type Roo.DatePicker */
36907 this.picker = this.component;
36908 this.addEvents({select: true});
36910 this.picker.on("render", function(picker){
36911 picker.getEl().swallowEvent("click");
36912 picker.container.addClass("x-menu-date-item");
36915 this.picker.on("select", this.onSelect, this);
36918 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
36920 onSelect : function(picker, date){
36921 this.fireEvent("select", this, date, picker);
36922 Roo.menu.DateItem.superclass.handleClick.call(this);
36926 * Ext JS Library 1.1.1
36927 * Copyright(c) 2006-2007, Ext JS, LLC.
36929 * Originally Released Under LGPL - original licence link has changed is not relivant.
36932 * <script type="text/javascript">
36936 * @class Roo.menu.ColorItem
36937 * @extends Roo.menu.Adapter
36938 * A menu item that wraps the {@link Roo.ColorPalette} component.
36940 * Creates a new ColorItem
36941 * @param {Object} config Configuration options
36943 Roo.menu.ColorItem = function(config){
36944 Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
36945 /** The Roo.ColorPalette object @type Roo.ColorPalette */
36946 this.palette = this.component;
36947 this.relayEvents(this.palette, ["select"]);
36948 if(this.selectHandler){
36949 this.on('select', this.selectHandler, this.scope);
36952 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
36954 * Ext JS Library 1.1.1
36955 * Copyright(c) 2006-2007, Ext JS, LLC.
36957 * Originally Released Under LGPL - original licence link has changed is not relivant.
36960 * <script type="text/javascript">
36965 * @class Roo.menu.DateMenu
36966 * @extends Roo.menu.Menu
36967 * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
36969 * Creates a new DateMenu
36970 * @param {Object} config Configuration options
36972 Roo.menu.DateMenu = function(config){
36973 Roo.menu.DateMenu.superclass.constructor.call(this, config);
36975 var di = new Roo.menu.DateItem(config);
36978 * The {@link Roo.DatePicker} instance for this DateMenu
36981 this.picker = di.picker;
36984 * @param {DatePicker} picker
36985 * @param {Date} date
36987 this.relayEvents(di, ["select"]);
36988 this.on('beforeshow', function(){
36990 this.picker.hideMonthPicker(false);
36994 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
36998 * Ext JS Library 1.1.1
36999 * Copyright(c) 2006-2007, Ext JS, LLC.
37001 * Originally Released Under LGPL - original licence link has changed is not relivant.
37004 * <script type="text/javascript">
37009 * @class Roo.menu.ColorMenu
37010 * @extends Roo.menu.Menu
37011 * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
37013 * Creates a new ColorMenu
37014 * @param {Object} config Configuration options
37016 Roo.menu.ColorMenu = function(config){
37017 Roo.menu.ColorMenu.superclass.constructor.call(this, config);
37019 var ci = new Roo.menu.ColorItem(config);
37022 * The {@link Roo.ColorPalette} instance for this ColorMenu
37023 * @type ColorPalette
37025 this.palette = ci.palette;
37028 * @param {ColorPalette} palette
37029 * @param {String} color
37031 this.relayEvents(ci, ["select"]);
37033 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
37035 * Ext JS Library 1.1.1
37036 * Copyright(c) 2006-2007, Ext JS, LLC.
37038 * Originally Released Under LGPL - original licence link has changed is not relivant.
37041 * <script type="text/javascript">
37045 * @class Roo.form.Field
37046 * @extends Roo.BoxComponent
37047 * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
37049 * Creates a new Field
37050 * @param {Object} config Configuration options
37052 Roo.form.Field = function(config){
37053 Roo.form.Field.superclass.constructor.call(this, config);
37056 Roo.extend(Roo.form.Field, Roo.BoxComponent, {
37058 * @cfg {String} fieldLabel Label to use when rendering a form.
37061 * @cfg {String} qtip Mouse over tip
37065 * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
37067 invalidClass : "x-form-invalid",
37069 * @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")
37071 invalidText : "The value in this field is invalid",
37073 * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
37075 focusClass : "x-form-focus",
37077 * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
37078 automatic validation (defaults to "keyup").
37080 validationEvent : "keyup",
37082 * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
37084 validateOnBlur : true,
37086 * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
37088 validationDelay : 250,
37090 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
37091 * {tag: "input", type: "text", size: "20", autocomplete: "off"})
37093 defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
37095 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
37097 fieldClass : "x-form-field",
37099 * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'):
37102 ----------- ----------------------------------------------------------------------
37103 qtip Display a quick tip when the user hovers over the field
37104 title Display a default browser title attribute popup
37105 under Add a block div beneath the field containing the error text
37106 side Add an error icon to the right of the field with a popup on hover
37107 [element id] Add the error text directly to the innerHTML of the specified element
37110 msgTarget : 'qtip',
37112 * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
37117 * @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.
37122 * @cfg {Boolean} disabled True to disable the field (defaults to false).
37127 * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
37129 inputType : undefined,
37132 * @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).
37134 tabIndex : undefined,
37137 isFormField : true,
37142 * @property {Roo.Element} fieldEl
37143 * Element Containing the rendered Field (with label etc.)
37146 * @cfg {Mixed} value A value to initialize this field with.
37151 * @cfg {String} name The field's HTML name attribute.
37154 * @cfg {String} cls A CSS class to apply to the field's underlying element.
37158 initComponent : function(){
37159 Roo.form.Field.superclass.initComponent.call(this);
37163 * Fires when this field receives input focus.
37164 * @param {Roo.form.Field} this
37169 * Fires when this field loses input focus.
37170 * @param {Roo.form.Field} this
37174 * @event specialkey
37175 * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
37176 * {@link Roo.EventObject#getKey} to determine which key was pressed.
37177 * @param {Roo.form.Field} this
37178 * @param {Roo.EventObject} e The event object
37183 * Fires just before the field blurs if the field value has changed.
37184 * @param {Roo.form.Field} this
37185 * @param {Mixed} newValue The new value
37186 * @param {Mixed} oldValue The original value
37191 * Fires after the field has been marked as invalid.
37192 * @param {Roo.form.Field} this
37193 * @param {String} msg The validation message
37198 * Fires after the field has been validated with no errors.
37199 * @param {Roo.form.Field} this
37204 * Fires after the key up
37205 * @param {Roo.form.Field} this
37206 * @param {Roo.EventObject} e The event Object
37213 * Returns the name attribute of the field if available
37214 * @return {String} name The field name
37216 getName: function(){
37217 return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
37221 onRender : function(ct, position){
37222 Roo.form.Field.superclass.onRender.call(this, ct, position);
37224 var cfg = this.getAutoCreate();
37226 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
37228 if (!cfg.name.length) {
37231 if(this.inputType){
37232 cfg.type = this.inputType;
37234 this.el = ct.createChild(cfg, position);
37236 var type = this.el.dom.type;
37238 if(type == 'password'){
37241 this.el.addClass('x-form-'+type);
37244 this.el.dom.readOnly = true;
37246 if(this.tabIndex !== undefined){
37247 this.el.dom.setAttribute('tabIndex', this.tabIndex);
37250 this.el.addClass([this.fieldClass, this.cls]);
37255 * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
37256 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
37257 * @return {Roo.form.Field} this
37259 applyTo : function(target){
37260 this.allowDomMove = false;
37261 this.el = Roo.get(target);
37262 this.render(this.el.dom.parentNode);
37267 initValue : function(){
37268 if(this.value !== undefined){
37269 this.setValue(this.value);
37270 }else if(this.el.dom.value.length > 0){
37271 this.setValue(this.el.dom.value);
37276 * Returns true if this field has been changed since it was originally loaded and is not disabled.
37278 isDirty : function() {
37279 if(this.disabled) {
37282 return String(this.getValue()) !== String(this.originalValue);
37286 afterRender : function(){
37287 Roo.form.Field.superclass.afterRender.call(this);
37292 fireKey : function(e){
37293 //Roo.log('field ' + e.getKey());
37294 if(e.isNavKeyPress()){
37295 this.fireEvent("specialkey", this, e);
37300 * Resets the current field value to the originally loaded value and clears any validation messages
37302 reset : function(){
37303 this.setValue(this.resetValue);
37304 this.clearInvalid();
37308 initEvents : function(){
37309 // safari killled keypress - so keydown is now used..
37310 this.el.on("keydown" , this.fireKey, this);
37311 this.el.on("focus", this.onFocus, this);
37312 this.el.on("blur", this.onBlur, this);
37313 this.el.relayEvent('keyup', this);
37315 // reference to original value for reset
37316 this.originalValue = this.getValue();
37317 this.resetValue = this.getValue();
37321 onFocus : function(){
37322 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
37323 this.el.addClass(this.focusClass);
37325 if(!this.hasFocus){
37326 this.hasFocus = true;
37327 this.startValue = this.getValue();
37328 this.fireEvent("focus", this);
37332 beforeBlur : Roo.emptyFn,
37335 onBlur : function(){
37337 if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
37338 this.el.removeClass(this.focusClass);
37340 this.hasFocus = false;
37341 if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
37344 var v = this.getValue();
37345 if(String(v) !== String(this.startValue)){
37346 this.fireEvent('change', this, v, this.startValue);
37348 this.fireEvent("blur", this);
37352 * Returns whether or not the field value is currently valid
37353 * @param {Boolean} preventMark True to disable marking the field invalid
37354 * @return {Boolean} True if the value is valid, else false
37356 isValid : function(preventMark){
37360 var restore = this.preventMark;
37361 this.preventMark = preventMark === true;
37362 var v = this.validateValue(this.processValue(this.getRawValue()));
37363 this.preventMark = restore;
37368 * Validates the field value
37369 * @return {Boolean} True if the value is valid, else false
37371 validate : function(){
37372 if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
37373 this.clearInvalid();
37379 processValue : function(value){
37384 // Subclasses should provide the validation implementation by overriding this
37385 validateValue : function(value){
37390 * Mark this field as invalid
37391 * @param {String} msg The validation message
37393 markInvalid : function(msg){
37394 if(!this.rendered || this.preventMark){ // not rendered
37398 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
37400 obj.el.addClass(this.invalidClass);
37401 msg = msg || this.invalidText;
37402 switch(this.msgTarget){
37404 obj.el.dom.qtip = msg;
37405 obj.el.dom.qclass = 'x-form-invalid-tip';
37406 if(Roo.QuickTips){ // fix for floating editors interacting with DND
37407 Roo.QuickTips.enable();
37411 this.el.dom.title = msg;
37415 var elp = this.el.findParent('.x-form-element', 5, true);
37416 this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
37417 this.errorEl.setWidth(elp.getWidth(true)-20);
37419 this.errorEl.update(msg);
37420 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
37423 if(!this.errorIcon){
37424 var elp = this.el.findParent('.x-form-element', 5, true);
37425 this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
37427 this.alignErrorIcon();
37428 this.errorIcon.dom.qtip = msg;
37429 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
37430 this.errorIcon.show();
37431 this.on('resize', this.alignErrorIcon, this);
37434 var t = Roo.getDom(this.msgTarget);
37436 t.style.display = this.msgDisplay;
37439 this.fireEvent('invalid', this, msg);
37443 alignErrorIcon : function(){
37444 this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
37448 * Clear any invalid styles/messages for this field
37450 clearInvalid : function(){
37451 if(!this.rendered || this.preventMark){ // not rendered
37454 var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
37456 obj.el.removeClass(this.invalidClass);
37457 switch(this.msgTarget){
37459 obj.el.dom.qtip = '';
37462 this.el.dom.title = '';
37466 Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
37470 if(this.errorIcon){
37471 this.errorIcon.dom.qtip = '';
37472 this.errorIcon.hide();
37473 this.un('resize', this.alignErrorIcon, this);
37477 var t = Roo.getDom(this.msgTarget);
37479 t.style.display = 'none';
37482 this.fireEvent('valid', this);
37486 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
37487 * @return {Mixed} value The field value
37489 getRawValue : function(){
37490 var v = this.el.getValue();
37496 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
37497 * @return {Mixed} value The field value
37499 getValue : function(){
37500 var v = this.el.getValue();
37506 * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
37507 * @param {Mixed} value The value to set
37509 setRawValue : function(v){
37510 return this.el.dom.value = (v === null || v === undefined ? '' : v);
37514 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
37515 * @param {Mixed} value The value to set
37517 setValue : function(v){
37520 this.el.dom.value = (v === null || v === undefined ? '' : v);
37525 adjustSize : function(w, h){
37526 var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
37527 s.width = this.adjustWidth(this.el.dom.tagName, s.width);
37531 adjustWidth : function(tag, w){
37532 tag = tag.toLowerCase();
37533 if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
37534 if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
37535 if(tag == 'input'){
37538 if(tag == 'textarea'){
37541 }else if(Roo.isOpera){
37542 if(tag == 'input'){
37545 if(tag == 'textarea'){
37555 // anything other than normal should be considered experimental
37556 Roo.form.Field.msgFx = {
37558 show: function(msgEl, f){
37559 msgEl.setDisplayed('block');
37562 hide : function(msgEl, f){
37563 msgEl.setDisplayed(false).update('');
37568 show: function(msgEl, f){
37569 msgEl.slideIn('t', {stopFx:true});
37572 hide : function(msgEl, f){
37573 msgEl.slideOut('t', {stopFx:true,useDisplay:true});
37578 show: function(msgEl, f){
37579 msgEl.fixDisplay();
37580 msgEl.alignTo(f.el, 'tl-tr');
37581 msgEl.slideIn('l', {stopFx:true});
37584 hide : function(msgEl, f){
37585 msgEl.slideOut('l', {stopFx:true,useDisplay:true});
37590 * Ext JS Library 1.1.1
37591 * Copyright(c) 2006-2007, Ext JS, LLC.
37593 * Originally Released Under LGPL - original licence link has changed is not relivant.
37596 * <script type="text/javascript">
37601 * @class Roo.form.TextField
37602 * @extends Roo.form.Field
37603 * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base
37604 * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
37606 * Creates a new TextField
37607 * @param {Object} config Configuration options
37609 Roo.form.TextField = function(config){
37610 Roo.form.TextField.superclass.constructor.call(this, config);
37614 * Fires when the autosize function is triggered. The field may or may not have actually changed size
37615 * according to the default logic, but this event provides a hook for the developer to apply additional
37616 * logic at runtime to resize the field if needed.
37617 * @param {Roo.form.Field} this This text field
37618 * @param {Number} width The new field width
37624 Roo.extend(Roo.form.TextField, Roo.form.Field, {
37626 * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
37630 * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
37634 * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
37638 * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
37642 * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
37646 * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
37648 disableKeyFilter : false,
37650 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
37654 * @cfg {Number} minLength Minimum input field length required (defaults to 0)
37658 * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
37660 maxLength : Number.MAX_VALUE,
37662 * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
37664 minLengthText : "The minimum length for this field is {0}",
37666 * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
37668 maxLengthText : "The maximum length for this field is {0}",
37670 * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
37672 selectOnFocus : false,
37674 * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
37676 blankText : "This field is required",
37678 * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
37679 * If available, this function will be called only after the basic validators all return true, and will be passed the
37680 * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
37684 * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
37685 * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
37686 * current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
37690 * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
37694 * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
37700 initEvents : function()
37702 if (this.emptyText) {
37703 this.el.attr('placeholder', this.emptyText);
37706 Roo.form.TextField.superclass.initEvents.call(this);
37707 if(this.validationEvent == 'keyup'){
37708 this.validationTask = new Roo.util.DelayedTask(this.validate, this);
37709 this.el.on('keyup', this.filterValidation, this);
37711 else if(this.validationEvent !== false){
37712 this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
37715 if(this.selectOnFocus){
37716 this.on("focus", this.preFocus, this);
37719 if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
37720 this.el.on("keypress", this.filterKeys, this);
37723 this.el.on("keyup", this.onKeyUp, this, {buffer:50});
37724 this.el.on("click", this.autoSize, this);
37726 if(this.el.is('input[type=password]') && Roo.isSafari){
37727 this.el.on('keydown', this.SafariOnKeyDown, this);
37731 processValue : function(value){
37732 if(this.stripCharsRe){
37733 var newValue = value.replace(this.stripCharsRe, '');
37734 if(newValue !== value){
37735 this.setRawValue(newValue);
37742 filterValidation : function(e){
37743 if(!e.isNavKeyPress()){
37744 this.validationTask.delay(this.validationDelay);
37749 onKeyUp : function(e){
37750 if(!e.isNavKeyPress()){
37756 * Resets the current field value to the originally-loaded value and clears any validation messages.
37759 reset : function(){
37760 Roo.form.TextField.superclass.reset.call(this);
37766 preFocus : function(){
37768 if(this.selectOnFocus){
37769 this.el.dom.select();
37775 filterKeys : function(e){
37776 var k = e.getKey();
37777 if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
37780 var c = e.getCharCode(), cc = String.fromCharCode(c);
37781 if(Roo.isIE && (e.isSpecialKey() || !cc)){
37784 if(!this.maskRe.test(cc)){
37789 setValue : function(v){
37791 Roo.form.TextField.superclass.setValue.apply(this, arguments);
37797 * Validates a value according to the field's validation rules and marks the field as invalid
37798 * if the validation fails
37799 * @param {Mixed} value The value to validate
37800 * @return {Boolean} True if the value is valid, else false
37802 validateValue : function(value){
37803 if(value.length < 1) { // if it's blank
37804 if(this.allowBlank){
37805 this.clearInvalid();
37808 this.markInvalid(this.blankText);
37812 if(value.length < this.minLength){
37813 this.markInvalid(String.format(this.minLengthText, this.minLength));
37816 if(value.length > this.maxLength){
37817 this.markInvalid(String.format(this.maxLengthText, this.maxLength));
37821 var vt = Roo.form.VTypes;
37822 if(!vt[this.vtype](value, this)){
37823 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
37827 if(typeof this.validator == "function"){
37828 var msg = this.validator(value);
37830 this.markInvalid(msg);
37834 if(this.regex && !this.regex.test(value)){
37835 this.markInvalid(this.regexText);
37842 * Selects text in this field
37843 * @param {Number} start (optional) The index where the selection should start (defaults to 0)
37844 * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
37846 selectText : function(start, end){
37847 var v = this.getRawValue();
37849 start = start === undefined ? 0 : start;
37850 end = end === undefined ? v.length : end;
37851 var d = this.el.dom;
37852 if(d.setSelectionRange){
37853 d.setSelectionRange(start, end);
37854 }else if(d.createTextRange){
37855 var range = d.createTextRange();
37856 range.moveStart("character", start);
37857 range.moveEnd("character", v.length-end);
37864 * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
37865 * This only takes effect if grow = true, and fires the autosize event.
37867 autoSize : function(){
37868 if(!this.grow || !this.rendered){
37872 this.metrics = Roo.util.TextMetrics.createInstance(this.el);
37875 var v = el.dom.value;
37876 var d = document.createElement('div');
37877 d.appendChild(document.createTextNode(v));
37881 var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
37882 this.el.setWidth(w);
37883 this.fireEvent("autosize", this, w);
37887 SafariOnKeyDown : function(event)
37889 // this is a workaround for a password hang bug on chrome/ webkit.
37891 var isSelectAll = false;
37893 if(this.el.dom.selectionEnd > 0){
37894 isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
37896 if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
37897 event.preventDefault();
37902 if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
37904 event.preventDefault();
37905 // this is very hacky as keydown always get's upper case.
37907 var cc = String.fromCharCode(event.getCharCode());
37910 this.setValue( event.shiftKey ? cc : cc.toLowerCase());
37918 * Ext JS Library 1.1.1
37919 * Copyright(c) 2006-2007, Ext JS, LLC.
37921 * Originally Released Under LGPL - original licence link has changed is not relivant.
37924 * <script type="text/javascript">
37928 * @class Roo.form.Hidden
37929 * @extends Roo.form.TextField
37930 * Simple Hidden element used on forms
37932 * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
37935 * Creates a new Hidden form element.
37936 * @param {Object} config Configuration options
37941 // easy hidden field...
37942 Roo.form.Hidden = function(config){
37943 Roo.form.Hidden.superclass.constructor.call(this, config);
37946 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
37948 inputType: 'hidden',
37951 labelSeparator: '',
37953 itemCls : 'x-form-item-display-none'
37961 * Ext JS Library 1.1.1
37962 * Copyright(c) 2006-2007, Ext JS, LLC.
37964 * Originally Released Under LGPL - original licence link has changed is not relivant.
37967 * <script type="text/javascript">
37971 * @class Roo.form.TriggerField
37972 * @extends Roo.form.TextField
37973 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
37974 * The trigger has no default action, so you must assign a function to implement the trigger click handler by
37975 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
37976 * for which you can provide a custom implementation. For example:
37978 var trigger = new Roo.form.TriggerField();
37979 trigger.onTriggerClick = myTriggerFn;
37980 trigger.applyTo('my-field');
37983 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
37984 * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
37985 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
37986 * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
37988 * Create a new TriggerField.
37989 * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
37990 * to the base TextField)
37992 Roo.form.TriggerField = function(config){
37993 this.mimicing = false;
37994 Roo.form.TriggerField.superclass.constructor.call(this, config);
37997 Roo.extend(Roo.form.TriggerField, Roo.form.TextField, {
37999 * @cfg {String} triggerClass A CSS class to apply to the trigger
38002 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
38003 * {tag: "input", type: "text", size: "16", autocomplete: "off"})
38005 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
38007 * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
38011 /** @cfg {Boolean} grow @hide */
38012 /** @cfg {Number} growMin @hide */
38013 /** @cfg {Number} growMax @hide */
38019 autoSize: Roo.emptyFn,
38023 deferHeight : true,
38026 actionMode : 'wrap',
38028 onResize : function(w, h){
38029 Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
38030 if(typeof w == 'number'){
38031 var x = w - this.trigger.getWidth();
38032 this.el.setWidth(this.adjustWidth('input', x));
38033 this.trigger.setStyle('left', x+'px');
38038 adjustSize : Roo.BoxComponent.prototype.adjustSize,
38041 getResizeEl : function(){
38046 getPositionEl : function(){
38051 alignErrorIcon : function(){
38052 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
38056 onRender : function(ct, position){
38057 Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
38058 this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
38059 this.trigger = this.wrap.createChild(this.triggerConfig ||
38060 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
38061 if(this.hideTrigger){
38062 this.trigger.setDisplayed(false);
38064 this.initTrigger();
38066 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
38071 initTrigger : function(){
38072 this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
38073 this.trigger.addClassOnOver('x-form-trigger-over');
38074 this.trigger.addClassOnClick('x-form-trigger-click');
38078 onDestroy : function(){
38080 this.trigger.removeAllListeners();
38081 this.trigger.remove();
38084 this.wrap.remove();
38086 Roo.form.TriggerField.superclass.onDestroy.call(this);
38090 onFocus : function(){
38091 Roo.form.TriggerField.superclass.onFocus.call(this);
38092 if(!this.mimicing){
38093 this.wrap.addClass('x-trigger-wrap-focus');
38094 this.mimicing = true;
38095 Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
38096 if(this.monitorTab){
38097 this.el.on("keydown", this.checkTab, this);
38103 checkTab : function(e){
38104 if(e.getKey() == e.TAB){
38105 this.triggerBlur();
38110 onBlur : function(){
38115 mimicBlur : function(e, t){
38116 if(!this.wrap.contains(t) && this.validateBlur()){
38117 this.triggerBlur();
38122 triggerBlur : function(){
38123 this.mimicing = false;
38124 Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
38125 if(this.monitorTab){
38126 this.el.un("keydown", this.checkTab, this);
38128 this.wrap.removeClass('x-trigger-wrap-focus');
38129 Roo.form.TriggerField.superclass.onBlur.call(this);
38133 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
38134 validateBlur : function(e, t){
38139 onDisable : function(){
38140 Roo.form.TriggerField.superclass.onDisable.call(this);
38142 this.wrap.addClass('x-item-disabled');
38147 onEnable : function(){
38148 Roo.form.TriggerField.superclass.onEnable.call(this);
38150 this.wrap.removeClass('x-item-disabled');
38155 onShow : function(){
38156 var ae = this.getActionEl();
38159 ae.dom.style.display = '';
38160 ae.dom.style.visibility = 'visible';
38166 onHide : function(){
38167 var ae = this.getActionEl();
38168 ae.dom.style.display = 'none';
38172 * The function that should handle the trigger's click event. This method does nothing by default until overridden
38173 * by an implementing function.
38175 * @param {EventObject} e
38177 onTriggerClick : Roo.emptyFn
38180 // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
38181 // to be extended by an implementing class. For an example of implementing this class, see the custom
38182 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
38183 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
38184 initComponent : function(){
38185 Roo.form.TwinTriggerField.superclass.initComponent.call(this);
38187 this.triggerConfig = {
38188 tag:'span', cls:'x-form-twin-triggers', cn:[
38189 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
38190 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
38194 getTrigger : function(index){
38195 return this.triggers[index];
38198 initTrigger : function(){
38199 var ts = this.trigger.select('.x-form-trigger', true);
38200 this.wrap.setStyle('overflow', 'hidden');
38201 var triggerField = this;
38202 ts.each(function(t, all, index){
38203 t.hide = function(){
38204 var w = triggerField.wrap.getWidth();
38205 this.dom.style.display = 'none';
38206 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
38208 t.show = function(){
38209 var w = triggerField.wrap.getWidth();
38210 this.dom.style.display = '';
38211 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
38213 var triggerIndex = 'Trigger'+(index+1);
38215 if(this['hide'+triggerIndex]){
38216 t.dom.style.display = 'none';
38218 t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
38219 t.addClassOnOver('x-form-trigger-over');
38220 t.addClassOnClick('x-form-trigger-click');
38222 this.triggers = ts.elements;
38225 onTrigger1Click : Roo.emptyFn,
38226 onTrigger2Click : Roo.emptyFn
38229 * Ext JS Library 1.1.1
38230 * Copyright(c) 2006-2007, Ext JS, LLC.
38232 * Originally Released Under LGPL - original licence link has changed is not relivant.
38235 * <script type="text/javascript">
38239 * @class Roo.form.TextArea
38240 * @extends Roo.form.TextField
38241 * Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
38242 * support for auto-sizing.
38244 * Creates a new TextArea
38245 * @param {Object} config Configuration options
38247 Roo.form.TextArea = function(config){
38248 Roo.form.TextArea.superclass.constructor.call(this, config);
38249 // these are provided exchanges for backwards compat
38250 // minHeight/maxHeight were replaced by growMin/growMax to be
38251 // compatible with TextField growing config values
38252 if(this.minHeight !== undefined){
38253 this.growMin = this.minHeight;
38255 if(this.maxHeight !== undefined){
38256 this.growMax = this.maxHeight;
38260 Roo.extend(Roo.form.TextArea, Roo.form.TextField, {
38262 * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
38266 * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
38270 * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
38271 * in the field (equivalent to setting overflow: hidden, defaults to false)
38273 preventScrollbars: false,
38275 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
38276 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
38280 onRender : function(ct, position){
38282 this.defaultAutoCreate = {
38284 style:"width:300px;height:60px;",
38285 autocomplete: "new-password"
38288 Roo.form.TextArea.superclass.onRender.call(this, ct, position);
38290 this.textSizeEl = Roo.DomHelper.append(document.body, {
38291 tag: "pre", cls: "x-form-grow-sizer"
38293 if(this.preventScrollbars){
38294 this.el.setStyle("overflow", "hidden");
38296 this.el.setHeight(this.growMin);
38300 onDestroy : function(){
38301 if(this.textSizeEl){
38302 this.textSizeEl.parentNode.removeChild(this.textSizeEl);
38304 Roo.form.TextArea.superclass.onDestroy.call(this);
38308 onKeyUp : function(e){
38309 if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
38315 * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
38316 * This only takes effect if grow = true, and fires the autosize event if the height changes.
38318 autoSize : function(){
38319 if(!this.grow || !this.textSizeEl){
38323 var v = el.dom.value;
38324 var ts = this.textSizeEl;
38327 ts.appendChild(document.createTextNode(v));
38330 Roo.fly(ts).setWidth(this.el.getWidth());
38332 v = "  ";
38335 v = v.replace(/\n/g, '<p> </p>');
38337 v += " \n ";
38340 var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
38341 if(h != this.lastHeight){
38342 this.lastHeight = h;
38343 this.el.setHeight(h);
38344 this.fireEvent("autosize", this, h);
38349 * Ext JS Library 1.1.1
38350 * Copyright(c) 2006-2007, Ext JS, LLC.
38352 * Originally Released Under LGPL - original licence link has changed is not relivant.
38355 * <script type="text/javascript">
38360 * @class Roo.form.NumberField
38361 * @extends Roo.form.TextField
38362 * Numeric text field that provides automatic keystroke filtering and numeric validation.
38364 * Creates a new NumberField
38365 * @param {Object} config Configuration options
38367 Roo.form.NumberField = function(config){
38368 Roo.form.NumberField.superclass.constructor.call(this, config);
38371 Roo.extend(Roo.form.NumberField, Roo.form.TextField, {
38373 * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
38375 fieldClass: "x-form-field x-form-num-field",
38377 * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
38379 allowDecimals : true,
38381 * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
38383 decimalSeparator : ".",
38385 * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
38387 decimalPrecision : 2,
38389 * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
38391 allowNegative : true,
38393 * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
38395 minValue : Number.NEGATIVE_INFINITY,
38397 * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
38399 maxValue : Number.MAX_VALUE,
38401 * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
38403 minText : "The minimum value for this field is {0}",
38405 * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
38407 maxText : "The maximum value for this field is {0}",
38409 * @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
38410 * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
38412 nanText : "{0} is not a valid number",
38415 initEvents : function(){
38416 Roo.form.NumberField.superclass.initEvents.call(this);
38417 var allowed = "0123456789";
38418 if(this.allowDecimals){
38419 allowed += this.decimalSeparator;
38421 if(this.allowNegative){
38424 this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
38425 var keyPress = function(e){
38426 var k = e.getKey();
38427 if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
38430 var c = e.getCharCode();
38431 if(allowed.indexOf(String.fromCharCode(c)) === -1){
38435 this.el.on("keypress", keyPress, this);
38439 validateValue : function(value){
38440 if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
38443 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
38446 var num = this.parseValue(value);
38448 this.markInvalid(String.format(this.nanText, value));
38451 if(num < this.minValue){
38452 this.markInvalid(String.format(this.minText, this.minValue));
38455 if(num > this.maxValue){
38456 this.markInvalid(String.format(this.maxText, this.maxValue));
38462 getValue : function(){
38463 return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
38467 parseValue : function(value){
38468 value = parseFloat(String(value).replace(this.decimalSeparator, "."));
38469 return isNaN(value) ? '' : value;
38473 fixPrecision : function(value){
38474 var nan = isNaN(value);
38475 if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
38476 return nan ? '' : value;
38478 return parseFloat(value).toFixed(this.decimalPrecision);
38481 setValue : function(v){
38482 v = this.fixPrecision(v);
38483 Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
38487 decimalPrecisionFcn : function(v){
38488 return Math.floor(v);
38491 beforeBlur : function(){
38492 var v = this.parseValue(this.getRawValue());
38499 * Ext JS Library 1.1.1
38500 * Copyright(c) 2006-2007, Ext JS, LLC.
38502 * Originally Released Under LGPL - original licence link has changed is not relivant.
38505 * <script type="text/javascript">
38509 * @class Roo.form.DateField
38510 * @extends Roo.form.TriggerField
38511 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
38513 * Create a new DateField
38514 * @param {Object} config
38516 Roo.form.DateField = function(config){
38517 Roo.form.DateField.superclass.constructor.call(this, config);
38523 * Fires when a date is selected
38524 * @param {Roo.form.DateField} combo This combo box
38525 * @param {Date} date The date selected
38532 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
38533 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
38534 this.ddMatch = null;
38535 if(this.disabledDates){
38536 var dd = this.disabledDates;
38538 for(var i = 0; i < dd.length; i++){
38540 if(i != dd.length-1) re += "|";
38542 this.ddMatch = new RegExp(re + ")");
38546 Roo.extend(Roo.form.DateField, Roo.form.TriggerField, {
38548 * @cfg {String} format
38549 * The default date format string which can be overriden for localization support. The format must be
38550 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
38554 * @cfg {String} altFormats
38555 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
38556 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
38558 altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
38560 * @cfg {Array} disabledDays
38561 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
38563 disabledDays : null,
38565 * @cfg {String} disabledDaysText
38566 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
38568 disabledDaysText : "Disabled",
38570 * @cfg {Array} disabledDates
38571 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
38572 * expression so they are very powerful. Some examples:
38574 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
38575 * <li>["03/08", "09/16"] would disable those days for every year</li>
38576 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
38577 * <li>["03/../2006"] would disable every day in March 2006</li>
38578 * <li>["^03"] would disable every day in every March</li>
38580 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
38581 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
38583 disabledDates : null,
38585 * @cfg {String} disabledDatesText
38586 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
38588 disabledDatesText : "Disabled",
38590 * @cfg {Date/String} minValue
38591 * The minimum allowed date. Can be either a Javascript date object or a string date in a
38592 * valid format (defaults to null).
38596 * @cfg {Date/String} maxValue
38597 * The maximum allowed date. Can be either a Javascript date object or a string date in a
38598 * valid format (defaults to null).
38602 * @cfg {String} minText
38603 * The error text to display when the date in the cell is before minValue (defaults to
38604 * 'The date in this field must be after {minValue}').
38606 minText : "The date in this field must be equal to or after {0}",
38608 * @cfg {String} maxText
38609 * The error text to display when the date in the cell is after maxValue (defaults to
38610 * 'The date in this field must be before {maxValue}').
38612 maxText : "The date in this field must be equal to or before {0}",
38614 * @cfg {String} invalidText
38615 * The error text to display when the date in the field is invalid (defaults to
38616 * '{value} is not a valid date - it must be in the format {format}').
38618 invalidText : "{0} is not a valid date - it must be in the format {1}",
38620 * @cfg {String} triggerClass
38621 * An additional CSS class used to style the trigger button. The trigger will always get the
38622 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
38623 * which displays a calendar icon).
38625 triggerClass : 'x-form-date-trigger',
38629 * @cfg {Boolean} useIso
38630 * if enabled, then the date field will use a hidden field to store the
38631 * real value as iso formated date. default (false)
38635 * @cfg {String/Object} autoCreate
38636 * A DomHelper element spec, or true for a default element spec (defaults to
38637 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
38640 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
38643 hiddenField: false,
38645 onRender : function(ct, position)
38647 Roo.form.DateField.superclass.onRender.call(this, ct, position);
38649 //this.el.dom.removeAttribute('name');
38650 Roo.log("Changing name?");
38651 this.el.dom.setAttribute('name', this.name + '____hidden___' );
38652 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
38654 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
38655 // prevent input submission
38656 this.hiddenName = this.name;
38663 validateValue : function(value)
38665 value = this.formatDate(value);
38666 if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
38667 Roo.log('super failed');
38670 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
38673 var svalue = value;
38674 value = this.parseDate(value);
38676 Roo.log('parse date failed' + svalue);
38677 this.markInvalid(String.format(this.invalidText, svalue, this.format));
38680 var time = value.getTime();
38681 if(this.minValue && time < this.minValue.getTime()){
38682 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
38685 if(this.maxValue && time > this.maxValue.getTime()){
38686 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
38689 if(this.disabledDays){
38690 var day = value.getDay();
38691 for(var i = 0; i < this.disabledDays.length; i++) {
38692 if(day === this.disabledDays[i]){
38693 this.markInvalid(this.disabledDaysText);
38698 var fvalue = this.formatDate(value);
38699 if(this.ddMatch && this.ddMatch.test(fvalue)){
38700 this.markInvalid(String.format(this.disabledDatesText, fvalue));
38707 // Provides logic to override the default TriggerField.validateBlur which just returns true
38708 validateBlur : function(){
38709 return !this.menu || !this.menu.isVisible();
38712 getName: function()
38714 // returns hidden if it's set..
38715 if (!this.rendered) {return ''};
38716 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
38721 * Returns the current date value of the date field.
38722 * @return {Date} The date value
38724 getValue : function(){
38726 return this.hiddenField ?
38727 this.hiddenField.value :
38728 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
38732 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
38733 * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
38734 * (the default format used is "m/d/y").
38737 //All of these calls set the same date value (May 4, 2006)
38739 //Pass a date object:
38740 var dt = new Date('5/4/06');
38741 dateField.setValue(dt);
38743 //Pass a date string (default format):
38744 dateField.setValue('5/4/06');
38746 //Pass a date string (custom format):
38747 dateField.format = 'Y-m-d';
38748 dateField.setValue('2006-5-4');
38750 * @param {String/Date} date The date or valid date string
38752 setValue : function(date){
38753 if (this.hiddenField) {
38754 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
38756 Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
38757 // make sure the value field is always stored as a date..
38758 this.value = this.parseDate(date);
38764 parseDate : function(value){
38765 if(!value || value instanceof Date){
38768 var v = Date.parseDate(value, this.format);
38769 if (!v && this.useIso) {
38770 v = Date.parseDate(value, 'Y-m-d');
38772 if(!v && this.altFormats){
38773 if(!this.altFormatsArray){
38774 this.altFormatsArray = this.altFormats.split("|");
38776 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
38777 v = Date.parseDate(value, this.altFormatsArray[i]);
38784 formatDate : function(date, fmt){
38785 return (!date || !(date instanceof Date)) ?
38786 date : date.dateFormat(fmt || this.format);
38791 select: function(m, d){
38794 this.fireEvent('select', this, d);
38796 show : function(){ // retain focus styling
38800 this.focus.defer(10, this);
38801 var ml = this.menuListeners;
38802 this.menu.un("select", ml.select, this);
38803 this.menu.un("show", ml.show, this);
38804 this.menu.un("hide", ml.hide, this);
38809 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
38810 onTriggerClick : function(){
38814 if(this.menu == null){
38815 this.menu = new Roo.menu.DateMenu();
38817 Roo.apply(this.menu.picker, {
38818 showClear: this.allowBlank,
38819 minDate : this.minValue,
38820 maxDate : this.maxValue,
38821 disabledDatesRE : this.ddMatch,
38822 disabledDatesText : this.disabledDatesText,
38823 disabledDays : this.disabledDays,
38824 disabledDaysText : this.disabledDaysText,
38825 format : this.useIso ? 'Y-m-d' : this.format,
38826 minText : String.format(this.minText, this.formatDate(this.minValue)),
38827 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
38829 this.menu.on(Roo.apply({}, this.menuListeners, {
38832 this.menu.picker.setValue(this.getValue() || new Date());
38833 this.menu.show(this.el, "tl-bl?");
38836 beforeBlur : function(){
38837 var v = this.parseDate(this.getRawValue());
38847 isDirty : function() {
38848 if(this.disabled) {
38852 if(typeof(this.startValue) === 'undefined'){
38856 return String(this.getValue()) !== String(this.startValue);
38861 * Ext JS Library 1.1.1
38862 * Copyright(c) 2006-2007, Ext JS, LLC.
38864 * Originally Released Under LGPL - original licence link has changed is not relivant.
38867 * <script type="text/javascript">
38871 * @class Roo.form.MonthField
38872 * @extends Roo.form.TriggerField
38873 * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
38875 * Create a new MonthField
38876 * @param {Object} config
38878 Roo.form.MonthField = function(config){
38880 Roo.form.MonthField.superclass.constructor.call(this, config);
38886 * Fires when a date is selected
38887 * @param {Roo.form.MonthFieeld} combo This combo box
38888 * @param {Date} date The date selected
38895 if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
38896 if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
38897 this.ddMatch = null;
38898 if(this.disabledDates){
38899 var dd = this.disabledDates;
38901 for(var i = 0; i < dd.length; i++){
38903 if(i != dd.length-1) re += "|";
38905 this.ddMatch = new RegExp(re + ")");
38909 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField, {
38911 * @cfg {String} format
38912 * The default date format string which can be overriden for localization support. The format must be
38913 * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
38917 * @cfg {String} altFormats
38918 * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
38919 * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
38921 altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
38923 * @cfg {Array} disabledDays
38924 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
38926 disabledDays : [0,1,2,3,4,5,6],
38928 * @cfg {String} disabledDaysText
38929 * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
38931 disabledDaysText : "Disabled",
38933 * @cfg {Array} disabledDates
38934 * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
38935 * expression so they are very powerful. Some examples:
38937 * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
38938 * <li>["03/08", "09/16"] would disable those days for every year</li>
38939 * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
38940 * <li>["03/../2006"] would disable every day in March 2006</li>
38941 * <li>["^03"] would disable every day in every March</li>
38943 * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
38944 * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
38946 disabledDates : null,
38948 * @cfg {String} disabledDatesText
38949 * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
38951 disabledDatesText : "Disabled",
38953 * @cfg {Date/String} minValue
38954 * The minimum allowed date. Can be either a Javascript date object or a string date in a
38955 * valid format (defaults to null).
38959 * @cfg {Date/String} maxValue
38960 * The maximum allowed date. Can be either a Javascript date object or a string date in a
38961 * valid format (defaults to null).
38965 * @cfg {String} minText
38966 * The error text to display when the date in the cell is before minValue (defaults to
38967 * 'The date in this field must be after {minValue}').
38969 minText : "The date in this field must be equal to or after {0}",
38971 * @cfg {String} maxTextf
38972 * The error text to display when the date in the cell is after maxValue (defaults to
38973 * 'The date in this field must be before {maxValue}').
38975 maxText : "The date in this field must be equal to or before {0}",
38977 * @cfg {String} invalidText
38978 * The error text to display when the date in the field is invalid (defaults to
38979 * '{value} is not a valid date - it must be in the format {format}').
38981 invalidText : "{0} is not a valid date - it must be in the format {1}",
38983 * @cfg {String} triggerClass
38984 * An additional CSS class used to style the trigger button. The trigger will always get the
38985 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
38986 * which displays a calendar icon).
38988 triggerClass : 'x-form-date-trigger',
38992 * @cfg {Boolean} useIso
38993 * if enabled, then the date field will use a hidden field to store the
38994 * real value as iso formated date. default (true)
38998 * @cfg {String/Object} autoCreate
38999 * A DomHelper element spec, or true for a default element spec (defaults to
39000 * {tag: "input", type: "text", size: "10", autocomplete: "off"})
39003 defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
39006 hiddenField: false,
39008 hideMonthPicker : false,
39010 onRender : function(ct, position)
39012 Roo.form.MonthField.superclass.onRender.call(this, ct, position);
39014 this.el.dom.removeAttribute('name');
39015 this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
39017 this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
39018 // prevent input submission
39019 this.hiddenName = this.name;
39026 validateValue : function(value)
39028 value = this.formatDate(value);
39029 if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
39032 if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
39035 var svalue = value;
39036 value = this.parseDate(value);
39038 this.markInvalid(String.format(this.invalidText, svalue, this.format));
39041 var time = value.getTime();
39042 if(this.minValue && time < this.minValue.getTime()){
39043 this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
39046 if(this.maxValue && time > this.maxValue.getTime()){
39047 this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
39050 /*if(this.disabledDays){
39051 var day = value.getDay();
39052 for(var i = 0; i < this.disabledDays.length; i++) {
39053 if(day === this.disabledDays[i]){
39054 this.markInvalid(this.disabledDaysText);
39060 var fvalue = this.formatDate(value);
39061 /*if(this.ddMatch && this.ddMatch.test(fvalue)){
39062 this.markInvalid(String.format(this.disabledDatesText, fvalue));
39070 // Provides logic to override the default TriggerField.validateBlur which just returns true
39071 validateBlur : function(){
39072 return !this.menu || !this.menu.isVisible();
39076 * Returns the current date value of the date field.
39077 * @return {Date} The date value
39079 getValue : function(){
39083 return this.hiddenField ?
39084 this.hiddenField.value :
39085 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
39089 * Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
39090 * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
39091 * (the default format used is "m/d/y").
39094 //All of these calls set the same date value (May 4, 2006)
39096 //Pass a date object:
39097 var dt = new Date('5/4/06');
39098 monthField.setValue(dt);
39100 //Pass a date string (default format):
39101 monthField.setValue('5/4/06');
39103 //Pass a date string (custom format):
39104 monthField.format = 'Y-m-d';
39105 monthField.setValue('2006-5-4');
39107 * @param {String/Date} date The date or valid date string
39109 setValue : function(date){
39110 Roo.log('month setValue' + date);
39111 // can only be first of month..
39113 var val = this.parseDate(date);
39115 if (this.hiddenField) {
39116 this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
39118 Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
39119 this.value = this.parseDate(date);
39123 parseDate : function(value){
39124 if(!value || value instanceof Date){
39125 value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
39128 var v = Date.parseDate(value, this.format);
39129 if (!v && this.useIso) {
39130 v = Date.parseDate(value, 'Y-m-d');
39134 v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
39138 if(!v && this.altFormats){
39139 if(!this.altFormatsArray){
39140 this.altFormatsArray = this.altFormats.split("|");
39142 for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
39143 v = Date.parseDate(value, this.altFormatsArray[i]);
39150 formatDate : function(date, fmt){
39151 return (!date || !(date instanceof Date)) ?
39152 date : date.dateFormat(fmt || this.format);
39157 select: function(m, d){
39159 this.fireEvent('select', this, d);
39161 show : function(){ // retain focus styling
39165 this.focus.defer(10, this);
39166 var ml = this.menuListeners;
39167 this.menu.un("select", ml.select, this);
39168 this.menu.un("show", ml.show, this);
39169 this.menu.un("hide", ml.hide, this);
39173 // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
39174 onTriggerClick : function(){
39178 if(this.menu == null){
39179 this.menu = new Roo.menu.DateMenu();
39183 Roo.apply(this.menu.picker, {
39185 showClear: this.allowBlank,
39186 minDate : this.minValue,
39187 maxDate : this.maxValue,
39188 disabledDatesRE : this.ddMatch,
39189 disabledDatesText : this.disabledDatesText,
39191 format : this.useIso ? 'Y-m-d' : this.format,
39192 minText : String.format(this.minText, this.formatDate(this.minValue)),
39193 maxText : String.format(this.maxText, this.formatDate(this.maxValue))
39196 this.menu.on(Roo.apply({}, this.menuListeners, {
39204 // hide month picker get's called when we called by 'before hide';
39206 var ignorehide = true;
39207 p.hideMonthPicker = function(disableAnim){
39211 if(this.monthPicker){
39212 Roo.log("hideMonthPicker called");
39213 if(disableAnim === true){
39214 this.monthPicker.hide();
39216 this.monthPicker.slideOut('t', {duration:.2});
39217 p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
39218 p.fireEvent("select", this, this.value);
39224 Roo.log('picker set value');
39225 Roo.log(this.getValue());
39226 p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
39227 m.show(this.el, 'tl-bl?');
39228 ignorehide = false;
39229 // this will trigger hideMonthPicker..
39232 // hidden the day picker
39233 Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
39239 p.showMonthPicker.defer(100, p);
39245 beforeBlur : function(){
39246 var v = this.parseDate(this.getRawValue());
39252 /** @cfg {Boolean} grow @hide */
39253 /** @cfg {Number} growMin @hide */
39254 /** @cfg {Number} growMax @hide */
39261 * Ext JS Library 1.1.1
39262 * Copyright(c) 2006-2007, Ext JS, LLC.
39264 * Originally Released Under LGPL - original licence link has changed is not relivant.
39267 * <script type="text/javascript">
39272 * @class Roo.form.ComboBox
39273 * @extends Roo.form.TriggerField
39274 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
39276 * Create a new ComboBox.
39277 * @param {Object} config Configuration options
39279 Roo.form.ComboBox = function(config){
39280 Roo.form.ComboBox.superclass.constructor.call(this, config);
39284 * Fires when the dropdown list is expanded
39285 * @param {Roo.form.ComboBox} combo This combo box
39290 * Fires when the dropdown list is collapsed
39291 * @param {Roo.form.ComboBox} combo This combo box
39295 * @event beforeselect
39296 * Fires before a list item is selected. Return false to cancel the selection.
39297 * @param {Roo.form.ComboBox} combo This combo box
39298 * @param {Roo.data.Record} record The data record returned from the underlying store
39299 * @param {Number} index The index of the selected item in the dropdown list
39301 'beforeselect' : true,
39304 * Fires when a list item is selected
39305 * @param {Roo.form.ComboBox} combo This combo box
39306 * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
39307 * @param {Number} index The index of the selected item in the dropdown list
39311 * @event beforequery
39312 * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
39313 * The event object passed has these properties:
39314 * @param {Roo.form.ComboBox} combo This combo box
39315 * @param {String} query The query
39316 * @param {Boolean} forceAll true to force "all" query
39317 * @param {Boolean} cancel true to cancel the query
39318 * @param {Object} e The query event object
39320 'beforequery': true,
39323 * Fires when the 'add' icon is pressed (add a listener to enable add button)
39324 * @param {Roo.form.ComboBox} combo This combo box
39329 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
39330 * @param {Roo.form.ComboBox} combo This combo box
39331 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
39337 if(this.transform){
39338 this.allowDomMove = false;
39339 var s = Roo.getDom(this.transform);
39340 if(!this.hiddenName){
39341 this.hiddenName = s.name;
39344 this.mode = 'local';
39345 var d = [], opts = s.options;
39346 for(var i = 0, len = opts.length;i < len; i++){
39348 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
39350 this.value = value;
39352 d.push([value, o.text]);
39354 this.store = new Roo.data.SimpleStore({
39356 fields: ['value', 'text'],
39359 this.valueField = 'value';
39360 this.displayField = 'text';
39362 s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
39363 if(!this.lazyRender){
39364 this.target = true;
39365 this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
39366 s.parentNode.removeChild(s); // remove it
39367 this.render(this.el.parentNode);
39369 s.parentNode.removeChild(s); // remove it
39374 this.store = Roo.factory(this.store, Roo.data);
39377 this.selectedIndex = -1;
39378 if(this.mode == 'local'){
39379 if(config.queryDelay === undefined){
39380 this.queryDelay = 10;
39382 if(config.minChars === undefined){
39388 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
39390 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
39393 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
39394 * rendering into an Roo.Editor, defaults to false)
39397 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
39398 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
39401 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
39404 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
39405 * the dropdown list (defaults to undefined, with no header element)
39409 * @cfg {String/Roo.Template} tpl The template to use to render the output
39413 defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
39415 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
39417 listWidth: undefined,
39419 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
39420 * mode = 'remote' or 'text' if mode = 'local')
39422 displayField: undefined,
39424 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
39425 * mode = 'remote' or 'value' if mode = 'local').
39426 * Note: use of a valueField requires the user make a selection
39427 * in order for a value to be mapped.
39429 valueField: undefined,
39433 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
39434 * field's data value (defaults to the underlying DOM element's name)
39436 hiddenName: undefined,
39438 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
39442 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
39444 selectedClass: 'x-combo-selected',
39446 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
39447 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
39448 * which displays a downward arrow icon).
39450 triggerClass : 'x-form-arrow-trigger',
39452 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
39456 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
39457 * anchor positions (defaults to 'tl-bl')
39459 listAlign: 'tl-bl?',
39461 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
39465 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
39466 * query specified by the allQuery config option (defaults to 'query')
39468 triggerAction: 'query',
39470 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
39471 * (defaults to 4, does not apply if editable = false)
39475 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
39476 * delay (typeAheadDelay) if it matches a known value (defaults to false)
39480 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
39481 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
39485 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
39486 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
39490 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
39491 * when editable = true (defaults to false)
39493 selectOnFocus:false,
39495 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
39497 queryParam: 'query',
39499 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
39500 * when mode = 'remote' (defaults to 'Loading...')
39502 loadingText: 'Loading...',
39504 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
39508 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
39512 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
39513 * traditional select (defaults to true)
39517 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
39521 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
39525 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
39526 * listWidth has a higher value)
39530 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
39531 * allow the user to set arbitrary text into the field (defaults to false)
39533 forceSelection:false,
39535 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
39536 * if typeAhead = true (defaults to 250)
39538 typeAheadDelay : 250,
39540 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
39541 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
39543 valueNotFoundText : undefined,
39545 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
39547 blockFocus : false,
39550 * @cfg {Boolean} disableClear Disable showing of clear button.
39552 disableClear : false,
39554 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
39556 alwaysQuery : false,
39562 // element that contains real text value.. (when hidden is used..)
39565 onRender : function(ct, position){
39566 Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
39567 if(this.hiddenName){
39568 this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)},
39570 this.hiddenField.value =
39571 this.hiddenValue !== undefined ? this.hiddenValue :
39572 this.value !== undefined ? this.value : '';
39574 // prevent input submission
39575 this.el.dom.removeAttribute('name');
39580 this.el.dom.setAttribute('autocomplete', 'off');
39583 var cls = 'x-combo-list';
39585 this.list = new Roo.Layer({
39586 shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
39589 var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
39590 this.list.setWidth(lw);
39591 this.list.swallowEvent('mousewheel');
39592 this.assetHeight = 0;
39595 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
39596 this.assetHeight += this.header.getHeight();
39599 this.innerList = this.list.createChild({cls:cls+'-inner'});
39600 this.innerList.on('mouseover', this.onViewOver, this);
39601 this.innerList.on('mousemove', this.onViewMove, this);
39602 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
39604 if(this.allowBlank && !this.pageSize && !this.disableClear){
39605 this.footer = this.list.createChild({cls:cls+'-ft'});
39606 this.pageTb = new Roo.Toolbar(this.footer);
39610 this.footer = this.list.createChild({cls:cls+'-ft'});
39611 this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
39612 {pageSize: this.pageSize});
39616 if (this.pageTb && this.allowBlank && !this.disableClear) {
39618 this.pageTb.add(new Roo.Toolbar.Fill(), {
39619 cls: 'x-btn-icon x-btn-clear',
39621 handler: function()
39624 _this.clearValue();
39625 _this.onSelect(false, -1);
39630 this.assetHeight += this.footer.getHeight();
39635 this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
39638 this.view = new Roo.View(this.innerList, this.tpl, {
39639 singleSelect:true, store: this.store, selectedClass: this.selectedClass
39642 this.view.on('click', this.onViewClick, this);
39644 this.store.on('beforeload', this.onBeforeLoad, this);
39645 this.store.on('load', this.onLoad, this);
39646 this.store.on('loadexception', this.onLoadException, this);
39648 if(this.resizable){
39649 this.resizer = new Roo.Resizable(this.list, {
39650 pinned:true, handles:'se'
39652 this.resizer.on('resize', function(r, w, h){
39653 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
39654 this.listWidth = w;
39655 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
39656 this.restrictHeight();
39658 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
39660 if(!this.editable){
39661 this.editable = true;
39662 this.setEditable(false);
39666 if (typeof(this.events.add.listeners) != 'undefined') {
39668 this.addicon = this.wrap.createChild(
39669 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });
39671 this.addicon.on('click', function(e) {
39672 this.fireEvent('add', this);
39675 if (typeof(this.events.edit.listeners) != 'undefined') {
39677 this.editicon = this.wrap.createChild(
39678 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });
39679 if (this.addicon) {
39680 this.editicon.setStyle('margin-left', '40px');
39682 this.editicon.on('click', function(e) {
39684 // we fire even if inothing is selected..
39685 this.fireEvent('edit', this, this.lastData );
39695 initEvents : function(){
39696 Roo.form.ComboBox.superclass.initEvents.call(this);
39698 this.keyNav = new Roo.KeyNav(this.el, {
39699 "up" : function(e){
39700 this.inKeyMode = true;
39704 "down" : function(e){
39705 if(!this.isExpanded()){
39706 this.onTriggerClick();
39708 this.inKeyMode = true;
39713 "enter" : function(e){
39714 this.onViewClick();
39718 "esc" : function(e){
39722 "tab" : function(e){
39723 this.onViewClick(false);
39724 this.fireEvent("specialkey", this, e);
39730 doRelay : function(foo, bar, hname){
39731 if(hname == 'down' || this.scope.isExpanded()){
39732 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
39739 this.queryDelay = Math.max(this.queryDelay || 10,
39740 this.mode == 'local' ? 10 : 250);
39741 this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
39742 if(this.typeAhead){
39743 this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
39745 if(this.editable !== false){
39746 this.el.on("keyup", this.onKeyUp, this);
39748 if(this.forceSelection){
39749 this.on('blur', this.doForce, this);
39753 onDestroy : function(){
39755 this.view.setStore(null);
39756 this.view.el.removeAllListeners();
39757 this.view.el.remove();
39758 this.view.purgeListeners();
39761 this.list.destroy();
39764 this.store.un('beforeload', this.onBeforeLoad, this);
39765 this.store.un('load', this.onLoad, this);
39766 this.store.un('loadexception', this.onLoadException, this);
39768 Roo.form.ComboBox.superclass.onDestroy.call(this);
39772 fireKey : function(e){
39773 if(e.isNavKeyPress() && !this.list.isVisible()){
39774 this.fireEvent("specialkey", this, e);
39779 onResize: function(w, h){
39780 Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
39782 if(typeof w != 'number'){
39783 // we do not handle it!?!?
39786 var tw = this.trigger.getWidth();
39787 tw += this.addicon ? this.addicon.getWidth() : 0;
39788 tw += this.editicon ? this.editicon.getWidth() : 0;
39790 this.el.setWidth( this.adjustWidth('input', x));
39792 this.trigger.setStyle('left', x+'px');
39794 if(this.list && this.listWidth === undefined){
39795 var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
39796 this.list.setWidth(lw);
39797 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
39805 * Allow or prevent the user from directly editing the field text. If false is passed,
39806 * the user will only be able to select from the items defined in the dropdown list. This method
39807 * is the runtime equivalent of setting the 'editable' config option at config time.
39808 * @param {Boolean} value True to allow the user to directly edit the field text
39810 setEditable : function(value){
39811 if(value == this.editable){
39814 this.editable = value;
39816 this.el.dom.setAttribute('readOnly', true);
39817 this.el.on('mousedown', this.onTriggerClick, this);
39818 this.el.addClass('x-combo-noedit');
39820 this.el.dom.setAttribute('readOnly', false);
39821 this.el.un('mousedown', this.onTriggerClick, this);
39822 this.el.removeClass('x-combo-noedit');
39827 onBeforeLoad : function(){
39828 if(!this.hasFocus){
39831 this.innerList.update(this.loadingText ?
39832 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
39833 this.restrictHeight();
39834 this.selectedIndex = -1;
39838 onLoad : function(){
39839 if(!this.hasFocus){
39842 if(this.store.getCount() > 0){
39844 this.restrictHeight();
39845 if(this.lastQuery == this.allQuery){
39847 this.el.dom.select();
39849 if(!this.selectByValue(this.value, true)){
39850 this.select(0, true);
39854 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
39855 this.taTask.delay(this.typeAheadDelay);
39859 this.onEmptyResults();
39864 onLoadException : function()
39867 Roo.log(this.store.reader.jsonData);
39868 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
39869 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
39875 onTypeAhead : function(){
39876 if(this.store.getCount() > 0){
39877 var r = this.store.getAt(0);
39878 var newValue = r.data[this.displayField];
39879 var len = newValue.length;
39880 var selStart = this.getRawValue().length;
39881 if(selStart != len){
39882 this.setRawValue(newValue);
39883 this.selectText(selStart, newValue.length);
39889 onSelect : function(record, index){
39890 if(this.fireEvent('beforeselect', this, record, index) !== false){
39891 this.setFromData(index > -1 ? record.data : false);
39893 this.fireEvent('select', this, record, index);
39898 * Returns the currently selected field value or empty string if no value is set.
39899 * @return {String} value The selected value
39901 getValue : function(){
39902 if(this.valueField){
39903 return typeof this.value != 'undefined' ? this.value : '';
39905 return Roo.form.ComboBox.superclass.getValue.call(this);
39909 * Clears any text/value currently set in the field
39911 clearValue : function(){
39912 if(this.hiddenField){
39913 this.hiddenField.value = '';
39916 this.setRawValue('');
39917 this.lastSelectionText = '';
39922 * Sets the specified value into the field. If the value finds a match, the corresponding record text
39923 * will be displayed in the field. If the value does not match the data value of an existing item,
39924 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
39925 * Otherwise the field will be blank (although the value will still be set).
39926 * @param {String} value The value to match
39928 setValue : function(v){
39930 if(this.valueField){
39931 var r = this.findRecord(this.valueField, v);
39933 text = r.data[this.displayField];
39934 }else if(this.valueNotFoundText !== undefined){
39935 text = this.valueNotFoundText;
39938 this.lastSelectionText = text;
39939 if(this.hiddenField){
39940 this.hiddenField.value = v;
39942 Roo.form.ComboBox.superclass.setValue.call(this, text);
39946 * @property {Object} the last set data for the element
39951 * Sets the value of the field based on a object which is related to the record format for the store.
39952 * @param {Object} value the value to set as. or false on reset?
39954 setFromData : function(o){
39955 var dv = ''; // display value
39956 var vv = ''; // value value..
39958 if (this.displayField) {
39959 dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
39961 // this is an error condition!!!
39962 Roo.log('no displayField value set for '+ (this.name ? this.name : this.id));
39965 if(this.valueField){
39966 vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
39968 if(this.hiddenField){
39969 this.hiddenField.value = vv;
39971 this.lastSelectionText = dv;
39972 Roo.form.ComboBox.superclass.setValue.call(this, dv);
39976 // no hidden field.. - we store the value in 'value', but still display
39977 // display field!!!!
39978 this.lastSelectionText = dv;
39979 Roo.form.ComboBox.superclass.setValue.call(this, dv);
39985 reset : function(){
39986 // overridden so that last data is reset..
39987 this.setValue(this.resetValue);
39988 this.clearInvalid();
39989 this.lastData = false;
39991 this.view.clearSelections();
39995 findRecord : function(prop, value){
39997 if(this.store.getCount() > 0){
39998 this.store.each(function(r){
39999 if(r.data[prop] == value){
40009 getName: function()
40011 // returns hidden if it's set..
40012 if (!this.rendered) {return ''};
40013 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
40017 onViewMove : function(e, t){
40018 this.inKeyMode = false;
40022 onViewOver : function(e, t){
40023 if(this.inKeyMode){ // prevent key nav and mouse over conflicts
40026 var item = this.view.findItemFromChild(t);
40028 var index = this.view.indexOf(item);
40029 this.select(index, false);
40034 onViewClick : function(doFocus)
40036 var index = this.view.getSelectedIndexes()[0];
40037 var r = this.store.getAt(index);
40039 this.onSelect(r, index);
40041 if(doFocus !== false && !this.blockFocus){
40047 restrictHeight : function(){
40048 this.innerList.dom.style.height = '';
40049 var inner = this.innerList.dom;
40050 var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
40051 this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
40052 this.list.beginUpdate();
40053 this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
40054 this.list.alignTo(this.el, this.listAlign);
40055 this.list.endUpdate();
40059 onEmptyResults : function(){
40064 * Returns true if the dropdown list is expanded, else false.
40066 isExpanded : function(){
40067 return this.list.isVisible();
40071 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
40072 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
40073 * @param {String} value The data value of the item to select
40074 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
40075 * selected item if it is not currently in view (defaults to true)
40076 * @return {Boolean} True if the value matched an item in the list, else false
40078 selectByValue : function(v, scrollIntoView){
40079 if(v !== undefined && v !== null){
40080 var r = this.findRecord(this.valueField || this.displayField, v);
40082 this.select(this.store.indexOf(r), scrollIntoView);
40090 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
40091 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
40092 * @param {Number} index The zero-based index of the list item to select
40093 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
40094 * selected item if it is not currently in view (defaults to true)
40096 select : function(index, scrollIntoView){
40097 this.selectedIndex = index;
40098 this.view.select(index);
40099 if(scrollIntoView !== false){
40100 var el = this.view.getNode(index);
40102 this.innerList.scrollChildIntoView(el, false);
40108 selectNext : function(){
40109 var ct = this.store.getCount();
40111 if(this.selectedIndex == -1){
40113 }else if(this.selectedIndex < ct-1){
40114 this.select(this.selectedIndex+1);
40120 selectPrev : function(){
40121 var ct = this.store.getCount();
40123 if(this.selectedIndex == -1){
40125 }else if(this.selectedIndex != 0){
40126 this.select(this.selectedIndex-1);
40132 onKeyUp : function(e){
40133 if(this.editable !== false && !e.isSpecialKey()){
40134 this.lastKey = e.getKey();
40135 this.dqTask.delay(this.queryDelay);
40140 validateBlur : function(){
40141 return !this.list || !this.list.isVisible();
40145 initQuery : function(){
40146 this.doQuery(this.getRawValue());
40150 doForce : function(){
40151 if(this.el.dom.value.length > 0){
40152 this.el.dom.value =
40153 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
40159 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
40160 * query allowing the query action to be canceled if needed.
40161 * @param {String} query The SQL query to execute
40162 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
40163 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
40164 * saved in the current store (defaults to false)
40166 doQuery : function(q, forceAll){
40167 if(q === undefined || q === null){
40172 forceAll: forceAll,
40176 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
40180 forceAll = qe.forceAll;
40181 if(forceAll === true || (q.length >= this.minChars)){
40182 if(this.lastQuery != q || this.alwaysQuery){
40183 this.lastQuery = q;
40184 if(this.mode == 'local'){
40185 this.selectedIndex = -1;
40187 this.store.clearFilter();
40189 this.store.filter(this.displayField, q);
40193 this.store.baseParams[this.queryParam] = q;
40195 params: this.getParams(q)
40200 this.selectedIndex = -1;
40207 getParams : function(q){
40209 //p[this.queryParam] = q;
40212 p.limit = this.pageSize;
40218 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
40220 collapse : function(){
40221 if(!this.isExpanded()){
40225 Roo.get(document).un('mousedown', this.collapseIf, this);
40226 Roo.get(document).un('mousewheel', this.collapseIf, this);
40227 if (!this.editable) {
40228 Roo.get(document).un('keydown', this.listKeyPress, this);
40230 this.fireEvent('collapse', this);
40234 collapseIf : function(e){
40235 if(!e.within(this.wrap) && !e.within(this.list)){
40241 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
40243 expand : function(){
40244 if(this.isExpanded() || !this.hasFocus){
40247 this.list.alignTo(this.el, this.listAlign);
40249 Roo.get(document).on('mousedown', this.collapseIf, this);
40250 Roo.get(document).on('mousewheel', this.collapseIf, this);
40251 if (!this.editable) {
40252 Roo.get(document).on('keydown', this.listKeyPress, this);
40255 this.fireEvent('expand', this);
40259 // Implements the default empty TriggerField.onTriggerClick function
40260 onTriggerClick : function(){
40264 if(this.isExpanded()){
40266 if (!this.blockFocus) {
40271 this.hasFocus = true;
40272 if(this.triggerAction == 'all') {
40273 this.doQuery(this.allQuery, true);
40275 this.doQuery(this.getRawValue());
40277 if (!this.blockFocus) {
40282 listKeyPress : function(e)
40284 //Roo.log('listkeypress');
40285 // scroll to first matching element based on key pres..
40286 if (e.isSpecialKey()) {
40289 var k = String.fromCharCode(e.getKey()).toUpperCase();
40292 var csel = this.view.getSelectedNodes();
40293 var cselitem = false;
40295 var ix = this.view.indexOf(csel[0]);
40296 cselitem = this.store.getAt(ix);
40297 if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
40303 this.store.each(function(v) {
40305 // start at existing selection.
40306 if (cselitem.id == v.id) {
40312 if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
40313 match = this.store.indexOf(v);
40318 if (match === false) {
40319 return true; // no more action?
40322 this.view.select(match);
40323 var sn = Roo.get(this.view.getSelectedNodes()[0])
40324 sn.scrollIntoView(sn.dom.parentNode, false);
40328 * @cfg {Boolean} grow
40332 * @cfg {Number} growMin
40336 * @cfg {Number} growMax
40344 * Copyright(c) 2010-2012, Roo J Solutions Limited
40351 * @class Roo.form.ComboBoxArray
40352 * @extends Roo.form.TextField
40353 * A facebook style adder... for lists of email / people / countries etc...
40354 * pick multiple items from a combo box, and shows each one.
40356 * Fred [x] Brian [x] [Pick another |v]
40359 * For this to work: it needs various extra information
40360 * - normal combo problay has
40362 * + displayField, valueField
40364 * For our purpose...
40367 * If we change from 'extends' to wrapping...
40374 * Create a new ComboBoxArray.
40375 * @param {Object} config Configuration options
40379 Roo.form.ComboBoxArray = function(config)
40383 * @event beforeremove
40384 * Fires before remove the value from the list
40385 * @param {Roo.form.ComboBoxArray} _self This combo box array
40386 * @param {Roo.form.ComboBoxArray.Item} item removed item
40388 'beforeremove' : true,
40391 * Fires when remove the value from the list
40392 * @param {Roo.form.ComboBoxArray} _self This combo box array
40393 * @param {Roo.form.ComboBoxArray.Item} item removed item
40400 Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
40402 this.items = new Roo.util.MixedCollection(false);
40404 // construct the child combo...
40414 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
40417 * @cfg {Roo.form.Combo} combo The combo box that is wrapped
40422 // behavies liek a hiddne field
40423 inputType: 'hidden',
40425 * @cfg {Number} width The width of the box that displays the selected element
40432 * @cfg {String} name The name of the visable items on this form (eg. titles not ids)
40436 * @cfg {String} hiddenName The hidden name of the field, often contains an comma seperated list of names
40438 hiddenName : false,
40441 // private the array of items that are displayed..
40443 // private - the hidden field el.
40445 // private - the filed el..
40448 //validateValue : function() { return true; }, // all values are ok!
40449 //onAddClick: function() { },
40451 onRender : function(ct, position)
40454 // create the standard hidden element
40455 //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
40458 // give fake names to child combo;
40459 this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
40460 this.combo.name = this.name? (this.name+'-subcombo') : this.name;
40462 this.combo = Roo.factory(this.combo, Roo.form);
40463 this.combo.onRender(ct, position);
40464 if (typeof(this.combo.width) != 'undefined') {
40465 this.combo.onResize(this.combo.width,0);
40468 this.combo.initEvents();
40470 // assigned so form know we need to do this..
40471 this.store = this.combo.store;
40472 this.valueField = this.combo.valueField;
40473 this.displayField = this.combo.displayField ;
40476 this.combo.wrap.addClass('x-cbarray-grp');
40478 var cbwrap = this.combo.wrap.createChild(
40479 {tag: 'div', cls: 'x-cbarray-cb'},
40484 this.hiddenEl = this.combo.wrap.createChild({
40485 tag: 'input', type:'hidden' , name: this.hiddenName, value : ''
40487 this.el = this.combo.wrap.createChild({
40488 tag: 'input', type:'hidden' , name: this.name, value : ''
40490 // this.el.dom.removeAttribute("name");
40493 this.outerWrap = this.combo.wrap;
40494 this.wrap = cbwrap;
40496 this.outerWrap.setWidth(this.width);
40497 this.outerWrap.dom.removeChild(this.el.dom);
40499 this.wrap.dom.appendChild(this.el.dom);
40500 this.outerWrap.dom.removeChild(this.combo.trigger.dom);
40501 this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
40503 this.combo.trigger.setStyle('position','relative');
40504 this.combo.trigger.setStyle('left', '0px');
40505 this.combo.trigger.setStyle('top', '2px');
40507 this.combo.el.setStyle('vertical-align', 'text-bottom');
40509 //this.trigger.setStyle('vertical-align', 'top');
40511 // this should use the code from combo really... on('add' ....)
40515 this.adder = this.outerWrap.createChild(
40516 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});
40518 this.adder.on('click', function(e) {
40519 _t.fireEvent('adderclick', this, e);
40523 //this.adder.on('click', this.onAddClick, _t);
40526 this.combo.on('select', function(cb, rec, ix) {
40527 this.addItem(rec.data);
40530 cb.el.dom.value = '';
40531 //cb.lastData = rec.data;
40540 getName: function()
40542 // returns hidden if it's set..
40543 if (!this.rendered) {return ''};
40544 return this.hiddenName ? this.hiddenName : this.name;
40549 onResize: function(w, h){
40552 // not sure if this is needed..
40553 //this.combo.onResize(w,h);
40555 if(typeof w != 'number'){
40556 // we do not handle it!?!?
40559 var tw = this.combo.trigger.getWidth();
40560 tw += this.addicon ? this.addicon.getWidth() : 0;
40561 tw += this.editicon ? this.editicon.getWidth() : 0;
40563 this.combo.el.setWidth( this.combo.adjustWidth('input', x));
40565 this.combo.trigger.setStyle('left', '0px');
40567 if(this.list && this.listWidth === undefined){
40568 var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
40569 this.list.setWidth(lw);
40570 this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
40577 addItem: function(rec)
40579 var valueField = this.combo.valueField;
40580 var displayField = this.combo.displayField;
40581 if (this.items.indexOfKey(rec[valueField]) > -1) {
40582 //console.log("GOT " + rec.data.id);
40586 var x = new Roo.form.ComboBoxArray.Item({
40587 //id : rec[this.idField],
40589 displayField : displayField ,
40590 tipField : displayField ,
40594 this.items.add(rec[valueField],x);
40595 // add it before the element..
40596 this.updateHiddenEl();
40597 x.render(this.outerWrap, this.wrap.dom);
40598 // add the image handler..
40601 updateHiddenEl : function()
40604 if (!this.hiddenEl) {
40608 var idField = this.combo.valueField;
40610 this.items.each(function(f) {
40611 ar.push(f.data[idField]);
40614 this.hiddenEl.dom.value = ar.join(',');
40620 //Roo.form.ComboBoxArray.superclass.reset.call(this);
40621 this.items.each(function(f) {
40624 this.el.dom.value = '';
40625 if (this.hiddenEl) {
40626 this.hiddenEl.dom.value = '';
40630 getValue: function()
40632 return this.hiddenEl ? this.hiddenEl.dom.value : '';
40634 setValue: function(v) // not a valid action - must use addItems..
40641 if (this.store.isLocal && (typeof(v) == 'string')) {
40642 // then we can use the store to find the values..
40643 // comma seperated at present.. this needs to allow JSON based encoding..
40644 this.hiddenEl.value = v;
40646 Roo.each(v.split(','), function(k) {
40647 Roo.log("CHECK " + this.valueField + ',' + k);
40648 var li = this.store.query(this.valueField, k);
40653 add[this.valueField] = k;
40654 add[this.displayField] = li.item(0).data[this.displayField];
40660 if (typeof(v) == 'object' ) {
40661 // then let's assume it's an array of objects..
40662 Roo.each(v, function(l) {
40670 setFromData: function(v)
40672 // this recieves an object, if setValues is called.
40674 this.el.dom.value = v[this.displayField];
40675 this.hiddenEl.dom.value = v[this.valueField];
40676 if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
40679 var kv = v[this.valueField];
40680 var dv = v[this.displayField];
40681 kv = typeof(kv) != 'string' ? '' : kv;
40682 dv = typeof(dv) != 'string' ? '' : dv;
40685 var keys = kv.split(',');
40686 var display = dv.split(',');
40687 for (var i = 0 ; i < keys.length; i++) {
40690 add[this.valueField] = keys[i];
40691 add[this.displayField] = display[i];
40699 * Validates the combox array value
40700 * @return {Boolean} True if the value is valid, else false
40702 validate : function(){
40703 if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
40704 this.clearInvalid();
40710 validateValue : function(value){
40711 return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
40719 isDirty : function() {
40720 if(this.disabled) {
40725 var d = Roo.decode(String(this.originalValue));
40727 return String(this.getValue()) !== String(this.originalValue);
40730 var originalValue = [];
40732 for (var i = 0; i < d.length; i++){
40733 originalValue.push(d[i][this.valueField]);
40736 return String(this.getValue()) !== String(originalValue.join(','));
40745 * @class Roo.form.ComboBoxArray.Item
40746 * @extends Roo.BoxComponent
40747 * A selected item in the list
40748 * Fred [x] Brian [x] [Pick another |v]
40751 * Create a new item.
40752 * @param {Object} config Configuration options
40755 Roo.form.ComboBoxArray.Item = function(config) {
40756 config.id = Roo.id();
40757 Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
40760 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
40763 displayField : false,
40767 defaultAutoCreate : {
40769 cls: 'x-cbarray-item',
40776 src : Roo.BLANK_IMAGE_URL ,
40784 onRender : function(ct, position)
40786 Roo.form.Field.superclass.onRender.call(this, ct, position);
40789 var cfg = this.getAutoCreate();
40790 this.el = ct.createChild(cfg, position);
40793 this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
40795 this.el.child('div').dom.innerHTML = this.cb.renderer ?
40796 this.cb.renderer(this.data) :
40797 String.format('{0}',this.data[this.displayField]);
40800 this.el.child('div').dom.setAttribute('qtip',
40801 String.format('{0}',this.data[this.tipField])
40804 this.el.child('img').on('click', this.remove, this);
40808 remove : function()
40810 if(this.cb.disabled){
40814 if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
40815 this.cb.items.remove(this);
40816 this.el.child('img').un('click', this.remove, this);
40818 this.cb.updateHiddenEl();
40820 this.cb.fireEvent('remove', this.cb, this);
40826 * Ext JS Library 1.1.1
40827 * Copyright(c) 2006-2007, Ext JS, LLC.
40829 * Originally Released Under LGPL - original licence link has changed is not relivant.
40832 * <script type="text/javascript">
40835 * @class Roo.form.Checkbox
40836 * @extends Roo.form.Field
40837 * Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
40839 * Creates a new Checkbox
40840 * @param {Object} config Configuration options
40842 Roo.form.Checkbox = function(config){
40843 Roo.form.Checkbox.superclass.constructor.call(this, config);
40847 * Fires when the checkbox is checked or unchecked.
40848 * @param {Roo.form.Checkbox} this This checkbox
40849 * @param {Boolean} checked The new checked value
40855 Roo.extend(Roo.form.Checkbox, Roo.form.Field, {
40857 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
40859 focusClass : undefined,
40861 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
40863 fieldClass: "x-form-field",
40865 * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
40869 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
40870 * {tag: "input", type: "checkbox", autocomplete: "off"})
40872 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
40874 * @cfg {String} boxLabel The text that appears beside the checkbox
40878 * @cfg {String} inputValue The value that should go into the generated input element's value attribute
40882 * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
40884 valueOff: '0', // value when not checked..
40886 actionMode : 'viewEl',
40889 itemCls : 'x-menu-check-item x-form-item',
40890 groupClass : 'x-menu-group-item',
40891 inputType : 'hidden',
40894 inSetChecked: false, // check that we are not calling self...
40896 inputElement: false, // real input element?
40897 basedOn: false, // ????
40899 isFormField: true, // not sure where this is needed!!!!
40901 onResize : function(){
40902 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
40903 if(!this.boxLabel){
40904 this.el.alignTo(this.wrap, 'c-c');
40908 initEvents : function(){
40909 Roo.form.Checkbox.superclass.initEvents.call(this);
40910 this.el.on("click", this.onClick, this);
40911 this.el.on("change", this.onClick, this);
40915 getResizeEl : function(){
40919 getPositionEl : function(){
40924 onRender : function(ct, position){
40925 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
40927 if(this.inputValue !== undefined){
40928 this.el.dom.value = this.inputValue;
40931 //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
40932 this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
40933 var viewEl = this.wrap.createChild({
40934 tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
40935 this.viewEl = viewEl;
40936 this.wrap.on('click', this.onClick, this);
40938 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
40939 this.el.on('propertychange', this.setFromHidden, this); //ie
40944 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
40945 // viewEl.on('click', this.onClick, this);
40947 //if(this.checked){
40948 this.setChecked(this.checked);
40950 //this.checked = this.el.dom;
40956 initValue : Roo.emptyFn,
40959 * Returns the checked state of the checkbox.
40960 * @return {Boolean} True if checked, else false
40962 getValue : function(){
40964 return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
40966 return this.valueOff;
40971 onClick : function(){
40972 if (this.disabled) {
40975 this.setChecked(!this.checked);
40977 //if(this.el.dom.checked != this.checked){
40978 // this.setValue(this.el.dom.checked);
40983 * Sets the checked state of the checkbox.
40984 * On is always based on a string comparison between inputValue and the param.
40985 * @param {Boolean/String} value - the value to set
40986 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
40988 setValue : function(v,suppressEvent){
40991 //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
40992 //if(this.el && this.el.dom){
40993 // this.el.dom.checked = this.checked;
40994 // this.el.dom.defaultChecked = this.checked;
40996 this.setChecked(String(v) === String(this.inputValue), suppressEvent);
40997 //this.fireEvent("check", this, this.checked);
41000 setChecked : function(state,suppressEvent)
41002 if (this.inSetChecked) {
41003 this.checked = state;
41009 this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
41011 this.checked = state;
41012 if(suppressEvent !== true){
41013 this.fireEvent('check', this, state);
41015 this.inSetChecked = true;
41016 this.el.dom.value = state ? this.inputValue : this.valueOff;
41017 this.inSetChecked = false;
41020 // handle setting of hidden value by some other method!!?!?
41021 setFromHidden: function()
41026 //console.log("SET FROM HIDDEN");
41027 //alert('setFrom hidden');
41028 this.setValue(this.el.dom.value);
41031 onDestroy : function()
41034 Roo.get(this.viewEl).remove();
41037 Roo.form.Checkbox.superclass.onDestroy.call(this);
41042 * Ext JS Library 1.1.1
41043 * Copyright(c) 2006-2007, Ext JS, LLC.
41045 * Originally Released Under LGPL - original licence link has changed is not relivant.
41048 * <script type="text/javascript">
41052 * @class Roo.form.Radio
41053 * @extends Roo.form.Checkbox
41054 * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
41055 * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
41057 * Creates a new Radio
41058 * @param {Object} config Configuration options
41060 Roo.form.Radio = function(){
41061 Roo.form.Radio.superclass.constructor.apply(this, arguments);
41063 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
41064 inputType: 'radio',
41067 * If this radio is part of a group, it will return the selected value
41070 getGroupValue : function(){
41071 return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
41075 onRender : function(ct, position){
41076 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
41078 if(this.inputValue !== undefined){
41079 this.el.dom.value = this.inputValue;
41082 this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
41083 //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
41084 //var viewEl = this.wrap.createChild({
41085 // tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
41086 //this.viewEl = viewEl;
41087 //this.wrap.on('click', this.onClick, this);
41089 //this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
41090 //this.el.on('propertychange', this.setFromHidden, this); //ie
41095 this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
41096 // viewEl.on('click', this.onClick, this);
41099 this.el.dom.checked = 'checked' ;
41105 });//<script type="text/javascript">
41108 * Based Ext JS Library 1.1.1
41109 * Copyright(c) 2006-2007, Ext JS, LLC.
41115 * @class Roo.HtmlEditorCore
41116 * @extends Roo.Component
41117 * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
41119 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
41122 Roo.HtmlEditorCore = function(config){
41125 Roo.HtmlEditorCore.superclass.constructor.call(this, config);
41130 * @event initialize
41131 * Fires when the editor is fully initialized (including the iframe)
41132 * @param {Roo.HtmlEditorCore} this
41137 * Fires when the editor is first receives the focus. Any insertion must wait
41138 * until after this event.
41139 * @param {Roo.HtmlEditorCore} this
41143 * @event beforesync
41144 * Fires before the textarea is updated with content from the editor iframe. Return false
41145 * to cancel the sync.
41146 * @param {Roo.HtmlEditorCore} this
41147 * @param {String} html
41151 * @event beforepush
41152 * Fires before the iframe editor is updated with content from the textarea. Return false
41153 * to cancel the push.
41154 * @param {Roo.HtmlEditorCore} this
41155 * @param {String} html
41160 * Fires when the textarea is updated with content from the editor iframe.
41161 * @param {Roo.HtmlEditorCore} this
41162 * @param {String} html
41167 * Fires when the iframe editor is updated with content from the textarea.
41168 * @param {Roo.HtmlEditorCore} this
41169 * @param {String} html
41174 * @event editorevent
41175 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
41176 * @param {Roo.HtmlEditorCore} this
41182 // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
41184 // defaults : white / black...
41185 this.applyBlacklists();
41192 Roo.extend(Roo.HtmlEditorCore, Roo.Component, {
41196 * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field
41202 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
41207 * @cfg {Number} height (in pixels)
41211 * @cfg {Number} width (in pixels)
41216 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
41219 stylesheets: false,
41224 // private properties
41225 validationEvent : false,
41227 initialized : false,
41229 sourceEditMode : false,
41230 onFocus : Roo.emptyFn,
41232 hideMode:'offsets',
41236 // blacklist + whitelisted elements..
41243 * Protected method that will not generally be called directly. It
41244 * is called when the editor initializes the iframe with HTML contents. Override this method if you
41245 * want to change the initialization markup of the iframe (e.g. to add stylesheets).
41247 getDocMarkup : function(){
41251 // inherit styels from page...??
41252 if (this.stylesheets === false) {
41254 Roo.get(document.head).select('style').each(function(node) {
41255 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
41258 Roo.get(document.head).select('link').each(function(node) {
41259 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
41262 } else if (!this.stylesheets.length) {
41264 st = '<style type="text/css">' +
41265 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
41271 st += '<style type="text/css">' +
41272 'IMG { cursor: pointer } ' +
41276 return '<html><head>' + st +
41277 //<style type="text/css">' +
41278 //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
41280 ' </head><body class="roo-htmleditor-body"></body></html>';
41284 onRender : function(ct, position)
41287 //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
41288 this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
41291 this.el.dom.style.border = '0 none';
41292 this.el.dom.setAttribute('tabIndex', -1);
41293 this.el.addClass('x-hidden hide');
41297 if(Roo.isIE){ // fix IE 1px bogus margin
41298 this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
41302 this.frameId = Roo.id();
41306 var iframe = this.owner.wrap.createChild({
41308 cls: 'form-control', // bootstrap..
41310 name: this.frameId,
41311 frameBorder : 'no',
41312 'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL : "javascript:false"
41317 this.iframe = iframe.dom;
41319 this.assignDocWin();
41321 this.doc.designMode = 'on';
41324 this.doc.write(this.getDocMarkup());
41328 var task = { // must defer to wait for browser to be ready
41330 //console.log("run task?" + this.doc.readyState);
41331 this.assignDocWin();
41332 if(this.doc.body || this.doc.readyState == 'complete'){
41334 this.doc.designMode="on";
41338 Roo.TaskMgr.stop(task);
41339 this.initEditor.defer(10, this);
41346 Roo.TaskMgr.start(task);
41351 onResize : function(w, h)
41353 Roo.log('resize: ' +w + ',' + h );
41354 //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
41358 if(typeof w == 'number'){
41360 this.iframe.style.width = w + 'px';
41362 if(typeof h == 'number'){
41364 this.iframe.style.height = h + 'px';
41366 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
41373 * Toggles the editor between standard and source edit mode.
41374 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
41376 toggleSourceEdit : function(sourceEditMode){
41378 this.sourceEditMode = sourceEditMode === true;
41380 if(this.sourceEditMode){
41382 Roo.get(this.iframe).addClass(['x-hidden','hide']); //FIXME - what's the BS styles for these
41385 Roo.get(this.iframe).removeClass(['x-hidden','hide']);
41386 //this.iframe.className = '';
41389 //this.setSize(this.owner.wrap.getSize());
41390 //this.fireEvent('editmodechange', this, this.sourceEditMode);
41397 * Protected method that will not generally be called directly. If you need/want
41398 * custom HTML cleanup, this is the method you should override.
41399 * @param {String} html The HTML to be cleaned
41400 * return {String} The cleaned HTML
41402 cleanHtml : function(html){
41403 html = String(html);
41404 if(html.length > 5){
41405 if(Roo.isSafari){ // strip safari nonsense
41406 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
41409 if(html == ' '){
41416 * HTML Editor -> Textarea
41417 * Protected method that will not generally be called directly. Syncs the contents
41418 * of the editor iframe with the textarea.
41420 syncValue : function(){
41421 if(this.initialized){
41422 var bd = (this.doc.body || this.doc.documentElement);
41423 //this.cleanUpPaste(); -- this is done else where and causes havoc..
41424 var html = bd.innerHTML;
41426 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
41427 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
41429 html = '<div style="'+m[0]+'">' + html + '</div>';
41432 html = this.cleanHtml(html);
41433 // fix up the special chars.. normaly like back quotes in word...
41434 // however we do not want to do this with chinese..
41435 html = html.replace(/([\x80-\uffff])/g, function (a, b) {
41436 var cc = b.charCodeAt();
41438 (cc >= 0x4E00 && cc < 0xA000 ) ||
41439 (cc >= 0x3400 && cc < 0x4E00 ) ||
41440 (cc >= 0xf900 && cc < 0xfb00 )
41446 if(this.owner.fireEvent('beforesync', this, html) !== false){
41447 this.el.dom.value = html;
41448 this.owner.fireEvent('sync', this, html);
41454 * Protected method that will not generally be called directly. Pushes the value of the textarea
41455 * into the iframe editor.
41457 pushValue : function(){
41458 if(this.initialized){
41459 var v = this.el.dom.value.trim();
41461 // if(v.length < 1){
41465 if(this.owner.fireEvent('beforepush', this, v) !== false){
41466 var d = (this.doc.body || this.doc.documentElement);
41468 this.cleanUpPaste();
41469 this.el.dom.value = d.innerHTML;
41470 this.owner.fireEvent('push', this, v);
41476 deferFocus : function(){
41477 this.focus.defer(10, this);
41481 focus : function(){
41482 if(this.win && !this.sourceEditMode){
41489 assignDocWin: function()
41491 var iframe = this.iframe;
41494 this.doc = iframe.contentWindow.document;
41495 this.win = iframe.contentWindow;
41497 // if (!Roo.get(this.frameId)) {
41500 // this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
41501 // this.win = Roo.get(this.frameId).dom.contentWindow;
41503 if (!Roo.get(this.frameId) && !iframe.contentDocument) {
41507 this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
41508 this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
41513 initEditor : function(){
41514 //console.log("INIT EDITOR");
41515 this.assignDocWin();
41519 this.doc.designMode="on";
41521 this.doc.write(this.getDocMarkup());
41524 var dbody = (this.doc.body || this.doc.documentElement);
41525 //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
41526 // this copies styles from the containing element into thsi one..
41527 // not sure why we need all of this..
41528 //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
41530 //var ss = this.el.getStyles( 'background-image', 'background-repeat');
41531 //ss['background-attachment'] = 'fixed'; // w3c
41532 dbody.bgProperties = 'fixed'; // ie
41533 //Roo.DomHelper.applyStyles(dbody, ss);
41534 Roo.EventManager.on(this.doc, {
41535 //'mousedown': this.onEditorEvent,
41536 'mouseup': this.onEditorEvent,
41537 'dblclick': this.onEditorEvent,
41538 'click': this.onEditorEvent,
41539 'keyup': this.onEditorEvent,
41544 Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
41546 if(Roo.isIE || Roo.isSafari || Roo.isOpera){
41547 Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
41549 this.initialized = true;
41551 this.owner.fireEvent('initialize', this);
41556 onDestroy : function(){
41562 //for (var i =0; i < this.toolbars.length;i++) {
41563 // // fixme - ask toolbars for heights?
41564 // this.toolbars[i].onDestroy();
41567 //this.wrap.dom.innerHTML = '';
41568 //this.wrap.remove();
41573 onFirstFocus : function(){
41575 this.assignDocWin();
41578 this.activated = true;
41581 if(Roo.isGecko){ // prevent silly gecko errors
41583 var s = this.win.getSelection();
41584 if(!s.focusNode || s.focusNode.nodeType != 3){
41585 var r = s.getRangeAt(0);
41586 r.selectNodeContents((this.doc.body || this.doc.documentElement));
41591 this.execCmd('useCSS', true);
41592 this.execCmd('styleWithCSS', false);
41595 this.owner.fireEvent('activate', this);
41599 adjustFont: function(btn){
41600 var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
41601 //if(Roo.isSafari){ // safari
41604 var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
41605 if(Roo.isSafari){ // safari
41606 var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
41607 v = (v < 10) ? 10 : v;
41608 v = (v > 48) ? 48 : v;
41609 v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
41614 v = Math.max(1, v+adjust);
41616 this.execCmd('FontSize', v );
41619 onEditorEvent : function(e)
41621 this.owner.fireEvent('editorevent', this, e);
41622 // this.updateToolbar();
41623 this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
41626 insertTag : function(tg)
41628 // could be a bit smarter... -> wrap the current selected tRoo..
41629 if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
41631 range = this.createRange(this.getSelection());
41632 var wrappingNode = this.doc.createElement(tg.toLowerCase());
41633 wrappingNode.appendChild(range.extractContents());
41634 range.insertNode(wrappingNode);
41641 this.execCmd("formatblock", tg);
41645 insertText : function(txt)
41649 var range = this.createRange();
41650 range.deleteContents();
41651 //alert(Sender.getAttribute('label'));
41653 range.insertNode(this.doc.createTextNode(txt));
41659 * Executes a Midas editor command on the editor document and performs necessary focus and
41660 * toolbar updates. <b>This should only be called after the editor is initialized.</b>
41661 * @param {String} cmd The Midas command
41662 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
41664 relayCmd : function(cmd, value){
41666 this.execCmd(cmd, value);
41667 this.owner.fireEvent('editorevent', this);
41668 //this.updateToolbar();
41669 this.owner.deferFocus();
41673 * Executes a Midas editor command directly on the editor document.
41674 * For visual commands, you should use {@link #relayCmd} instead.
41675 * <b>This should only be called after the editor is initialized.</b>
41676 * @param {String} cmd The Midas command
41677 * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
41679 execCmd : function(cmd, value){
41680 this.doc.execCommand(cmd, false, value === undefined ? null : value);
41687 * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
41689 * @param {String} text | dom node..
41691 insertAtCursor : function(text)
41696 if(!this.activated){
41702 var r = this.doc.selection.createRange();
41713 if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
41717 // from jquery ui (MIT licenced)
41719 var win = this.win;
41721 if (win.getSelection && win.getSelection().getRangeAt) {
41722 range = win.getSelection().getRangeAt(0);
41723 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
41724 range.insertNode(node);
41725 } else if (win.document.selection && win.document.selection.createRange) {
41726 // no firefox support
41727 var txt = typeof(text) == 'string' ? text : text.outerHTML;
41728 win.document.selection.createRange().pasteHTML(txt);
41730 // no firefox support
41731 var txt = typeof(text) == 'string' ? text : text.outerHTML;
41732 this.execCmd('InsertHTML', txt);
41741 mozKeyPress : function(e){
41743 var c = e.getCharCode(), cmd;
41746 c = String.fromCharCode(c).toLowerCase();
41760 this.cleanUpPaste.defer(100, this);
41768 e.preventDefault();
41776 fixKeys : function(){ // load time branching for fastest keydown performance
41778 return function(e){
41779 var k = e.getKey(), r;
41782 r = this.doc.selection.createRange();
41785 r.pasteHTML('    ');
41792 r = this.doc.selection.createRange();
41794 var target = r.parentElement();
41795 if(!target || target.tagName.toLowerCase() != 'li'){
41797 r.pasteHTML('<br />');
41803 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41804 this.cleanUpPaste.defer(100, this);
41810 }else if(Roo.isOpera){
41811 return function(e){
41812 var k = e.getKey();
41816 this.execCmd('InsertHTML','    ');
41819 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41820 this.cleanUpPaste.defer(100, this);
41825 }else if(Roo.isSafari){
41826 return function(e){
41827 var k = e.getKey();
41831 this.execCmd('InsertText','\t');
41835 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
41836 this.cleanUpPaste.defer(100, this);
41844 getAllAncestors: function()
41846 var p = this.getSelectedNode();
41849 a.push(p); // push blank onto stack..
41850 p = this.getParentElement();
41854 while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
41858 a.push(this.doc.body);
41862 lastSelNode : false,
41865 getSelection : function()
41867 this.assignDocWin();
41868 return Roo.isIE ? this.doc.selection : this.win.getSelection();
41871 getSelectedNode: function()
41873 // this may only work on Gecko!!!
41875 // should we cache this!!!!
41880 var range = this.createRange(this.getSelection()).cloneRange();
41883 var parent = range.parentElement();
41885 var testRange = range.duplicate();
41886 testRange.moveToElementText(parent);
41887 if (testRange.inRange(range)) {
41890 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
41893 parent = parent.parentElement;
41898 // is ancestor a text element.
41899 var ac = range.commonAncestorContainer;
41900 if (ac.nodeType == 3) {
41901 ac = ac.parentNode;
41904 var ar = ac.childNodes;
41907 var other_nodes = [];
41908 var has_other_nodes = false;
41909 for (var i=0;i<ar.length;i++) {
41910 if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ?
41913 // fullly contained node.
41915 if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
41920 // probably selected..
41921 if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
41922 other_nodes.push(ar[i]);
41926 if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0)) {
41931 has_other_nodes = true;
41933 if (!nodes.length && other_nodes.length) {
41934 nodes= other_nodes;
41936 if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
41942 createRange: function(sel)
41944 // this has strange effects when using with
41945 // top toolbar - not sure if it's a great idea.
41946 //this.editor.contentWindow.focus();
41947 if (typeof sel != "undefined") {
41949 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
41951 return this.doc.createRange();
41954 return this.doc.createRange();
41957 getParentElement: function()
41960 this.assignDocWin();
41961 var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
41963 var range = this.createRange(sel);
41966 var p = range.commonAncestorContainer;
41967 while (p.nodeType == 3) { // text node
41978 * Range intersection.. the hard stuff...
41982 * [ -- selected range --- ]
41986 * if end is before start or hits it. fail.
41987 * if start is after end or hits it fail.
41989 * if either hits (but other is outside. - then it's not
41995 // @see http://www.thismuchiknow.co.uk/?p=64.
41996 rangeIntersectsNode : function(range, node)
41998 var nodeRange = node.ownerDocument.createRange();
42000 nodeRange.selectNode(node);
42002 nodeRange.selectNodeContents(node);
42005 var rangeStartRange = range.cloneRange();
42006 rangeStartRange.collapse(true);
42008 var rangeEndRange = range.cloneRange();
42009 rangeEndRange.collapse(false);
42011 var nodeStartRange = nodeRange.cloneRange();
42012 nodeStartRange.collapse(true);
42014 var nodeEndRange = nodeRange.cloneRange();
42015 nodeEndRange.collapse(false);
42017 return rangeStartRange.compareBoundaryPoints(
42018 Range.START_TO_START, nodeEndRange) == -1 &&
42019 rangeEndRange.compareBoundaryPoints(
42020 Range.START_TO_START, nodeStartRange) == 1;
42024 rangeCompareNode : function(range, node)
42026 var nodeRange = node.ownerDocument.createRange();
42028 nodeRange.selectNode(node);
42030 nodeRange.selectNodeContents(node);
42034 range.collapse(true);
42036 nodeRange.collapse(true);
42038 var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
42039 var ee = range.compareBoundaryPoints( Range.END_TO_END, nodeRange);
42041 //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
42043 var nodeIsBefore = ss == 1;
42044 var nodeIsAfter = ee == -1;
42046 if (nodeIsBefore && nodeIsAfter)
42048 if (!nodeIsBefore && nodeIsAfter)
42049 return 1; //right trailed.
42051 if (nodeIsBefore && !nodeIsAfter)
42052 return 2; // left trailed.
42057 // private? - in a new class?
42058 cleanUpPaste : function()
42060 // cleans up the whole document..
42061 Roo.log('cleanuppaste');
42063 this.cleanUpChildren(this.doc.body);
42064 var clean = this.cleanWordChars(this.doc.body.innerHTML);
42065 if (clean != this.doc.body.innerHTML) {
42066 this.doc.body.innerHTML = clean;
42071 cleanWordChars : function(input) {// change the chars to hex code
42072 var he = Roo.HtmlEditorCore;
42074 var output = input;
42075 Roo.each(he.swapCodes, function(sw) {
42076 var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
42078 output = output.replace(swapper, sw[1]);
42085 cleanUpChildren : function (n)
42087 if (!n.childNodes.length) {
42090 for (var i = n.childNodes.length-1; i > -1 ; i--) {
42091 this.cleanUpChild(n.childNodes[i]);
42098 cleanUpChild : function (node)
42101 //console.log(node);
42102 if (node.nodeName == "#text") {
42103 // clean up silly Windows -- stuff?
42106 if (node.nodeName == "#comment") {
42107 node.parentNode.removeChild(node);
42108 // clean up silly Windows -- stuff?
42111 var lcname = node.tagName.toLowerCase();
42112 // we ignore whitelists... ?? = not really the way to go, but we probably have not got a full
42113 // whitelist of tags..
42115 if (this.black.indexOf(lcname) > -1 && this.clearUp ) {
42117 node.parentNode.removeChild(node);
42122 var remove_keep_children= Roo.HtmlEditorCore.remove.indexOf(node.tagName.toLowerCase()) > -1;
42124 // remove <a name=....> as rendering on yahoo mailer is borked with this.
42125 // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
42127 //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
42128 // remove_keep_children = true;
42131 if (remove_keep_children) {
42132 this.cleanUpChildren(node);
42133 // inserts everything just before this node...
42134 while (node.childNodes.length) {
42135 var cn = node.childNodes[0];
42136 node.removeChild(cn);
42137 node.parentNode.insertBefore(cn, node);
42139 node.parentNode.removeChild(node);
42143 if (!node.attributes || !node.attributes.length) {
42144 this.cleanUpChildren(node);
42148 function cleanAttr(n,v)
42151 if (v.match(/^\./) || v.match(/^\//)) {
42154 if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
42157 if (v.match(/^#/)) {
42160 // Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
42161 node.removeAttribute(n);
42165 var cwhite = this.cwhite;
42166 var cblack = this.cblack;
42168 function cleanStyle(n,v)
42170 if (v.match(/expression/)) { //XSS?? should we even bother..
42171 node.removeAttribute(n);
42175 var parts = v.split(/;/);
42178 Roo.each(parts, function(p) {
42179 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
42183 var l = p.split(':').shift().replace(/\s+/g,'');
42184 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
42186 if ( cwhite.length && cblack.indexOf(l) > -1) {
42187 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
42188 //node.removeAttribute(n);
42192 // only allow 'c whitelisted system attributes'
42193 if ( cwhite.length && cwhite.indexOf(l) < 0) {
42194 // Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
42195 //node.removeAttribute(n);
42205 if (clean.length) {
42206 node.setAttribute(n, clean.join(';'));
42208 node.removeAttribute(n);
42214 for (var i = node.attributes.length-1; i > -1 ; i--) {
42215 var a = node.attributes[i];
42218 if (a.name.toLowerCase().substr(0,2)=='on') {
42219 node.removeAttribute(a.name);
42222 if (Roo.HtmlEditorCore.ablack.indexOf(a.name.toLowerCase()) > -1) {
42223 node.removeAttribute(a.name);
42226 if (Roo.HtmlEditorCore.aclean.indexOf(a.name.toLowerCase()) > -1) {
42227 cleanAttr(a.name,a.value); // fixme..
42230 if (a.name == 'style') {
42231 cleanStyle(a.name,a.value);
42234 /// clean up MS crap..
42235 // tecnically this should be a list of valid class'es..
42238 if (a.name == 'class') {
42239 if (a.value.match(/^Mso/)) {
42240 node.className = '';
42243 if (a.value.match(/body/)) {
42244 node.className = '';
42255 this.cleanUpChildren(node);
42261 * Clean up MS wordisms...
42263 cleanWord : function(node)
42268 this.cleanWord(this.doc.body);
42271 if (node.nodeName == "#text") {
42272 // clean up silly Windows -- stuff?
42275 if (node.nodeName == "#comment") {
42276 node.parentNode.removeChild(node);
42277 // clean up silly Windows -- stuff?
42281 if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
42282 node.parentNode.removeChild(node);
42286 // remove - but keep children..
42287 if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|font)/)) {
42288 while (node.childNodes.length) {
42289 var cn = node.childNodes[0];
42290 node.removeChild(cn);
42291 node.parentNode.insertBefore(cn, node);
42293 node.parentNode.removeChild(node);
42294 this.iterateChildren(node, this.cleanWord);
42298 if (node.className.length) {
42300 var cn = node.className.split(/\W+/);
42302 Roo.each(cn, function(cls) {
42303 if (cls.match(/Mso[a-zA-Z]+/)) {
42308 node.className = cna.length ? cna.join(' ') : '';
42310 node.removeAttribute("class");
42314 if (node.hasAttribute("lang")) {
42315 node.removeAttribute("lang");
42318 if (node.hasAttribute("style")) {
42320 var styles = node.getAttribute("style").split(";");
42322 Roo.each(styles, function(s) {
42323 if (!s.match(/:/)) {
42326 var kv = s.split(":");
42327 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
42330 // what ever is left... we allow.
42333 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
42334 if (!nstyle.length) {
42335 node.removeAttribute('style');
42338 this.iterateChildren(node, this.cleanWord);
42344 * iterateChildren of a Node, calling fn each time, using this as the scole..
42345 * @param {DomNode} node node to iterate children of.
42346 * @param {Function} fn method of this class to call on each item.
42348 iterateChildren : function(node, fn)
42350 if (!node.childNodes.length) {
42353 for (var i = node.childNodes.length-1; i > -1 ; i--) {
42354 fn.call(this, node.childNodes[i])
42360 * cleanTableWidths.
42362 * Quite often pasting from word etc.. results in tables with column and widths.
42363 * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
42366 cleanTableWidths : function(node)
42371 this.cleanTableWidths(this.doc.body);
42376 if (node.nodeName == "#text" || node.nodeName == "#comment") {
42379 Roo.log(node.tagName);
42380 if (!node.tagName.toLowerCase().match(/^(table|td|tr)$/)) {
42381 this.iterateChildren(node, this.cleanTableWidths);
42384 if (node.hasAttribute('width')) {
42385 node.removeAttribute('width');
42389 if (node.hasAttribute("style")) {
42392 var styles = node.getAttribute("style").split(";");
42394 Roo.each(styles, function(s) {
42395 if (!s.match(/:/)) {
42398 var kv = s.split(":");
42399 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
42402 // what ever is left... we allow.
42405 node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
42406 if (!nstyle.length) {
42407 node.removeAttribute('style');
42411 this.iterateChildren(node, this.cleanTableWidths);
42419 domToHTML : function(currentElement, depth, nopadtext) {
42421 depth = depth || 0;
42422 nopadtext = nopadtext || false;
42424 if (!currentElement) {
42425 return this.domToHTML(this.doc.body);
42428 //Roo.log(currentElement);
42430 var allText = false;
42431 var nodeName = currentElement.nodeName;
42432 var tagName = Roo.util.Format.htmlEncode(currentElement.tagName);
42434 if (nodeName == '#text') {
42436 return nopadtext ? currentElement.nodeValue : currentElement.nodeValue.trim();
42441 if (nodeName != 'BODY') {
42444 // Prints the node tagName, such as <A>, <IMG>, etc
42447 for(i = 0; i < currentElement.attributes.length;i++) {
42449 var aname = currentElement.attributes.item(i).name;
42450 if (!currentElement.attributes.item(i).value.length) {
42453 attr.push(aname + '="' + Roo.util.Format.htmlEncode(currentElement.attributes.item(i).value) + '"' );
42456 ret = "<"+currentElement.tagName+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">";
42465 if (['IMG', 'BR', 'HR', 'INPUT'].indexOf(tagName) > -1) {
42468 if (['PRE', 'TEXTAREA', 'TD', 'A', 'SPAN'].indexOf(tagName) > -1) { // or code?
42473 // Traverse the tree
42475 var currentElementChild = currentElement.childNodes.item(i);
42476 var allText = true;
42477 var innerHTML = '';
42479 while (currentElementChild) {
42480 // Formatting code (indent the tree so it looks nice on the screen)
42481 var nopad = nopadtext;
42482 if (lastnode == 'SPAN') {
42486 if (currentElementChild.nodeName == '#text') {
42487 var toadd = Roo.util.Format.htmlEncode(currentElementChild.nodeValue);
42488 toadd = nopadtext ? toadd : toadd.trim();
42489 if (!nopad && toadd.length > 80) {
42490 innerHTML += "\n" + (new Array( depth + 1 )).join( " " );
42492 innerHTML += toadd;
42495 currentElementChild = currentElement.childNodes.item(i);
42501 innerHTML += nopad ? '' : "\n" + (new Array( depth + 1 )).join( " " );
42503 // Recursively traverse the tree structure of the child node
42504 innerHTML += this.domToHTML(currentElementChild, depth+1, nopadtext);
42505 lastnode = currentElementChild.nodeName;
42507 currentElementChild=currentElement.childNodes.item(i);
42513 // The remaining code is mostly for formatting the tree
42514 ret+= nopadtext ? '' : "\n" + (new Array( depth )).join( " " );
42519 ret+= "</"+tagName+">";
42525 applyBlacklists : function()
42527 var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white : [];
42528 var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black : [];
42532 Roo.each(Roo.HtmlEditorCore.white, function(tag) {
42533 if (b.indexOf(tag) > -1) {
42536 this.white.push(tag);
42540 Roo.each(w, function(tag) {
42541 if (b.indexOf(tag) > -1) {
42544 if (this.white.indexOf(tag) > -1) {
42547 this.white.push(tag);
42552 Roo.each(Roo.HtmlEditorCore.black, function(tag) {
42553 if (w.indexOf(tag) > -1) {
42556 this.black.push(tag);
42560 Roo.each(b, function(tag) {
42561 if (w.indexOf(tag) > -1) {
42564 if (this.black.indexOf(tag) > -1) {
42567 this.black.push(tag);
42572 w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite : [];
42573 b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack : [];
42577 Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
42578 if (b.indexOf(tag) > -1) {
42581 this.cwhite.push(tag);
42585 Roo.each(w, function(tag) {
42586 if (b.indexOf(tag) > -1) {
42589 if (this.cwhite.indexOf(tag) > -1) {
42592 this.cwhite.push(tag);
42597 Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
42598 if (w.indexOf(tag) > -1) {
42601 this.cblack.push(tag);
42605 Roo.each(b, function(tag) {
42606 if (w.indexOf(tag) > -1) {
42609 if (this.cblack.indexOf(tag) > -1) {
42612 this.cblack.push(tag);
42617 setStylesheets : function(stylesheets)
42619 if(typeof(stylesheets) == 'string'){
42620 Roo.get(this.iframe.contentDocument.head).createChild({
42622 rel : 'stylesheet',
42631 Roo.each(stylesheets, function(s) {
42636 Roo.get(_this.iframe.contentDocument.head).createChild({
42638 rel : 'stylesheet',
42647 removeStylesheets : function()
42651 Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
42656 // hide stuff that is not compatible
42670 * @event specialkey
42674 * @cfg {String} fieldClass @hide
42677 * @cfg {String} focusClass @hide
42680 * @cfg {String} autoCreate @hide
42683 * @cfg {String} inputType @hide
42686 * @cfg {String} invalidClass @hide
42689 * @cfg {String} invalidText @hide
42692 * @cfg {String} msgFx @hide
42695 * @cfg {String} validateOnBlur @hide
42699 Roo.HtmlEditorCore.white = [
42700 'area', 'br', 'img', 'input', 'hr', 'wbr',
42702 'address', 'blockquote', 'center', 'dd', 'dir', 'div',
42703 'dl', 'dt', 'h1', 'h2', 'h3', 'h4',
42704 'h5', 'h6', 'hr', 'isindex', 'listing', 'marquee',
42705 'menu', 'multicol', 'ol', 'p', 'plaintext', 'pre',
42706 'table', 'ul', 'xmp',
42708 'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
42711 'dir', 'menu', 'ol', 'ul', 'dl',
42717 Roo.HtmlEditorCore.black = [
42718 // 'embed', 'object', // enable - backend responsiblity to clean thiese
42720 'base', 'basefont', 'bgsound', 'blink', 'body',
42721 'frame', 'frameset', 'head', 'html', 'ilayer',
42722 'iframe', 'layer', 'link', 'meta', 'object',
42723 'script', 'style' ,'title', 'xml' // clean later..
42725 Roo.HtmlEditorCore.clean = [
42726 'script', 'style', 'title', 'xml'
42728 Roo.HtmlEditorCore.remove = [
42733 Roo.HtmlEditorCore.ablack = [
42737 Roo.HtmlEditorCore.aclean = [
42738 'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc'
42742 Roo.HtmlEditorCore.pwhite= [
42743 'http', 'https', 'mailto'
42746 // white listed style attributes.
42747 Roo.HtmlEditorCore.cwhite= [
42748 // 'text-align', /// default is to allow most things..
42754 // black listed style attributes.
42755 Roo.HtmlEditorCore.cblack= [
42756 // 'font-size' -- this can be set by the project
42760 Roo.HtmlEditorCore.swapCodes =[
42771 //<script type="text/javascript">
42774 * Ext JS Library 1.1.1
42775 * Copyright(c) 2006-2007, Ext JS, LLC.
42781 Roo.form.HtmlEditor = function(config){
42785 Roo.form.HtmlEditor.superclass.constructor.call(this, config);
42787 if (!this.toolbars) {
42788 this.toolbars = [];
42790 this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
42796 * @class Roo.form.HtmlEditor
42797 * @extends Roo.form.Field
42798 * Provides a lightweight HTML Editor component.
42800 * This has been tested on Fireforx / Chrome.. IE may not be so great..
42802 * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
42803 * supported by this editor.</b><br/><br/>
42804 * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
42805 * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
42807 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
42809 * @cfg {Boolean} clearUp
42813 * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
42818 * @cfg {String} resizable 's' or 'se' or 'e' - wrapps the element in a
42823 * @cfg {Number} height (in pixels)
42827 * @cfg {Number} width (in pixels)
42832 * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
42835 stylesheets: false,
42839 * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
42844 * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
42850 * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
42855 * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
42863 // private properties
42864 validationEvent : false,
42866 initialized : false,
42869 onFocus : Roo.emptyFn,
42871 hideMode:'offsets',
42873 actionMode : 'container', // defaults to hiding it...
42875 defaultAutoCreate : { // modified by initCompnoent..
42877 style:"width:500px;height:300px;",
42878 autocomplete: "new-password"
42882 initComponent : function(){
42885 * @event initialize
42886 * Fires when the editor is fully initialized (including the iframe)
42887 * @param {HtmlEditor} this
42892 * Fires when the editor is first receives the focus. Any insertion must wait
42893 * until after this event.
42894 * @param {HtmlEditor} this
42898 * @event beforesync
42899 * Fires before the textarea is updated with content from the editor iframe. Return false
42900 * to cancel the sync.
42901 * @param {HtmlEditor} this
42902 * @param {String} html
42906 * @event beforepush
42907 * Fires before the iframe editor is updated with content from the textarea. Return false
42908 * to cancel the push.
42909 * @param {HtmlEditor} this
42910 * @param {String} html
42915 * Fires when the textarea is updated with content from the editor iframe.
42916 * @param {HtmlEditor} this
42917 * @param {String} html
42922 * Fires when the iframe editor is updated with content from the textarea.
42923 * @param {HtmlEditor} this
42924 * @param {String} html
42928 * @event editmodechange
42929 * Fires when the editor switches edit modes
42930 * @param {HtmlEditor} this
42931 * @param {Boolean} sourceEdit True if source edit, false if standard editing.
42933 editmodechange: true,
42935 * @event editorevent
42936 * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
42937 * @param {HtmlEditor} this
42941 * @event firstfocus
42942 * Fires when on first focus - needed by toolbars..
42943 * @param {HtmlEditor} this
42948 * Auto save the htmlEditor value as a file into Events
42949 * @param {HtmlEditor} this
42953 * @event savedpreview
42954 * preview the saved version of htmlEditor
42955 * @param {HtmlEditor} this
42957 savedpreview: true,
42960 * @event stylesheetsclick
42961 * Fires when press the Sytlesheets button
42962 * @param {Roo.HtmlEditorCore} this
42964 stylesheetsclick: true
42966 this.defaultAutoCreate = {
42968 style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
42969 autocomplete: "new-password"
42974 * Protected method that will not generally be called directly. It
42975 * is called when the editor creates its toolbar. Override this method if you need to
42976 * add custom toolbar buttons.
42977 * @param {HtmlEditor} editor
42979 createToolbar : function(editor){
42980 Roo.log("create toolbars");
42981 if (!editor.toolbars || !editor.toolbars.length) {
42982 editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
42985 for (var i =0 ; i < editor.toolbars.length;i++) {
42986 editor.toolbars[i] = Roo.factory(
42987 typeof(editor.toolbars[i]) == 'string' ?
42988 { xtype: editor.toolbars[i]} : editor.toolbars[i],
42989 Roo.form.HtmlEditor);
42990 editor.toolbars[i].init(editor);
42998 onRender : function(ct, position)
43001 Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
43003 this.wrap = this.el.wrap({
43004 cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
43007 this.editorcore.onRender(ct, position);
43009 if (this.resizable) {
43010 this.resizeEl = new Roo.Resizable(this.wrap, {
43014 minHeight : this.height,
43015 height: this.height,
43016 handles : this.resizable,
43019 resize : function(r, w, h) {
43020 _t.onResize(w,h); // -something
43026 this.createToolbar(this);
43030 this.setSize(this.wrap.getSize());
43032 if (this.resizeEl) {
43033 this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
43034 // should trigger onReize..
43037 this.keyNav = new Roo.KeyNav(this.el, {
43039 "tab" : function(e){
43040 e.preventDefault();
43042 var value = this.getValue();
43044 var start = this.el.dom.selectionStart;
43045 var end = this.el.dom.selectionEnd;
43049 this.setValue(value.substring(0, start) + "\t" + value.substring(end));
43050 this.el.dom.setSelectionRange(end + 1, end + 1);
43054 var f = value.substring(0, start).split("\t");
43056 if(f.pop().length != 0){
43060 this.setValue(f.join("\t") + value.substring(end));
43061 this.el.dom.setSelectionRange(start - 1, start - 1);
43065 "home" : function(e){
43066 e.preventDefault();
43068 var curr = this.el.dom.selectionStart;
43069 var lines = this.getValue().split("\n");
43076 this.el.dom.setSelectionRange(0, 0);
43082 for (var i = 0; i < lines.length;i++) {
43083 pos += lines[i].length;
43093 pos -= lines[i].length;
43099 this.el.dom.setSelectionRange(pos, pos);
43103 this.el.dom.selectionStart = pos;
43104 this.el.dom.selectionEnd = curr;
43107 "end" : function(e){
43108 e.preventDefault();
43110 var curr = this.el.dom.selectionStart;
43111 var lines = this.getValue().split("\n");
43118 this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
43124 for (var i = 0; i < lines.length;i++) {
43126 pos += lines[i].length;
43140 this.el.dom.setSelectionRange(pos, pos);
43144 this.el.dom.selectionStart = curr;
43145 this.el.dom.selectionEnd = pos;
43150 doRelay : function(foo, bar, hname){
43151 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
43157 // if(this.autosave && this.w){
43158 // this.autoSaveFn = setInterval(this.autosave, 1000);
43163 onResize : function(w, h)
43165 Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
43170 if(typeof w == 'number'){
43171 var aw = w - this.wrap.getFrameWidth('lr');
43172 this.el.setWidth(this.adjustWidth('textarea', aw));
43175 if(typeof h == 'number'){
43177 for (var i =0; i < this.toolbars.length;i++) {
43178 // fixme - ask toolbars for heights?
43179 tbh += this.toolbars[i].tb.el.getHeight();
43180 if (this.toolbars[i].footer) {
43181 tbh += this.toolbars[i].footer.el.getHeight();
43188 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
43189 ah -= 5; // knock a few pixes off for look..
43191 this.el.setHeight(this.adjustWidth('textarea', ah));
43195 Roo.log('onResize:' + [w,h,ew,eh].join(',') );
43196 this.editorcore.onResize(ew,eh);
43201 * Toggles the editor between standard and source edit mode.
43202 * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
43204 toggleSourceEdit : function(sourceEditMode)
43206 this.editorcore.toggleSourceEdit(sourceEditMode);
43208 if(this.editorcore.sourceEditMode){
43209 Roo.log('editor - showing textarea');
43212 // Roo.log(this.syncValue());
43213 this.editorcore.syncValue();
43214 this.el.removeClass('x-hidden');
43215 this.el.dom.removeAttribute('tabIndex');
43218 for (var i = 0; i < this.toolbars.length; i++) {
43219 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
43220 this.toolbars[i].tb.hide();
43221 this.toolbars[i].footer.hide();
43226 Roo.log('editor - hiding textarea');
43228 // Roo.log(this.pushValue());
43229 this.editorcore.pushValue();
43231 this.el.addClass('x-hidden');
43232 this.el.dom.setAttribute('tabIndex', -1);
43234 for (var i = 0; i < this.toolbars.length; i++) {
43235 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
43236 this.toolbars[i].tb.show();
43237 this.toolbars[i].footer.show();
43241 //this.deferFocus();
43244 this.setSize(this.wrap.getSize());
43245 this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
43247 this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
43250 // private (for BoxComponent)
43251 adjustSize : Roo.BoxComponent.prototype.adjustSize,
43253 // private (for BoxComponent)
43254 getResizeEl : function(){
43258 // private (for BoxComponent)
43259 getPositionEl : function(){
43264 initEvents : function(){
43265 this.originalValue = this.getValue();
43269 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
43272 markInvalid : Roo.emptyFn,
43274 * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
43277 clearInvalid : Roo.emptyFn,
43279 setValue : function(v){
43280 Roo.form.HtmlEditor.superclass.setValue.call(this, v);
43281 this.editorcore.pushValue();
43286 deferFocus : function(){
43287 this.focus.defer(10, this);
43291 focus : function(){
43292 this.editorcore.focus();
43298 onDestroy : function(){
43304 for (var i =0; i < this.toolbars.length;i++) {
43305 // fixme - ask toolbars for heights?
43306 this.toolbars[i].onDestroy();
43309 this.wrap.dom.innerHTML = '';
43310 this.wrap.remove();
43315 onFirstFocus : function(){
43316 //Roo.log("onFirstFocus");
43317 this.editorcore.onFirstFocus();
43318 for (var i =0; i < this.toolbars.length;i++) {
43319 this.toolbars[i].onFirstFocus();
43325 syncValue : function()
43327 this.editorcore.syncValue();
43330 pushValue : function()
43332 this.editorcore.pushValue();
43335 setStylesheets : function(stylesheets)
43337 this.editorcore.setStylesheets(stylesheets);
43340 removeStylesheets : function()
43342 this.editorcore.removeStylesheets();
43346 // hide stuff that is not compatible
43360 * @event specialkey
43364 * @cfg {String} fieldClass @hide
43367 * @cfg {String} focusClass @hide
43370 * @cfg {String} autoCreate @hide
43373 * @cfg {String} inputType @hide
43376 * @cfg {String} invalidClass @hide
43379 * @cfg {String} invalidText @hide
43382 * @cfg {String} msgFx @hide
43385 * @cfg {String} validateOnBlur @hide
43389 // <script type="text/javascript">
43392 * Ext JS Library 1.1.1
43393 * Copyright(c) 2006-2007, Ext JS, LLC.
43399 * @class Roo.form.HtmlEditorToolbar1
43404 new Roo.form.HtmlEditor({
43407 new Roo.form.HtmlEditorToolbar1({
43408 disable : { fonts: 1 , format: 1, ..., ... , ...],
43414 * @cfg {Object} disable List of elements to disable..
43415 * @cfg {Array} btns List of additional buttons.
43419 * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
43422 Roo.form.HtmlEditor.ToolbarStandard = function(config)
43425 Roo.apply(this, config);
43427 // default disabled, based on 'good practice'..
43428 this.disable = this.disable || {};
43429 Roo.applyIf(this.disable, {
43432 specialElements : true
43436 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
43437 // dont call parent... till later.
43440 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype, {
43447 editorcore : false,
43449 * @cfg {Object} disable List of toolbar elements to disable
43456 * @cfg {String} createLinkText The default text for the create link prompt
43458 createLinkText : 'Please enter the URL for the link:',
43460 * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
43462 defaultLinkValue : 'http:/'+'/',
43466 * @cfg {Array} fontFamilies An array of available font families
43484 // "á" , ?? a acute?
43489 "°" // , // degrees
43491 // "é" , // e ecute
43492 // "ú" , // u ecute?
43495 specialElements : [
43497 text: "Insert Table",
43500 ihtml : '<table><tr><td>Cell</td></tr></table>'
43504 text: "Insert Image",
43507 ihtml : '<img src="about:blank"/>'
43516 "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password",
43517 "input:submit", "input:button", "select", "textarea", "label" ],
43520 ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],
43522 ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
43530 * @cfg {String} defaultFont default font to use.
43532 defaultFont: 'tahoma',
43534 fontSelect : false,
43537 formatCombo : false,
43539 init : function(editor)
43541 this.editor = editor;
43542 this.editorcore = editor.editorcore ? editor.editorcore : editor;
43543 var editorcore = this.editorcore;
43547 var fid = editorcore.frameId;
43549 function btn(id, toggle, handler){
43550 var xid = fid + '-'+ id ;
43554 cls : 'x-btn-icon x-edit-'+id,
43555 enableToggle:toggle !== false,
43556 scope: _t, // was editor...
43557 handler:handler||_t.relayBtnCmd,
43558 clickEvent:'mousedown',
43559 tooltip: etb.buttonTips[id] || undefined, ///tips ???
43566 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
43568 // stop form submits
43569 tb.el.on('click', function(e){
43570 e.preventDefault(); // what does this do?
43573 if(!this.disable.font) { // && !Roo.isSafari){
43574 /* why no safari for fonts
43575 editor.fontSelect = tb.el.createChild({
43578 cls:'x-font-select',
43579 html: this.createFontOptions()
43582 editor.fontSelect.on('change', function(){
43583 var font = editor.fontSelect.dom.value;
43584 editor.relayCmd('fontname', font);
43585 editor.deferFocus();
43589 editor.fontSelect.dom,
43595 if(!this.disable.formats){
43596 this.formatCombo = new Roo.form.ComboBox({
43597 store: new Roo.data.SimpleStore({
43600 data : this.formats // from states.js
43604 //autoCreate : {tag: "div", size: "20"},
43605 displayField:'tag',
43609 triggerAction: 'all',
43610 emptyText:'Add tag',
43611 selectOnFocus:true,
43614 'select': function(c, r, i) {
43615 editorcore.insertTag(r.get('tag'));
43621 tb.addField(this.formatCombo);
43625 if(!this.disable.format){
43632 if(!this.disable.fontSize){
43637 btn('increasefontsize', false, editorcore.adjustFont),
43638 btn('decreasefontsize', false, editorcore.adjustFont)
43643 if(!this.disable.colors){
43646 id:editorcore.frameId +'-forecolor',
43647 cls:'x-btn-icon x-edit-forecolor',
43648 clickEvent:'mousedown',
43649 tooltip: this.buttonTips['forecolor'] || undefined,
43651 menu : new Roo.menu.ColorMenu({
43652 allowReselect: true,
43653 focus: Roo.emptyFn,
43656 selectHandler: function(cp, color){
43657 editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
43658 editor.deferFocus();
43661 clickEvent:'mousedown'
43664 id:editorcore.frameId +'backcolor',
43665 cls:'x-btn-icon x-edit-backcolor',
43666 clickEvent:'mousedown',
43667 tooltip: this.buttonTips['backcolor'] || undefined,
43669 menu : new Roo.menu.ColorMenu({
43670 focus: Roo.emptyFn,
43673 allowReselect: true,
43674 selectHandler: function(cp, color){
43676 editorcore.execCmd('useCSS', false);
43677 editorcore.execCmd('hilitecolor', color);
43678 editorcore.execCmd('useCSS', true);
43679 editor.deferFocus();
43681 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor',
43682 Roo.isSafari || Roo.isIE ? '#'+color : color);
43683 editor.deferFocus();
43687 clickEvent:'mousedown'
43692 // now add all the items...
43695 if(!this.disable.alignments){
43698 btn('justifyleft'),
43699 btn('justifycenter'),
43700 btn('justifyright')
43704 //if(!Roo.isSafari){
43705 if(!this.disable.links){
43708 btn('createlink', false, this.createLink) /// MOVE TO HERE?!!?!?!?!
43712 if(!this.disable.lists){
43715 btn('insertorderedlist'),
43716 btn('insertunorderedlist')
43719 if(!this.disable.sourceEdit){
43722 btn('sourceedit', true, function(btn){
43723 this.toggleSourceEdit(btn.pressed);
43730 // special menu.. - needs to be tidied up..
43731 if (!this.disable.special) {
43734 cls: 'x-edit-none',
43740 for (var i =0; i < this.specialChars.length; i++) {
43741 smenu.menu.items.push({
43743 html: this.specialChars[i],
43744 handler: function(a,b) {
43745 editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
43746 //editor.insertAtCursor(a.html);
43760 if (!this.disable.cleanStyles) {
43762 cls: 'x-btn-icon x-btn-clear',
43768 for (var i =0; i < this.cleanStyles.length; i++) {
43769 cmenu.menu.items.push({
43770 actiontype : this.cleanStyles[i],
43771 html: 'Remove ' + this.cleanStyles[i],
43772 handler: function(a,b) {
43775 var c = Roo.get(editorcore.doc.body);
43776 c.select('[style]').each(function(s) {
43777 s.dom.style.removeProperty(a.actiontype);
43779 editorcore.syncValue();
43784 cmenu.menu.items.push({
43785 actiontype : 'tablewidths',
43786 html: 'Remove Table Widths',
43787 handler: function(a,b) {
43788 editorcore.cleanTableWidths();
43789 editorcore.syncValue();
43793 cmenu.menu.items.push({
43794 actiontype : 'word',
43795 html: 'Remove MS Word Formating',
43796 handler: function(a,b) {
43797 editorcore.cleanWord();
43798 editorcore.syncValue();
43803 cmenu.menu.items.push({
43804 actiontype : 'all',
43805 html: 'Remove All Styles',
43806 handler: function(a,b) {
43808 var c = Roo.get(editorcore.doc.body);
43809 c.select('[style]').each(function(s) {
43810 s.dom.removeAttribute('style');
43812 editorcore.syncValue();
43817 cmenu.menu.items.push({
43818 actiontype : 'all',
43819 html: 'Remove All CSS Classes',
43820 handler: function(a,b) {
43822 var c = Roo.get(editorcore.doc.body);
43823 c.select('[class]').each(function(s) {
43824 s.dom.className = '';
43826 editorcore.syncValue();
43831 cmenu.menu.items.push({
43832 actiontype : 'tidy',
43833 html: 'Tidy HTML Source',
43834 handler: function(a,b) {
43835 editorcore.doc.body.innerHTML = editorcore.domToHTML();
43836 editorcore.syncValue();
43845 if (!this.disable.specialElements) {
43848 cls: 'x-edit-none',
43853 for (var i =0; i < this.specialElements.length; i++) {
43854 semenu.menu.items.push(
43856 handler: function(a,b) {
43857 editor.insertAtCursor(this.ihtml);
43859 }, this.specialElements[i])
43871 for(var i =0; i< this.btns.length;i++) {
43872 var b = Roo.factory(this.btns[i],Roo.form);
43873 b.cls = 'x-edit-none';
43875 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
43876 b.cls += ' x-init-enable';
43879 b.scope = editorcore;
43887 // disable everything...
43889 this.tb.items.each(function(item){
43892 item.id != editorcore.frameId+ '-sourceedit' &&
43893 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
43899 this.rendered = true;
43901 // the all the btns;
43902 editor.on('editorevent', this.updateToolbar, this);
43903 // other toolbars need to implement this..
43904 //editor.on('editmodechange', this.updateToolbar, this);
43908 relayBtnCmd : function(btn) {
43909 this.editorcore.relayCmd(btn.cmd);
43911 // private used internally
43912 createLink : function(){
43913 Roo.log("create link?");
43914 var url = prompt(this.createLinkText, this.defaultLinkValue);
43915 if(url && url != 'http:/'+'/'){
43916 this.editorcore.relayCmd('createlink', url);
43922 * Protected method that will not generally be called directly. It triggers
43923 * a toolbar update by reading the markup state of the current selection in the editor.
43925 updateToolbar: function(){
43927 if(!this.editorcore.activated){
43928 this.editor.onFirstFocus();
43932 var btns = this.tb.items.map,
43933 doc = this.editorcore.doc,
43934 frameId = this.editorcore.frameId;
43936 if(!this.disable.font && !Roo.isSafari){
43938 var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
43939 if(name != this.fontSelect.dom.value){
43940 this.fontSelect.dom.value = name;
43944 if(!this.disable.format){
43945 btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
43946 btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
43947 btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
43949 if(!this.disable.alignments){
43950 btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
43951 btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
43952 btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
43954 if(!Roo.isSafari && !this.disable.lists){
43955 btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
43956 btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
43959 var ans = this.editorcore.getAllAncestors();
43960 if (this.formatCombo) {
43963 var store = this.formatCombo.store;
43964 this.formatCombo.setValue("");
43965 for (var i =0; i < ans.length;i++) {
43966 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
43968 this.formatCombo.setValue(ans[i].tagName.toLowerCase());
43976 // hides menus... - so this cant be on a menu...
43977 Roo.menu.MenuMgr.hideAll();
43979 //this.editorsyncValue();
43983 createFontOptions : function(){
43984 var buf = [], fs = this.fontFamilies, ff, lc;
43988 for(var i = 0, len = fs.length; i< len; i++){
43990 lc = ff.toLowerCase();
43992 '<option value="',lc,'" style="font-family:',ff,';"',
43993 (this.defaultFont == lc ? ' selected="true">' : '>'),
43998 return buf.join('');
44001 toggleSourceEdit : function(sourceEditMode){
44003 Roo.log("toolbar toogle");
44004 if(sourceEditMode === undefined){
44005 sourceEditMode = !this.sourceEditMode;
44007 this.sourceEditMode = sourceEditMode === true;
44008 var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
44009 // just toggle the button?
44010 if(btn.pressed !== this.sourceEditMode){
44011 btn.toggle(this.sourceEditMode);
44015 if(sourceEditMode){
44016 Roo.log("disabling buttons");
44017 this.tb.items.each(function(item){
44018 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
44024 Roo.log("enabling buttons");
44025 if(this.editorcore.initialized){
44026 this.tb.items.each(function(item){
44032 Roo.log("calling toggole on editor");
44033 // tell the editor that it's been pressed..
44034 this.editor.toggleSourceEdit(sourceEditMode);
44038 * Object collection of toolbar tooltips for the buttons in the editor. The key
44039 * is the command id associated with that button and the value is a valid QuickTips object.
44044 title: 'Bold (Ctrl+B)',
44045 text: 'Make the selected text bold.',
44046 cls: 'x-html-editor-tip'
44049 title: 'Italic (Ctrl+I)',
44050 text: 'Make the selected text italic.',
44051 cls: 'x-html-editor-tip'
44059 title: 'Bold (Ctrl+B)',
44060 text: 'Make the selected text bold.',
44061 cls: 'x-html-editor-tip'
44064 title: 'Italic (Ctrl+I)',
44065 text: 'Make the selected text italic.',
44066 cls: 'x-html-editor-tip'
44069 title: 'Underline (Ctrl+U)',
44070 text: 'Underline the selected text.',
44071 cls: 'x-html-editor-tip'
44073 increasefontsize : {
44074 title: 'Grow Text',
44075 text: 'Increase the font size.',
44076 cls: 'x-html-editor-tip'
44078 decreasefontsize : {
44079 title: 'Shrink Text',
44080 text: 'Decrease the font size.',
44081 cls: 'x-html-editor-tip'
44084 title: 'Text Highlight Color',
44085 text: 'Change the background color of the selected text.',
44086 cls: 'x-html-editor-tip'
44089 title: 'Font Color',
44090 text: 'Change the color of the selected text.',
44091 cls: 'x-html-editor-tip'
44094 title: 'Align Text Left',
44095 text: 'Align text to the left.',
44096 cls: 'x-html-editor-tip'
44099 title: 'Center Text',
44100 text: 'Center text in the editor.',
44101 cls: 'x-html-editor-tip'
44104 title: 'Align Text Right',
44105 text: 'Align text to the right.',
44106 cls: 'x-html-editor-tip'
44108 insertunorderedlist : {
44109 title: 'Bullet List',
44110 text: 'Start a bulleted list.',
44111 cls: 'x-html-editor-tip'
44113 insertorderedlist : {
44114 title: 'Numbered List',
44115 text: 'Start a numbered list.',
44116 cls: 'x-html-editor-tip'
44119 title: 'Hyperlink',
44120 text: 'Make the selected text a hyperlink.',
44121 cls: 'x-html-editor-tip'
44124 title: 'Source Edit',
44125 text: 'Switch to source editing mode.',
44126 cls: 'x-html-editor-tip'
44130 onDestroy : function(){
44133 this.tb.items.each(function(item){
44135 item.menu.removeAll();
44137 item.menu.el.destroy();
44145 onFirstFocus: function() {
44146 this.tb.items.each(function(item){
44155 // <script type="text/javascript">
44158 * Ext JS Library 1.1.1
44159 * Copyright(c) 2006-2007, Ext JS, LLC.
44166 * @class Roo.form.HtmlEditor.ToolbarContext
44171 new Roo.form.HtmlEditor({
44174 { xtype: 'ToolbarStandard', styles : {} }
44175 { xtype: 'ToolbarContext', disable : {} }
44181 * @config : {Object} disable List of elements to disable.. (not done yet.)
44182 * @config : {Object} styles Map of styles available.
44186 Roo.form.HtmlEditor.ToolbarContext = function(config)
44189 Roo.apply(this, config);
44190 //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
44191 // dont call parent... till later.
44192 this.styles = this.styles || {};
44197 Roo.form.HtmlEditor.ToolbarContext.types = {
44209 opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
44275 opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
44280 opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
44290 style : 'fontFamily',
44291 displayField: 'display',
44292 optname : 'font-family',
44341 // should we really allow this??
44342 // should this just be
44353 style : 'fontFamily',
44354 displayField: 'display',
44355 optname : 'font-family',
44362 style : 'fontFamily',
44363 displayField: 'display',
44364 optname : 'font-family',
44371 style : 'fontFamily',
44372 displayField: 'display',
44373 optname : 'font-family',
44384 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
44385 Roo.form.HtmlEditor.ToolbarContext.stores = false;
44387 Roo.form.HtmlEditor.ToolbarContext.options = {
44389 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
44390 [ 'Courier New', 'Courier New'],
44391 [ 'Tahoma', 'Tahoma'],
44392 [ 'Times New Roman,serif', 'Times'],
44393 [ 'Verdana','Verdana' ]
44397 // fixme - these need to be configurable..
44400 Roo.form.HtmlEditor.ToolbarContext.types
44403 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype, {
44410 editorcore : false,
44412 * @cfg {Object} disable List of toolbar elements to disable
44417 * @cfg {Object} styles List of styles
44418 * eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] }
44420 * These must be defined in the page, so they get rendered correctly..
44431 init : function(editor)
44433 this.editor = editor;
44434 this.editorcore = editor.editorcore ? editor.editorcore : editor;
44435 var editorcore = this.editorcore;
44437 var fid = editorcore.frameId;
44439 function btn(id, toggle, handler){
44440 var xid = fid + '-'+ id ;
44444 cls : 'x-btn-icon x-edit-'+id,
44445 enableToggle:toggle !== false,
44446 scope: editorcore, // was editor...
44447 handler:handler||editorcore.relayBtnCmd,
44448 clickEvent:'mousedown',
44449 tooltip: etb.buttonTips[id] || undefined, ///tips ???
44453 // create a new element.
44454 var wdiv = editor.wrap.createChild({
44456 }, editor.wrap.dom.firstChild.nextSibling, true);
44458 // can we do this more than once??
44460 // stop form submits
44463 // disable everything...
44464 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
44465 this.toolbars = {};
44467 for (var i in ty) {
44469 this.toolbars[i] = this.buildToolbar(ty[i],i);
44471 this.tb = this.toolbars.BODY;
44473 this.buildFooter();
44474 this.footer.show();
44475 editor.on('hide', function( ) { this.footer.hide() }, this);
44476 editor.on('show', function( ) { this.footer.show() }, this);
44479 this.rendered = true;
44481 // the all the btns;
44482 editor.on('editorevent', this.updateToolbar, this);
44483 // other toolbars need to implement this..
44484 //editor.on('editmodechange', this.updateToolbar, this);
44490 * Protected method that will not generally be called directly. It triggers
44491 * a toolbar update by reading the markup state of the current selection in the editor.
44493 * Note you can force an update by calling on('editorevent', scope, false)
44495 updateToolbar: function(editor,ev,sel){
44498 // capture mouse up - this is handy for selecting images..
44499 // perhaps should go somewhere else...
44500 if(!this.editorcore.activated){
44501 this.editor.onFirstFocus();
44507 // http://developer.yahoo.com/yui/docs/simple-editor.js.html
44508 // selectNode - might want to handle IE?
44510 (ev.type == 'mouseup' || ev.type == 'click' ) &&
44511 ev.target && ev.target.tagName == 'IMG') {
44512 // they have click on an image...
44513 // let's see if we can change the selection...
44516 var nodeRange = sel.ownerDocument.createRange();
44518 nodeRange.selectNode(sel);
44520 nodeRange.selectNodeContents(sel);
44522 //nodeRange.collapse(true);
44523 var s = this.editorcore.win.getSelection();
44524 s.removeAllRanges();
44525 s.addRange(nodeRange);
44529 var updateFooter = sel ? false : true;
44532 var ans = this.editorcore.getAllAncestors();
44535 var ty= Roo.form.HtmlEditor.ToolbarContext.types;
44538 sel = ans.length ? (ans[0] ? ans[0] : ans[1]) : this.editorcore.doc.body;
44539 sel = sel ? sel : this.editorcore.doc.body;
44540 sel = sel.tagName.length ? sel : this.editorcore.doc.body;
44543 // pick a menu that exists..
44544 var tn = sel.tagName.toUpperCase();
44545 //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
44547 tn = sel.tagName.toUpperCase();
44549 var lastSel = this.tb.selectedNode
44551 this.tb.selectedNode = sel;
44553 // if current menu does not match..
44555 if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode) || ev === false) {
44558 ///console.log("show: " + tn);
44559 this.tb = typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
44562 this.tb.items.first().el.innerHTML = tn + ': ';
44565 // update attributes
44566 if (this.tb.fields) {
44567 this.tb.fields.each(function(e) {
44569 e.setValue(sel.style[e.stylename]);
44572 e.setValue(sel.getAttribute(e.attrname));
44576 var hasStyles = false;
44577 for(var i in this.styles) {
44584 var st = this.tb.fields.item(0);
44586 st.store.removeAll();
44589 var cn = sel.className.split(/\s+/);
44592 if (this.styles['*']) {
44594 Roo.each(this.styles['*'], function(v) {
44595 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
44598 if (this.styles[tn]) {
44599 Roo.each(this.styles[tn], function(v) {
44600 avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );
44604 st.store.loadData(avs);
44608 // flag our selected Node.
44609 this.tb.selectedNode = sel;
44612 Roo.menu.MenuMgr.hideAll();
44616 if (!updateFooter) {
44617 //this.footDisp.dom.innerHTML = '';
44620 // update the footer
44624 this.footerEls = ans.reverse();
44625 Roo.each(this.footerEls, function(a,i) {
44626 if (!a) { return; }
44627 html += html.length ? ' > ' : '';
44629 html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
44634 var sz = this.footDisp.up('td').getSize();
44635 this.footDisp.dom.style.width = (sz.width -10) + 'px';
44636 this.footDisp.dom.style.marginLeft = '5px';
44638 this.footDisp.dom.style.overflow = 'hidden';
44640 this.footDisp.dom.innerHTML = html;
44642 //this.editorsyncValue();
44649 onDestroy : function(){
44652 this.tb.items.each(function(item){
44654 item.menu.removeAll();
44656 item.menu.el.destroy();
44664 onFirstFocus: function() {
44665 // need to do this for all the toolbars..
44666 this.tb.items.each(function(item){
44670 buildToolbar: function(tlist, nm)
44672 var editor = this.editor;
44673 var editorcore = this.editorcore;
44674 // create a new element.
44675 var wdiv = editor.wrap.createChild({
44677 }, editor.wrap.dom.firstChild.nextSibling, true);
44680 var tb = new Roo.Toolbar(wdiv);
44683 tb.add(nm+ ": ");
44686 for(var i in this.styles) {
44691 if (styles && styles.length) {
44693 // this needs a multi-select checkbox...
44694 tb.addField( new Roo.form.ComboBox({
44695 store: new Roo.data.SimpleStore({
44697 fields: ['val', 'selected'],
44700 name : '-roo-edit-className',
44701 attrname : 'className',
44702 displayField: 'val',
44706 triggerAction: 'all',
44707 emptyText:'Select Style',
44708 selectOnFocus:true,
44711 'select': function(c, r, i) {
44712 // initial support only for on class per el..
44713 tb.selectedNode.className = r ? r.get('val') : '';
44714 editorcore.syncValue();
44721 var tbc = Roo.form.HtmlEditor.ToolbarContext;
44722 var tbops = tbc.options;
44724 for (var i in tlist) {
44726 var item = tlist[i];
44727 tb.add(item.title + ": ");
44730 //optname == used so you can configure the options available..
44731 var opts = item.opts ? item.opts : false;
44732 if (item.optname) {
44733 opts = tbops[item.optname];
44738 // opts == pulldown..
44739 tb.addField( new Roo.form.ComboBox({
44740 store: typeof(tbc.stores[i]) != 'undefined' ? Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
44742 fields: ['val', 'display'],
44745 name : '-roo-edit-' + i,
44747 stylename : item.style ? item.style : false,
44748 displayField: item.displayField ? item.displayField : 'val',
44749 valueField : 'val',
44751 mode: typeof(tbc.stores[i]) != 'undefined' ? 'remote' : 'local',
44753 triggerAction: 'all',
44754 emptyText:'Select',
44755 selectOnFocus:true,
44756 width: item.width ? item.width : 130,
44758 'select': function(c, r, i) {
44760 tb.selectedNode.style[c.stylename] = r.get('val');
44763 tb.selectedNode.setAttribute(c.attrname, r.get('val'));
44772 tb.addField( new Roo.form.TextField({
44775 //allowBlank:false,
44780 tb.addField( new Roo.form.TextField({
44781 name: '-roo-edit-' + i,
44788 'change' : function(f, nv, ov) {
44789 tb.selectedNode.setAttribute(f.attrname, nv);
44802 text: 'Stylesheets',
44805 click : function ()
44807 _this.editor.fireEvent('stylesheetsclick', _this.editor);
44815 text: 'Remove Tag',
44818 click : function ()
44821 // undo does not work.
44823 var sn = tb.selectedNode;
44825 var pn = sn.parentNode;
44827 var stn = sn.childNodes[0];
44828 var en = sn.childNodes[sn.childNodes.length - 1 ];
44829 while (sn.childNodes.length) {
44830 var node = sn.childNodes[0];
44831 sn.removeChild(node);
44833 pn.insertBefore(node, sn);
44836 pn.removeChild(sn);
44837 var range = editorcore.createRange();
44839 range.setStart(stn,0);
44840 range.setEnd(en,0); //????
44841 //range.selectNode(sel);
44844 var selection = editorcore.getSelection();
44845 selection.removeAllRanges();
44846 selection.addRange(range);
44850 //_this.updateToolbar(null, null, pn);
44851 _this.updateToolbar(null, null, null);
44852 _this.footDisp.dom.innerHTML = '';
44862 tb.el.on('click', function(e){
44863 e.preventDefault(); // what does this do?
44865 tb.el.setVisibilityMode( Roo.Element.DISPLAY);
44868 // dont need to disable them... as they will get hidden
44873 buildFooter : function()
44876 var fel = this.editor.wrap.createChild();
44877 this.footer = new Roo.Toolbar(fel);
44878 // toolbar has scrolly on left / right?
44879 var footDisp= new Roo.Toolbar.Fill();
44885 handler : function() {
44886 _t.footDisp.scrollTo('left',0,true)
44890 this.footer.add( footDisp );
44895 handler : function() {
44897 _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
44901 var fel = Roo.get(footDisp.el);
44902 fel.addClass('x-editor-context');
44903 this.footDispWrap = fel;
44904 this.footDispWrap.overflow = 'hidden';
44906 this.footDisp = fel.createChild();
44907 this.footDispWrap.on('click', this.onContextClick, this)
44911 onContextClick : function (ev,dom)
44913 ev.preventDefault();
44914 var cn = dom.className;
44916 if (!cn.match(/x-ed-loc-/)) {
44919 var n = cn.split('-').pop();
44920 var ans = this.footerEls;
44924 var range = this.editorcore.createRange();
44926 range.selectNodeContents(sel);
44927 //range.selectNode(sel);
44930 var selection = this.editorcore.getSelection();
44931 selection.removeAllRanges();
44932 selection.addRange(range);
44936 this.updateToolbar(null, null, sel);
44953 * Ext JS Library 1.1.1
44954 * Copyright(c) 2006-2007, Ext JS, LLC.
44956 * Originally Released Under LGPL - original licence link has changed is not relivant.
44959 * <script type="text/javascript">
44963 * @class Roo.form.BasicForm
44964 * @extends Roo.util.Observable
44965 * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
44967 * @param {String/HTMLElement/Roo.Element} el The form element or its id
44968 * @param {Object} config Configuration options
44970 Roo.form.BasicForm = function(el, config){
44971 this.allItems = [];
44972 this.childForms = [];
44973 Roo.apply(this, config);
44975 * The Roo.form.Field items in this form.
44976 * @type MixedCollection
44980 this.items = new Roo.util.MixedCollection(false, function(o){
44981 return o.id || (o.id = Roo.id());
44985 * @event beforeaction
44986 * Fires before any action is performed. Return false to cancel the action.
44987 * @param {Form} this
44988 * @param {Action} action The action to be performed
44990 beforeaction: true,
44992 * @event actionfailed
44993 * Fires when an action fails.
44994 * @param {Form} this
44995 * @param {Action} action The action that failed
44997 actionfailed : true,
44999 * @event actioncomplete
45000 * Fires when an action is completed.
45001 * @param {Form} this
45002 * @param {Action} action The action that completed
45004 actioncomplete : true
45009 Roo.form.BasicForm.superclass.constructor.call(this);
45012 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
45014 * @cfg {String} method
45015 * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
45018 * @cfg {DataReader} reader
45019 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
45020 * This is optional as there is built-in support for processing JSON.
45023 * @cfg {DataReader} errorReader
45024 * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
45025 * This is completely optional as there is built-in support for processing JSON.
45028 * @cfg {String} url
45029 * The URL to use for form actions if one isn't supplied in the action options.
45032 * @cfg {Boolean} fileUpload
45033 * Set to true if this form is a file upload.
45037 * @cfg {Object} baseParams
45038 * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
45043 * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
45048 activeAction : null,
45051 * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
45052 * or setValues() data instead of when the form was first created.
45054 trackResetOnLoad : false,
45058 * childForms - used for multi-tab forms
45061 childForms : false,
45064 * allItems - full list of fields.
45070 * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
45071 * element by passing it or its id or mask the form itself by passing in true.
45074 waitMsgTarget : false,
45077 initEl : function(el){
45078 this.el = Roo.get(el);
45079 this.id = this.el.id || Roo.id();
45080 this.el.on('submit', this.onSubmit, this);
45081 this.el.addClass('x-form');
45085 onSubmit : function(e){
45090 * Returns true if client-side validation on the form is successful.
45093 isValid : function(){
45095 this.items.each(function(f){
45104 * Returns true if any fields in this form have changed since their original load.
45107 isDirty : function(){
45109 this.items.each(function(f){
45119 * Performs a predefined action (submit or load) or custom actions you define on this form.
45120 * @param {String} actionName The name of the action type
45121 * @param {Object} options (optional) The options to pass to the action. All of the config options listed
45122 * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
45123 * accept other config options):
45125 Property Type Description
45126 ---------------- --------------- ----------------------------------------------------------------------------------
45127 url String The url for the action (defaults to the form's url)
45128 method String The form method to use (defaults to the form's method, or POST if not defined)
45129 params String/Object The params to pass (defaults to the form's baseParams, or none if not defined)
45130 clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to
45131 validate the form on the client (defaults to false)
45133 * @return {BasicForm} this
45135 doAction : function(action, options){
45136 if(typeof action == 'string'){
45137 action = new Roo.form.Action.ACTION_TYPES[action](this, options);
45139 if(this.fireEvent('beforeaction', this, action) !== false){
45140 this.beforeAction(action);
45141 action.run.defer(100, action);
45147 * Shortcut to do a submit action.
45148 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
45149 * @return {BasicForm} this
45151 submit : function(options){
45152 this.doAction('submit', options);
45157 * Shortcut to do a load action.
45158 * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
45159 * @return {BasicForm} this
45161 load : function(options){
45162 this.doAction('load', options);
45167 * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
45168 * @param {Record} record The record to edit
45169 * @return {BasicForm} this
45171 updateRecord : function(record){
45172 record.beginEdit();
45173 var fs = record.fields;
45174 fs.each(function(f){
45175 var field = this.findField(f.name);
45177 record.set(f.name, field.getValue());
45185 * Loads an Roo.data.Record into this form.
45186 * @param {Record} record The record to load
45187 * @return {BasicForm} this
45189 loadRecord : function(record){
45190 this.setValues(record.data);
45195 beforeAction : function(action){
45196 var o = action.options;
45199 if(this.waitMsgTarget === true){
45200 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
45201 }else if(this.waitMsgTarget){
45202 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
45203 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
45205 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
45211 afterAction : function(action, success){
45212 this.activeAction = null;
45213 var o = action.options;
45215 if(this.waitMsgTarget === true){
45217 }else if(this.waitMsgTarget){
45218 this.waitMsgTarget.unmask();
45220 Roo.MessageBox.updateProgress(1);
45221 Roo.MessageBox.hide();
45228 Roo.callback(o.success, o.scope, [this, action]);
45229 this.fireEvent('actioncomplete', this, action);
45233 // failure condition..
45234 // we have a scenario where updates need confirming.
45235 // eg. if a locking scenario exists..
45236 // we look for { errors : { needs_confirm : true }} in the response.
45238 (typeof(action.result) != 'undefined') &&
45239 (typeof(action.result.errors) != 'undefined') &&
45240 (typeof(action.result.errors.needs_confirm) != 'undefined')
45243 Roo.MessageBox.confirm(
45244 "Change requires confirmation",
45245 action.result.errorMsg,
45250 _t.doAction('submit', { params : { _submit_confirmed : 1 } } );
45260 Roo.callback(o.failure, o.scope, [this, action]);
45261 // show an error message if no failed handler is set..
45262 if (!this.hasListener('actionfailed')) {
45263 Roo.MessageBox.alert("Error",
45264 (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
45265 action.result.errorMsg :
45266 "Saving Failed, please check your entries or try again"
45270 this.fireEvent('actionfailed', this, action);
45276 * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
45277 * @param {String} id The value to search for
45280 findField : function(id){
45281 var field = this.items.get(id);
45283 this.items.each(function(f){
45284 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
45290 return field || null;
45294 * Add a secondary form to this one,
45295 * Used to provide tabbed forms. One form is primary, with hidden values
45296 * which mirror the elements from the other forms.
45298 * @param {Roo.form.Form} form to add.
45301 addForm : function(form)
45304 if (this.childForms.indexOf(form) > -1) {
45308 this.childForms.push(form);
45310 Roo.each(form.allItems, function (fe) {
45312 n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
45313 if (this.findField(n)) { // already added..
45316 var add = new Roo.form.Hidden({
45319 add.render(this.el);
45326 * Mark fields in this form invalid in bulk.
45327 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
45328 * @return {BasicForm} this
45330 markInvalid : function(errors){
45331 if(errors instanceof Array){
45332 for(var i = 0, len = errors.length; i < len; i++){
45333 var fieldError = errors[i];
45334 var f = this.findField(fieldError.id);
45336 f.markInvalid(fieldError.msg);
45342 if(typeof errors[id] != 'function' && (field = this.findField(id))){
45343 field.markInvalid(errors[id]);
45347 Roo.each(this.childForms || [], function (f) {
45348 f.markInvalid(errors);
45355 * Set values for fields in this form in bulk.
45356 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
45357 * @return {BasicForm} this
45359 setValues : function(values){
45360 if(values instanceof Array){ // array of objects
45361 for(var i = 0, len = values.length; i < len; i++){
45363 var f = this.findField(v.id);
45365 f.setValue(v.value);
45366 if(this.trackResetOnLoad){
45367 f.originalValue = f.getValue();
45371 }else{ // object hash
45374 if(typeof values[id] != 'function' && (field = this.findField(id))){
45376 if (field.setFromData &&
45377 field.valueField &&
45378 field.displayField &&
45379 // combos' with local stores can
45380 // be queried via setValue()
45381 // to set their value..
45382 (field.store && !field.store.isLocal)
45386 sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
45387 sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
45388 field.setFromData(sd);
45391 field.setValue(values[id]);
45395 if(this.trackResetOnLoad){
45396 field.originalValue = field.getValue();
45402 Roo.each(this.childForms || [], function (f) {
45403 f.setValues(values);
45410 * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
45411 * they are returned as an array.
45412 * @param {Boolean} asString
45415 getValues : function(asString){
45416 if (this.childForms) {
45417 // copy values from the child forms
45418 Roo.each(this.childForms, function (f) {
45419 this.setValues(f.getValues());
45425 var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
45426 if(asString === true){
45429 return Roo.urlDecode(fs);
45433 * Returns the fields in this form as an object with key/value pairs.
45434 * This differs from getValues as it calls getValue on each child item, rather than using dom data.
45437 getFieldValues : function(with_hidden)
45439 if (this.childForms) {
45440 // copy values from the child forms
45441 // should this call getFieldValues - probably not as we do not currently copy
45442 // hidden fields when we generate..
45443 Roo.each(this.childForms, function (f) {
45444 this.setValues(f.getValues());
45449 this.items.each(function(f){
45450 if (!f.getName()) {
45453 var v = f.getValue();
45454 if (f.inputType =='radio') {
45455 if (typeof(ret[f.getName()]) == 'undefined') {
45456 ret[f.getName()] = ''; // empty..
45459 if (!f.el.dom.checked) {
45463 v = f.el.dom.value;
45467 // not sure if this supported any more..
45468 if ((typeof(v) == 'object') && f.getRawValue) {
45469 v = f.getRawValue() ; // dates..
45471 // combo boxes where name != hiddenName...
45472 if (f.name != f.getName()) {
45473 ret[f.name] = f.getRawValue();
45475 ret[f.getName()] = v;
45482 * Clears all invalid messages in this form.
45483 * @return {BasicForm} this
45485 clearInvalid : function(){
45486 this.items.each(function(f){
45490 Roo.each(this.childForms || [], function (f) {
45499 * Resets this form.
45500 * @return {BasicForm} this
45502 reset : function(){
45503 this.items.each(function(f){
45507 Roo.each(this.childForms || [], function (f) {
45516 * Add Roo.form components to this form.
45517 * @param {Field} field1
45518 * @param {Field} field2 (optional)
45519 * @param {Field} etc (optional)
45520 * @return {BasicForm} this
45523 this.items.addAll(Array.prototype.slice.call(arguments, 0));
45529 * Removes a field from the items collection (does NOT remove its markup).
45530 * @param {Field} field
45531 * @return {BasicForm} this
45533 remove : function(field){
45534 this.items.remove(field);
45539 * Looks at the fields in this form, checks them for an id attribute,
45540 * and calls applyTo on the existing dom element with that id.
45541 * @return {BasicForm} this
45543 render : function(){
45544 this.items.each(function(f){
45545 if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
45553 * Calls {@link Ext#apply} for all fields in this form with the passed object.
45554 * @param {Object} values
45555 * @return {BasicForm} this
45557 applyToFields : function(o){
45558 this.items.each(function(f){
45565 * Calls {@link Ext#applyIf} for all field in this form with the passed object.
45566 * @param {Object} values
45567 * @return {BasicForm} this
45569 applyIfToFields : function(o){
45570 this.items.each(function(f){
45578 Roo.BasicForm = Roo.form.BasicForm;/*
45580 * Ext JS Library 1.1.1
45581 * Copyright(c) 2006-2007, Ext JS, LLC.
45583 * Originally Released Under LGPL - original licence link has changed is not relivant.
45586 * <script type="text/javascript">
45590 * @class Roo.form.Form
45591 * @extends Roo.form.BasicForm
45592 * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
45594 * @param {Object} config Configuration options
45596 Roo.form.Form = function(config){
45598 if (config.items) {
45599 xitems = config.items;
45600 delete config.items;
45604 Roo.form.Form.superclass.constructor.call(this, null, config);
45605 this.url = this.url || this.action;
45607 this.root = new Roo.form.Layout(Roo.applyIf({
45611 this.active = this.root;
45613 * Array of all the buttons that have been added to this form via {@link addButton}
45617 this.allItems = [];
45620 * @event clientvalidation
45621 * If the monitorValid config option is true, this event fires repetitively to notify of valid state
45622 * @param {Form} this
45623 * @param {Boolean} valid true if the form has passed client-side validation
45625 clientvalidation: true,
45628 * Fires when the form is rendered
45629 * @param {Roo.form.Form} form
45634 if (this.progressUrl) {
45635 // push a hidden field onto the list of fields..
45639 name : 'UPLOAD_IDENTIFIER'
45644 Roo.each(xitems, this.addxtype, this);
45650 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
45652 * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
45655 * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
45658 * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
45660 buttonAlign:'center',
45663 * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
45668 * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
45669 * This property cascades to child containers if not set.
45674 * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
45675 * fires a looping event with that state. This is required to bind buttons to the valid
45676 * state using the config value formBind:true on the button.
45678 monitorValid : false,
45681 * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
45686 * @cfg {String} progressUrl - Url to return progress data
45689 progressUrl : false,
45692 * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
45693 * fields are added and the column is closed. If no fields are passed the column remains open
45694 * until end() is called.
45695 * @param {Object} config The config to pass to the column
45696 * @param {Field} field1 (optional)
45697 * @param {Field} field2 (optional)
45698 * @param {Field} etc (optional)
45699 * @return Column The column container object
45701 column : function(c){
45702 var col = new Roo.form.Column(c);
45704 if(arguments.length > 1){ // duplicate code required because of Opera
45705 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45712 * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
45713 * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
45714 * until end() is called.
45715 * @param {Object} config The config to pass to the fieldset
45716 * @param {Field} field1 (optional)
45717 * @param {Field} field2 (optional)
45718 * @param {Field} etc (optional)
45719 * @return FieldSet The fieldset container object
45721 fieldset : function(c){
45722 var fs = new Roo.form.FieldSet(c);
45724 if(arguments.length > 1){ // duplicate code required because of Opera
45725 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45732 * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
45733 * fields are added and the container is closed. If no fields are passed the container remains open
45734 * until end() is called.
45735 * @param {Object} config The config to pass to the Layout
45736 * @param {Field} field1 (optional)
45737 * @param {Field} field2 (optional)
45738 * @param {Field} etc (optional)
45739 * @return Layout The container object
45741 container : function(c){
45742 var l = new Roo.form.Layout(c);
45744 if(arguments.length > 1){ // duplicate code required because of Opera
45745 this.add.apply(this, Array.prototype.slice.call(arguments, 1));
45752 * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
45753 * @param {Object} container A Roo.form.Layout or subclass of Layout
45754 * @return {Form} this
45756 start : function(c){
45757 // cascade label info
45758 Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
45759 this.active.stack.push(c);
45760 c.ownerCt = this.active;
45766 * Closes the current open container
45767 * @return {Form} this
45770 if(this.active == this.root){
45773 this.active = this.active.ownerCt;
45778 * Add Roo.form components to the current open container (e.g. column, fieldset, etc.). Fields added via this method
45779 * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
45780 * as the label of the field.
45781 * @param {Field} field1
45782 * @param {Field} field2 (optional)
45783 * @param {Field} etc. (optional)
45784 * @return {Form} this
45787 this.active.stack.push.apply(this.active.stack, arguments);
45788 this.allItems.push.apply(this.allItems,arguments);
45790 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
45791 if(a[i].isFormField){
45796 Roo.form.Form.superclass.add.apply(this, r);
45806 * Find any element that has been added to a form, using it's ID or name
45807 * This can include framesets, columns etc. along with regular fields..
45808 * @param {String} id - id or name to find.
45810 * @return {Element} e - or false if nothing found.
45812 findbyId : function(id)
45818 Roo.each(this.allItems, function(f){
45819 if (f.id == id || f.name == id ){
45830 * Render this form into the passed container. This should only be called once!
45831 * @param {String/HTMLElement/Element} container The element this component should be rendered into
45832 * @return {Form} this
45834 render : function(ct)
45840 var o = this.autoCreate || {
45842 method : this.method || 'POST',
45843 id : this.id || Roo.id()
45845 this.initEl(ct.createChild(o));
45847 this.root.render(this.el);
45851 this.items.each(function(f){
45852 f.render('x-form-el-'+f.id);
45855 if(this.buttons.length > 0){
45856 // tables are required to maintain order and for correct IE layout
45857 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
45858 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
45859 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
45861 var tr = tb.getElementsByTagName('tr')[0];
45862 for(var i = 0, len = this.buttons.length; i < len; i++) {
45863 var b = this.buttons[i];
45864 var td = document.createElement('td');
45865 td.className = 'x-form-btn-td';
45866 b.render(tr.appendChild(td));
45869 if(this.monitorValid){ // initialize after render
45870 this.startMonitoring();
45872 this.fireEvent('rendered', this);
45877 * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
45878 * @param {String/Object} config A string becomes the button text, an object can either be a Button config
45879 * object or a valid Roo.DomHelper element config
45880 * @param {Function} handler The function called when the button is clicked
45881 * @param {Object} scope (optional) The scope of the handler function
45882 * @return {Roo.Button}
45884 addButton : function(config, handler, scope){
45888 minWidth: this.minButtonWidth,
45891 if(typeof config == "string"){
45894 Roo.apply(bc, config);
45896 var btn = new Roo.Button(null, bc);
45897 this.buttons.push(btn);
45902 * Adds a series of form elements (using the xtype property as the factory method.
45903 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
45904 * @param {Object} config
45907 addxtype : function()
45909 var ar = Array.prototype.slice.call(arguments, 0);
45911 for(var i = 0; i < ar.length; i++) {
45913 continue; // skip -- if this happends something invalid got sent, we
45914 // should ignore it, as basically that interface element will not show up
45915 // and that should be pretty obvious!!
45918 if (Roo.form[ar[i].xtype]) {
45920 var fe = Roo.factory(ar[i], Roo.form);
45926 fe.store.form = this;
45931 this.allItems.push(fe);
45932 if (fe.items && fe.addxtype) {
45933 fe.addxtype.apply(fe, fe.items);
45943 // console.log('adding ' + ar[i].xtype);
45945 if (ar[i].xtype == 'Button') {
45946 //console.log('adding button');
45947 //console.log(ar[i]);
45948 this.addButton(ar[i]);
45949 this.allItems.push(fe);
45953 if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
45954 alert('end is not supported on xtype any more, use items');
45956 // //console.log('adding end');
45964 * Starts monitoring of the valid state of this form. Usually this is done by passing the config
45965 * option "monitorValid"
45967 startMonitoring : function(){
45970 Roo.TaskMgr.start({
45971 run : this.bindHandler,
45972 interval : this.monitorPoll || 200,
45979 * Stops monitoring of the valid state of this form
45981 stopMonitoring : function(){
45982 this.bound = false;
45986 bindHandler : function(){
45988 return false; // stops binding
45991 this.items.each(function(f){
45992 if(!f.isValid(true)){
45997 for(var i = 0, len = this.buttons.length; i < len; i++){
45998 var btn = this.buttons[i];
45999 if(btn.formBind === true && btn.disabled === valid){
46000 btn.setDisabled(!valid);
46003 this.fireEvent('clientvalidation', this, valid);
46017 Roo.Form = Roo.form.Form;
46020 * Ext JS Library 1.1.1
46021 * Copyright(c) 2006-2007, Ext JS, LLC.
46023 * Originally Released Under LGPL - original licence link has changed is not relivant.
46026 * <script type="text/javascript">
46029 // as we use this in bootstrap.
46030 Roo.namespace('Roo.form');
46032 * @class Roo.form.Action
46033 * Internal Class used to handle form actions
46035 * @param {Roo.form.BasicForm} el The form element or its id
46036 * @param {Object} config Configuration options
46041 // define the action interface
46042 Roo.form.Action = function(form, options){
46044 this.options = options || {};
46047 * Client Validation Failed
46050 Roo.form.Action.CLIENT_INVALID = 'client';
46052 * Server Validation Failed
46055 Roo.form.Action.SERVER_INVALID = 'server';
46057 * Connect to Server Failed
46060 Roo.form.Action.CONNECT_FAILURE = 'connect';
46062 * Reading Data from Server Failed
46065 Roo.form.Action.LOAD_FAILURE = 'load';
46067 Roo.form.Action.prototype = {
46069 failureType : undefined,
46070 response : undefined,
46071 result : undefined,
46073 // interface method
46074 run : function(options){
46078 // interface method
46079 success : function(response){
46083 // interface method
46084 handleResponse : function(response){
46088 // default connection failure
46089 failure : function(response){
46091 this.response = response;
46092 this.failureType = Roo.form.Action.CONNECT_FAILURE;
46093 this.form.afterAction(this, false);
46096 processResponse : function(response){
46097 this.response = response;
46098 if(!response.responseText){
46101 this.result = this.handleResponse(response);
46102 return this.result;
46105 // utility functions used internally
46106 getUrl : function(appendParams){
46107 var url = this.options.url || this.form.url || this.form.el.dom.action;
46109 var p = this.getParams();
46111 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
46117 getMethod : function(){
46118 return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
46121 getParams : function(){
46122 var bp = this.form.baseParams;
46123 var p = this.options.params;
46125 if(typeof p == "object"){
46126 p = Roo.urlEncode(Roo.applyIf(p, bp));
46127 }else if(typeof p == 'string' && bp){
46128 p += '&' + Roo.urlEncode(bp);
46131 p = Roo.urlEncode(bp);
46136 createCallback : function(){
46138 success: this.success,
46139 failure: this.failure,
46141 timeout: (this.form.timeout*1000),
46142 upload: this.form.fileUpload ? this.success : undefined
46147 Roo.form.Action.Submit = function(form, options){
46148 Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
46151 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
46154 haveProgress : false,
46155 uploadComplete : false,
46157 // uploadProgress indicator.
46158 uploadProgress : function()
46160 if (!this.form.progressUrl) {
46164 if (!this.haveProgress) {
46165 Roo.MessageBox.progress("Uploading", "Uploading");
46167 if (this.uploadComplete) {
46168 Roo.MessageBox.hide();
46172 this.haveProgress = true;
46174 var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
46176 var c = new Roo.data.Connection();
46178 url : this.form.progressUrl,
46183 success : function(req){
46184 //console.log(data);
46188 rdata = Roo.decode(req.responseText)
46190 Roo.log("Invalid data from server..");
46194 if (!rdata || !rdata.success) {
46196 Roo.MessageBox.alert(Roo.encode(rdata));
46199 var data = rdata.data;
46201 if (this.uploadComplete) {
46202 Roo.MessageBox.hide();
46207 Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
46208 Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
46211 this.uploadProgress.defer(2000,this);
46214 failure: function(data) {
46215 Roo.log('progress url failed ');
46226 // run get Values on the form, so it syncs any secondary forms.
46227 this.form.getValues();
46229 var o = this.options;
46230 var method = this.getMethod();
46231 var isPost = method == 'POST';
46232 if(o.clientValidation === false || this.form.isValid()){
46234 if (this.form.progressUrl) {
46235 this.form.findField('UPLOAD_IDENTIFIER').setValue(
46236 (new Date() * 1) + '' + Math.random());
46241 Roo.Ajax.request(Roo.apply(this.createCallback(), {
46242 form:this.form.el.dom,
46243 url:this.getUrl(!isPost),
46245 params:isPost ? this.getParams() : null,
46246 isUpload: this.form.fileUpload
46249 this.uploadProgress();
46251 }else if (o.clientValidation !== false){ // client validation failed
46252 this.failureType = Roo.form.Action.CLIENT_INVALID;
46253 this.form.afterAction(this, false);
46257 success : function(response)
46259 this.uploadComplete= true;
46260 if (this.haveProgress) {
46261 Roo.MessageBox.hide();
46265 var result = this.processResponse(response);
46266 if(result === true || result.success){
46267 this.form.afterAction(this, true);
46271 this.form.markInvalid(result.errors);
46272 this.failureType = Roo.form.Action.SERVER_INVALID;
46274 this.form.afterAction(this, false);
46276 failure : function(response)
46278 this.uploadComplete= true;
46279 if (this.haveProgress) {
46280 Roo.MessageBox.hide();
46283 this.response = response;
46284 this.failureType = Roo.form.Action.CONNECT_FAILURE;
46285 this.form.afterAction(this, false);
46288 handleResponse : function(response){
46289 if(this.form.errorReader){
46290 var rs = this.form.errorReader.read(response);
46293 for(var i = 0, len = rs.records.length; i < len; i++) {
46294 var r = rs.records[i];
46295 errors[i] = r.data;
46298 if(errors.length < 1){
46302 success : rs.success,
46308 ret = Roo.decode(response.responseText);
46312 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
46322 Roo.form.Action.Load = function(form, options){
46323 Roo.form.Action.Load.superclass.constructor.call(this, form, options);
46324 this.reader = this.form.reader;
46327 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
46332 Roo.Ajax.request(Roo.apply(
46333 this.createCallback(), {
46334 method:this.getMethod(),
46335 url:this.getUrl(false),
46336 params:this.getParams()
46340 success : function(response){
46342 var result = this.processResponse(response);
46343 if(result === true || !result.success || !result.data){
46344 this.failureType = Roo.form.Action.LOAD_FAILURE;
46345 this.form.afterAction(this, false);
46348 this.form.clearInvalid();
46349 this.form.setValues(result.data);
46350 this.form.afterAction(this, true);
46353 handleResponse : function(response){
46354 if(this.form.reader){
46355 var rs = this.form.reader.read(response);
46356 var data = rs.records && rs.records[0] ? rs.records[0].data : null;
46358 success : rs.success,
46362 return Roo.decode(response.responseText);
46366 Roo.form.Action.ACTION_TYPES = {
46367 'load' : Roo.form.Action.Load,
46368 'submit' : Roo.form.Action.Submit
46371 * Ext JS Library 1.1.1
46372 * Copyright(c) 2006-2007, Ext JS, LLC.
46374 * Originally Released Under LGPL - original licence link has changed is not relivant.
46377 * <script type="text/javascript">
46381 * @class Roo.form.Layout
46382 * @extends Roo.Component
46383 * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
46385 * @param {Object} config Configuration options
46387 Roo.form.Layout = function(config){
46389 if (config.items) {
46390 xitems = config.items;
46391 delete config.items;
46393 Roo.form.Layout.superclass.constructor.call(this, config);
46395 Roo.each(xitems, this.addxtype, this);
46399 Roo.extend(Roo.form.Layout, Roo.Component, {
46401 * @cfg {String/Object} autoCreate
46402 * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
46405 * @cfg {String/Object/Function} style
46406 * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
46407 * a function which returns such a specification.
46410 * @cfg {String} labelAlign
46411 * Valid values are "left," "top" and "right" (defaults to "left")
46414 * @cfg {Number} labelWidth
46415 * Fixed width in pixels of all field labels (defaults to undefined)
46418 * @cfg {Boolean} clear
46419 * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
46423 * @cfg {String} labelSeparator
46424 * The separator to use after field labels (defaults to ':')
46426 labelSeparator : ':',
46428 * @cfg {Boolean} hideLabels
46429 * True to suppress the display of field labels in this layout (defaults to false)
46431 hideLabels : false,
46434 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
46439 onRender : function(ct, position){
46440 if(this.el){ // from markup
46441 this.el = Roo.get(this.el);
46442 }else { // generate
46443 var cfg = this.getAutoCreate();
46444 this.el = ct.createChild(cfg, position);
46447 this.el.applyStyles(this.style);
46449 if(this.labelAlign){
46450 this.el.addClass('x-form-label-'+this.labelAlign);
46452 if(this.hideLabels){
46453 this.labelStyle = "display:none";
46454 this.elementStyle = "padding-left:0;";
46456 if(typeof this.labelWidth == 'number'){
46457 this.labelStyle = "width:"+this.labelWidth+"px;";
46458 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
46460 if(this.labelAlign == 'top'){
46461 this.labelStyle = "width:auto;";
46462 this.elementStyle = "padding-left:0;";
46465 var stack = this.stack;
46466 var slen = stack.length;
46468 if(!this.fieldTpl){
46469 var t = new Roo.Template(
46470 '<div class="x-form-item {5}">',
46471 '<label for="{0}" style="{2}">{1}{4}</label>',
46472 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
46474 '</div><div class="x-form-clear-left"></div>'
46476 t.disableFormats = true;
46478 Roo.form.Layout.prototype.fieldTpl = t;
46480 for(var i = 0; i < slen; i++) {
46481 if(stack[i].isFormField){
46482 this.renderField(stack[i]);
46484 this.renderComponent(stack[i]);
46489 this.el.createChild({cls:'x-form-clear'});
46494 renderField : function(f){
46495 f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
46498 f.labelStyle||this.labelStyle||'', //2
46499 this.elementStyle||'', //3
46500 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
46501 f.itemCls||this.itemCls||'' //5
46502 ], true).getPrevSibling());
46506 renderComponent : function(c){
46507 c.render(c.isLayout ? this.el : this.el.createChild());
46510 * Adds a object form elements (using the xtype property as the factory method.)
46511 * Valid xtypes are: TextField, TextArea .... Button, Layout, FieldSet, Column
46512 * @param {Object} config
46514 addxtype : function(o)
46516 // create the lement.
46517 o.form = this.form;
46518 var fe = Roo.factory(o, Roo.form);
46519 this.form.allItems.push(fe);
46520 this.stack.push(fe);
46522 if (fe.isFormField) {
46523 this.form.items.add(fe);
46531 * @class Roo.form.Column
46532 * @extends Roo.form.Layout
46533 * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
46535 * @param {Object} config Configuration options
46537 Roo.form.Column = function(config){
46538 Roo.form.Column.superclass.constructor.call(this, config);
46541 Roo.extend(Roo.form.Column, Roo.form.Layout, {
46543 * @cfg {Number/String} width
46544 * The fixed width of the column in pixels or CSS value (defaults to "auto")
46547 * @cfg {String/Object} autoCreate
46548 * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
46552 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
46555 onRender : function(ct, position){
46556 Roo.form.Column.superclass.onRender.call(this, ct, position);
46558 this.el.setWidth(this.width);
46565 * @class Roo.form.Row
46566 * @extends Roo.form.Layout
46567 * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
46569 * @param {Object} config Configuration options
46573 Roo.form.Row = function(config){
46574 Roo.form.Row.superclass.constructor.call(this, config);
46577 Roo.extend(Roo.form.Row, Roo.form.Layout, {
46579 * @cfg {Number/String} width
46580 * The fixed width of the column in pixels or CSS value (defaults to "auto")
46583 * @cfg {Number/String} height
46584 * The fixed height of the column in pixels or CSS value (defaults to "auto")
46586 defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
46590 onRender : function(ct, position){
46591 //console.log('row render');
46593 var t = new Roo.Template(
46594 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
46595 '<label for="{0}" style="{2}">{1}{4}</label>',
46596 '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
46600 t.disableFormats = true;
46602 Roo.form.Layout.prototype.rowTpl = t;
46604 this.fieldTpl = this.rowTpl;
46606 //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
46607 var labelWidth = 100;
46609 if ((this.labelAlign != 'top')) {
46610 if (typeof this.labelWidth == 'number') {
46611 labelWidth = this.labelWidth
46613 this.padWidth = 20 + labelWidth;
46617 Roo.form.Column.superclass.onRender.call(this, ct, position);
46619 this.el.setWidth(this.width);
46622 this.el.setHeight(this.height);
46627 renderField : function(f){
46628 f.fieldEl = this.fieldTpl.append(this.el, [
46629 f.id, f.fieldLabel,
46630 f.labelStyle||this.labelStyle||'',
46631 this.elementStyle||'',
46632 typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
46633 f.itemCls||this.itemCls||'',
46634 f.width ? f.width + this.padWidth : 160 + this.padWidth
46641 * @class Roo.form.FieldSet
46642 * @extends Roo.form.Layout
46643 * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
46645 * @param {Object} config Configuration options
46647 Roo.form.FieldSet = function(config){
46648 Roo.form.FieldSet.superclass.constructor.call(this, config);
46651 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
46653 * @cfg {String} legend
46654 * The text to display as the legend for the FieldSet (defaults to '')
46657 * @cfg {String/Object} autoCreate
46658 * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
46662 defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
46665 onRender : function(ct, position){
46666 Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
46668 this.setLegend(this.legend);
46673 setLegend : function(text){
46675 this.el.child('legend').update(text);
46680 * Ext JS Library 1.1.1
46681 * Copyright(c) 2006-2007, Ext JS, LLC.
46683 * Originally Released Under LGPL - original licence link has changed is not relivant.
46686 * <script type="text/javascript">
46689 * @class Roo.form.VTypes
46690 * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
46693 Roo.form.VTypes = function(){
46694 // closure these in so they are only created once.
46695 var alpha = /^[a-zA-Z_]+$/;
46696 var alphanum = /^[a-zA-Z0-9_]+$/;
46697 var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
46698 var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
46700 // All these messages and functions are configurable
46703 * The function used to validate email addresses
46704 * @param {String} value The email address
46706 'email' : function(v){
46707 return email.test(v);
46710 * The error text to display when the email validation function returns false
46713 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
46715 * The keystroke filter mask to be applied on email input
46718 'emailMask' : /[a-z0-9_\.\-@]/i,
46721 * The function used to validate URLs
46722 * @param {String} value The URL
46724 'url' : function(v){
46725 return url.test(v);
46728 * The error text to display when the url validation function returns false
46731 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
46734 * The function used to validate alpha values
46735 * @param {String} value The value
46737 'alpha' : function(v){
46738 return alpha.test(v);
46741 * The error text to display when the alpha validation function returns false
46744 'alphaText' : 'This field should only contain letters and _',
46746 * The keystroke filter mask to be applied on alpha input
46749 'alphaMask' : /[a-z_]/i,
46752 * The function used to validate alphanumeric values
46753 * @param {String} value The value
46755 'alphanum' : function(v){
46756 return alphanum.test(v);
46759 * The error text to display when the alphanumeric validation function returns false
46762 'alphanumText' : 'This field should only contain letters, numbers and _',
46764 * The keystroke filter mask to be applied on alphanumeric input
46767 'alphanumMask' : /[a-z0-9_]/i
46769 }();//<script type="text/javascript">
46772 * @class Roo.form.FCKeditor
46773 * @extends Roo.form.TextArea
46774 * Wrapper around the FCKEditor http://www.fckeditor.net
46776 * Creates a new FCKeditor
46777 * @param {Object} config Configuration options
46779 Roo.form.FCKeditor = function(config){
46780 Roo.form.FCKeditor.superclass.constructor.call(this, config);
46783 * @event editorinit
46784 * Fired when the editor is initialized - you can add extra handlers here..
46785 * @param {FCKeditor} this
46786 * @param {Object} the FCK object.
46793 Roo.form.FCKeditor.editors = { };
46794 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
46796 //defaultAutoCreate : {
46797 // tag : "textarea",style : "width:100px;height:60px;" ,autocomplete : "off"
46801 * @cfg {Object} fck options - see fck manual for details.
46806 * @cfg {Object} fck toolbar set (Basic or Default)
46808 toolbarSet : 'Basic',
46810 * @cfg {Object} fck BasePath
46812 basePath : '/fckeditor/',
46820 onRender : function(ct, position)
46823 this.defaultAutoCreate = {
46825 style:"width:300px;height:60px;",
46826 autocomplete: "new-password"
46829 Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
46832 this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
46833 if(this.preventScrollbars){
46834 this.el.setStyle("overflow", "hidden");
46836 this.el.setHeight(this.growMin);
46839 //console.log('onrender' + this.getId() );
46840 Roo.form.FCKeditor.editors[this.getId()] = this;
46843 this.replaceTextarea() ;
46847 getEditor : function() {
46848 return this.fckEditor;
46851 * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
46852 * @param {Mixed} value The value to set
46856 setValue : function(value)
46858 //console.log('setValue: ' + value);
46860 if(typeof(value) == 'undefined') { // not sure why this is happending...
46863 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
46865 //if(!this.el || !this.getEditor()) {
46866 // this.value = value;
46867 //this.setValue.defer(100,this,[value]);
46871 if(!this.getEditor()) {
46875 this.getEditor().SetData(value);
46882 * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
46883 * @return {Mixed} value The field value
46885 getValue : function()
46888 if (this.frame && this.frame.dom.style.display == 'none') {
46889 return Roo.form.FCKeditor.superclass.getValue.call(this);
46892 if(!this.el || !this.getEditor()) {
46894 // this.getValue.defer(100,this);
46899 var value=this.getEditor().GetData();
46900 Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
46901 return Roo.form.FCKeditor.superclass.getValue.call(this);
46907 * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
46908 * @return {Mixed} value The field value
46910 getRawValue : function()
46912 if (this.frame && this.frame.dom.style.display == 'none') {
46913 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
46916 if(!this.el || !this.getEditor()) {
46917 //this.getRawValue.defer(100,this);
46924 var value=this.getEditor().GetData();
46925 Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
46926 return Roo.form.FCKeditor.superclass.getRawValue.call(this);
46930 setSize : function(w,h) {
46934 //if (this.frame && this.frame.dom.style.display == 'none') {
46935 // Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
46938 //if(!this.el || !this.getEditor()) {
46939 // this.setSize.defer(100,this, [w,h]);
46945 Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
46947 this.frame.dom.setAttribute('width', w);
46948 this.frame.dom.setAttribute('height', h);
46949 this.frame.setSize(w,h);
46953 toggleSourceEdit : function(value) {
46957 this.el.dom.style.display = value ? '' : 'none';
46958 this.frame.dom.style.display = value ? 'none' : '';
46963 focus: function(tag)
46965 if (this.frame.dom.style.display == 'none') {
46966 return Roo.form.FCKeditor.superclass.focus.call(this);
46968 if(!this.el || !this.getEditor()) {
46969 this.focus.defer(100,this, [tag]);
46976 var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
46977 this.getEditor().Focus();
46979 if (!this.getEditor().Selection.GetSelection()) {
46980 this.focus.defer(100,this, [tag]);
46985 var r = this.getEditor().EditorDocument.createRange();
46986 r.setStart(tgs[0],0);
46987 r.setEnd(tgs[0],0);
46988 this.getEditor().Selection.GetSelection().removeAllRanges();
46989 this.getEditor().Selection.GetSelection().addRange(r);
46990 this.getEditor().Focus();
46997 replaceTextarea : function()
46999 if ( document.getElementById( this.getId() + '___Frame' ) )
47001 //if ( !this.checkBrowser || this._isCompatibleBrowser() )
47003 // We must check the elements firstly using the Id and then the name.
47004 var oTextarea = document.getElementById( this.getId() );
47006 var colElementsByName = document.getElementsByName( this.getId() ) ;
47008 oTextarea.style.display = 'none' ;
47010 if ( oTextarea.tabIndex ) {
47011 this.TabIndex = oTextarea.tabIndex ;
47014 this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
47015 this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
47016 this.frame = Roo.get(this.getId() + '___Frame')
47019 _getConfigHtml : function()
47023 for ( var o in this.fckconfig ) {
47024 sConfig += sConfig.length > 0 ? '&' : '';
47025 sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
47028 return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
47032 _getIFrameHtml : function()
47034 var sFile = 'fckeditor.html' ;
47035 /* no idea what this is about..
47038 if ( (/fcksource=true/i).test( window.top.location.search ) )
47039 sFile = 'fckeditor.original.html' ;
47044 var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
47045 sLink += this.toolbarSet ? ( '&Toolbar=' + this.toolbarSet) : '';
47048 var html = '<iframe id="' + this.getId() +
47049 '___Frame" src="' + sLink +
47050 '" width="' + this.width +
47051 '" height="' + this.height + '"' +
47052 (this.tabIndex ? ' tabindex="' + this.tabIndex + '"' :'' ) +
47053 ' frameborder="0" scrolling="no"></iframe>' ;
47058 _insertHtmlBefore : function( html, element )
47060 if ( element.insertAdjacentHTML ) {
47062 element.insertAdjacentHTML( 'beforeBegin', html ) ;
47064 var oRange = document.createRange() ;
47065 oRange.setStartBefore( element ) ;
47066 var oFragment = oRange.createContextualFragment( html );
47067 element.parentNode.insertBefore( oFragment, element ) ;
47080 //Roo.reg('fckeditor', Roo.form.FCKeditor);
47082 function FCKeditor_OnComplete(editorInstance){
47083 var f = Roo.form.FCKeditor.editors[editorInstance.Name];
47084 f.fckEditor = editorInstance;
47085 //console.log("loaded");
47086 f.fireEvent('editorinit', f, editorInstance);
47106 //<script type="text/javascript">
47108 * @class Roo.form.GridField
47109 * @extends Roo.form.Field
47110 * Embed a grid (or editable grid into a form)
47113 * This embeds a grid in a form, the value of the field should be the json encoded array of rows
47115 * xgrid.store = Roo.data.Store
47116 * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
47117 * xgrid.store.reader = Roo.data.JsonReader
47121 * Creates a new GridField
47122 * @param {Object} config Configuration options
47124 Roo.form.GridField = function(config){
47125 Roo.form.GridField.superclass.constructor.call(this, config);
47129 Roo.extend(Roo.form.GridField, Roo.form.Field, {
47131 * @cfg {Number} width - used to restrict width of grid..
47135 * @cfg {Number} height - used to restrict height of grid..
47139 * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
47145 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47146 * {tag: "input", type: "checkbox", autocomplete: "off"})
47148 // defaultAutoCreate : { tag: 'div' },
47149 defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
47151 * @cfg {String} addTitle Text to include for adding a title.
47155 onResize : function(){
47156 Roo.form.Field.superclass.onResize.apply(this, arguments);
47159 initEvents : function(){
47160 // Roo.form.Checkbox.superclass.initEvents.call(this);
47161 // has no events...
47166 getResizeEl : function(){
47170 getPositionEl : function(){
47175 onRender : function(ct, position){
47177 this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
47178 var style = this.style;
47181 Roo.form.GridField.superclass.onRender.call(this, ct, position);
47182 this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
47183 this.viewEl = this.wrap.createChild({ tag: 'div' });
47185 this.viewEl.applyStyles(style);
47188 this.viewEl.setWidth(this.width);
47191 this.viewEl.setHeight(this.height);
47193 //if(this.inputValue !== undefined){
47194 //this.setValue(this.value);
47197 this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
47200 this.grid.render();
47201 this.grid.getDataSource().on('remove', this.refreshValue, this);
47202 this.grid.getDataSource().on('update', this.refreshValue, this);
47203 this.grid.on('afteredit', this.refreshValue, this);
47209 * Sets the value of the item.
47210 * @param {String} either an object or a string..
47212 setValue : function(v){
47214 v = v || []; // empty set..
47215 // this does not seem smart - it really only affects memoryproxy grids..
47216 if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
47217 var ds = this.grid.getDataSource();
47218 // assumes a json reader..
47220 data[ds.reader.meta.root ] = typeof(v) == 'string' ? Roo.decode(v) : v;
47221 ds.loadData( data);
47223 // clear selection so it does not get stale.
47224 if (this.grid.sm) {
47225 this.grid.sm.clearSelections();
47228 Roo.form.GridField.superclass.setValue.call(this, v);
47229 this.refreshValue();
47230 // should load data in the grid really....
47234 refreshValue: function() {
47236 this.grid.getDataSource().each(function(r) {
47239 this.el.dom.value = Roo.encode(val);
47247 * Ext JS Library 1.1.1
47248 * Copyright(c) 2006-2007, Ext JS, LLC.
47250 * Originally Released Under LGPL - original licence link has changed is not relivant.
47253 * <script type="text/javascript">
47256 * @class Roo.form.DisplayField
47257 * @extends Roo.form.Field
47258 * A generic Field to display non-editable data.
47260 * Creates a new Display Field item.
47261 * @param {Object} config Configuration options
47263 Roo.form.DisplayField = function(config){
47264 Roo.form.DisplayField.superclass.constructor.call(this, config);
47268 Roo.extend(Roo.form.DisplayField, Roo.form.TextField, {
47269 inputType: 'hidden',
47275 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
47277 focusClass : undefined,
47279 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
47281 fieldClass: 'x-form-field',
47284 * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
47286 valueRenderer: undefined,
47290 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47291 * {tag: "input", type: "checkbox", autocomplete: "off"})
47294 // defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
47296 onResize : function(){
47297 Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
47301 initEvents : function(){
47302 // Roo.form.Checkbox.superclass.initEvents.call(this);
47303 // has no events...
47308 getResizeEl : function(){
47312 getPositionEl : function(){
47317 onRender : function(ct, position){
47319 Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
47320 //if(this.inputValue !== undefined){
47321 this.wrap = this.el.wrap();
47323 this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
47325 if (this.bodyStyle) {
47326 this.viewEl.applyStyles(this.bodyStyle);
47328 //this.viewEl.setStyle('padding', '2px');
47330 this.setValue(this.value);
47335 initValue : Roo.emptyFn,
47340 onClick : function(){
47345 * Sets the checked state of the checkbox.
47346 * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
47348 setValue : function(v){
47350 var html = this.valueRenderer ? this.valueRenderer(v) : String.format('{0}', v);
47351 // this might be called before we have a dom element..
47352 if (!this.viewEl) {
47355 this.viewEl.dom.innerHTML = html;
47356 Roo.form.DisplayField.superclass.setValue.call(this, v);
47366 * @class Roo.form.DayPicker
47367 * @extends Roo.form.Field
47368 * A Day picker show [M] [T] [W] ....
47370 * Creates a new Day Picker
47371 * @param {Object} config Configuration options
47373 Roo.form.DayPicker= function(config){
47374 Roo.form.DayPicker.superclass.constructor.call(this, config);
47378 Roo.extend(Roo.form.DayPicker, Roo.form.Field, {
47380 * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
47382 focusClass : undefined,
47384 * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
47386 fieldClass: "x-form-field",
47389 * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
47390 * {tag: "input", type: "checkbox", autocomplete: "off"})
47392 defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
47395 actionMode : 'viewEl',
47399 inputType : 'hidden',
47402 inputElement: false, // real input element?
47403 basedOn: false, // ????
47405 isFormField: true, // not sure where this is needed!!!!
47407 onResize : function(){
47408 Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
47409 if(!this.boxLabel){
47410 this.el.alignTo(this.wrap, 'c-c');
47414 initEvents : function(){
47415 Roo.form.Checkbox.superclass.initEvents.call(this);
47416 this.el.on("click", this.onClick, this);
47417 this.el.on("change", this.onClick, this);
47421 getResizeEl : function(){
47425 getPositionEl : function(){
47431 onRender : function(ct, position){
47432 Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
47434 this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
47436 var r1 = '<table><tr>';
47437 var r2 = '<tr class="x-form-daypick-icons">';
47438 for (var i=0; i < 7; i++) {
47439 r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
47440 r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL +'"></td>';
47443 var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
47444 viewEl.select('img').on('click', this.onClick, this);
47445 this.viewEl = viewEl;
47448 // this will not work on Chrome!!!
47449 this.el.on('DOMAttrModified', this.setFromHidden, this); //ff
47450 this.el.on('propertychange', this.setFromHidden, this); //ie
47458 initValue : Roo.emptyFn,
47461 * Returns the checked state of the checkbox.
47462 * @return {Boolean} True if checked, else false
47464 getValue : function(){
47465 return this.el.dom.value;
47470 onClick : function(e){
47471 //this.setChecked(!this.checked);
47472 Roo.get(e.target).toggleClass('x-menu-item-checked');
47473 this.refreshValue();
47474 //if(this.el.dom.checked != this.checked){
47475 // this.setValue(this.el.dom.checked);
47480 refreshValue : function()
47483 this.viewEl.select('img',true).each(function(e,i,n) {
47484 val += e.is(".x-menu-item-checked") ? String(n) : '';
47486 this.setValue(val, true);
47490 * Sets the checked state of the checkbox.
47491 * On is always based on a string comparison between inputValue and the param.
47492 * @param {Boolean/String} value - the value to set
47493 * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
47495 setValue : function(v,suppressEvent){
47496 if (!this.el.dom) {
47499 var old = this.el.dom.value ;
47500 this.el.dom.value = v;
47501 if (suppressEvent) {
47505 // update display..
47506 this.viewEl.select('img',true).each(function(e,i,n) {
47508 var on = e.is(".x-menu-item-checked");
47509 var newv = v.indexOf(String(n)) > -1;
47511 e.toggleClass('x-menu-item-checked');
47517 this.fireEvent('change', this, v, old);
47522 // handle setting of hidden value by some other method!!?!?
47523 setFromHidden: function()
47528 //console.log("SET FROM HIDDEN");
47529 //alert('setFrom hidden');
47530 this.setValue(this.el.dom.value);
47533 onDestroy : function()
47536 Roo.get(this.viewEl).remove();
47539 Roo.form.DayPicker.superclass.onDestroy.call(this);
47543 * RooJS Library 1.1.1
47544 * Copyright(c) 2008-2011 Alan Knowles
47551 * @class Roo.form.ComboCheck
47552 * @extends Roo.form.ComboBox
47553 * A combobox for multiple select items.
47555 * FIXME - could do with a reset button..
47558 * Create a new ComboCheck
47559 * @param {Object} config Configuration options
47561 Roo.form.ComboCheck = function(config){
47562 Roo.form.ComboCheck.superclass.constructor.call(this, config);
47563 // should verify some data...
47565 // hiddenName = required..
47566 // displayField = required
47567 // valudField == required
47568 var req= [ 'hiddenName', 'displayField', 'valueField' ];
47570 Roo.each(req, function(e) {
47571 if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
47572 throw "Roo.form.ComboCheck : missing value for: " + e;
47579 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
47584 selectedClass: 'x-menu-item-checked',
47587 onRender : function(ct, position){
47593 var cls = 'x-combo-list';
47596 this.tpl = new Roo.Template({
47597 html : '<div class="'+cls+'-item x-menu-check-item">' +
47598 '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' +
47599 '<span>{' + this.displayField + '}</span>' +
47606 Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
47607 this.view.singleSelect = false;
47608 this.view.multiSelect = true;
47609 this.view.toggleSelect = true;
47610 this.pageTb.add(new Roo.Toolbar.Fill(), {
47613 handler: function()
47620 onViewOver : function(e, t){
47626 onViewClick : function(doFocus,index){
47630 select: function () {
47631 //Roo.log("SELECT CALLED");
47634 selectByValue : function(xv, scrollIntoView){
47635 var ar = this.getValueArray();
47638 Roo.each(ar, function(v) {
47639 if(v === undefined || v === null){
47642 var r = this.findRecord(this.valueField, v);
47644 sels.push(this.store.indexOf(r))
47648 this.view.select(sels);
47654 onSelect : function(record, index){
47655 // Roo.log("onselect Called");
47656 // this is only called by the clear button now..
47657 this.view.clearSelections();
47658 this.setValue('[]');
47659 if (this.value != this.valueBefore) {
47660 this.fireEvent('change', this, this.value, this.valueBefore);
47661 this.valueBefore = this.value;
47664 getValueArray : function()
47669 //Roo.log(this.value);
47670 if (typeof(this.value) == 'undefined') {
47673 var ar = Roo.decode(this.value);
47674 return ar instanceof Array ? ar : []; //?? valid?
47677 Roo.log(e + "\nRoo.form.ComboCheck:getValueArray invalid data:" + this.getValue());
47682 expand : function ()
47685 Roo.form.ComboCheck.superclass.expand.call(this);
47686 this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
47687 //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
47692 collapse : function(){
47693 Roo.form.ComboCheck.superclass.collapse.call(this);
47694 var sl = this.view.getSelectedIndexes();
47695 var st = this.store;
47699 Roo.each(sl, function(i) {
47701 nv.push(r.get(this.valueField));
47703 this.setValue(Roo.encode(nv));
47704 if (this.value != this.valueBefore) {
47706 this.fireEvent('change', this, this.value, this.valueBefore);
47707 this.valueBefore = this.value;
47712 setValue : function(v){
47716 var vals = this.getValueArray();
47718 Roo.each(vals, function(k) {
47719 var r = this.findRecord(this.valueField, k);
47721 tv.push(r.data[this.displayField]);
47722 }else if(this.valueNotFoundText !== undefined){
47723 tv.push( this.valueNotFoundText );
47728 Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
47729 this.hiddenField.value = v;
47735 * Ext JS Library 1.1.1
47736 * Copyright(c) 2006-2007, Ext JS, LLC.
47738 * Originally Released Under LGPL - original licence link has changed is not relivant.
47741 * <script type="text/javascript">
47745 * @class Roo.form.Signature
47746 * @extends Roo.form.Field
47750 * @param {Object} config Configuration options
47753 Roo.form.Signature = function(config){
47754 Roo.form.Signature.superclass.constructor.call(this, config);
47756 this.addEvents({// not in used??
47759 * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
47760 * @param {Roo.form.Signature} combo This combo box
47765 * Fires when the 'edit' icon is pressed (add a listener to enable add button)
47766 * @param {Roo.form.ComboBox} combo This combo box
47767 * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
47773 Roo.extend(Roo.form.Signature, Roo.form.Field, {
47775 * @cfg {Object} labels Label to use when rendering a form.
47779 * confirm : "Confirm"
47784 confirm : "Confirm"
47787 * @cfg {Number} width The signature panel width (defaults to 300)
47791 * @cfg {Number} height The signature panel height (defaults to 100)
47795 * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
47797 allowBlank : false,
47800 // {Object} signPanel The signature SVG panel element (defaults to {})
47802 // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
47803 isMouseDown : false,
47804 // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
47805 isConfirmed : false,
47806 // {String} signatureTmp SVG mapping string (defaults to empty string)
47810 defaultAutoCreate : { // modified by initCompnoent..
47816 onRender : function(ct, position){
47818 Roo.form.Signature.superclass.onRender.call(this, ct, position);
47820 this.wrap = this.el.wrap({
47821 cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
47824 this.createToolbar(this);
47825 this.signPanel = this.wrap.createChild({
47827 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
47831 this.svgID = Roo.id();
47832 this.svgEl = this.signPanel.createChild({
47833 xmlns : 'http://www.w3.org/2000/svg',
47835 id : this.svgID + "-svg",
47837 height: this.height,
47838 viewBox: '0 0 '+this.width+' '+this.height,
47842 id: this.svgID + "-svg-r",
47844 height: this.height,
47849 id: this.svgID + "-svg-l",
47851 y1: (this.height*0.8), // start set the line in 80% of height
47852 x2: this.width, // end
47853 y2: (this.height*0.8), // end set the line in 80% of height
47855 'stroke-width': "1",
47856 'stroke-dasharray': "3",
47857 'shape-rendering': "crispEdges",
47858 'pointer-events': "none"
47862 id: this.svgID + "-svg-p",
47864 'stroke-width': "3",
47866 'pointer-events': 'none'
47871 this.svgBox = this.svgEl.dom.getScreenCTM();
47873 createSVG : function(){
47874 var svg = this.signPanel;
47875 var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
47878 r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
47879 r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
47880 r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
47881 r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
47882 r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
47883 r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
47884 r.addEventListener('touchend', function(e) { return t.up(e); }, false);
47887 isTouchEvent : function(e){
47888 return e.type.match(/^touch/);
47890 getCoords : function (e) {
47891 var pt = this.svgEl.dom.createSVGPoint();
47894 if (this.isTouchEvent(e)) {
47895 pt.x = e.targetTouches[0].clientX
47896 pt.y = e.targetTouches[0].clientY;
47898 var a = this.svgEl.dom.getScreenCTM();
47899 var b = a.inverse();
47900 var mx = pt.matrixTransform(b);
47901 return mx.x + ',' + mx.y;
47903 //mouse event headler
47904 down : function (e) {
47905 this.signatureTmp += 'M' + this.getCoords(e) + ' ';
47906 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
47908 this.isMouseDown = true;
47910 e.preventDefault();
47912 move : function (e) {
47913 if (this.isMouseDown) {
47914 this.signatureTmp += 'L' + this.getCoords(e) + ' ';
47915 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
47918 e.preventDefault();
47920 up : function (e) {
47921 this.isMouseDown = false;
47922 var sp = this.signatureTmp.split(' ');
47925 if(!sp[sp.length-2].match(/^L/)){
47929 this.signatureTmp = sp.join(" ");
47932 if(this.getValue() != this.signatureTmp){
47933 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
47934 this.isConfirmed = false;
47936 e.preventDefault();
47940 * Protected method that will not generally be called directly. It
47941 * is called when the editor creates its toolbar. Override this method if you need to
47942 * add custom toolbar buttons.
47943 * @param {HtmlEditor} editor
47945 createToolbar : function(editor){
47946 function btn(id, toggle, handler){
47947 var xid = fid + '-'+ id ;
47951 cls : 'x-btn-icon x-edit-'+id,
47952 enableToggle:toggle !== false,
47953 scope: editor, // was editor...
47954 handler:handler||editor.relayBtnCmd,
47955 clickEvent:'mousedown',
47956 tooltip: etb.buttonTips[id] || undefined, ///tips ???
47962 var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
47966 cls : ' x-signature-btn x-signature-'+id,
47967 scope: editor, // was editor...
47968 handler: this.reset,
47969 clickEvent:'mousedown',
47970 text: this.labels.clear
47977 cls : ' x-signature-btn x-signature-'+id,
47978 scope: editor, // was editor...
47979 handler: this.confirmHandler,
47980 clickEvent:'mousedown',
47981 text: this.labels.confirm
47988 * when user is clicked confirm then show this image.....
47990 * @return {String} Image Data URI
47992 getImageDataURI : function(){
47993 var svg = this.svgEl.dom.parentNode.innerHTML;
47994 var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
47999 * @return {Boolean} this.isConfirmed
48001 getConfirmed : function(){
48002 return this.isConfirmed;
48006 * @return {Number} this.width
48008 getWidth : function(){
48013 * @return {Number} this.height
48015 getHeight : function(){
48016 return this.height;
48019 getSignature : function(){
48020 return this.signatureTmp;
48023 reset : function(){
48024 this.signatureTmp = '';
48025 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
48026 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
48027 this.isConfirmed = false;
48028 Roo.form.Signature.superclass.reset.call(this);
48030 setSignature : function(s){
48031 this.signatureTmp = s;
48032 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
48033 this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
48035 this.isConfirmed = false;
48036 Roo.form.Signature.superclass.reset.call(this);
48039 // Roo.log(this.signPanel.dom.contentWindow.up())
48042 setConfirmed : function(){
48046 // Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
48049 confirmHandler : function(){
48050 if(!this.getSignature()){
48054 this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
48055 this.setValue(this.getSignature());
48056 this.isConfirmed = true;
48058 this.fireEvent('confirm', this);
48061 // Subclasses should provide the validation implementation by overriding this
48062 validateValue : function(value){
48063 if(this.allowBlank){
48067 if(this.isConfirmed){
48074 * Ext JS Library 1.1.1
48075 * Copyright(c) 2006-2007, Ext JS, LLC.
48077 * Originally Released Under LGPL - original licence link has changed is not relivant.
48080 * <script type="text/javascript">
48085 * @class Roo.form.ComboBox
48086 * @extends Roo.form.TriggerField
48087 * A combobox control with support for autocomplete, remote-loading, paging and many other features.
48089 * Create a new ComboBox.
48090 * @param {Object} config Configuration options
48092 Roo.form.Select = function(config){
48093 Roo.form.Select.superclass.constructor.call(this, config);
48097 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
48099 * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
48102 * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
48103 * rendering into an Roo.Editor, defaults to false)
48106 * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
48107 * {tag: "input", type: "text", size: "24", autocomplete: "off"})
48110 * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
48113 * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
48114 * the dropdown list (defaults to undefined, with no header element)
48118 * @cfg {String/Roo.Template} tpl The template to use to render the output
48122 defaultAutoCreate : {tag: "select" },
48124 * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
48126 listWidth: undefined,
48128 * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
48129 * mode = 'remote' or 'text' if mode = 'local')
48131 displayField: undefined,
48133 * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
48134 * mode = 'remote' or 'value' if mode = 'local').
48135 * Note: use of a valueField requires the user make a selection
48136 * in order for a value to be mapped.
48138 valueField: undefined,
48142 * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
48143 * field's data value (defaults to the underlying DOM element's name)
48145 hiddenName: undefined,
48147 * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
48151 * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
48153 selectedClass: 'x-combo-selected',
48155 * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the
48156 * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
48157 * which displays a downward arrow icon).
48159 triggerClass : 'x-form-arrow-trigger',
48161 * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
48165 * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
48166 * anchor positions (defaults to 'tl-bl')
48168 listAlign: 'tl-bl?',
48170 * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
48174 * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the
48175 * query specified by the allQuery config option (defaults to 'query')
48177 triggerAction: 'query',
48179 * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
48180 * (defaults to 4, does not apply if editable = false)
48184 * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
48185 * delay (typeAheadDelay) if it matches a known value (defaults to false)
48189 * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
48190 * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
48194 * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
48195 * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
48199 * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies
48200 * when editable = true (defaults to false)
48202 selectOnFocus:false,
48204 * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
48206 queryParam: 'query',
48208 * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
48209 * when mode = 'remote' (defaults to 'Loading...')
48211 loadingText: 'Loading...',
48213 * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
48217 * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
48221 * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
48222 * traditional select (defaults to true)
48226 * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
48230 * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
48234 * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
48235 * listWidth has a higher value)
48239 * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
48240 * allow the user to set arbitrary text into the field (defaults to false)
48242 forceSelection:false,
48244 * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
48245 * if typeAhead = true (defaults to 250)
48247 typeAheadDelay : 250,
48249 * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
48250 * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
48252 valueNotFoundText : undefined,
48255 * @cfg {String} defaultValue The value displayed after loading the store.
48260 * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
48262 blockFocus : false,
48265 * @cfg {Boolean} disableClear Disable showing of clear button.
48267 disableClear : false,
48269 * @cfg {Boolean} alwaysQuery Disable caching of results, and always send query
48271 alwaysQuery : false,
48277 // element that contains real text value.. (when hidden is used..)
48280 onRender : function(ct, position){
48281 Roo.form.Field.prototype.onRender.call(this, ct, position);
48284 this.store.on('beforeload', this.onBeforeLoad, this);
48285 this.store.on('load', this.onLoad, this);
48286 this.store.on('loadexception', this.onLoadException, this);
48287 this.store.load({});
48295 initEvents : function(){
48296 //Roo.form.ComboBox.superclass.initEvents.call(this);
48300 onDestroy : function(){
48303 this.store.un('beforeload', this.onBeforeLoad, this);
48304 this.store.un('load', this.onLoad, this);
48305 this.store.un('loadexception', this.onLoadException, this);
48307 //Roo.form.ComboBox.superclass.onDestroy.call(this);
48311 fireKey : function(e){
48312 if(e.isNavKeyPress() && !this.list.isVisible()){
48313 this.fireEvent("specialkey", this, e);
48318 onResize: function(w, h){
48326 * Allow or prevent the user from directly editing the field text. If false is passed,
48327 * the user will only be able to select from the items defined in the dropdown list. This method
48328 * is the runtime equivalent of setting the 'editable' config option at config time.
48329 * @param {Boolean} value True to allow the user to directly edit the field text
48331 setEditable : function(value){
48336 onBeforeLoad : function(){
48338 Roo.log("Select before load");
48341 this.innerList.update(this.loadingText ?
48342 '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
48343 //this.restrictHeight();
48344 this.selectedIndex = -1;
48348 onLoad : function(){
48351 var dom = this.el.dom;
48352 dom.innerHTML = '';
48353 var od = dom.ownerDocument;
48355 if (this.emptyText) {
48356 var op = od.createElement('option');
48357 op.setAttribute('value', '');
48358 op.innerHTML = String.format('{0}', this.emptyText);
48359 dom.appendChild(op);
48361 if(this.store.getCount() > 0){
48363 var vf = this.valueField;
48364 var df = this.displayField;
48365 this.store.data.each(function(r) {
48366 // which colmsn to use... testing - cdoe / title..
48367 var op = od.createElement('option');
48368 op.setAttribute('value', r.data[vf]);
48369 op.innerHTML = String.format('{0}', r.data[df]);
48370 dom.appendChild(op);
48372 if (typeof(this.defaultValue != 'undefined')) {
48373 this.setValue(this.defaultValue);
48378 //this.onEmptyResults();
48383 onLoadException : function()
48385 dom.innerHTML = '';
48387 Roo.log("Select on load exception");
48391 Roo.log(this.store.reader.jsonData);
48392 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
48393 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
48399 onTypeAhead : function(){
48404 onSelect : function(record, index){
48405 Roo.log('on select?');
48407 if(this.fireEvent('beforeselect', this, record, index) !== false){
48408 this.setFromData(index > -1 ? record.data : false);
48410 this.fireEvent('select', this, record, index);
48415 * Returns the currently selected field value or empty string if no value is set.
48416 * @return {String} value The selected value
48418 getValue : function(){
48419 var dom = this.el.dom;
48420 this.value = dom.options[dom.selectedIndex].value;
48426 * Clears any text/value currently set in the field
48428 clearValue : function(){
48430 this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
48435 * Sets the specified value into the field. If the value finds a match, the corresponding record text
48436 * will be displayed in the field. If the value does not match the data value of an existing item,
48437 * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
48438 * Otherwise the field will be blank (although the value will still be set).
48439 * @param {String} value The value to match
48441 setValue : function(v){
48442 var d = this.el.dom;
48443 for (var i =0; i < d.options.length;i++) {
48444 if (v == d.options[i].value) {
48445 d.selectedIndex = i;
48453 * @property {Object} the last set data for the element
48458 * Sets the value of the field based on a object which is related to the record format for the store.
48459 * @param {Object} value the value to set as. or false on reset?
48461 setFromData : function(o){
48462 Roo.log('setfrom data?');
48468 reset : function(){
48472 findRecord : function(prop, value){
48477 if(this.store.getCount() > 0){
48478 this.store.each(function(r){
48479 if(r.data[prop] == value){
48489 getName: function()
48491 // returns hidden if it's set..
48492 if (!this.rendered) {return ''};
48493 return !this.hiddenName && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
48501 onEmptyResults : function(){
48502 Roo.log('empty results');
48507 * Returns true if the dropdown list is expanded, else false.
48509 isExpanded : function(){
48514 * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
48515 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
48516 * @param {String} value The data value of the item to select
48517 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
48518 * selected item if it is not currently in view (defaults to true)
48519 * @return {Boolean} True if the value matched an item in the list, else false
48521 selectByValue : function(v, scrollIntoView){
48522 Roo.log('select By Value');
48525 if(v !== undefined && v !== null){
48526 var r = this.findRecord(this.valueField || this.displayField, v);
48528 this.select(this.store.indexOf(r), scrollIntoView);
48536 * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
48537 * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
48538 * @param {Number} index The zero-based index of the list item to select
48539 * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
48540 * selected item if it is not currently in view (defaults to true)
48542 select : function(index, scrollIntoView){
48543 Roo.log('select ');
48546 this.selectedIndex = index;
48547 this.view.select(index);
48548 if(scrollIntoView !== false){
48549 var el = this.view.getNode(index);
48551 this.innerList.scrollChildIntoView(el, false);
48559 validateBlur : function(){
48566 initQuery : function(){
48567 this.doQuery(this.getRawValue());
48571 doForce : function(){
48572 if(this.el.dom.value.length > 0){
48573 this.el.dom.value =
48574 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
48580 * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the
48581 * query allowing the query action to be canceled if needed.
48582 * @param {String} query The SQL query to execute
48583 * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
48584 * in the field than the minimum specified by the minChars config option. It also clears any filter previously
48585 * saved in the current store (defaults to false)
48587 doQuery : function(q, forceAll){
48589 Roo.log('doQuery?');
48590 if(q === undefined || q === null){
48595 forceAll: forceAll,
48599 if(this.fireEvent('beforequery', qe)===false || qe.cancel){
48603 forceAll = qe.forceAll;
48604 if(forceAll === true || (q.length >= this.minChars)){
48605 if(this.lastQuery != q || this.alwaysQuery){
48606 this.lastQuery = q;
48607 if(this.mode == 'local'){
48608 this.selectedIndex = -1;
48610 this.store.clearFilter();
48612 this.store.filter(this.displayField, q);
48616 this.store.baseParams[this.queryParam] = q;
48618 params: this.getParams(q)
48623 this.selectedIndex = -1;
48630 getParams : function(q){
48632 //p[this.queryParam] = q;
48635 p.limit = this.pageSize;
48641 * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
48643 collapse : function(){
48648 collapseIf : function(e){
48653 * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
48655 expand : function(){
48663 * @cfg {Boolean} grow
48667 * @cfg {Number} growMin
48671 * @cfg {Number} growMax
48679 setWidth : function()
48683 getResizeEl : function(){
48686 });//<script type="text/javasscript">
48690 * @class Roo.DDView
48691 * A DnD enabled version of Roo.View.
48692 * @param {Element/String} container The Element in which to create the View.
48693 * @param {String} tpl The template string used to create the markup for each element of the View
48694 * @param {Object} config The configuration properties. These include all the config options of
48695 * {@link Roo.View} plus some specific to this class.<br>
48697 * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
48698 * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
48700 * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
48701 .x-view-drag-insert-above {
48702 border-top:1px dotted #3366cc;
48704 .x-view-drag-insert-below {
48705 border-bottom:1px dotted #3366cc;
48711 Roo.DDView = function(container, tpl, config) {
48712 Roo.DDView.superclass.constructor.apply(this, arguments);
48713 this.getEl().setStyle("outline", "0px none");
48714 this.getEl().unselectable();
48715 if (this.dragGroup) {
48716 this.setDraggable(this.dragGroup.split(","));
48718 if (this.dropGroup) {
48719 this.setDroppable(this.dropGroup.split(","));
48721 if (this.deletable) {
48722 this.setDeletable();
48724 this.isDirtyFlag = false;
48730 Roo.extend(Roo.DDView, Roo.View, {
48731 /** @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
48732 /** @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
48733 /** @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
48734 /** @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
48738 reset: Roo.emptyFn,
48740 clearInvalid: Roo.form.Field.prototype.clearInvalid,
48742 validate: function() {
48746 destroy: function() {
48747 this.purgeListeners();
48748 this.getEl.removeAllListeners();
48749 this.getEl().remove();
48750 if (this.dragZone) {
48751 if (this.dragZone.destroy) {
48752 this.dragZone.destroy();
48755 if (this.dropZone) {
48756 if (this.dropZone.destroy) {
48757 this.dropZone.destroy();
48762 /** Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
48763 getName: function() {
48767 /** Loads the View from a JSON string representing the Records to put into the Store. */
48768 setValue: function(v) {
48770 throw "DDView.setValue(). DDView must be constructed with a valid Store";
48773 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
48774 this.store.proxy = new Roo.data.MemoryProxy(data);
48778 /** @return {String} a parenthesised list of the ids of the Records in the View. */
48779 getValue: function() {
48781 this.store.each(function(rec) {
48782 result += rec.id + ',';
48784 return result.substr(0, result.length - 1) + ')';
48787 getIds: function() {
48788 var i = 0, result = new Array(this.store.getCount());
48789 this.store.each(function(rec) {
48790 result[i++] = rec.id;
48795 isDirty: function() {
48796 return this.isDirtyFlag;
48800 * Part of the Roo.dd.DropZone interface. If no target node is found, the
48801 * whole Element becomes the target, and this causes the drop gesture to append.
48803 getTargetFromEvent : function(e) {
48804 var target = e.getTarget();
48805 while ((target !== null) && (target.parentNode != this.el.dom)) {
48806 target = target.parentNode;
48809 target = this.el.dom.lastChild || this.el.dom;
48815 * Create the drag data which consists of an object which has the property "ddel" as
48816 * the drag proxy element.
48818 getDragData : function(e) {
48819 var target = this.findItemFromChild(e.getTarget());
48821 this.handleSelection(e);
48822 var selNodes = this.getSelectedNodes();
48825 copy: this.copy || (this.allowCopy && e.ctrlKey),
48829 var selectedIndices = this.getSelectedIndexes();
48830 for (var i = 0; i < selectedIndices.length; i++) {
48831 dragData.records.push(this.store.getAt(selectedIndices[i]));
48833 if (selNodes.length == 1) {
48834 dragData.ddel = target.cloneNode(true); // the div element
48836 var div = document.createElement('div'); // create the multi element drag "ghost"
48837 div.className = 'multi-proxy';
48838 for (var i = 0, len = selNodes.length; i < len; i++) {
48839 div.appendChild(selNodes[i].cloneNode(true));
48841 dragData.ddel = div;
48843 //console.log(dragData)
48844 //console.log(dragData.ddel.innerHTML)
48847 //console.log('nodragData')
48851 /** Specify to which ddGroup items in this DDView may be dragged. */
48852 setDraggable: function(ddGroup) {
48853 if (ddGroup instanceof Array) {
48854 Roo.each(ddGroup, this.setDraggable, this);
48857 if (this.dragZone) {
48858 this.dragZone.addToGroup(ddGroup);
48860 this.dragZone = new Roo.dd.DragZone(this.getEl(), {
48861 containerScroll: true,
48865 // Draggability implies selection. DragZone's mousedown selects the element.
48866 if (!this.multiSelect) { this.singleSelect = true; }
48868 // Wire the DragZone's handlers up to methods in *this*
48869 this.dragZone.getDragData = this.getDragData.createDelegate(this);
48873 /** Specify from which ddGroup this DDView accepts drops. */
48874 setDroppable: function(ddGroup) {
48875 if (ddGroup instanceof Array) {
48876 Roo.each(ddGroup, this.setDroppable, this);
48879 if (this.dropZone) {
48880 this.dropZone.addToGroup(ddGroup);
48882 this.dropZone = new Roo.dd.DropZone(this.getEl(), {
48883 containerScroll: true,
48887 // Wire the DropZone's handlers up to methods in *this*
48888 this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
48889 this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
48890 this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
48891 this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
48892 this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
48896 /** Decide whether to drop above or below a View node. */
48897 getDropPoint : function(e, n, dd){
48898 if (n == this.el.dom) { return "above"; }
48899 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
48900 var c = t + (b - t) / 2;
48901 var y = Roo.lib.Event.getPageY(e);
48909 onNodeEnter : function(n, dd, e, data){
48913 onNodeOver : function(n, dd, e, data){
48914 var pt = this.getDropPoint(e, n, dd);
48915 // set the insert point style on the target node
48916 var dragElClass = this.dropNotAllowed;
48919 if (pt == "above"){
48920 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
48921 targetElClass = "x-view-drag-insert-above";
48923 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
48924 targetElClass = "x-view-drag-insert-below";
48926 if (this.lastInsertClass != targetElClass){
48927 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
48928 this.lastInsertClass = targetElClass;
48931 return dragElClass;
48934 onNodeOut : function(n, dd, e, data){
48935 this.removeDropIndicators(n);
48938 onNodeDrop : function(n, dd, e, data){
48939 if (this.fireEvent("drop", this, n, dd, e, data) === false) {
48942 var pt = this.getDropPoint(e, n, dd);
48943 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
48944 if (pt == "below") { insertAt++; }
48945 for (var i = 0; i < data.records.length; i++) {
48946 var r = data.records[i];
48947 var dup = this.store.getById(r.id);
48948 if (dup && (dd != this.dragZone)) {
48949 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
48952 this.store.insert(insertAt++, r.copy());
48954 data.source.isDirtyFlag = true;
48956 this.store.insert(insertAt++, r);
48958 this.isDirtyFlag = true;
48961 this.dragZone.cachedTarget = null;
48965 removeDropIndicators : function(n){
48967 Roo.fly(n).removeClass([
48968 "x-view-drag-insert-above",
48969 "x-view-drag-insert-below"]);
48970 this.lastInsertClass = "_noclass";
48975 * Utility method. Add a delete option to the DDView's context menu.
48976 * @param {String} imageUrl The URL of the "delete" icon image.
48978 setDeletable: function(imageUrl) {
48979 if (!this.singleSelect && !this.multiSelect) {
48980 this.singleSelect = true;
48982 var c = this.getContextMenu();
48983 this.contextMenu.on("itemclick", function(item) {
48986 this.remove(this.getSelectedIndexes());
48990 this.contextMenu.add({
48997 /** Return the context menu for this DDView. */
48998 getContextMenu: function() {
48999 if (!this.contextMenu) {
49000 // Create the View's context menu
49001 this.contextMenu = new Roo.menu.Menu({
49002 id: this.id + "-contextmenu"
49004 this.el.on("contextmenu", this.showContextMenu, this);
49006 return this.contextMenu;
49009 disableContextMenu: function() {
49010 if (this.contextMenu) {
49011 this.el.un("contextmenu", this.showContextMenu, this);
49015 showContextMenu: function(e, item) {
49016 item = this.findItemFromChild(e.getTarget());
49019 this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
49020 this.contextMenu.showAt(e.getXY());
49025 * Remove {@link Roo.data.Record}s at the specified indices.
49026 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
49028 remove: function(selectedIndices) {
49029 selectedIndices = [].concat(selectedIndices);
49030 for (var i = 0; i < selectedIndices.length; i++) {
49031 var rec = this.store.getAt(selectedIndices[i]);
49032 this.store.remove(rec);
49037 * Double click fires the event, but also, if this is draggable, and there is only one other
49038 * related DropZone, it transfers the selected node.
49040 onDblClick : function(e){
49041 var item = this.findItemFromChild(e.getTarget());
49043 if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
49046 if (this.dragGroup) {
49047 var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
49048 while (targets.indexOf(this.dropZone) > -1) {
49049 targets.remove(this.dropZone);
49051 if (targets.length == 1) {
49052 this.dragZone.cachedTarget = null;
49053 var el = Roo.get(targets[0].getEl());
49054 var box = el.getBox(true);
49055 targets[0].onNodeDrop(el.dom, {
49057 xy: [box.x, box.y + box.height - 1]
49058 }, null, this.getDragData(e));
49064 handleSelection: function(e) {
49065 this.dragZone.cachedTarget = null;
49066 var item = this.findItemFromChild(e.getTarget());
49068 this.clearSelections(true);
49071 if (item && (this.multiSelect || this.singleSelect)){
49072 if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
49073 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
49074 }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
49075 this.unselect(item);
49077 this.select(item, this.multiSelect && e.ctrlKey);
49078 this.lastSelection = item;
49083 onItemClick : function(item, index, e){
49084 if(this.fireEvent("beforeclick", this, index, item, e) === false){
49090 unselect : function(nodeInfo, suppressEvent){
49091 var node = this.getNode(nodeInfo);
49092 if(node && this.isSelected(node)){
49093 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
49094 Roo.fly(node).removeClass(this.selectedClass);
49095 this.selections.remove(node);
49096 if(!suppressEvent){
49097 this.fireEvent("selectionchange", this, this.selections);
49105 * Ext JS Library 1.1.1
49106 * Copyright(c) 2006-2007, Ext JS, LLC.
49108 * Originally Released Under LGPL - original licence link has changed is not relivant.
49111 * <script type="text/javascript">
49115 * @class Roo.LayoutManager
49116 * @extends Roo.util.Observable
49117 * Base class for layout managers.
49119 Roo.LayoutManager = function(container, config){
49120 Roo.LayoutManager.superclass.constructor.call(this);
49121 this.el = Roo.get(container);
49122 // ie scrollbar fix
49123 if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
49124 document.body.scroll = "no";
49125 }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
49126 this.el.position('relative');
49128 this.id = this.el.id;
49129 this.el.addClass("x-layout-container");
49130 /** false to disable window resize monitoring @type Boolean */
49131 this.monitorWindowResize = true;
49136 * Fires when a layout is performed.
49137 * @param {Roo.LayoutManager} this
49141 * @event regionresized
49142 * Fires when the user resizes a region.
49143 * @param {Roo.LayoutRegion} region The resized region
49144 * @param {Number} newSize The new size (width for east/west, height for north/south)
49146 "regionresized" : true,
49148 * @event regioncollapsed
49149 * Fires when a region is collapsed.
49150 * @param {Roo.LayoutRegion} region The collapsed region
49152 "regioncollapsed" : true,
49154 * @event regionexpanded
49155 * Fires when a region is expanded.
49156 * @param {Roo.LayoutRegion} region The expanded region
49158 "regionexpanded" : true
49160 this.updating = false;
49161 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
49164 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
49166 * Returns true if this layout is currently being updated
49167 * @return {Boolean}
49169 isUpdating : function(){
49170 return this.updating;
49174 * Suspend the LayoutManager from doing auto-layouts while
49175 * making multiple add or remove calls
49177 beginUpdate : function(){
49178 this.updating = true;
49182 * Restore auto-layouts and optionally disable the manager from performing a layout
49183 * @param {Boolean} noLayout true to disable a layout update
49185 endUpdate : function(noLayout){
49186 this.updating = false;
49192 layout: function(){
49196 onRegionResized : function(region, newSize){
49197 this.fireEvent("regionresized", region, newSize);
49201 onRegionCollapsed : function(region){
49202 this.fireEvent("regioncollapsed", region);
49205 onRegionExpanded : function(region){
49206 this.fireEvent("regionexpanded", region);
49210 * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
49211 * performs box-model adjustments.
49212 * @return {Object} The size as an object {width: (the width), height: (the height)}
49214 getViewSize : function(){
49216 if(this.el.dom != document.body){
49217 size = this.el.getSize();
49219 size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
49221 size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
49222 size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
49227 * Returns the Element this layout is bound to.
49228 * @return {Roo.Element}
49230 getEl : function(){
49235 * Returns the specified region.
49236 * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
49237 * @return {Roo.LayoutRegion}
49239 getRegion : function(target){
49240 return this.regions[target.toLowerCase()];
49243 onWindowResize : function(){
49244 if(this.monitorWindowResize){
49250 * Ext JS Library 1.1.1
49251 * Copyright(c) 2006-2007, Ext JS, LLC.
49253 * Originally Released Under LGPL - original licence link has changed is not relivant.
49256 * <script type="text/javascript">
49259 * @class Roo.BorderLayout
49260 * @extends Roo.LayoutManager
49261 * This class represents a common layout manager used in desktop applications. For screenshots and more details,
49262 * please see: <br><br>
49263 * <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>
49264 * <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>
49267 var layout = new Roo.BorderLayout(document.body, {
49301 preferredTabWidth: 150
49306 var CP = Roo.ContentPanel;
49308 layout.beginUpdate();
49309 layout.add("north", new CP("north", "North"));
49310 layout.add("south", new CP("south", {title: "South", closable: true}));
49311 layout.add("west", new CP("west", {title: "West"}));
49312 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
49313 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
49314 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
49315 layout.getRegion("center").showPanel("center1");
49316 layout.endUpdate();
49319 <b>The container the layout is rendered into can be either the body element or any other element.
49320 If it is not the body element, the container needs to either be an absolute positioned element,
49321 or you will need to add "position:relative" to the css of the container. You will also need to specify
49322 the container size if it is not the body element.</b>
49325 * Create a new BorderLayout
49326 * @param {String/HTMLElement/Element} container The container this layout is bound to
49327 * @param {Object} config Configuration options
49329 Roo.BorderLayout = function(container, config){
49330 config = config || {};
49331 Roo.BorderLayout.superclass.constructor.call(this, container, config);
49332 this.factory = config.factory || Roo.BorderLayout.RegionFactory;
49333 for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
49334 var target = this.factory.validRegions[i];
49335 if(config[target]){
49336 this.addRegion(target, config[target]);
49341 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
49343 * Creates and adds a new region if it doesn't already exist.
49344 * @param {String} target The target region key (north, south, east, west or center).
49345 * @param {Object} config The regions config object
49346 * @return {BorderLayoutRegion} The new region
49348 addRegion : function(target, config){
49349 if(!this.regions[target]){
49350 var r = this.factory.create(target, this, config);
49351 this.bindRegion(target, r);
49353 return this.regions[target];
49357 bindRegion : function(name, r){
49358 this.regions[name] = r;
49359 r.on("visibilitychange", this.layout, this);
49360 r.on("paneladded", this.layout, this);
49361 r.on("panelremoved", this.layout, this);
49362 r.on("invalidated", this.layout, this);
49363 r.on("resized", this.onRegionResized, this);
49364 r.on("collapsed", this.onRegionCollapsed, this);
49365 r.on("expanded", this.onRegionExpanded, this);
49369 * Performs a layout update.
49371 layout : function(){
49372 if(this.updating) return;
49373 var size = this.getViewSize();
49374 var w = size.width;
49375 var h = size.height;
49380 //var x = 0, y = 0;
49382 var rs = this.regions;
49383 var north = rs["north"];
49384 var south = rs["south"];
49385 var west = rs["west"];
49386 var east = rs["east"];
49387 var center = rs["center"];
49388 //if(this.hideOnLayout){ // not supported anymore
49389 //c.el.setStyle("display", "none");
49391 if(north && north.isVisible()){
49392 var b = north.getBox();
49393 var m = north.getMargins();
49394 b.width = w - (m.left+m.right);
49397 centerY = b.height + b.y + m.bottom;
49398 centerH -= centerY;
49399 north.updateBox(this.safeBox(b));
49401 if(south && south.isVisible()){
49402 var b = south.getBox();
49403 var m = south.getMargins();
49404 b.width = w - (m.left+m.right);
49406 var totalHeight = (b.height + m.top + m.bottom);
49407 b.y = h - totalHeight + m.top;
49408 centerH -= totalHeight;
49409 south.updateBox(this.safeBox(b));
49411 if(west && west.isVisible()){
49412 var b = west.getBox();
49413 var m = west.getMargins();
49414 b.height = centerH - (m.top+m.bottom);
49416 b.y = centerY + m.top;
49417 var totalWidth = (b.width + m.left + m.right);
49418 centerX += totalWidth;
49419 centerW -= totalWidth;
49420 west.updateBox(this.safeBox(b));
49422 if(east && east.isVisible()){
49423 var b = east.getBox();
49424 var m = east.getMargins();
49425 b.height = centerH - (m.top+m.bottom);
49426 var totalWidth = (b.width + m.left + m.right);
49427 b.x = w - totalWidth + m.left;
49428 b.y = centerY + m.top;
49429 centerW -= totalWidth;
49430 east.updateBox(this.safeBox(b));
49433 var m = center.getMargins();
49435 x: centerX + m.left,
49436 y: centerY + m.top,
49437 width: centerW - (m.left+m.right),
49438 height: centerH - (m.top+m.bottom)
49440 //if(this.hideOnLayout){
49441 //center.el.setStyle("display", "block");
49443 center.updateBox(this.safeBox(centerBox));
49446 this.fireEvent("layout", this);
49450 safeBox : function(box){
49451 box.width = Math.max(0, box.width);
49452 box.height = Math.max(0, box.height);
49457 * Adds a ContentPanel (or subclass) to this layout.
49458 * @param {String} target The target region key (north, south, east, west or center).
49459 * @param {Roo.ContentPanel} panel The panel to add
49460 * @return {Roo.ContentPanel} The added panel
49462 add : function(target, panel){
49464 target = target.toLowerCase();
49465 return this.regions[target].add(panel);
49469 * Remove a ContentPanel (or subclass) to this layout.
49470 * @param {String} target The target region key (north, south, east, west or center).
49471 * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
49472 * @return {Roo.ContentPanel} The removed panel
49474 remove : function(target, panel){
49475 target = target.toLowerCase();
49476 return this.regions[target].remove(panel);
49480 * Searches all regions for a panel with the specified id
49481 * @param {String} panelId
49482 * @return {Roo.ContentPanel} The panel or null if it wasn't found
49484 findPanel : function(panelId){
49485 var rs = this.regions;
49486 for(var target in rs){
49487 if(typeof rs[target] != "function"){
49488 var p = rs[target].getPanel(panelId);
49498 * Searches all regions for a panel with the specified id and activates (shows) it.
49499 * @param {String/ContentPanel} panelId The panels id or the panel itself
49500 * @return {Roo.ContentPanel} The shown panel or null
49502 showPanel : function(panelId) {
49503 var rs = this.regions;
49504 for(var target in rs){
49505 var r = rs[target];
49506 if(typeof r != "function"){
49507 if(r.hasPanel(panelId)){
49508 return r.showPanel(panelId);
49516 * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
49517 * @param {Roo.state.Provider} provider (optional) An alternate state provider
49519 restoreState : function(provider){
49521 provider = Roo.state.Manager;
49523 var sm = new Roo.LayoutStateManager();
49524 sm.init(this, provider);
49528 * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object. This config
49529 * object should contain properties for each region to add ContentPanels to, and each property's value should be
49530 * a valid ContentPanel config object. Example:
49532 // Create the main layout
49533 var layout = new Roo.BorderLayout('main-ct', {
49544 // Create and add multiple ContentPanels at once via configs
49547 id: 'source-files',
49549 title:'Ext Source Files',
49562 * @param {Object} regions An object containing ContentPanel configs by region name
49564 batchAdd : function(regions){
49565 this.beginUpdate();
49566 for(var rname in regions){
49567 var lr = this.regions[rname];
49569 this.addTypedPanels(lr, regions[rname]);
49576 addTypedPanels : function(lr, ps){
49577 if(typeof ps == 'string'){
49578 lr.add(new Roo.ContentPanel(ps));
49580 else if(ps instanceof Array){
49581 for(var i =0, len = ps.length; i < len; i++){
49582 this.addTypedPanels(lr, ps[i]);
49585 else if(!ps.events){ // raw config?
49587 delete ps.el; // prevent conflict
49588 lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
49590 else { // panel object assumed!
49595 * Adds a xtype elements to the layout.
49599 xtype : 'ContentPanel',
49606 xtype : 'NestedLayoutPanel',
49612 items : [ ... list of content panels or nested layout panels.. ]
49616 * @param {Object} cfg Xtype definition of item to add.
49618 addxtype : function(cfg)
49620 // basically accepts a pannel...
49621 // can accept a layout region..!?!?
49622 //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
49624 if (!cfg.xtype.match(/Panel$/)) {
49629 if (typeof(cfg.region) == 'undefined') {
49630 Roo.log("Failed to add Panel, region was not set");
49634 var region = cfg.region;
49640 xitems = cfg.items;
49647 case 'ContentPanel': // ContentPanel (el, cfg)
49648 case 'ScrollPanel': // ContentPanel (el, cfg)
49650 if(cfg.autoCreate) {
49651 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49653 var el = this.el.createChild();
49654 ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
49657 this.add(region, ret);
49661 case 'TreePanel': // our new panel!
49662 cfg.el = this.el.createChild();
49663 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49664 this.add(region, ret);
49667 case 'NestedLayoutPanel':
49668 // create a new Layout (which is a Border Layout...
49669 var el = this.el.createChild();
49670 var clayout = cfg.layout;
49672 clayout.items = clayout.items || [];
49673 // replace this exitems with the clayout ones..
49674 xitems = clayout.items;
49677 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
49678 cfg.background = false;
49680 var layout = new Roo.BorderLayout(el, clayout);
49682 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
49683 //console.log('adding nested layout panel ' + cfg.toSource());
49684 this.add(region, ret);
49685 nb = {}; /// find first...
49690 // needs grid and region
49692 //var el = this.getRegion(region).el.createChild();
49693 var el = this.el.createChild();
49694 // create the grid first...
49696 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
49698 if (region == 'center' && this.active ) {
49699 cfg.background = false;
49701 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
49703 this.add(region, ret);
49704 if (cfg.background) {
49705 ret.on('activate', function(gp) {
49706 if (!gp.grid.rendered) {
49721 if (typeof(Roo[cfg.xtype]) != 'undefined') {
49723 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
49724 this.add(region, ret);
49727 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
49731 // GridPanel (grid, cfg)
49734 this.beginUpdate();
49738 Roo.each(xitems, function(i) {
49739 region = nb && i.region ? i.region : false;
49741 var add = ret.addxtype(i);
49744 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
49745 if (!i.background) {
49746 abn[region] = nb[region] ;
49753 // make the last non-background panel active..
49754 //if (nb) { Roo.log(abn); }
49757 for(var r in abn) {
49758 region = this.getRegion(r);
49760 // tried using nb[r], but it does not work..
49762 region.showPanel(abn[r]);
49773 * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
49774 * the beginUpdate and endUpdate calls internally. The key to this method is the <b>panels</b> property that can be
49775 * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
49776 * during creation. The following code is equivalent to the constructor-based example at the beginning of this class:
49779 var CP = Roo.ContentPanel;
49781 var layout = Roo.BorderLayout.create({
49785 panels: [new CP("north", "North")]
49794 panels: [new CP("west", {title: "West"})]
49803 panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
49812 panels: [new CP("south", {title: "South", closable: true})]
49819 preferredTabWidth: 150,
49821 new CP("center1", {title: "Close Me", closable: true}),
49822 new CP("center2", {title: "Center Panel", closable: false})
49827 layout.getRegion("center").showPanel("center1");
49832 Roo.BorderLayout.create = function(config, targetEl){
49833 var layout = new Roo.BorderLayout(targetEl || document.body, config);
49834 layout.beginUpdate();
49835 var regions = Roo.BorderLayout.RegionFactory.validRegions;
49836 for(var j = 0, jlen = regions.length; j < jlen; j++){
49837 var lr = regions[j];
49838 if(layout.regions[lr] && config[lr].panels){
49839 var r = layout.regions[lr];
49840 var ps = config[lr].panels;
49841 layout.addTypedPanels(r, ps);
49844 layout.endUpdate();
49849 Roo.BorderLayout.RegionFactory = {
49851 validRegions : ["north","south","east","west","center"],
49854 create : function(target, mgr, config){
49855 target = target.toLowerCase();
49856 if(config.lightweight || config.basic){
49857 return new Roo.BasicLayoutRegion(mgr, config, target);
49861 return new Roo.NorthLayoutRegion(mgr, config);
49863 return new Roo.SouthLayoutRegion(mgr, config);
49865 return new Roo.EastLayoutRegion(mgr, config);
49867 return new Roo.WestLayoutRegion(mgr, config);
49869 return new Roo.CenterLayoutRegion(mgr, config);
49871 throw 'Layout region "'+target+'" not supported.';
49875 * Ext JS Library 1.1.1
49876 * Copyright(c) 2006-2007, Ext JS, LLC.
49878 * Originally Released Under LGPL - original licence link has changed is not relivant.
49881 * <script type="text/javascript">
49885 * @class Roo.BasicLayoutRegion
49886 * @extends Roo.util.Observable
49887 * This class represents a lightweight region in a layout manager. This region does not move dom nodes
49888 * and does not have a titlebar, tabs or any other features. All it does is size and position
49889 * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
49891 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
49893 this.position = pos;
49896 * @scope Roo.BasicLayoutRegion
49900 * @event beforeremove
49901 * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
49902 * @param {Roo.LayoutRegion} this
49903 * @param {Roo.ContentPanel} panel The panel
49904 * @param {Object} e The cancel event object
49906 "beforeremove" : true,
49908 * @event invalidated
49909 * Fires when the layout for this region is changed.
49910 * @param {Roo.LayoutRegion} this
49912 "invalidated" : true,
49914 * @event visibilitychange
49915 * Fires when this region is shown or hidden
49916 * @param {Roo.LayoutRegion} this
49917 * @param {Boolean} visibility true or false
49919 "visibilitychange" : true,
49921 * @event paneladded
49922 * Fires when a panel is added.
49923 * @param {Roo.LayoutRegion} this
49924 * @param {Roo.ContentPanel} panel The panel
49926 "paneladded" : true,
49928 * @event panelremoved
49929 * Fires when a panel is removed.
49930 * @param {Roo.LayoutRegion} this
49931 * @param {Roo.ContentPanel} panel The panel
49933 "panelremoved" : true,
49936 * Fires when this region is collapsed.
49937 * @param {Roo.LayoutRegion} this
49939 "collapsed" : true,
49942 * Fires when this region is expanded.
49943 * @param {Roo.LayoutRegion} this
49948 * Fires when this region is slid into view.
49949 * @param {Roo.LayoutRegion} this
49951 "slideshow" : true,
49954 * Fires when this region slides out of view.
49955 * @param {Roo.LayoutRegion} this
49957 "slidehide" : true,
49959 * @event panelactivated
49960 * Fires when a panel is activated.
49961 * @param {Roo.LayoutRegion} this
49962 * @param {Roo.ContentPanel} panel The activated panel
49964 "panelactivated" : true,
49967 * Fires when the user resizes this region.
49968 * @param {Roo.LayoutRegion} this
49969 * @param {Number} newSize The new size (width for east/west, height for north/south)
49973 /** A collection of panels in this region. @type Roo.util.MixedCollection */
49974 this.panels = new Roo.util.MixedCollection();
49975 this.panels.getKey = this.getPanelId.createDelegate(this);
49977 this.activePanel = null;
49978 // ensure listeners are added...
49980 if (config.listeners || config.events) {
49981 Roo.BasicLayoutRegion.superclass.constructor.call(this, {
49982 listeners : config.listeners || {},
49983 events : config.events || {}
49987 if(skipConfig !== true){
49988 this.applyConfig(config);
49992 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
49993 getPanelId : function(p){
49997 applyConfig : function(config){
49998 this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
49999 this.config = config;
50004 * Resizes the region to the specified size. For vertical regions (west, east) this adjusts
50005 * the width, for horizontal (north, south) the height.
50006 * @param {Number} newSize The new width or height
50008 resizeTo : function(newSize){
50009 var el = this.el ? this.el :
50010 (this.activePanel ? this.activePanel.getEl() : null);
50012 switch(this.position){
50015 el.setWidth(newSize);
50016 this.fireEvent("resized", this, newSize);
50020 el.setHeight(newSize);
50021 this.fireEvent("resized", this, newSize);
50027 getBox : function(){
50028 return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
50031 getMargins : function(){
50032 return this.margins;
50035 updateBox : function(box){
50037 var el = this.activePanel.getEl();
50038 el.dom.style.left = box.x + "px";
50039 el.dom.style.top = box.y + "px";
50040 this.activePanel.setSize(box.width, box.height);
50044 * Returns the container element for this region.
50045 * @return {Roo.Element}
50047 getEl : function(){
50048 return this.activePanel;
50052 * Returns true if this region is currently visible.
50053 * @return {Boolean}
50055 isVisible : function(){
50056 return this.activePanel ? true : false;
50059 setActivePanel : function(panel){
50060 panel = this.getPanel(panel);
50061 if(this.activePanel && this.activePanel != panel){
50062 this.activePanel.setActiveState(false);
50063 this.activePanel.getEl().setLeftTop(-10000,-10000);
50065 this.activePanel = panel;
50066 panel.setActiveState(true);
50068 panel.setSize(this.box.width, this.box.height);
50070 this.fireEvent("panelactivated", this, panel);
50071 this.fireEvent("invalidated");
50075 * Show the specified panel.
50076 * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
50077 * @return {Roo.ContentPanel} The shown panel or null
50079 showPanel : function(panel){
50080 if(panel = this.getPanel(panel)){
50081 this.setActivePanel(panel);
50087 * Get the active panel for this region.
50088 * @return {Roo.ContentPanel} The active panel or null
50090 getActivePanel : function(){
50091 return this.activePanel;
50095 * Add the passed ContentPanel(s)
50096 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
50097 * @return {Roo.ContentPanel} The panel added (if only one was added)
50099 add : function(panel){
50100 if(arguments.length > 1){
50101 for(var i = 0, len = arguments.length; i < len; i++) {
50102 this.add(arguments[i]);
50106 if(this.hasPanel(panel)){
50107 this.showPanel(panel);
50110 var el = panel.getEl();
50111 if(el.dom.parentNode != this.mgr.el.dom){
50112 this.mgr.el.dom.appendChild(el.dom);
50114 if(panel.setRegion){
50115 panel.setRegion(this);
50117 this.panels.add(panel);
50118 el.setStyle("position", "absolute");
50119 if(!panel.background){
50120 this.setActivePanel(panel);
50121 if(this.config.initialSize && this.panels.getCount()==1){
50122 this.resizeTo(this.config.initialSize);
50125 this.fireEvent("paneladded", this, panel);
50130 * Returns true if the panel is in this region.
50131 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50132 * @return {Boolean}
50134 hasPanel : function(panel){
50135 if(typeof panel == "object"){ // must be panel obj
50136 panel = panel.getId();
50138 return this.getPanel(panel) ? true : false;
50142 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
50143 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50144 * @param {Boolean} preservePanel Overrides the config preservePanel option
50145 * @return {Roo.ContentPanel} The panel that was removed
50147 remove : function(panel, preservePanel){
50148 panel = this.getPanel(panel);
50153 this.fireEvent("beforeremove", this, panel, e);
50154 if(e.cancel === true){
50157 var panelId = panel.getId();
50158 this.panels.removeKey(panelId);
50163 * Returns the panel specified or null if it's not in this region.
50164 * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
50165 * @return {Roo.ContentPanel}
50167 getPanel : function(id){
50168 if(typeof id == "object"){ // must be panel obj
50171 return this.panels.get(id);
50175 * Returns this regions position (north/south/east/west/center).
50178 getPosition: function(){
50179 return this.position;
50183 * Ext JS Library 1.1.1
50184 * Copyright(c) 2006-2007, Ext JS, LLC.
50186 * Originally Released Under LGPL - original licence link has changed is not relivant.
50189 * <script type="text/javascript">
50193 * @class Roo.LayoutRegion
50194 * @extends Roo.BasicLayoutRegion
50195 * This class represents a region in a layout manager.
50196 * @cfg {Boolean} collapsible False to disable collapsing (defaults to true)
50197 * @cfg {Boolean} collapsed True to set the initial display to collapsed (defaults to false)
50198 * @cfg {Boolean} floatable False to disable floating (defaults to true)
50199 * @cfg {Object} margins Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
50200 * @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})
50201 * @cfg {String} tabPosition (top|bottom) "top" or "bottom" (defaults to "bottom")
50202 * @cfg {String} collapsedTitle Optional string message to display in the collapsed block of a north or south region
50203 * @cfg {Boolean} alwaysShowTabs True to always display tabs even when there is only 1 panel (defaults to false)
50204 * @cfg {Boolean} autoScroll True to enable overflow scrolling (defaults to false)
50205 * @cfg {Boolean} titlebar True to display a title bar (defaults to true)
50206 * @cfg {String} title The title for the region (overrides panel titles)
50207 * @cfg {Boolean} animate True to animate expand/collapse (defaults to false)
50208 * @cfg {Boolean} autoHide False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
50209 * @cfg {Boolean} preservePanels True to preserve removed panels so they can be readded later (defaults to false)
50210 * @cfg {Boolean} closeOnTab True to place the close icon on the tabs instead of the region titlebar (defaults to false)
50211 * @cfg {Boolean} hideTabs True to hide the tab strip (defaults to false)
50212 * @cfg {Boolean} resizeTabs True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
50213 * the space available, similar to FireFox 1.5 tabs (defaults to false)
50214 * @cfg {Number} minTabWidth The minimum tab width (defaults to 40)
50215 * @cfg {Number} preferredTabWidth The preferred tab width (defaults to 150)
50216 * @cfg {Boolean} showPin True to show a pin button
50217 * @cfg {Boolean} hidden True to start the region hidden (defaults to false)
50218 * @cfg {Boolean} hideWhenEmpty True to hide the region when it has no panels
50219 * @cfg {Boolean} disableTabTips True to disable tab tooltips
50220 * @cfg {Number} width For East/West panels
50221 * @cfg {Number} height For North/South panels
50222 * @cfg {Boolean} split To show the splitter
50223 * @cfg {Boolean} toolbar xtype configuration for a toolbar - shows on right of tabbar
50225 Roo.LayoutRegion = function(mgr, config, pos){
50226 Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
50227 var dh = Roo.DomHelper;
50228 /** This region's container element
50229 * @type Roo.Element */
50230 this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
50231 /** This region's title element
50232 * @type Roo.Element */
50234 this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
50235 {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: " "},
50236 {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
50238 this.titleEl.enableDisplayMode();
50239 /** This region's title text element
50240 * @type HTMLElement */
50241 this.titleTextEl = this.titleEl.dom.firstChild;
50242 this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
50243 this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
50244 this.closeBtn.enableDisplayMode();
50245 this.closeBtn.on("click", this.closeClicked, this);
50246 this.closeBtn.hide();
50248 this.createBody(config);
50249 this.visible = true;
50250 this.collapsed = false;
50252 if(config.hideWhenEmpty){
50254 this.on("paneladded", this.validateVisibility, this);
50255 this.on("panelremoved", this.validateVisibility, this);
50257 this.applyConfig(config);
50260 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
50262 createBody : function(){
50263 /** This region's body element
50264 * @type Roo.Element */
50265 this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
50268 applyConfig : function(c){
50269 if(c.collapsible && this.position != "center" && !this.collapsedEl){
50270 var dh = Roo.DomHelper;
50271 if(c.titlebar !== false){
50272 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
50273 this.collapseBtn.on("click", this.collapse, this);
50274 this.collapseBtn.enableDisplayMode();
50276 if(c.showPin === true || this.showPin){
50277 this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
50278 this.stickBtn.enableDisplayMode();
50279 this.stickBtn.on("click", this.expand, this);
50280 this.stickBtn.hide();
50283 /** This region's collapsed element
50284 * @type Roo.Element */
50285 this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
50286 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
50288 if(c.floatable !== false){
50289 this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
50290 this.collapsedEl.on("click", this.collapseClick, this);
50293 if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
50294 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
50295 id: "message", unselectable: "on", style:{"float":"left"}});
50296 this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
50298 this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
50299 this.expandBtn.on("click", this.expand, this);
50301 if(this.collapseBtn){
50302 this.collapseBtn.setVisible(c.collapsible == true);
50304 this.cmargins = c.cmargins || this.cmargins ||
50305 (this.position == "west" || this.position == "east" ?
50306 {top: 0, left: 2, right:2, bottom: 0} :
50307 {top: 2, left: 0, right:0, bottom: 2});
50308 this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
50309 this.bottomTabs = c.tabPosition != "top";
50310 this.autoScroll = c.autoScroll || false;
50311 if(this.autoScroll){
50312 this.bodyEl.setStyle("overflow", "auto");
50314 this.bodyEl.setStyle("overflow", "hidden");
50316 //if(c.titlebar !== false){
50317 if((!c.titlebar && !c.title) || c.titlebar === false){
50318 this.titleEl.hide();
50320 this.titleEl.show();
50322 this.titleTextEl.innerHTML = c.title;
50326 this.duration = c.duration || .30;
50327 this.slideDuration = c.slideDuration || .45;
50330 this.collapse(true);
50337 * Returns true if this region is currently visible.
50338 * @return {Boolean}
50340 isVisible : function(){
50341 return this.visible;
50345 * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
50346 * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&#160;")
50348 setCollapsedTitle : function(title){
50349 title = title || " ";
50350 if(this.collapsedTitleTextEl){
50351 this.collapsedTitleTextEl.innerHTML = title;
50355 getBox : function(){
50357 if(!this.collapsed){
50358 b = this.el.getBox(false, true);
50360 b = this.collapsedEl.getBox(false, true);
50365 getMargins : function(){
50366 return this.collapsed ? this.cmargins : this.margins;
50369 highlight : function(){
50370 this.el.addClass("x-layout-panel-dragover");
50373 unhighlight : function(){
50374 this.el.removeClass("x-layout-panel-dragover");
50377 updateBox : function(box){
50379 if(!this.collapsed){
50380 this.el.dom.style.left = box.x + "px";
50381 this.el.dom.style.top = box.y + "px";
50382 this.updateBody(box.width, box.height);
50384 this.collapsedEl.dom.style.left = box.x + "px";
50385 this.collapsedEl.dom.style.top = box.y + "px";
50386 this.collapsedEl.setSize(box.width, box.height);
50389 this.tabs.autoSizeTabs();
50393 updateBody : function(w, h){
50395 this.el.setWidth(w);
50396 w -= this.el.getBorderWidth("rl");
50397 if(this.config.adjustments){
50398 w += this.config.adjustments[0];
50402 this.el.setHeight(h);
50403 h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
50404 h -= this.el.getBorderWidth("tb");
50405 if(this.config.adjustments){
50406 h += this.config.adjustments[1];
50408 this.bodyEl.setHeight(h);
50410 h = this.tabs.syncHeight(h);
50413 if(this.panelSize){
50414 w = w !== null ? w : this.panelSize.width;
50415 h = h !== null ? h : this.panelSize.height;
50417 if(this.activePanel){
50418 var el = this.activePanel.getEl();
50419 w = w !== null ? w : el.getWidth();
50420 h = h !== null ? h : el.getHeight();
50421 this.panelSize = {width: w, height: h};
50422 this.activePanel.setSize(w, h);
50424 if(Roo.isIE && this.tabs){
50425 this.tabs.el.repaint();
50430 * Returns the container element for this region.
50431 * @return {Roo.Element}
50433 getEl : function(){
50438 * Hides this region.
50441 if(!this.collapsed){
50442 this.el.dom.style.left = "-2000px";
50445 this.collapsedEl.dom.style.left = "-2000px";
50446 this.collapsedEl.hide();
50448 this.visible = false;
50449 this.fireEvent("visibilitychange", this, false);
50453 * Shows this region if it was previously hidden.
50456 if(!this.collapsed){
50459 this.collapsedEl.show();
50461 this.visible = true;
50462 this.fireEvent("visibilitychange", this, true);
50465 closeClicked : function(){
50466 if(this.activePanel){
50467 this.remove(this.activePanel);
50471 collapseClick : function(e){
50473 e.stopPropagation();
50476 e.stopPropagation();
50482 * Collapses this region.
50483 * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
50485 collapse : function(skipAnim){
50486 if(this.collapsed) return;
50487 this.collapsed = true;
50489 this.split.el.hide();
50491 if(this.config.animate && skipAnim !== true){
50492 this.fireEvent("invalidated", this);
50493 this.animateCollapse();
50495 this.el.setLocation(-20000,-20000);
50497 this.collapsedEl.show();
50498 this.fireEvent("collapsed", this);
50499 this.fireEvent("invalidated", this);
50503 animateCollapse : function(){
50508 * Expands this region if it was previously collapsed.
50509 * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
50510 * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
50512 expand : function(e, skipAnim){
50513 if(e) e.stopPropagation();
50514 if(!this.collapsed || this.el.hasActiveFx()) return;
50516 this.afterSlideIn();
50519 this.collapsed = false;
50520 if(this.config.animate && skipAnim !== true){
50521 this.animateExpand();
50525 this.split.el.show();
50527 this.collapsedEl.setLocation(-2000,-2000);
50528 this.collapsedEl.hide();
50529 this.fireEvent("invalidated", this);
50530 this.fireEvent("expanded", this);
50534 animateExpand : function(){
50538 initTabs : function()
50540 this.bodyEl.setStyle("overflow", "hidden");
50541 var ts = new Roo.TabPanel(
50544 tabPosition: this.bottomTabs ? 'bottom' : 'top',
50545 disableTooltips: this.config.disableTabTips,
50546 toolbar : this.config.toolbar
50549 if(this.config.hideTabs){
50550 ts.stripWrap.setDisplayed(false);
50553 ts.resizeTabs = this.config.resizeTabs === true;
50554 ts.minTabWidth = this.config.minTabWidth || 40;
50555 ts.maxTabWidth = this.config.maxTabWidth || 250;
50556 ts.preferredTabWidth = this.config.preferredTabWidth || 150;
50557 ts.monitorResize = false;
50558 ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
50559 ts.bodyEl.addClass('x-layout-tabs-body');
50560 this.panels.each(this.initPanelAsTab, this);
50563 initPanelAsTab : function(panel){
50564 var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
50565 this.config.closeOnTab && panel.isClosable());
50566 if(panel.tabTip !== undefined){
50567 ti.setTooltip(panel.tabTip);
50569 ti.on("activate", function(){
50570 this.setActivePanel(panel);
50572 if(this.config.closeOnTab){
50573 ti.on("beforeclose", function(t, e){
50575 this.remove(panel);
50581 updatePanelTitle : function(panel, title){
50582 if(this.activePanel == panel){
50583 this.updateTitle(title);
50586 var ti = this.tabs.getTab(panel.getEl().id);
50588 if(panel.tabTip !== undefined){
50589 ti.setTooltip(panel.tabTip);
50594 updateTitle : function(title){
50595 if(this.titleTextEl && !this.config.title){
50596 this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : " ");
50600 setActivePanel : function(panel){
50601 panel = this.getPanel(panel);
50602 if(this.activePanel && this.activePanel != panel){
50603 this.activePanel.setActiveState(false);
50605 this.activePanel = panel;
50606 panel.setActiveState(true);
50607 if(this.panelSize){
50608 panel.setSize(this.panelSize.width, this.panelSize.height);
50611 this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
50613 this.updateTitle(panel.getTitle());
50615 this.fireEvent("invalidated", this);
50617 this.fireEvent("panelactivated", this, panel);
50621 * Shows the specified panel.
50622 * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
50623 * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
50625 showPanel : function(panel)
50627 panel = this.getPanel(panel);
50630 var tab = this.tabs.getTab(panel.getEl().id);
50631 if(tab.isHidden()){
50632 this.tabs.unhideTab(tab.id);
50636 this.setActivePanel(panel);
50643 * Get the active panel for this region.
50644 * @return {Roo.ContentPanel} The active panel or null
50646 getActivePanel : function(){
50647 return this.activePanel;
50650 validateVisibility : function(){
50651 if(this.panels.getCount() < 1){
50652 this.updateTitle(" ");
50653 this.closeBtn.hide();
50656 if(!this.isVisible()){
50663 * Adds the passed ContentPanel(s) to this region.
50664 * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
50665 * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
50667 add : function(panel){
50668 if(arguments.length > 1){
50669 for(var i = 0, len = arguments.length; i < len; i++) {
50670 this.add(arguments[i]);
50674 if(this.hasPanel(panel)){
50675 this.showPanel(panel);
50678 panel.setRegion(this);
50679 this.panels.add(panel);
50680 if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
50681 this.bodyEl.dom.appendChild(panel.getEl().dom);
50682 if(panel.background !== true){
50683 this.setActivePanel(panel);
50685 this.fireEvent("paneladded", this, panel);
50691 this.initPanelAsTab(panel);
50693 if(panel.background !== true){
50694 this.tabs.activate(panel.getEl().id);
50696 this.fireEvent("paneladded", this, panel);
50701 * Hides the tab for the specified panel.
50702 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50704 hidePanel : function(panel){
50705 if(this.tabs && (panel = this.getPanel(panel))){
50706 this.tabs.hideTab(panel.getEl().id);
50711 * Unhides the tab for a previously hidden panel.
50712 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50714 unhidePanel : function(panel){
50715 if(this.tabs && (panel = this.getPanel(panel))){
50716 this.tabs.unhideTab(panel.getEl().id);
50720 clearPanels : function(){
50721 while(this.panels.getCount() > 0){
50722 this.remove(this.panels.first());
50727 * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
50728 * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
50729 * @param {Boolean} preservePanel Overrides the config preservePanel option
50730 * @return {Roo.ContentPanel} The panel that was removed
50732 remove : function(panel, preservePanel){
50733 panel = this.getPanel(panel);
50738 this.fireEvent("beforeremove", this, panel, e);
50739 if(e.cancel === true){
50742 preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
50743 var panelId = panel.getId();
50744 this.panels.removeKey(panelId);
50746 document.body.appendChild(panel.getEl().dom);
50749 this.tabs.removeTab(panel.getEl().id);
50750 }else if (!preservePanel){
50751 this.bodyEl.dom.removeChild(panel.getEl().dom);
50753 if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
50754 var p = this.panels.first();
50755 var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
50756 tempEl.appendChild(p.getEl().dom);
50757 this.bodyEl.update("");
50758 this.bodyEl.dom.appendChild(p.getEl().dom);
50760 this.updateTitle(p.getTitle());
50762 this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
50763 this.setActivePanel(p);
50765 panel.setRegion(null);
50766 if(this.activePanel == panel){
50767 this.activePanel = null;
50769 if(this.config.autoDestroy !== false && preservePanel !== true){
50770 try{panel.destroy();}catch(e){}
50772 this.fireEvent("panelremoved", this, panel);
50777 * Returns the TabPanel component used by this region
50778 * @return {Roo.TabPanel}
50780 getTabs : function(){
50784 createTool : function(parentEl, className){
50785 var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
50786 children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: " "}]}, true);
50787 btn.addClassOnOver("x-layout-tools-button-over");
50792 * Ext JS Library 1.1.1
50793 * Copyright(c) 2006-2007, Ext JS, LLC.
50795 * Originally Released Under LGPL - original licence link has changed is not relivant.
50798 * <script type="text/javascript">
50804 * @class Roo.SplitLayoutRegion
50805 * @extends Roo.LayoutRegion
50806 * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
50808 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
50809 this.cursor = cursor;
50810 Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
50813 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
50814 splitTip : "Drag to resize.",
50815 collapsibleSplitTip : "Drag to resize. Double click to hide.",
50816 useSplitTips : false,
50818 applyConfig : function(config){
50819 Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
50822 var splitEl = Roo.DomHelper.append(this.mgr.el.dom,
50823 {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: " "});
50824 /** The SplitBar for this region
50825 * @type Roo.SplitBar */
50826 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
50827 this.split.on("moved", this.onSplitMove, this);
50828 this.split.useShim = config.useShim === true;
50829 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
50830 if(this.useSplitTips){
50831 this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
50833 if(config.collapsible){
50834 this.split.el.on("dblclick", this.collapse, this);
50837 if(typeof config.minSize != "undefined"){
50838 this.split.minSize = config.minSize;
50840 if(typeof config.maxSize != "undefined"){
50841 this.split.maxSize = config.maxSize;
50843 if(config.hideWhenEmpty || config.hidden || config.collapsed){
50844 this.hideSplitter();
50849 getHMaxSize : function(){
50850 var cmax = this.config.maxSize || 10000;
50851 var center = this.mgr.getRegion("center");
50852 return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
50855 getVMaxSize : function(){
50856 var cmax = this.config.maxSize || 10000;
50857 var center = this.mgr.getRegion("center");
50858 return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
50861 onSplitMove : function(split, newSize){
50862 this.fireEvent("resized", this, newSize);
50866 * Returns the {@link Roo.SplitBar} for this region.
50867 * @return {Roo.SplitBar}
50869 getSplitBar : function(){
50874 this.hideSplitter();
50875 Roo.SplitLayoutRegion.superclass.hide.call(this);
50878 hideSplitter : function(){
50880 this.split.el.setLocation(-2000,-2000);
50881 this.split.el.hide();
50887 this.split.el.show();
50889 Roo.SplitLayoutRegion.superclass.show.call(this);
50892 beforeSlide: function(){
50893 if(Roo.isGecko){// firefox overflow auto bug workaround
50894 this.bodyEl.clip();
50895 if(this.tabs) this.tabs.bodyEl.clip();
50896 if(this.activePanel){
50897 this.activePanel.getEl().clip();
50899 if(this.activePanel.beforeSlide){
50900 this.activePanel.beforeSlide();
50906 afterSlide : function(){
50907 if(Roo.isGecko){// firefox overflow auto bug workaround
50908 this.bodyEl.unclip();
50909 if(this.tabs) this.tabs.bodyEl.unclip();
50910 if(this.activePanel){
50911 this.activePanel.getEl().unclip();
50912 if(this.activePanel.afterSlide){
50913 this.activePanel.afterSlide();
50919 initAutoHide : function(){
50920 if(this.autoHide !== false){
50921 if(!this.autoHideHd){
50922 var st = new Roo.util.DelayedTask(this.slideIn, this);
50923 this.autoHideHd = {
50924 "mouseout": function(e){
50925 if(!e.within(this.el, true)){
50929 "mouseover" : function(e){
50935 this.el.on(this.autoHideHd);
50939 clearAutoHide : function(){
50940 if(this.autoHide !== false){
50941 this.el.un("mouseout", this.autoHideHd.mouseout);
50942 this.el.un("mouseover", this.autoHideHd.mouseover);
50946 clearMonitor : function(){
50947 Roo.get(document).un("click", this.slideInIf, this);
50950 // these names are backwards but not changed for compat
50951 slideOut : function(){
50952 if(this.isSlid || this.el.hasActiveFx()){
50955 this.isSlid = true;
50956 if(this.collapseBtn){
50957 this.collapseBtn.hide();
50959 this.closeBtnState = this.closeBtn.getStyle('display');
50960 this.closeBtn.hide();
50962 this.stickBtn.show();
50965 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
50966 this.beforeSlide();
50967 this.el.setStyle("z-index", 10001);
50968 this.el.slideIn(this.getSlideAnchor(), {
50969 callback: function(){
50971 this.initAutoHide();
50972 Roo.get(document).on("click", this.slideInIf, this);
50973 this.fireEvent("slideshow", this);
50980 afterSlideIn : function(){
50981 this.clearAutoHide();
50982 this.isSlid = false;
50983 this.clearMonitor();
50984 this.el.setStyle("z-index", "");
50985 if(this.collapseBtn){
50986 this.collapseBtn.show();
50988 this.closeBtn.setStyle('display', this.closeBtnState);
50990 this.stickBtn.hide();
50992 this.fireEvent("slidehide", this);
50995 slideIn : function(cb){
50996 if(!this.isSlid || this.el.hasActiveFx()){
51000 this.isSlid = false;
51001 this.beforeSlide();
51002 this.el.slideOut(this.getSlideAnchor(), {
51003 callback: function(){
51004 this.el.setLeftTop(-10000, -10000);
51006 this.afterSlideIn();
51014 slideInIf : function(e){
51015 if(!e.within(this.el)){
51020 animateCollapse : function(){
51021 this.beforeSlide();
51022 this.el.setStyle("z-index", 20000);
51023 var anchor = this.getSlideAnchor();
51024 this.el.slideOut(anchor, {
51025 callback : function(){
51026 this.el.setStyle("z-index", "");
51027 this.collapsedEl.slideIn(anchor, {duration:.3});
51029 this.el.setLocation(-10000,-10000);
51031 this.fireEvent("collapsed", this);
51038 animateExpand : function(){
51039 this.beforeSlide();
51040 this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
51041 this.el.setStyle("z-index", 20000);
51042 this.collapsedEl.hide({
51045 this.el.slideIn(this.getSlideAnchor(), {
51046 callback : function(){
51047 this.el.setStyle("z-index", "");
51050 this.split.el.show();
51052 this.fireEvent("invalidated", this);
51053 this.fireEvent("expanded", this);
51081 getAnchor : function(){
51082 return this.anchors[this.position];
51085 getCollapseAnchor : function(){
51086 return this.canchors[this.position];
51089 getSlideAnchor : function(){
51090 return this.sanchors[this.position];
51093 getAlignAdj : function(){
51094 var cm = this.cmargins;
51095 switch(this.position){
51111 getExpandAdj : function(){
51112 var c = this.collapsedEl, cm = this.cmargins;
51113 switch(this.position){
51115 return [-(cm.right+c.getWidth()+cm.left), 0];
51118 return [cm.right+c.getWidth()+cm.left, 0];
51121 return [0, -(cm.top+cm.bottom+c.getHeight())];
51124 return [0, cm.top+cm.bottom+c.getHeight()];
51130 * Ext JS Library 1.1.1
51131 * Copyright(c) 2006-2007, Ext JS, LLC.
51133 * Originally Released Under LGPL - original licence link has changed is not relivant.
51136 * <script type="text/javascript">
51139 * These classes are private internal classes
51141 Roo.CenterLayoutRegion = function(mgr, config){
51142 Roo.LayoutRegion.call(this, mgr, config, "center");
51143 this.visible = true;
51144 this.minWidth = config.minWidth || 20;
51145 this.minHeight = config.minHeight || 20;
51148 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
51150 // center panel can't be hidden
51154 // center panel can't be hidden
51157 getMinWidth: function(){
51158 return this.minWidth;
51161 getMinHeight: function(){
51162 return this.minHeight;
51167 Roo.NorthLayoutRegion = function(mgr, config){
51168 Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
51170 this.split.placement = Roo.SplitBar.TOP;
51171 this.split.orientation = Roo.SplitBar.VERTICAL;
51172 this.split.el.addClass("x-layout-split-v");
51174 var size = config.initialSize || config.height;
51175 if(typeof size != "undefined"){
51176 this.el.setHeight(size);
51179 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
51180 orientation: Roo.SplitBar.VERTICAL,
51181 getBox : function(){
51182 if(this.collapsed){
51183 return this.collapsedEl.getBox();
51185 var box = this.el.getBox();
51187 box.height += this.split.el.getHeight();
51192 updateBox : function(box){
51193 if(this.split && !this.collapsed){
51194 box.height -= this.split.el.getHeight();
51195 this.split.el.setLeft(box.x);
51196 this.split.el.setTop(box.y+box.height);
51197 this.split.el.setWidth(box.width);
51199 if(this.collapsed){
51200 this.updateBody(box.width, null);
51202 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51206 Roo.SouthLayoutRegion = function(mgr, config){
51207 Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
51209 this.split.placement = Roo.SplitBar.BOTTOM;
51210 this.split.orientation = Roo.SplitBar.VERTICAL;
51211 this.split.el.addClass("x-layout-split-v");
51213 var size = config.initialSize || config.height;
51214 if(typeof size != "undefined"){
51215 this.el.setHeight(size);
51218 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
51219 orientation: Roo.SplitBar.VERTICAL,
51220 getBox : function(){
51221 if(this.collapsed){
51222 return this.collapsedEl.getBox();
51224 var box = this.el.getBox();
51226 var sh = this.split.el.getHeight();
51233 updateBox : function(box){
51234 if(this.split && !this.collapsed){
51235 var sh = this.split.el.getHeight();
51238 this.split.el.setLeft(box.x);
51239 this.split.el.setTop(box.y-sh);
51240 this.split.el.setWidth(box.width);
51242 if(this.collapsed){
51243 this.updateBody(box.width, null);
51245 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51249 Roo.EastLayoutRegion = function(mgr, config){
51250 Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
51252 this.split.placement = Roo.SplitBar.RIGHT;
51253 this.split.orientation = Roo.SplitBar.HORIZONTAL;
51254 this.split.el.addClass("x-layout-split-h");
51256 var size = config.initialSize || config.width;
51257 if(typeof size != "undefined"){
51258 this.el.setWidth(size);
51261 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
51262 orientation: Roo.SplitBar.HORIZONTAL,
51263 getBox : function(){
51264 if(this.collapsed){
51265 return this.collapsedEl.getBox();
51267 var box = this.el.getBox();
51269 var sw = this.split.el.getWidth();
51276 updateBox : function(box){
51277 if(this.split && !this.collapsed){
51278 var sw = this.split.el.getWidth();
51280 this.split.el.setLeft(box.x);
51281 this.split.el.setTop(box.y);
51282 this.split.el.setHeight(box.height);
51285 if(this.collapsed){
51286 this.updateBody(null, box.height);
51288 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51292 Roo.WestLayoutRegion = function(mgr, config){
51293 Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
51295 this.split.placement = Roo.SplitBar.LEFT;
51296 this.split.orientation = Roo.SplitBar.HORIZONTAL;
51297 this.split.el.addClass("x-layout-split-h");
51299 var size = config.initialSize || config.width;
51300 if(typeof size != "undefined"){
51301 this.el.setWidth(size);
51304 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
51305 orientation: Roo.SplitBar.HORIZONTAL,
51306 getBox : function(){
51307 if(this.collapsed){
51308 return this.collapsedEl.getBox();
51310 var box = this.el.getBox();
51312 box.width += this.split.el.getWidth();
51317 updateBox : function(box){
51318 if(this.split && !this.collapsed){
51319 var sw = this.split.el.getWidth();
51321 this.split.el.setLeft(box.x+box.width);
51322 this.split.el.setTop(box.y);
51323 this.split.el.setHeight(box.height);
51325 if(this.collapsed){
51326 this.updateBody(null, box.height);
51328 Roo.LayoutRegion.prototype.updateBox.call(this, box);
51333 * Ext JS Library 1.1.1
51334 * Copyright(c) 2006-2007, Ext JS, LLC.
51336 * Originally Released Under LGPL - original licence link has changed is not relivant.
51339 * <script type="text/javascript">
51344 * Private internal class for reading and applying state
51346 Roo.LayoutStateManager = function(layout){
51347 // default empty state
51356 Roo.LayoutStateManager.prototype = {
51357 init : function(layout, provider){
51358 this.provider = provider;
51359 var state = provider.get(layout.id+"-layout-state");
51361 var wasUpdating = layout.isUpdating();
51363 layout.beginUpdate();
51365 for(var key in state){
51366 if(typeof state[key] != "function"){
51367 var rstate = state[key];
51368 var r = layout.getRegion(key);
51371 r.resizeTo(rstate.size);
51373 if(rstate.collapsed == true){
51376 r.expand(null, true);
51382 layout.endUpdate();
51384 this.state = state;
51386 this.layout = layout;
51387 layout.on("regionresized", this.onRegionResized, this);
51388 layout.on("regioncollapsed", this.onRegionCollapsed, this);
51389 layout.on("regionexpanded", this.onRegionExpanded, this);
51392 storeState : function(){
51393 this.provider.set(this.layout.id+"-layout-state", this.state);
51396 onRegionResized : function(region, newSize){
51397 this.state[region.getPosition()].size = newSize;
51401 onRegionCollapsed : function(region){
51402 this.state[region.getPosition()].collapsed = true;
51406 onRegionExpanded : function(region){
51407 this.state[region.getPosition()].collapsed = false;
51412 * Ext JS Library 1.1.1
51413 * Copyright(c) 2006-2007, Ext JS, LLC.
51415 * Originally Released Under LGPL - original licence link has changed is not relivant.
51418 * <script type="text/javascript">
51421 * @class Roo.ContentPanel
51422 * @extends Roo.util.Observable
51423 * A basic ContentPanel element.
51424 * @cfg {Boolean} fitToFrame True for this panel to adjust its size to fit when the region resizes (defaults to false)
51425 * @cfg {Boolean} fitContainer When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container (defaults to false)
51426 * @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
51427 * @cfg {Boolean} closable True if the panel can be closed/removed
51428 * @cfg {Boolean} background True if the panel should not be activated when it is added (defaults to false)
51429 * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
51430 * @cfg {Toolbar} toolbar A toolbar for this panel
51431 * @cfg {Boolean} autoScroll True to scroll overflow in this panel (use with {@link #fitToFrame})
51432 * @cfg {String} title The title for this panel
51433 * @cfg {Array} adjustments Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
51434 * @cfg {String} url Calls {@link #setUrl} with this value
51435 * @cfg {String} region (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
51436 * @cfg {String/Object} params When used with {@link #url}, calls {@link #setUrl} with this value
51437 * @cfg {Boolean} loadOnce When used with {@link #url}, calls {@link #setUrl} with this value
51438 * @cfg {String} content Raw content to fill content panel with (uses setContent on construction.)
51441 * Create a new ContentPanel.
51442 * @param {String/HTMLElement/Roo.Element} el The container element for this panel
51443 * @param {String/Object} config A string to set only the title or a config object
51444 * @param {String} content (optional) Set the HTML content for this panel
51445 * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
51447 Roo.ContentPanel = function(el, config, content){
51451 if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
51455 if (config && config.parentLayout) {
51456 el = config.parentLayout.el.createChild();
51459 if(el.autoCreate){ // xtype is available if this is called from factory
51463 this.el = Roo.get(el);
51464 if(!this.el && config && config.autoCreate){
51465 if(typeof config.autoCreate == "object"){
51466 if(!config.autoCreate.id){
51467 config.autoCreate.id = config.id||el;
51469 this.el = Roo.DomHelper.append(document.body,
51470 config.autoCreate, true);
51472 this.el = Roo.DomHelper.append(document.body,
51473 {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
51476 this.closable = false;
51477 this.loaded = false;
51478 this.active = false;
51479 if(typeof config == "string"){
51480 this.title = config;
51482 Roo.apply(this, config);
51485 if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
51486 this.wrapEl = this.el.wrap();
51487 this.toolbar.container = this.el.insertSibling(false, 'before');
51488 this.toolbar = new Roo.Toolbar(this.toolbar);
51491 // xtype created footer. - not sure if will work as we normally have to render first..
51492 if (this.footer && !this.footer.el && this.footer.xtype) {
51493 if (!this.wrapEl) {
51494 this.wrapEl = this.el.wrap();
51497 this.footer.container = this.wrapEl.createChild();
51499 this.footer = Roo.factory(this.footer, Roo);
51504 this.resizeEl = Roo.get(this.resizeEl, true);
51506 this.resizeEl = this.el;
51508 // handle view.xtype
51516 * Fires when this panel is activated.
51517 * @param {Roo.ContentPanel} this
51521 * @event deactivate
51522 * Fires when this panel is activated.
51523 * @param {Roo.ContentPanel} this
51525 "deactivate" : true,
51529 * Fires when this panel is resized if fitToFrame is true.
51530 * @param {Roo.ContentPanel} this
51531 * @param {Number} width The width after any component adjustments
51532 * @param {Number} height The height after any component adjustments
51538 * Fires when this tab is created
51539 * @param {Roo.ContentPanel} this
51550 if(this.autoScroll){
51551 this.resizeEl.setStyle("overflow", "auto");
51553 // fix randome scrolling
51554 this.el.on('scroll', function() {
51555 Roo.log('fix random scolling');
51556 this.scrollTo('top',0);
51559 content = content || this.content;
51561 this.setContent(content);
51563 if(config && config.url){
51564 this.setUrl(this.url, this.params, this.loadOnce);
51569 Roo.ContentPanel.superclass.constructor.call(this);
51571 if (this.view && typeof(this.view.xtype) != 'undefined') {
51572 this.view.el = this.el.appendChild(document.createElement("div"));
51573 this.view = Roo.factory(this.view);
51574 this.view.render && this.view.render(false, '');
51578 this.fireEvent('render', this);
51581 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
51583 setRegion : function(region){
51584 this.region = region;
51586 this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
51588 this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
51593 * Returns the toolbar for this Panel if one was configured.
51594 * @return {Roo.Toolbar}
51596 getToolbar : function(){
51597 return this.toolbar;
51600 setActiveState : function(active){
51601 this.active = active;
51603 this.fireEvent("deactivate", this);
51605 this.fireEvent("activate", this);
51609 * Updates this panel's element
51610 * @param {String} content The new content
51611 * @param {Boolean} loadScripts (optional) true to look for and process scripts
51613 setContent : function(content, loadScripts){
51614 this.el.update(content, loadScripts);
51617 ignoreResize : function(w, h){
51618 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
51621 this.lastSize = {width: w, height: h};
51626 * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
51627 * @return {Roo.UpdateManager} The UpdateManager
51629 getUpdateManager : function(){
51630 return this.el.getUpdateManager();
51633 * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
51634 * @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:
51637 url: "your-url.php",
51638 params: {param1: "foo", param2: "bar"}, // or a URL encoded string
51639 callback: yourFunction,
51640 scope: yourObject, //(optional scope)
51643 text: "Loading...",
51648 * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
51649 * 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.
51650 * @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}
51651 * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
51652 * @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.
51653 * @return {Roo.ContentPanel} this
51656 var um = this.el.getUpdateManager();
51657 um.update.apply(um, arguments);
51663 * 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.
51664 * @param {String/Function} url The URL to load the content from or a function to call to get the URL
51665 * @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)
51666 * @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)
51667 * @return {Roo.UpdateManager} The UpdateManager
51669 setUrl : function(url, params, loadOnce){
51670 if(this.refreshDelegate){
51671 this.removeListener("activate", this.refreshDelegate);
51673 this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
51674 this.on("activate", this.refreshDelegate);
51675 return this.el.getUpdateManager();
51678 _handleRefresh : function(url, params, loadOnce){
51679 if(!loadOnce || !this.loaded){
51680 var updater = this.el.getUpdateManager();
51681 updater.update(url, params, this._setLoaded.createDelegate(this));
51685 _setLoaded : function(){
51686 this.loaded = true;
51690 * Returns this panel's id
51693 getId : function(){
51698 * Returns this panel's element - used by regiosn to add.
51699 * @return {Roo.Element}
51701 getEl : function(){
51702 return this.wrapEl || this.el;
51705 adjustForComponents : function(width, height)
51707 //Roo.log('adjustForComponents ');
51708 if(this.resizeEl != this.el){
51709 width -= this.el.getFrameWidth('lr');
51710 height -= this.el.getFrameWidth('tb');
51713 var te = this.toolbar.getEl();
51714 height -= te.getHeight();
51715 te.setWidth(width);
51718 var te = this.footer.getEl();
51719 Roo.log("footer:" + te.getHeight());
51721 height -= te.getHeight();
51722 te.setWidth(width);
51726 if(this.adjustments){
51727 width += this.adjustments[0];
51728 height += this.adjustments[1];
51730 return {"width": width, "height": height};
51733 setSize : function(width, height){
51734 if(this.fitToFrame && !this.ignoreResize(width, height)){
51735 if(this.fitContainer && this.resizeEl != this.el){
51736 this.el.setSize(width, height);
51738 var size = this.adjustForComponents(width, height);
51739 this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
51740 this.fireEvent('resize', this, size.width, size.height);
51745 * Returns this panel's title
51748 getTitle : function(){
51753 * Set this panel's title
51754 * @param {String} title
51756 setTitle : function(title){
51757 this.title = title;
51759 this.region.updatePanelTitle(this, title);
51764 * Returns true is this panel was configured to be closable
51765 * @return {Boolean}
51767 isClosable : function(){
51768 return this.closable;
51771 beforeSlide : function(){
51773 this.resizeEl.clip();
51776 afterSlide : function(){
51778 this.resizeEl.unclip();
51782 * Force a content refresh from the URL specified in the {@link #setUrl} method.
51783 * Will fail silently if the {@link #setUrl} method has not been called.
51784 * This does not activate the panel, just updates its content.
51786 refresh : function(){
51787 if(this.refreshDelegate){
51788 this.loaded = false;
51789 this.refreshDelegate();
51794 * Destroys this panel
51796 destroy : function(){
51797 this.el.removeAllListeners();
51798 var tempEl = document.createElement("span");
51799 tempEl.appendChild(this.el.dom);
51800 tempEl.innerHTML = "";
51806 * form - if the content panel contains a form - this is a reference to it.
51807 * @type {Roo.form.Form}
51811 * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
51812 * This contains a reference to it.
51818 * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
51828 * @param {Object} cfg Xtype definition of item to add.
51831 addxtype : function(cfg) {
51833 if (cfg.xtype.match(/^Form$/)) {
51836 //if (this.footer) {
51837 // el = this.footer.container.insertSibling(false, 'before');
51839 el = this.el.createChild();
51842 this.form = new Roo.form.Form(cfg);
51845 if ( this.form.allItems.length) this.form.render(el.dom);
51848 // should only have one of theses..
51849 if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
51850 // views.. should not be just added - used named prop 'view''
51852 cfg.el = this.el.appendChild(document.createElement("div"));
51855 var ret = new Roo.factory(cfg);
51857 ret.render && ret.render(false, ''); // render blank..
51866 * @class Roo.GridPanel
51867 * @extends Roo.ContentPanel
51869 * Create a new GridPanel.
51870 * @param {Roo.grid.Grid} grid The grid for this panel
51871 * @param {String/Object} config A string to set only the panel's title, or a config object
51873 Roo.GridPanel = function(grid, config){
51876 this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
51877 {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
51879 this.wrapper.dom.appendChild(grid.getGridEl().dom);
51881 Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
51884 this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
51886 // xtype created footer. - not sure if will work as we normally have to render first..
51887 if (this.footer && !this.footer.el && this.footer.xtype) {
51889 this.footer.container = this.grid.getView().getFooterPanel(true);
51890 this.footer.dataSource = this.grid.dataSource;
51891 this.footer = Roo.factory(this.footer, Roo);
51895 grid.monitorWindowResize = false; // turn off autosizing
51896 grid.autoHeight = false;
51897 grid.autoWidth = false;
51899 this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
51902 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
51903 getId : function(){
51904 return this.grid.id;
51908 * Returns the grid for this panel
51909 * @return {Roo.grid.Grid}
51911 getGrid : function(){
51915 setSize : function(width, height){
51916 if(!this.ignoreResize(width, height)){
51917 var grid = this.grid;
51918 var size = this.adjustForComponents(width, height);
51919 grid.getGridEl().setSize(size.width, size.height);
51924 beforeSlide : function(){
51925 this.grid.getView().scroller.clip();
51928 afterSlide : function(){
51929 this.grid.getView().scroller.unclip();
51932 destroy : function(){
51933 this.grid.destroy();
51935 Roo.GridPanel.superclass.destroy.call(this);
51941 * @class Roo.NestedLayoutPanel
51942 * @extends Roo.ContentPanel
51944 * Create a new NestedLayoutPanel.
51947 * @param {Roo.BorderLayout} layout The layout for this panel
51948 * @param {String/Object} config A string to set only the title or a config object
51950 Roo.NestedLayoutPanel = function(layout, config)
51952 // construct with only one argument..
51953 /* FIXME - implement nicer consturctors
51954 if (layout.layout) {
51956 layout = config.layout;
51957 delete config.layout;
51959 if (layout.xtype && !layout.getEl) {
51960 // then layout needs constructing..
51961 layout = Roo.factory(layout, Roo);
51966 Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
51968 layout.monitorWindowResize = false; // turn off autosizing
51969 this.layout = layout;
51970 this.layout.getEl().addClass("x-layout-nested-layout");
51977 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
51979 setSize : function(width, height){
51980 if(!this.ignoreResize(width, height)){
51981 var size = this.adjustForComponents(width, height);
51982 var el = this.layout.getEl();
51983 el.setSize(size.width, size.height);
51984 var touch = el.dom.offsetWidth;
51985 this.layout.layout();
51986 // ie requires a double layout on the first pass
51987 if(Roo.isIE && !this.initialized){
51988 this.initialized = true;
51989 this.layout.layout();
51994 // activate all subpanels if not currently active..
51996 setActiveState : function(active){
51997 this.active = active;
51999 this.fireEvent("deactivate", this);
52003 this.fireEvent("activate", this);
52004 // not sure if this should happen before or after..
52005 if (!this.layout) {
52006 return; // should not happen..
52009 for (var r in this.layout.regions) {
52010 reg = this.layout.getRegion(r);
52011 if (reg.getActivePanel()) {
52012 //reg.showPanel(reg.getActivePanel()); // force it to activate..
52013 reg.setActivePanel(reg.getActivePanel());
52016 if (!reg.panels.length) {
52019 reg.showPanel(reg.getPanel(0));
52028 * Returns the nested BorderLayout for this panel
52029 * @return {Roo.BorderLayout}
52031 getLayout : function(){
52032 return this.layout;
52036 * Adds a xtype elements to the layout of the nested panel
52040 xtype : 'ContentPanel',
52047 xtype : 'NestedLayoutPanel',
52053 items : [ ... list of content panels or nested layout panels.. ]
52057 * @param {Object} cfg Xtype definition of item to add.
52059 addxtype : function(cfg) {
52060 return this.layout.addxtype(cfg);
52065 Roo.ScrollPanel = function(el, config, content){
52066 config = config || {};
52067 config.fitToFrame = true;
52068 Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
52070 this.el.dom.style.overflow = "hidden";
52071 var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
52072 this.el.removeClass("x-layout-inactive-content");
52073 this.el.on("mousewheel", this.onWheel, this);
52075 var up = wrap.createChild({cls: "x-scroller-up", html: " "}, this.el.dom);
52076 var down = wrap.createChild({cls: "x-scroller-down", html: " "});
52077 up.unselectable(); down.unselectable();
52078 up.on("click", this.scrollUp, this);
52079 down.on("click", this.scrollDown, this);
52080 up.addClassOnOver("x-scroller-btn-over");
52081 down.addClassOnOver("x-scroller-btn-over");
52082 up.addClassOnClick("x-scroller-btn-click");
52083 down.addClassOnClick("x-scroller-btn-click");
52084 this.adjustments = [0, -(up.getHeight() + down.getHeight())];
52086 this.resizeEl = this.el;
52087 this.el = wrap; this.up = up; this.down = down;
52090 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
52092 wheelIncrement : 5,
52093 scrollUp : function(){
52094 this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
52097 scrollDown : function(){
52098 this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
52101 afterScroll : function(){
52102 var el = this.resizeEl;
52103 var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
52104 this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
52105 this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
52108 setSize : function(){
52109 Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
52110 this.afterScroll();
52113 onWheel : function(e){
52114 var d = e.getWheelDelta();
52115 this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
52116 this.afterScroll();
52120 setContent : function(content, loadScripts){
52121 this.resizeEl.update(content, loadScripts);
52135 * @class Roo.TreePanel
52136 * @extends Roo.ContentPanel
52138 * Create a new TreePanel. - defaults to fit/scoll contents.
52139 * @param {String/Object} config A string to set only the panel's title, or a config object
52140 * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
52142 Roo.TreePanel = function(config){
52143 var el = config.el;
52144 var tree = config.tree;
52145 delete config.tree;
52146 delete config.el; // hopefull!
52148 // wrapper for IE7 strict & safari scroll issue
52150 var treeEl = el.createChild();
52151 config.resizeEl = treeEl;
52155 Roo.TreePanel.superclass.constructor.call(this, el, config);
52158 this.tree = new Roo.tree.TreePanel(treeEl , tree);
52159 //console.log(tree);
52160 this.on('activate', function()
52162 if (this.tree.rendered) {
52165 //console.log('render tree');
52166 this.tree.render();
52168 // this should not be needed.. - it's actually the 'el' that resizes?
52169 // actuall it breaks the containerScroll - dragging nodes auto scroll at top
52171 //this.on('resize', function (cp, w, h) {
52172 // this.tree.innerCt.setWidth(w);
52173 // this.tree.innerCt.setHeight(h);
52174 // //this.tree.innerCt.setStyle('overflow-y', 'auto');
52181 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {
52198 * Ext JS Library 1.1.1
52199 * Copyright(c) 2006-2007, Ext JS, LLC.
52201 * Originally Released Under LGPL - original licence link has changed is not relivant.
52204 * <script type="text/javascript">
52209 * @class Roo.ReaderLayout
52210 * @extends Roo.BorderLayout
52211 * This is a pre-built layout that represents a classic, 5-pane application. It consists of a header, a primary
52212 * center region containing two nested regions (a top one for a list view and one for item preview below),
52213 * and regions on either side that can be used for navigation, application commands, informational displays, etc.
52214 * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
52215 * expedites the setup of the overall layout and regions for this common application style.
52218 var reader = new Roo.ReaderLayout();
52219 var CP = Roo.ContentPanel; // shortcut for adding
52221 reader.beginUpdate();
52222 reader.add("north", new CP("north", "North"));
52223 reader.add("west", new CP("west", {title: "West"}));
52224 reader.add("east", new CP("east", {title: "East"}));
52226 reader.regions.listView.add(new CP("listView", "List"));
52227 reader.regions.preview.add(new CP("preview", "Preview"));
52228 reader.endUpdate();
52231 * Create a new ReaderLayout
52232 * @param {Object} config Configuration options
52233 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
52234 * document.body if omitted)
52236 Roo.ReaderLayout = function(config, renderTo){
52237 var c = config || {size:{}};
52238 Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
52239 north: c.north !== false ? Roo.apply({
52243 }, c.north) : false,
52244 west: c.west !== false ? Roo.apply({
52252 margins:{left:5,right:0,bottom:5,top:5},
52253 cmargins:{left:5,right:5,bottom:5,top:5}
52254 }, c.west) : false,
52255 east: c.east !== false ? Roo.apply({
52263 margins:{left:0,right:5,bottom:5,top:5},
52264 cmargins:{left:5,right:5,bottom:5,top:5}
52265 }, c.east) : false,
52266 center: Roo.apply({
52267 tabPosition: 'top',
52271 margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
52275 this.el.addClass('x-reader');
52277 this.beginUpdate();
52279 var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
52280 south: c.preview !== false ? Roo.apply({
52287 cmargins:{top:5,left:0, right:0, bottom:0}
52288 }, c.preview) : false,
52289 center: Roo.apply({
52295 this.add('center', new Roo.NestedLayoutPanel(inner,
52296 Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
52300 this.regions.preview = inner.getRegion('south');
52301 this.regions.listView = inner.getRegion('center');
52304 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
52306 * Ext JS Library 1.1.1
52307 * Copyright(c) 2006-2007, Ext JS, LLC.
52309 * Originally Released Under LGPL - original licence link has changed is not relivant.
52312 * <script type="text/javascript">
52316 * @class Roo.grid.Grid
52317 * @extends Roo.util.Observable
52318 * This class represents the primary interface of a component based grid control.
52319 * <br><br>Usage:<pre><code>
52320 var grid = new Roo.grid.Grid("my-container-id", {
52323 selModel: mySelectionModel,
52324 autoSizeColumns: true,
52325 monitorWindowResize: false,
52326 trackMouseOver: true
52331 * <b>Common Problems:</b><br/>
52332 * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
52333 * element will correct this<br/>
52334 * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
52335 * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
52336 * are unpredictable.<br/>
52337 * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
52338 * grid to calculate dimensions/offsets.<br/>
52340 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
52341 * The container MUST have some type of size defined for the grid to fill. The container will be
52342 * automatically set to position relative if it isn't already.
52343 * @param {Object} config A config object that sets properties on this grid.
52345 Roo.grid.Grid = function(container, config){
52346 // initialize the container
52347 this.container = Roo.get(container);
52348 this.container.update("");
52349 this.container.setStyle("overflow", "hidden");
52350 this.container.addClass('x-grid-container');
52352 this.id = this.container.id;
52354 Roo.apply(this, config);
52355 // check and correct shorthanded configs
52357 this.dataSource = this.ds;
52361 this.colModel = this.cm;
52365 this.selModel = this.sm;
52369 if (this.selModel) {
52370 this.selModel = Roo.factory(this.selModel, Roo.grid);
52371 this.sm = this.selModel;
52372 this.sm.xmodule = this.xmodule || false;
52374 if (typeof(this.colModel.config) == 'undefined') {
52375 this.colModel = new Roo.grid.ColumnModel(this.colModel);
52376 this.cm = this.colModel;
52377 this.cm.xmodule = this.xmodule || false;
52379 if (this.dataSource) {
52380 this.dataSource= Roo.factory(this.dataSource, Roo.data);
52381 this.ds = this.dataSource;
52382 this.ds.xmodule = this.xmodule || false;
52389 this.container.setWidth(this.width);
52393 this.container.setHeight(this.height);
52400 * The raw click event for the entire grid.
52401 * @param {Roo.EventObject} e
52406 * The raw dblclick event for the entire grid.
52407 * @param {Roo.EventObject} e
52411 * @event contextmenu
52412 * The raw contextmenu event for the entire grid.
52413 * @param {Roo.EventObject} e
52415 "contextmenu" : true,
52418 * The raw mousedown event for the entire grid.
52419 * @param {Roo.EventObject} e
52421 "mousedown" : true,
52424 * The raw mouseup event for the entire grid.
52425 * @param {Roo.EventObject} e
52430 * The raw mouseover event for the entire grid.
52431 * @param {Roo.EventObject} e
52433 "mouseover" : true,
52436 * The raw mouseout event for the entire grid.
52437 * @param {Roo.EventObject} e
52442 * The raw keypress event for the entire grid.
52443 * @param {Roo.EventObject} e
52448 * The raw keydown event for the entire grid.
52449 * @param {Roo.EventObject} e
52457 * Fires when a cell is clicked
52458 * @param {Grid} this
52459 * @param {Number} rowIndex
52460 * @param {Number} columnIndex
52461 * @param {Roo.EventObject} e
52463 "cellclick" : true,
52465 * @event celldblclick
52466 * Fires when a cell is double clicked
52467 * @param {Grid} this
52468 * @param {Number} rowIndex
52469 * @param {Number} columnIndex
52470 * @param {Roo.EventObject} e
52472 "celldblclick" : true,
52475 * Fires when a row is clicked
52476 * @param {Grid} this
52477 * @param {Number} rowIndex
52478 * @param {Roo.EventObject} e
52482 * @event rowdblclick
52483 * Fires when a row is double clicked
52484 * @param {Grid} this
52485 * @param {Number} rowIndex
52486 * @param {Roo.EventObject} e
52488 "rowdblclick" : true,
52490 * @event headerclick
52491 * Fires when a header is clicked
52492 * @param {Grid} this
52493 * @param {Number} columnIndex
52494 * @param {Roo.EventObject} e
52496 "headerclick" : true,
52498 * @event headerdblclick
52499 * Fires when a header cell is double clicked
52500 * @param {Grid} this
52501 * @param {Number} columnIndex
52502 * @param {Roo.EventObject} e
52504 "headerdblclick" : true,
52506 * @event rowcontextmenu
52507 * Fires when a row is right clicked
52508 * @param {Grid} this
52509 * @param {Number} rowIndex
52510 * @param {Roo.EventObject} e
52512 "rowcontextmenu" : true,
52514 * @event cellcontextmenu
52515 * Fires when a cell is right clicked
52516 * @param {Grid} this
52517 * @param {Number} rowIndex
52518 * @param {Number} cellIndex
52519 * @param {Roo.EventObject} e
52521 "cellcontextmenu" : true,
52523 * @event headercontextmenu
52524 * Fires when a header is right clicked
52525 * @param {Grid} this
52526 * @param {Number} columnIndex
52527 * @param {Roo.EventObject} e
52529 "headercontextmenu" : true,
52531 * @event bodyscroll
52532 * Fires when the body element is scrolled
52533 * @param {Number} scrollLeft
52534 * @param {Number} scrollTop
52536 "bodyscroll" : true,
52538 * @event columnresize
52539 * Fires when the user resizes a column
52540 * @param {Number} columnIndex
52541 * @param {Number} newSize
52543 "columnresize" : true,
52545 * @event columnmove
52546 * Fires when the user moves a column
52547 * @param {Number} oldIndex
52548 * @param {Number} newIndex
52550 "columnmove" : true,
52553 * Fires when row(s) start being dragged
52554 * @param {Grid} this
52555 * @param {Roo.GridDD} dd The drag drop object
52556 * @param {event} e The raw browser event
52558 "startdrag" : true,
52561 * Fires when a drag operation is complete
52562 * @param {Grid} this
52563 * @param {Roo.GridDD} dd The drag drop object
52564 * @param {event} e The raw browser event
52569 * Fires when dragged row(s) are dropped on a valid DD target
52570 * @param {Grid} this
52571 * @param {Roo.GridDD} dd The drag drop object
52572 * @param {String} targetId The target drag drop object
52573 * @param {event} e The raw browser event
52578 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
52579 * @param {Grid} this
52580 * @param {Roo.GridDD} dd The drag drop object
52581 * @param {String} targetId The target drag drop object
52582 * @param {event} e The raw browser event
52587 * Fires when the dragged row(s) first cross another DD target while being dragged
52588 * @param {Grid} this
52589 * @param {Roo.GridDD} dd The drag drop object
52590 * @param {String} targetId The target drag drop object
52591 * @param {event} e The raw browser event
52593 "dragenter" : true,
52596 * Fires when the dragged row(s) leave another DD target while being dragged
52597 * @param {Grid} this
52598 * @param {Roo.GridDD} dd The drag drop object
52599 * @param {String} targetId The target drag drop object
52600 * @param {event} e The raw browser event
52605 * Fires when a row is rendered, so you can change add a style to it.
52606 * @param {GridView} gridview The grid view
52607 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
52613 * Fires when the grid is rendered
52614 * @param {Grid} grid
52619 Roo.grid.Grid.superclass.constructor.call(this);
52621 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
52624 * @cfg {String} ddGroup - drag drop group.
52628 * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
52630 minColumnWidth : 25,
52633 * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
52634 * <b>on initial render.</b> It is more efficient to explicitly size the columns
52635 * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option. Default is false.
52637 autoSizeColumns : false,
52640 * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
52642 autoSizeHeaders : true,
52645 * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
52647 monitorWindowResize : true,
52650 * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
52651 * rows measured to get a columns size. Default is 0 (all rows).
52653 maxRowsToMeasure : 0,
52656 * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
52658 trackMouseOver : true,
52661 * @cfg {Boolean} enableDrag True to enable drag of rows. Default is false. (double check if this is needed?)
52665 * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
52667 enableDragDrop : false,
52670 * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
52672 enableColumnMove : true,
52675 * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
52677 enableColumnHide : true,
52680 * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
52682 enableRowHeightSync : false,
52685 * @cfg {Boolean} stripeRows True to stripe the rows. Default is true.
52690 * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
52692 autoHeight : false,
52695 * @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.
52697 autoExpandColumn : false,
52700 * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
52703 autoExpandMin : 50,
52706 * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
52708 autoExpandMax : 1000,
52711 * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
52716 * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
52720 * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
52730 * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
52731 * of a fixed width. Default is false.
52734 * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
52737 * Called once after all setup has been completed and the grid is ready to be rendered.
52738 * @return {Roo.grid.Grid} this
52740 render : function()
52742 var c = this.container;
52743 // try to detect autoHeight/width mode
52744 if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
52745 this.autoHeight = true;
52747 var view = this.getView();
52750 c.on("click", this.onClick, this);
52751 c.on("dblclick", this.onDblClick, this);
52752 c.on("contextmenu", this.onContextMenu, this);
52753 c.on("keydown", this.onKeyDown, this);
52755 c.on("touchstart", this.onTouchStart, this);
52758 this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
52760 this.getSelectionModel().init(this);
52765 this.loadMask = new Roo.LoadMask(this.container,
52766 Roo.apply({store:this.dataSource}, this.loadMask));
52770 if (this.toolbar && this.toolbar.xtype) {
52771 this.toolbar.container = this.getView().getHeaderPanel(true);
52772 this.toolbar = new Roo.Toolbar(this.toolbar);
52774 if (this.footer && this.footer.xtype) {
52775 this.footer.dataSource = this.getDataSource();
52776 this.footer.container = this.getView().getFooterPanel(true);
52777 this.footer = Roo.factory(this.footer, Roo);
52779 if (this.dropTarget && this.dropTarget.xtype) {
52780 delete this.dropTarget.xtype;
52781 this.dropTarget = new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
52785 this.rendered = true;
52786 this.fireEvent('render', this);
52791 * Reconfigures the grid to use a different Store and Column Model.
52792 * The View will be bound to the new objects and refreshed.
52793 * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
52794 * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
52796 reconfigure : function(dataSource, colModel){
52798 this.loadMask.destroy();
52799 this.loadMask = new Roo.LoadMask(this.container,
52800 Roo.apply({store:dataSource}, this.loadMask));
52802 this.view.bind(dataSource, colModel);
52803 this.dataSource = dataSource;
52804 this.colModel = colModel;
52805 this.view.refresh(true);
52809 onKeyDown : function(e){
52810 this.fireEvent("keydown", e);
52814 * Destroy this grid.
52815 * @param {Boolean} removeEl True to remove the element
52817 destroy : function(removeEl, keepListeners){
52819 this.loadMask.destroy();
52821 var c = this.container;
52822 c.removeAllListeners();
52823 this.view.destroy();
52824 this.colModel.purgeListeners();
52825 if(!keepListeners){
52826 this.purgeListeners();
52829 if(removeEl === true){
52835 processEvent : function(name, e){
52836 // does this fire select???
52837 //Roo.log('grid:processEvent ' + name);
52839 if (name != 'touchstart' ) {
52840 this.fireEvent(name, e);
52843 var t = e.getTarget();
52845 var header = v.findHeaderIndex(t);
52846 if(header !== false){
52847 var ename = name == 'touchstart' ? 'click' : name;
52849 this.fireEvent("header" + ename, this, header, e);
52851 var row = v.findRowIndex(t);
52852 var cell = v.findCellIndex(t);
52853 if (name == 'touchstart') {
52854 // first touch is always a click.
52855 // hopefull this happens after selection is updated.?
52858 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
52859 var cs = this.selModel.getSelectedCell();
52860 if (row == cs[0] && cell == cs[1]){
52864 if (typeof(this.selModel.getSelections) != 'undefined') {
52865 var cs = this.selModel.getSelections();
52866 var ds = this.dataSource;
52867 if (cs.length == 1 && ds.getAt(row) == cs[0]){
52878 this.fireEvent("row" + name, this, row, e);
52879 if(cell !== false){
52880 this.fireEvent("cell" + name, this, row, cell, e);
52887 onClick : function(e){
52888 this.processEvent("click", e);
52891 onTouchStart : function(e){
52892 this.processEvent("touchstart", e);
52896 onContextMenu : function(e, t){
52897 this.processEvent("contextmenu", e);
52901 onDblClick : function(e){
52902 this.processEvent("dblclick", e);
52906 walkCells : function(row, col, step, fn, scope){
52907 var cm = this.colModel, clen = cm.getColumnCount();
52908 var ds = this.dataSource, rlen = ds.getCount(), first = true;
52920 if(fn.call(scope || this, row, col, cm) === true){
52938 if(fn.call(scope || this, row, col, cm) === true){
52950 getSelections : function(){
52951 return this.selModel.getSelections();
52955 * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
52956 * but if manual update is required this method will initiate it.
52958 autoSize : function(){
52960 this.view.layout();
52961 if(this.view.adjustForScroll){
52962 this.view.adjustForScroll();
52968 * Returns the grid's underlying element.
52969 * @return {Element} The element
52971 getGridEl : function(){
52972 return this.container;
52975 // private for compatibility, overridden by editor grid
52976 stopEditing : function(){},
52979 * Returns the grid's SelectionModel.
52980 * @return {SelectionModel}
52982 getSelectionModel : function(){
52983 if(!this.selModel){
52984 this.selModel = new Roo.grid.RowSelectionModel();
52986 return this.selModel;
52990 * Returns the grid's DataSource.
52991 * @return {DataSource}
52993 getDataSource : function(){
52994 return this.dataSource;
52998 * Returns the grid's ColumnModel.
52999 * @return {ColumnModel}
53001 getColumnModel : function(){
53002 return this.colModel;
53006 * Returns the grid's GridView object.
53007 * @return {GridView}
53009 getView : function(){
53011 this.view = new Roo.grid.GridView(this.viewConfig);
53016 * Called to get grid's drag proxy text, by default returns this.ddText.
53019 getDragDropText : function(){
53020 var count = this.selModel.getCount();
53021 return String.format(this.ddText, count, count == 1 ? '' : 's');
53025 * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
53026 * %0 is replaced with the number of selected rows.
53029 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
53031 * Ext JS Library 1.1.1
53032 * Copyright(c) 2006-2007, Ext JS, LLC.
53034 * Originally Released Under LGPL - original licence link has changed is not relivant.
53037 * <script type="text/javascript">
53040 Roo.grid.AbstractGridView = function(){
53044 "beforerowremoved" : true,
53045 "beforerowsinserted" : true,
53046 "beforerefresh" : true,
53047 "rowremoved" : true,
53048 "rowsinserted" : true,
53049 "rowupdated" : true,
53052 Roo.grid.AbstractGridView.superclass.constructor.call(this);
53055 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
53056 rowClass : "x-grid-row",
53057 cellClass : "x-grid-cell",
53058 tdClass : "x-grid-td",
53059 hdClass : "x-grid-hd",
53060 splitClass : "x-grid-hd-split",
53062 init: function(grid){
53064 var cid = this.grid.getGridEl().id;
53065 this.colSelector = "#" + cid + " ." + this.cellClass + "-";
53066 this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
53067 this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
53068 this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
53071 getColumnRenderers : function(){
53072 var renderers = [];
53073 var cm = this.grid.colModel;
53074 var colCount = cm.getColumnCount();
53075 for(var i = 0; i < colCount; i++){
53076 renderers[i] = cm.getRenderer(i);
53081 getColumnIds : function(){
53083 var cm = this.grid.colModel;
53084 var colCount = cm.getColumnCount();
53085 for(var i = 0; i < colCount; i++){
53086 ids[i] = cm.getColumnId(i);
53091 getDataIndexes : function(){
53092 if(!this.indexMap){
53093 this.indexMap = this.buildIndexMap();
53095 return this.indexMap.colToData;
53098 getColumnIndexByDataIndex : function(dataIndex){
53099 if(!this.indexMap){
53100 this.indexMap = this.buildIndexMap();
53102 return this.indexMap.dataToCol[dataIndex];
53106 * Set a css style for a column dynamically.
53107 * @param {Number} colIndex The index of the column
53108 * @param {String} name The css property name
53109 * @param {String} value The css value
53111 setCSSStyle : function(colIndex, name, value){
53112 var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
53113 Roo.util.CSS.updateRule(selector, name, value);
53116 generateRules : function(cm){
53117 var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
53118 Roo.util.CSS.removeStyleSheet(rulesId);
53119 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53120 var cid = cm.getColumnId(i);
53121 ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
53122 this.tdSelector, cid, " {\n}\n",
53123 this.hdSelector, cid, " {\n}\n",
53124 this.splitSelector, cid, " {\n}\n");
53126 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
53130 * Ext JS Library 1.1.1
53131 * Copyright(c) 2006-2007, Ext JS, LLC.
53133 * Originally Released Under LGPL - original licence link has changed is not relivant.
53136 * <script type="text/javascript">
53140 // This is a support class used internally by the Grid components
53141 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
53143 this.view = grid.getView();
53144 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
53145 Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
53147 this.setHandleElId(Roo.id(hd));
53148 this.setOuterHandleElId(Roo.id(hd2));
53150 this.scroll = false;
53152 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
53154 getDragData : function(e){
53155 var t = Roo.lib.Event.getTarget(e);
53156 var h = this.view.findHeaderCell(t);
53158 return {ddel: h.firstChild, header:h};
53163 onInitDrag : function(e){
53164 this.view.headersDisabled = true;
53165 var clone = this.dragData.ddel.cloneNode(true);
53166 clone.id = Roo.id();
53167 clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
53168 this.proxy.update(clone);
53172 afterValidDrop : function(){
53174 setTimeout(function(){
53175 v.headersDisabled = false;
53179 afterInvalidDrop : function(){
53181 setTimeout(function(){
53182 v.headersDisabled = false;
53188 * Ext JS Library 1.1.1
53189 * Copyright(c) 2006-2007, Ext JS, LLC.
53191 * Originally Released Under LGPL - original licence link has changed is not relivant.
53194 * <script type="text/javascript">
53197 // This is a support class used internally by the Grid components
53198 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
53200 this.view = grid.getView();
53201 // split the proxies so they don't interfere with mouse events
53202 this.proxyTop = Roo.DomHelper.append(document.body, {
53203 cls:"col-move-top", html:" "
53205 this.proxyBottom = Roo.DomHelper.append(document.body, {
53206 cls:"col-move-bottom", html:" "
53208 this.proxyTop.hide = this.proxyBottom.hide = function(){
53209 this.setLeftTop(-100,-100);
53210 this.setStyle("visibility", "hidden");
53212 this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
53213 // temporarily disabled
53214 //Roo.dd.ScrollManager.register(this.view.scroller.dom);
53215 Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
53217 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
53218 proxyOffsets : [-4, -9],
53219 fly: Roo.Element.fly,
53221 getTargetFromEvent : function(e){
53222 var t = Roo.lib.Event.getTarget(e);
53223 var cindex = this.view.findCellIndex(t);
53224 if(cindex !== false){
53225 return this.view.getHeaderCell(cindex);
53230 nextVisible : function(h){
53231 var v = this.view, cm = this.grid.colModel;
53234 if(!cm.isHidden(v.getCellIndex(h))){
53242 prevVisible : function(h){
53243 var v = this.view, cm = this.grid.colModel;
53246 if(!cm.isHidden(v.getCellIndex(h))){
53254 positionIndicator : function(h, n, e){
53255 var x = Roo.lib.Event.getPageX(e);
53256 var r = Roo.lib.Dom.getRegion(n.firstChild);
53257 var px, pt, py = r.top + this.proxyOffsets[1];
53258 if((r.right - x) <= (r.right-r.left)/2){
53259 px = r.right+this.view.borderWidth;
53265 var oldIndex = this.view.getCellIndex(h);
53266 var newIndex = this.view.getCellIndex(n);
53268 if(this.grid.colModel.isFixed(newIndex)){
53272 var locked = this.grid.colModel.isLocked(newIndex);
53277 if(oldIndex < newIndex){
53280 if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
53283 px += this.proxyOffsets[0];
53284 this.proxyTop.setLeftTop(px, py);
53285 this.proxyTop.show();
53286 if(!this.bottomOffset){
53287 this.bottomOffset = this.view.mainHd.getHeight();
53289 this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
53290 this.proxyBottom.show();
53294 onNodeEnter : function(n, dd, e, data){
53295 if(data.header != n){
53296 this.positionIndicator(data.header, n, e);
53300 onNodeOver : function(n, dd, e, data){
53301 var result = false;
53302 if(data.header != n){
53303 result = this.positionIndicator(data.header, n, e);
53306 this.proxyTop.hide();
53307 this.proxyBottom.hide();
53309 return result ? this.dropAllowed : this.dropNotAllowed;
53312 onNodeOut : function(n, dd, e, data){
53313 this.proxyTop.hide();
53314 this.proxyBottom.hide();
53317 onNodeDrop : function(n, dd, e, data){
53318 var h = data.header;
53320 var cm = this.grid.colModel;
53321 var x = Roo.lib.Event.getPageX(e);
53322 var r = Roo.lib.Dom.getRegion(n.firstChild);
53323 var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
53324 var oldIndex = this.view.getCellIndex(h);
53325 var newIndex = this.view.getCellIndex(n);
53326 var locked = cm.isLocked(newIndex);
53330 if(oldIndex < newIndex){
53333 if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
53336 cm.setLocked(oldIndex, locked, true);
53337 cm.moveColumn(oldIndex, newIndex);
53338 this.grid.fireEvent("columnmove", oldIndex, newIndex);
53346 * Ext JS Library 1.1.1
53347 * Copyright(c) 2006-2007, Ext JS, LLC.
53349 * Originally Released Under LGPL - original licence link has changed is not relivant.
53352 * <script type="text/javascript">
53356 * @class Roo.grid.GridView
53357 * @extends Roo.util.Observable
53360 * @param {Object} config
53362 Roo.grid.GridView = function(config){
53363 Roo.grid.GridView.superclass.constructor.call(this);
53366 Roo.apply(this, config);
53369 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
53371 unselectable : 'unselectable="on"',
53372 unselectableCls : 'x-unselectable',
53375 rowClass : "x-grid-row",
53377 cellClass : "x-grid-col",
53379 tdClass : "x-grid-td",
53381 hdClass : "x-grid-hd",
53383 splitClass : "x-grid-split",
53385 sortClasses : ["sort-asc", "sort-desc"],
53387 enableMoveAnim : false,
53391 dh : Roo.DomHelper,
53393 fly : Roo.Element.fly,
53395 css : Roo.util.CSS,
53401 scrollIncrement : 22,
53403 cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
53405 findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
53407 bind : function(ds, cm){
53409 this.ds.un("load", this.onLoad, this);
53410 this.ds.un("datachanged", this.onDataChange, this);
53411 this.ds.un("add", this.onAdd, this);
53412 this.ds.un("remove", this.onRemove, this);
53413 this.ds.un("update", this.onUpdate, this);
53414 this.ds.un("clear", this.onClear, this);
53417 ds.on("load", this.onLoad, this);
53418 ds.on("datachanged", this.onDataChange, this);
53419 ds.on("add", this.onAdd, this);
53420 ds.on("remove", this.onRemove, this);
53421 ds.on("update", this.onUpdate, this);
53422 ds.on("clear", this.onClear, this);
53427 this.cm.un("widthchange", this.onColWidthChange, this);
53428 this.cm.un("headerchange", this.onHeaderChange, this);
53429 this.cm.un("hiddenchange", this.onHiddenChange, this);
53430 this.cm.un("columnmoved", this.onColumnMove, this);
53431 this.cm.un("columnlockchange", this.onColumnLock, this);
53434 this.generateRules(cm);
53435 cm.on("widthchange", this.onColWidthChange, this);
53436 cm.on("headerchange", this.onHeaderChange, this);
53437 cm.on("hiddenchange", this.onHiddenChange, this);
53438 cm.on("columnmoved", this.onColumnMove, this);
53439 cm.on("columnlockchange", this.onColumnLock, this);
53444 init: function(grid){
53445 Roo.grid.GridView.superclass.init.call(this, grid);
53447 this.bind(grid.dataSource, grid.colModel);
53449 grid.on("headerclick", this.handleHeaderClick, this);
53451 if(grid.trackMouseOver){
53452 grid.on("mouseover", this.onRowOver, this);
53453 grid.on("mouseout", this.onRowOut, this);
53455 grid.cancelTextSelection = function(){};
53456 this.gridId = grid.id;
53458 var tpls = this.templates || {};
53461 tpls.master = new Roo.Template(
53462 '<div class="x-grid" hidefocus="true">',
53463 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
53464 '<div class="x-grid-topbar"></div>',
53465 '<div class="x-grid-scroller"><div></div></div>',
53466 '<div class="x-grid-locked">',
53467 '<div class="x-grid-header">{lockedHeader}</div>',
53468 '<div class="x-grid-body">{lockedBody}</div>',
53470 '<div class="x-grid-viewport">',
53471 '<div class="x-grid-header">{header}</div>',
53472 '<div class="x-grid-body">{body}</div>',
53474 '<div class="x-grid-bottombar"></div>',
53476 '<div class="x-grid-resize-proxy"> </div>',
53479 tpls.master.disableformats = true;
53483 tpls.header = new Roo.Template(
53484 '<table border="0" cellspacing="0" cellpadding="0">',
53485 '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
53488 tpls.header.disableformats = true;
53490 tpls.header.compile();
53493 tpls.hcell = new Roo.Template(
53494 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
53495 '<div class="x-grid-hd-text ' + this.unselectableCls + '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
53498 tpls.hcell.disableFormats = true;
53500 tpls.hcell.compile();
53503 tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
53504 this.unselectableCls + '" ' + this.unselectable +'> </div>');
53505 tpls.hsplit.disableFormats = true;
53507 tpls.hsplit.compile();
53510 tpls.body = new Roo.Template(
53511 '<table border="0" cellspacing="0" cellpadding="0">',
53512 "<tbody>{rows}</tbody>",
53515 tpls.body.disableFormats = true;
53517 tpls.body.compile();
53520 tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
53521 tpls.row.disableFormats = true;
53523 tpls.row.compile();
53526 tpls.cell = new Roo.Template(
53527 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
53528 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
53529 this.unselectableCls + '" ' + this.unselectable +'" {attr}>{value}</div></div>',
53532 tpls.cell.disableFormats = true;
53534 tpls.cell.compile();
53536 this.templates = tpls;
53539 // remap these for backwards compat
53540 onColWidthChange : function(){
53541 this.updateColumns.apply(this, arguments);
53543 onHeaderChange : function(){
53544 this.updateHeaders.apply(this, arguments);
53546 onHiddenChange : function(){
53547 this.handleHiddenChange.apply(this, arguments);
53549 onColumnMove : function(){
53550 this.handleColumnMove.apply(this, arguments);
53552 onColumnLock : function(){
53553 this.handleLockChange.apply(this, arguments);
53556 onDataChange : function(){
53558 this.updateHeaderSortState();
53561 onClear : function(){
53565 onUpdate : function(ds, record){
53566 this.refreshRow(record);
53569 refreshRow : function(record){
53570 var ds = this.ds, index;
53571 if(typeof record == 'number'){
53573 record = ds.getAt(index);
53575 index = ds.indexOf(record);
53577 this.insertRows(ds, index, index, true);
53578 this.onRemove(ds, record, index+1, true);
53579 this.syncRowHeights(index, index);
53581 this.fireEvent("rowupdated", this, index, record);
53584 onAdd : function(ds, records, index){
53585 this.insertRows(ds, index, index + (records.length-1));
53588 onRemove : function(ds, record, index, isUpdate){
53589 if(isUpdate !== true){
53590 this.fireEvent("beforerowremoved", this, index, record);
53592 var bt = this.getBodyTable(), lt = this.getLockedTable();
53593 if(bt.rows[index]){
53594 bt.firstChild.removeChild(bt.rows[index]);
53596 if(lt.rows[index]){
53597 lt.firstChild.removeChild(lt.rows[index]);
53599 if(isUpdate !== true){
53600 this.stripeRows(index);
53601 this.syncRowHeights(index, index);
53603 this.fireEvent("rowremoved", this, index, record);
53607 onLoad : function(){
53608 this.scrollToTop();
53612 * Scrolls the grid to the top
53614 scrollToTop : function(){
53616 this.scroller.dom.scrollTop = 0;
53622 * Gets a panel in the header of the grid that can be used for toolbars etc.
53623 * After modifying the contents of this panel a call to grid.autoSize() may be
53624 * required to register any changes in size.
53625 * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
53626 * @return Roo.Element
53628 getHeaderPanel : function(doShow){
53630 this.headerPanel.show();
53632 return this.headerPanel;
53636 * Gets a panel in the footer of the grid that can be used for toolbars etc.
53637 * After modifying the contents of this panel a call to grid.autoSize() may be
53638 * required to register any changes in size.
53639 * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
53640 * @return Roo.Element
53642 getFooterPanel : function(doShow){
53644 this.footerPanel.show();
53646 return this.footerPanel;
53649 initElements : function(){
53650 var E = Roo.Element;
53651 var el = this.grid.getGridEl().dom.firstChild;
53652 var cs = el.childNodes;
53654 this.el = new E(el);
53656 this.focusEl = new E(el.firstChild);
53657 this.focusEl.swallowEvent("click", true);
53659 this.headerPanel = new E(cs[1]);
53660 this.headerPanel.enableDisplayMode("block");
53662 this.scroller = new E(cs[2]);
53663 this.scrollSizer = new E(this.scroller.dom.firstChild);
53665 this.lockedWrap = new E(cs[3]);
53666 this.lockedHd = new E(this.lockedWrap.dom.firstChild);
53667 this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
53669 this.mainWrap = new E(cs[4]);
53670 this.mainHd = new E(this.mainWrap.dom.firstChild);
53671 this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
53673 this.footerPanel = new E(cs[5]);
53674 this.footerPanel.enableDisplayMode("block");
53676 this.resizeProxy = new E(cs[6]);
53678 this.headerSelector = String.format(
53679 '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
53680 this.lockedHd.id, this.mainHd.id
53683 this.splitterSelector = String.format(
53684 '#{0} div.x-grid-split, #{1} div.x-grid-split',
53685 this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
53688 idToCssName : function(s)
53690 return s.replace(/[^a-z0-9]+/ig, '-');
53693 getHeaderCell : function(index){
53694 return Roo.DomQuery.select(this.headerSelector)[index];
53697 getHeaderCellMeasure : function(index){
53698 return this.getHeaderCell(index).firstChild;
53701 getHeaderCellText : function(index){
53702 return this.getHeaderCell(index).firstChild.firstChild;
53705 getLockedTable : function(){
53706 return this.lockedBody.dom.firstChild;
53709 getBodyTable : function(){
53710 return this.mainBody.dom.firstChild;
53713 getLockedRow : function(index){
53714 return this.getLockedTable().rows[index];
53717 getRow : function(index){
53718 return this.getBodyTable().rows[index];
53721 getRowComposite : function(index){
53723 this.rowEl = new Roo.CompositeElementLite();
53725 var els = [], lrow, mrow;
53726 if(lrow = this.getLockedRow(index)){
53729 if(mrow = this.getRow(index)){
53732 this.rowEl.elements = els;
53736 * Gets the 'td' of the cell
53738 * @param {Integer} rowIndex row to select
53739 * @param {Integer} colIndex column to select
53743 getCell : function(rowIndex, colIndex){
53744 var locked = this.cm.getLockedCount();
53746 if(colIndex < locked){
53747 source = this.lockedBody.dom.firstChild;
53749 source = this.mainBody.dom.firstChild;
53750 colIndex -= locked;
53752 return source.rows[rowIndex].childNodes[colIndex];
53755 getCellText : function(rowIndex, colIndex){
53756 return this.getCell(rowIndex, colIndex).firstChild.firstChild;
53759 getCellBox : function(cell){
53760 var b = this.fly(cell).getBox();
53761 if(Roo.isOpera){ // opera fails to report the Y
53762 b.y = cell.offsetTop + this.mainBody.getY();
53767 getCellIndex : function(cell){
53768 var id = String(cell.className).match(this.cellRE);
53770 return parseInt(id[1], 10);
53775 findHeaderIndex : function(n){
53776 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
53777 return r ? this.getCellIndex(r) : false;
53780 findHeaderCell : function(n){
53781 var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
53782 return r ? r : false;
53785 findRowIndex : function(n){
53789 var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
53790 return r ? r.rowIndex : false;
53793 findCellIndex : function(node){
53794 var stop = this.el.dom;
53795 while(node && node != stop){
53796 if(this.findRE.test(node.className)){
53797 return this.getCellIndex(node);
53799 node = node.parentNode;
53804 getColumnId : function(index){
53805 return this.cm.getColumnId(index);
53808 getSplitters : function()
53810 if(this.splitterSelector){
53811 return Roo.DomQuery.select(this.splitterSelector);
53817 getSplitter : function(index){
53818 return this.getSplitters()[index];
53821 onRowOver : function(e, t){
53823 if((row = this.findRowIndex(t)) !== false){
53824 this.getRowComposite(row).addClass("x-grid-row-over");
53828 onRowOut : function(e, t){
53830 if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
53831 this.getRowComposite(row).removeClass("x-grid-row-over");
53835 renderHeaders : function(){
53837 var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
53838 var cb = [], lb = [], sb = [], lsb = [], p = {};
53839 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53840 p.cellId = "x-grid-hd-0-" + i;
53841 p.splitId = "x-grid-csplit-0-" + i;
53842 p.id = cm.getColumnId(i);
53843 p.title = cm.getColumnTooltip(i) || "";
53844 p.value = cm.getColumnHeader(i) || "";
53845 p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
53846 if(!cm.isLocked(i)){
53847 cb[cb.length] = ct.apply(p);
53848 sb[sb.length] = st.apply(p);
53850 lb[lb.length] = ct.apply(p);
53851 lsb[lsb.length] = st.apply(p);
53854 return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
53855 ht.apply({cells: cb.join(""), splits:sb.join("")})];
53858 updateHeaders : function(){
53859 var html = this.renderHeaders();
53860 this.lockedHd.update(html[0]);
53861 this.mainHd.update(html[1]);
53865 * Focuses the specified row.
53866 * @param {Number} row The row index
53868 focusRow : function(row)
53870 //Roo.log('GridView.focusRow');
53871 var x = this.scroller.dom.scrollLeft;
53872 this.focusCell(row, 0, false);
53873 this.scroller.dom.scrollLeft = x;
53877 * Focuses the specified cell.
53878 * @param {Number} row The row index
53879 * @param {Number} col The column index
53880 * @param {Boolean} hscroll false to disable horizontal scrolling
53882 focusCell : function(row, col, hscroll)
53884 //Roo.log('GridView.focusCell');
53885 var el = this.ensureVisible(row, col, hscroll);
53886 this.focusEl.alignTo(el, "tl-tl");
53888 this.focusEl.focus();
53890 this.focusEl.focus.defer(1, this.focusEl);
53895 * Scrolls the specified cell into view
53896 * @param {Number} row The row index
53897 * @param {Number} col The column index
53898 * @param {Boolean} hscroll false to disable horizontal scrolling
53900 ensureVisible : function(row, col, hscroll)
53902 //Roo.log('GridView.ensureVisible,' + row + ',' + col);
53903 //return null; //disable for testing.
53904 if(typeof row != "number"){
53905 row = row.rowIndex;
53907 if(row < 0 && row >= this.ds.getCount()){
53910 col = (col !== undefined ? col : 0);
53911 var cm = this.grid.colModel;
53912 while(cm.isHidden(col)){
53916 var el = this.getCell(row, col);
53920 var c = this.scroller.dom;
53922 var ctop = parseInt(el.offsetTop, 10);
53923 var cleft = parseInt(el.offsetLeft, 10);
53924 var cbot = ctop + el.offsetHeight;
53925 var cright = cleft + el.offsetWidth;
53927 var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
53928 var stop = parseInt(c.scrollTop, 10);
53929 var sleft = parseInt(c.scrollLeft, 10);
53930 var sbot = stop + ch;
53931 var sright = sleft + c.clientWidth;
53933 Roo.log('GridView.ensureVisible:' +
53935 ' c.clientHeight:' + c.clientHeight +
53936 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
53944 c.scrollTop = ctop;
53945 //Roo.log("set scrolltop to ctop DISABLE?");
53946 }else if(cbot > sbot){
53947 //Roo.log("set scrolltop to cbot-ch");
53948 c.scrollTop = cbot-ch;
53951 if(hscroll !== false){
53953 c.scrollLeft = cleft;
53954 }else if(cright > sright){
53955 c.scrollLeft = cright-c.clientWidth;
53962 updateColumns : function(){
53963 this.grid.stopEditing();
53964 var cm = this.grid.colModel, colIds = this.getColumnIds();
53965 //var totalWidth = cm.getTotalWidth();
53967 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53968 //if(cm.isHidden(i)) continue;
53969 var w = cm.getColumnWidth(i);
53970 this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
53971 this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
53973 this.updateSplitters();
53976 generateRules : function(cm){
53977 var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
53978 Roo.util.CSS.removeStyleSheet(rulesId);
53979 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
53980 var cid = cm.getColumnId(i);
53982 if(cm.config[i].align){
53983 align = 'text-align:'+cm.config[i].align+';';
53986 if(cm.isHidden(i)){
53987 hidden = 'display:none;';
53989 var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
53991 this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
53992 this.hdSelector, cid, " {\n", align, width, "}\n",
53993 this.tdSelector, cid, " {\n",hidden,"\n}\n",
53994 this.splitSelector, cid, " {\n", hidden , "\n}\n");
53996 return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
53999 updateSplitters : function(){
54000 var cm = this.cm, s = this.getSplitters();
54001 if(s){ // splitters not created yet
54002 var pos = 0, locked = true;
54003 for(var i = 0, len = cm.getColumnCount(); i < len; i++){
54004 if(cm.isHidden(i)) continue;
54005 var w = cm.getColumnWidth(i); // make sure it's a number
54006 if(!cm.isLocked(i) && locked){
54011 s[i].style.left = (pos-this.splitOffset) + "px";
54016 handleHiddenChange : function(colModel, colIndex, hidden){
54018 this.hideColumn(colIndex);
54020 this.unhideColumn(colIndex);
54024 hideColumn : function(colIndex){
54025 var cid = this.getColumnId(colIndex);
54026 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
54027 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
54029 this.updateHeaders();
54031 this.updateSplitters();
54035 unhideColumn : function(colIndex){
54036 var cid = this.getColumnId(colIndex);
54037 this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
54038 this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
54041 this.updateHeaders();
54043 this.updateSplitters();
54047 insertRows : function(dm, firstRow, lastRow, isUpdate){
54048 if(firstRow == 0 && lastRow == dm.getCount()-1){
54052 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
54054 var s = this.getScrollState();
54055 var markup = this.renderRows(firstRow, lastRow);
54056 this.bufferRows(markup[0], this.getLockedTable(), firstRow);
54057 this.bufferRows(markup[1], this.getBodyTable(), firstRow);
54058 this.restoreScroll(s);
54060 this.fireEvent("rowsinserted", this, firstRow, lastRow);
54061 this.syncRowHeights(firstRow, lastRow);
54062 this.stripeRows(firstRow);
54068 bufferRows : function(markup, target, index){
54069 var before = null, trows = target.rows, tbody = target.tBodies[0];
54070 if(index < trows.length){
54071 before = trows[index];
54073 var b = document.createElement("div");
54074 b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
54075 var rows = b.firstChild.rows;
54076 for(var i = 0, len = rows.length; i < len; i++){
54078 tbody.insertBefore(rows[0], before);
54080 tbody.appendChild(rows[0]);
54087 deleteRows : function(dm, firstRow, lastRow){
54088 if(dm.getRowCount()<1){
54089 this.fireEvent("beforerefresh", this);
54090 this.mainBody.update("");
54091 this.lockedBody.update("");
54092 this.fireEvent("refresh", this);
54094 this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
54095 var bt = this.getBodyTable();
54096 var tbody = bt.firstChild;
54097 var rows = bt.rows;
54098 for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
54099 tbody.removeChild(rows[firstRow]);
54101 this.stripeRows(firstRow);
54102 this.fireEvent("rowsdeleted", this, firstRow, lastRow);
54106 updateRows : function(dataSource, firstRow, lastRow){
54107 var s = this.getScrollState();
54109 this.restoreScroll(s);
54112 handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
54116 this.updateHeaderSortState();
54119 getScrollState : function(){
54121 var sb = this.scroller.dom;
54122 return {left: sb.scrollLeft, top: sb.scrollTop};
54125 stripeRows : function(startRow){
54126 if(!this.grid.stripeRows || this.ds.getCount() < 1){
54129 startRow = startRow || 0;
54130 var rows = this.getBodyTable().rows;
54131 var lrows = this.getLockedTable().rows;
54132 var cls = ' x-grid-row-alt ';
54133 for(var i = startRow, len = rows.length; i < len; i++){
54134 var row = rows[i], lrow = lrows[i];
54135 var isAlt = ((i+1) % 2 == 0);
54136 var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
54137 if(isAlt == hasAlt){
54141 row.className += " x-grid-row-alt";
54143 row.className = row.className.replace("x-grid-row-alt", "");
54146 lrow.className = row.className;
54151 restoreScroll : function(state){
54152 //Roo.log('GridView.restoreScroll');
54153 var sb = this.scroller.dom;
54154 sb.scrollLeft = state.left;
54155 sb.scrollTop = state.top;
54159 syncScroll : function(){
54160 //Roo.log('GridView.syncScroll');
54161 var sb = this.scroller.dom;
54162 var sh = this.mainHd.dom;
54163 var bs = this.mainBody.dom;
54164 var lv = this.lockedBody.dom;
54165 sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
54166 lv.scrollTop = bs.scrollTop = sb.scrollTop;
54169 handleScroll : function(e){
54171 var sb = this.scroller.dom;
54172 this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
54176 handleWheel : function(e){
54177 var d = e.getWheelDelta();
54178 this.scroller.dom.scrollTop -= d*22;
54179 // set this here to prevent jumpy scrolling on large tables
54180 this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
54184 renderRows : function(startRow, endRow){
54185 // pull in all the crap needed to render rows
54186 var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
54187 var colCount = cm.getColumnCount();
54189 if(ds.getCount() < 1){
54193 // build a map for all the columns
54195 for(var i = 0; i < colCount; i++){
54196 var name = cm.getDataIndex(i);
54198 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
54199 renderer : cm.getRenderer(i),
54200 id : cm.getColumnId(i),
54201 locked : cm.isLocked(i)
54205 startRow = startRow || 0;
54206 endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
54208 // records to render
54209 var rs = ds.getRange(startRow, endRow);
54211 return this.doRender(cs, rs, ds, startRow, colCount, stripe);
54214 // As much as I hate to duplicate code, this was branched because FireFox really hates
54215 // [].join("") on strings. The performance difference was substantial enough to
54216 // branch this function
54217 doRender : Roo.isGecko ?
54218 function(cs, rs, ds, startRow, colCount, stripe){
54219 var ts = this.templates, ct = ts.cell, rt = ts.row;
54221 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
54223 var hasListener = this.grid.hasListener('rowclass');
54225 for(var j = 0, len = rs.length; j < len; j++){
54226 r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
54227 for(var i = 0; i < colCount; i++){
54229 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
54231 p.css = p.attr = "";
54232 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
54233 if(p.value == undefined || p.value === "") p.value = " ";
54234 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
54235 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
54237 var markup = ct.apply(p);
54245 if(stripe && ((rowIndex+1) % 2 == 0)){
54246 alt.push("x-grid-row-alt")
54249 alt.push( " x-grid-dirty-row");
54252 if(this.getRowClass){
54253 alt.push(this.getRowClass(r, rowIndex));
54259 rowIndex : rowIndex,
54262 this.grid.fireEvent('rowclass', this, rowcfg);
54263 alt.push(rowcfg.rowClass);
54265 rp.alt = alt.join(" ");
54266 lbuf+= rt.apply(rp);
54268 buf+= rt.apply(rp);
54270 return [lbuf, buf];
54272 function(cs, rs, ds, startRow, colCount, stripe){
54273 var ts = this.templates, ct = ts.cell, rt = ts.row;
54275 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
54276 var hasListener = this.grid.hasListener('rowclass');
54279 for(var j = 0, len = rs.length; j < len; j++){
54280 r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
54281 for(var i = 0; i < colCount; i++){
54283 p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
54285 p.css = p.attr = "";
54286 p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
54287 if(p.value == undefined || p.value === "") p.value = " ";
54288 if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
54289 p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
54292 var markup = ct.apply(p);
54294 cb[cb.length] = markup;
54296 lcb[lcb.length] = markup;
54300 if(stripe && ((rowIndex+1) % 2 == 0)){
54301 alt.push( "x-grid-row-alt");
54304 alt.push(" x-grid-dirty-row");
54307 if(this.getRowClass){
54308 alt.push( this.getRowClass(r, rowIndex));
54314 rowIndex : rowIndex,
54317 this.grid.fireEvent('rowclass', this, rowcfg);
54318 alt.push(rowcfg.rowClass);
54320 rp.alt = alt.join(" ");
54321 rp.cells = lcb.join("");
54322 lbuf[lbuf.length] = rt.apply(rp);
54323 rp.cells = cb.join("");
54324 buf[buf.length] = rt.apply(rp);
54326 return [lbuf.join(""), buf.join("")];
54329 renderBody : function(){
54330 var markup = this.renderRows();
54331 var bt = this.templates.body;
54332 return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
54336 * Refreshes the grid
54337 * @param {Boolean} headersToo
54339 refresh : function(headersToo){
54340 this.fireEvent("beforerefresh", this);
54341 this.grid.stopEditing();
54342 var result = this.renderBody();
54343 this.lockedBody.update(result[0]);
54344 this.mainBody.update(result[1]);
54345 if(headersToo === true){
54346 this.updateHeaders();
54347 this.updateColumns();
54348 this.updateSplitters();
54349 this.updateHeaderSortState();
54351 this.syncRowHeights();
54353 this.fireEvent("refresh", this);
54356 handleColumnMove : function(cm, oldIndex, newIndex){
54357 this.indexMap = null;
54358 var s = this.getScrollState();
54359 this.refresh(true);
54360 this.restoreScroll(s);
54361 this.afterMove(newIndex);
54364 afterMove : function(colIndex){
54365 if(this.enableMoveAnim && Roo.enableFx){
54366 this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
54368 // if multisort - fix sortOrder, and reload..
54369 if (this.grid.dataSource.multiSort) {
54370 // the we can call sort again..
54371 var dm = this.grid.dataSource;
54372 var cm = this.grid.colModel;
54374 for(var i = 0; i < cm.config.length; i++ ) {
54376 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
54377 continue; // dont' bother, it's not in sort list or being set.
54380 so.push(cm.config[i].dataIndex);
54383 dm.load(dm.lastOptions);
54390 updateCell : function(dm, rowIndex, dataIndex){
54391 var colIndex = this.getColumnIndexByDataIndex(dataIndex);
54392 if(typeof colIndex == "undefined"){ // not present in grid
54395 var cm = this.grid.colModel;
54396 var cell = this.getCell(rowIndex, colIndex);
54397 var cellText = this.getCellText(rowIndex, colIndex);
54400 cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
54401 id : cm.getColumnId(colIndex),
54402 css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
54404 var renderer = cm.getRenderer(colIndex);
54405 var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
54406 if(typeof val == "undefined" || val === "") val = " ";
54407 cellText.innerHTML = val;
54408 cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
54409 this.syncRowHeights(rowIndex, rowIndex);
54412 calcColumnWidth : function(colIndex, maxRowsToMeasure){
54414 if(this.grid.autoSizeHeaders){
54415 var h = this.getHeaderCellMeasure(colIndex);
54416 maxWidth = Math.max(maxWidth, h.scrollWidth);
54419 if(this.cm.isLocked(colIndex)){
54420 tb = this.getLockedTable();
54423 tb = this.getBodyTable();
54424 index = colIndex - this.cm.getLockedCount();
54427 var rows = tb.rows;
54428 var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
54429 for(var i = 0; i < stopIndex; i++){
54430 var cell = rows[i].childNodes[index].firstChild;
54431 maxWidth = Math.max(maxWidth, cell.scrollWidth);
54434 return maxWidth + /*margin for error in IE*/ 5;
54437 * Autofit a column to its content.
54438 * @param {Number} colIndex
54439 * @param {Boolean} forceMinSize true to force the column to go smaller if possible
54441 autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
54442 if(this.cm.isHidden(colIndex)){
54443 return; // can't calc a hidden column
54446 var cid = this.cm.getColumnId(colIndex);
54447 this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
54448 if(this.grid.autoSizeHeaders){
54449 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
54452 var newWidth = this.calcColumnWidth(colIndex);
54453 this.cm.setColumnWidth(colIndex,
54454 Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
54455 if(!suppressEvent){
54456 this.grid.fireEvent("columnresize", colIndex, newWidth);
54461 * Autofits all columns to their content and then expands to fit any extra space in the grid
54463 autoSizeColumns : function(){
54464 var cm = this.grid.colModel;
54465 var colCount = cm.getColumnCount();
54466 for(var i = 0; i < colCount; i++){
54467 this.autoSizeColumn(i, true, true);
54469 if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
54472 this.updateColumns();
54478 * Autofits all columns to the grid's width proportionate with their current size
54479 * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
54481 fitColumns : function(reserveScrollSpace){
54482 var cm = this.grid.colModel;
54483 var colCount = cm.getColumnCount();
54487 for (i = 0; i < colCount; i++){
54488 if(!cm.isHidden(i) && !cm.isFixed(i)){
54489 w = cm.getColumnWidth(i);
54495 var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
54496 if(reserveScrollSpace){
54499 var frac = (avail - cm.getTotalWidth())/width;
54500 while (cols.length){
54503 cm.setColumnWidth(i, Math.floor(w + w*frac), true);
54505 this.updateColumns();
54509 onRowSelect : function(rowIndex){
54510 var row = this.getRowComposite(rowIndex);
54511 row.addClass("x-grid-row-selected");
54514 onRowDeselect : function(rowIndex){
54515 var row = this.getRowComposite(rowIndex);
54516 row.removeClass("x-grid-row-selected");
54519 onCellSelect : function(row, col){
54520 var cell = this.getCell(row, col);
54522 Roo.fly(cell).addClass("x-grid-cell-selected");
54526 onCellDeselect : function(row, col){
54527 var cell = this.getCell(row, col);
54529 Roo.fly(cell).removeClass("x-grid-cell-selected");
54533 updateHeaderSortState : function(){
54535 // sort state can be single { field: xxx, direction : yyy}
54536 // or { xxx=>ASC , yyy : DESC ..... }
54539 if (!this.ds.multiSort) {
54540 var state = this.ds.getSortState();
54544 mstate[state.field] = state.direction;
54545 // FIXME... - this is not used here.. but might be elsewhere..
54546 this.sortState = state;
54549 mstate = this.ds.sortToggle;
54551 //remove existing sort classes..
54553 var sc = this.sortClasses;
54554 var hds = this.el.select(this.headerSelector).removeClass(sc);
54556 for(var f in mstate) {
54558 var sortColumn = this.cm.findColumnIndex(f);
54560 if(sortColumn != -1){
54561 var sortDir = mstate[f];
54562 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
54571 handleHeaderClick : function(g, index,e){
54573 Roo.log("header click");
54576 // touch events on header are handled by context
54577 this.handleHdCtx(g,index,e);
54582 if(this.headersDisabled){
54585 var dm = g.dataSource, cm = g.colModel;
54586 if(!cm.isSortable(index)){
54591 if (dm.multiSort) {
54592 // update the sortOrder
54594 for(var i = 0; i < cm.config.length; i++ ) {
54596 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
54597 continue; // dont' bother, it's not in sort list or being set.
54600 so.push(cm.config[i].dataIndex);
54606 dm.sort(cm.getDataIndex(index));
54610 destroy : function(){
54612 this.colMenu.removeAll();
54613 Roo.menu.MenuMgr.unregister(this.colMenu);
54614 this.colMenu.getEl().remove();
54615 delete this.colMenu;
54618 this.hmenu.removeAll();
54619 Roo.menu.MenuMgr.unregister(this.hmenu);
54620 this.hmenu.getEl().remove();
54623 if(this.grid.enableColumnMove){
54624 var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
54626 for(var dd in dds){
54627 if(!dds[dd].config.isTarget && dds[dd].dragElId){
54628 var elid = dds[dd].dragElId;
54630 Roo.get(elid).remove();
54631 } else if(dds[dd].config.isTarget){
54632 dds[dd].proxyTop.remove();
54633 dds[dd].proxyBottom.remove();
54636 if(Roo.dd.DDM.locationCache[dd]){
54637 delete Roo.dd.DDM.locationCache[dd];
54640 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
54643 Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
54644 this.bind(null, null);
54645 Roo.EventManager.removeResizeListener(this.onWindowResize, this);
54648 handleLockChange : function(){
54649 this.refresh(true);
54652 onDenyColumnLock : function(){
54656 onDenyColumnHide : function(){
54660 handleHdMenuClick : function(item){
54661 var index = this.hdCtxIndex;
54662 var cm = this.cm, ds = this.ds;
54665 ds.sort(cm.getDataIndex(index), "ASC");
54668 ds.sort(cm.getDataIndex(index), "DESC");
54671 var lc = cm.getLockedCount();
54672 if(cm.getColumnCount(true) <= lc+1){
54673 this.onDenyColumnLock();
54677 cm.setLocked(index, true, true);
54678 cm.moveColumn(index, lc);
54679 this.grid.fireEvent("columnmove", index, lc);
54681 cm.setLocked(index, true);
54685 var lc = cm.getLockedCount();
54686 if((lc-1) != index){
54687 cm.setLocked(index, false, true);
54688 cm.moveColumn(index, lc-1);
54689 this.grid.fireEvent("columnmove", index, lc-1);
54691 cm.setLocked(index, false);
54694 case 'wider': // used to expand cols on touch..
54696 var cw = cm.getColumnWidth(index);
54697 cw += (item.id == 'wider' ? 1 : -1) * 50;
54698 cw = Math.max(0, cw);
54699 cw = Math.min(cw,4000);
54700 cm.setColumnWidth(index, cw);
54704 index = cm.getIndexById(item.id.substr(4));
54706 if(item.checked && cm.getColumnCount(true) <= 1){
54707 this.onDenyColumnHide();
54710 cm.setHidden(index, item.checked);
54716 beforeColMenuShow : function(){
54717 var cm = this.cm, colCount = cm.getColumnCount();
54718 this.colMenu.removeAll();
54719 for(var i = 0; i < colCount; i++){
54720 this.colMenu.add(new Roo.menu.CheckItem({
54721 id: "col-"+cm.getColumnId(i),
54722 text: cm.getColumnHeader(i),
54723 checked: !cm.isHidden(i),
54729 handleHdCtx : function(g, index, e){
54731 var hd = this.getHeaderCell(index);
54732 this.hdCtxIndex = index;
54733 var ms = this.hmenu.items, cm = this.cm;
54734 ms.get("asc").setDisabled(!cm.isSortable(index));
54735 ms.get("desc").setDisabled(!cm.isSortable(index));
54736 if(this.grid.enableColLock !== false){
54737 ms.get("lock").setDisabled(cm.isLocked(index));
54738 ms.get("unlock").setDisabled(!cm.isLocked(index));
54740 this.hmenu.show(hd, "tl-bl");
54743 handleHdOver : function(e){
54744 var hd = this.findHeaderCell(e.getTarget());
54745 if(hd && !this.headersDisabled){
54746 if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
54747 this.fly(hd).addClass("x-grid-hd-over");
54752 handleHdOut : function(e){
54753 var hd = this.findHeaderCell(e.getTarget());
54755 this.fly(hd).removeClass("x-grid-hd-over");
54759 handleSplitDblClick : function(e, t){
54760 var i = this.getCellIndex(t);
54761 if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
54762 this.autoSizeColumn(i, true);
54767 render : function(){
54770 var colCount = cm.getColumnCount();
54772 if(this.grid.monitorWindowResize === true){
54773 Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
54775 var header = this.renderHeaders();
54776 var body = this.templates.body.apply({rows:""});
54777 var html = this.templates.master.apply({
54780 lockedHeader: header[0],
54784 //this.updateColumns();
54786 this.grid.getGridEl().dom.innerHTML = html;
54788 this.initElements();
54790 // a kludge to fix the random scolling effect in webkit
54791 this.el.on("scroll", function() {
54792 this.el.dom.scrollTop=0; // hopefully not recursive..
54795 this.scroller.on("scroll", this.handleScroll, this);
54796 this.lockedBody.on("mousewheel", this.handleWheel, this);
54797 this.mainBody.on("mousewheel", this.handleWheel, this);
54799 this.mainHd.on("mouseover", this.handleHdOver, this);
54800 this.mainHd.on("mouseout", this.handleHdOut, this);
54801 this.mainHd.on("dblclick", this.handleSplitDblClick, this,
54802 {delegate: "."+this.splitClass});
54804 this.lockedHd.on("mouseover", this.handleHdOver, this);
54805 this.lockedHd.on("mouseout", this.handleHdOut, this);
54806 this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
54807 {delegate: "."+this.splitClass});
54809 if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
54810 new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54813 this.updateSplitters();
54815 if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
54816 new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54817 new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
54820 if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
54821 this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
54823 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
54824 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
54826 if(this.grid.enableColLock !== false){
54827 this.hmenu.add('-',
54828 {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
54829 {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
54833 this.hmenu.add('-',
54834 {id:"wider", text: this.columnsWiderText},
54835 {id:"narrow", text: this.columnsNarrowText }
54841 if(this.grid.enableColumnHide !== false){
54843 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
54844 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
54845 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
54847 this.hmenu.add('-',
54848 {id:"columns", text: this.columnsText, menu: this.colMenu}
54851 this.hmenu.on("itemclick", this.handleHdMenuClick, this);
54853 this.grid.on("headercontextmenu", this.handleHdCtx, this);
54856 if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
54857 this.dd = new Roo.grid.GridDragZone(this.grid, {
54858 ddGroup : this.grid.ddGroup || 'GridDD'
54864 for(var i = 0; i < colCount; i++){
54865 if(cm.isHidden(i)){
54866 this.hideColumn(i);
54868 if(cm.config[i].align){
54869 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
54870 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
54874 this.updateHeaderSortState();
54876 this.beforeInitialResize();
54879 // two part rendering gives faster view to the user
54880 this.renderPhase2.defer(1, this);
54883 renderPhase2 : function(){
54884 // render the rows now
54886 if(this.grid.autoSizeColumns){
54887 this.autoSizeColumns();
54891 beforeInitialResize : function(){
54895 onColumnSplitterMoved : function(i, w){
54896 this.userResized = true;
54897 var cm = this.grid.colModel;
54898 cm.setColumnWidth(i, w, true);
54899 var cid = cm.getColumnId(i);
54900 this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
54901 this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
54902 this.updateSplitters();
54904 this.grid.fireEvent("columnresize", i, w);
54907 syncRowHeights : function(startIndex, endIndex){
54908 if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
54909 startIndex = startIndex || 0;
54910 var mrows = this.getBodyTable().rows;
54911 var lrows = this.getLockedTable().rows;
54912 var len = mrows.length-1;
54913 endIndex = Math.min(endIndex || len, len);
54914 for(var i = startIndex; i <= endIndex; i++){
54915 var m = mrows[i], l = lrows[i];
54916 var h = Math.max(m.offsetHeight, l.offsetHeight);
54917 m.style.height = l.style.height = h + "px";
54922 layout : function(initialRender, is2ndPass){
54924 var auto = g.autoHeight;
54925 var scrollOffset = 16;
54926 var c = g.getGridEl(), cm = this.cm,
54927 expandCol = g.autoExpandColumn,
54929 //c.beginMeasure();
54931 if(!c.dom.offsetWidth){ // display:none?
54933 this.lockedWrap.show();
54934 this.mainWrap.show();
54939 var hasLock = this.cm.isLocked(0);
54941 var tbh = this.headerPanel.getHeight();
54942 var bbh = this.footerPanel.getHeight();
54945 var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
54946 var newHeight = ch + c.getBorderWidth("tb");
54948 newHeight = Math.min(g.maxHeight, newHeight);
54950 c.setHeight(newHeight);
54954 c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
54957 var s = this.scroller;
54959 var csize = c.getSize(true);
54961 this.el.setSize(csize.width, csize.height);
54963 this.headerPanel.setWidth(csize.width);
54964 this.footerPanel.setWidth(csize.width);
54966 var hdHeight = this.mainHd.getHeight();
54967 var vw = csize.width;
54968 var vh = csize.height - (tbh + bbh);
54972 var bt = this.getBodyTable();
54973 var ltWidth = hasLock ?
54974 Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
54976 var scrollHeight = bt.offsetHeight;
54977 var scrollWidth = ltWidth + bt.offsetWidth;
54978 var vscroll = false, hscroll = false;
54980 this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
54982 var lw = this.lockedWrap, mw = this.mainWrap;
54983 var lb = this.lockedBody, mb = this.mainBody;
54985 setTimeout(function(){
54986 var t = s.dom.offsetTop;
54987 var w = s.dom.clientWidth,
54988 h = s.dom.clientHeight;
54991 lw.setSize(ltWidth, h);
54993 mw.setLeftTop(ltWidth, t);
54994 mw.setSize(w-ltWidth, h);
54996 lb.setHeight(h-hdHeight);
54997 mb.setHeight(h-hdHeight);
54999 if(is2ndPass !== true && !gv.userResized && expandCol){
55000 // high speed resize without full column calculation
55002 var ci = cm.getIndexById(expandCol);
55004 ci = cm.findColumnIndex(expandCol);
55006 ci = Math.max(0, ci); // make sure it's got at least the first col.
55007 var expandId = cm.getColumnId(ci);
55008 var tw = cm.getTotalWidth(false);
55009 var currentWidth = cm.getColumnWidth(ci);
55010 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
55011 if(currentWidth != cw){
55012 cm.setColumnWidth(ci, cw, true);
55013 gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
55014 gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
55015 gv.updateSplitters();
55016 gv.layout(false, true);
55028 onWindowResize : function(){
55029 if(!this.grid.monitorWindowResize || this.grid.autoHeight){
55035 appendFooter : function(parentEl){
55039 sortAscText : "Sort Ascending",
55040 sortDescText : "Sort Descending",
55041 lockText : "Lock Column",
55042 unlockText : "Unlock Column",
55043 columnsText : "Columns",
55045 columnsWiderText : "Wider",
55046 columnsNarrowText : "Thinner"
55050 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
55051 Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
55052 this.proxy.el.addClass('x-grid3-col-dd');
55055 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
55056 handleMouseDown : function(e){
55060 callHandleMouseDown : function(e){
55061 Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
55066 * Ext JS Library 1.1.1
55067 * Copyright(c) 2006-2007, Ext JS, LLC.
55069 * Originally Released Under LGPL - original licence link has changed is not relivant.
55072 * <script type="text/javascript">
55076 // This is a support class used internally by the Grid components
55077 Roo.grid.SplitDragZone = function(grid, hd, hd2){
55079 this.view = grid.getView();
55080 this.proxy = this.view.resizeProxy;
55081 Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
55082 "gridSplitters" + this.grid.getGridEl().id, {
55083 dragElId : Roo.id(this.proxy.dom), resizeFrame:false
55085 this.setHandleElId(Roo.id(hd));
55086 this.setOuterHandleElId(Roo.id(hd2));
55087 this.scroll = false;
55089 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
55090 fly: Roo.Element.fly,
55092 b4StartDrag : function(x, y){
55093 this.view.headersDisabled = true;
55094 this.proxy.setHeight(this.view.mainWrap.getHeight());
55095 var w = this.cm.getColumnWidth(this.cellIndex);
55096 var minw = Math.max(w-this.grid.minColumnWidth, 0);
55097 this.resetConstraints();
55098 this.setXConstraint(minw, 1000);
55099 this.setYConstraint(0, 0);
55100 this.minX = x - minw;
55101 this.maxX = x + 1000;
55103 Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
55107 handleMouseDown : function(e){
55108 ev = Roo.EventObject.setEvent(e);
55109 var t = this.fly(ev.getTarget());
55110 if(t.hasClass("x-grid-split")){
55111 this.cellIndex = this.view.getCellIndex(t.dom);
55112 this.split = t.dom;
55113 this.cm = this.grid.colModel;
55114 if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
55115 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
55120 endDrag : function(e){
55121 this.view.headersDisabled = false;
55122 var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
55123 var diff = endX - this.startPos;
55124 this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
55127 autoOffset : function(){
55128 this.setDelta(0,0);
55132 * Ext JS Library 1.1.1
55133 * Copyright(c) 2006-2007, Ext JS, LLC.
55135 * Originally Released Under LGPL - original licence link has changed is not relivant.
55138 * <script type="text/javascript">
55142 // This is a support class used internally by the Grid components
55143 Roo.grid.GridDragZone = function(grid, config){
55144 this.view = grid.getView();
55145 Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
55146 if(this.view.lockedBody){
55147 this.setHandleElId(Roo.id(this.view.mainBody.dom));
55148 this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
55150 this.scroll = false;
55152 this.ddel = document.createElement('div');
55153 this.ddel.className = 'x-grid-dd-wrap';
55156 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
55157 ddGroup : "GridDD",
55159 getDragData : function(e){
55160 var t = Roo.lib.Event.getTarget(e);
55161 var rowIndex = this.view.findRowIndex(t);
55162 var sm = this.grid.selModel;
55164 //Roo.log(rowIndex);
55166 if (sm.getSelectedCell) {
55167 // cell selection..
55168 if (!sm.getSelectedCell()) {
55171 if (rowIndex != sm.getSelectedCell()[0]) {
55177 if(rowIndex !== false){
55182 //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
55184 //if(!sm.isSelected(rowIndex) || e.hasModifier()){
55187 if (e.hasModifier()){
55188 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
55191 Roo.log("getDragData");
55196 rowIndex: rowIndex,
55197 selections:sm.getSelections ? sm.getSelections() : (
55198 sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
55205 onInitDrag : function(e){
55206 var data = this.dragData;
55207 this.ddel.innerHTML = this.grid.getDragDropText();
55208 this.proxy.update(this.ddel);
55209 // fire start drag?
55212 afterRepair : function(){
55213 this.dragging = false;
55216 getRepairXY : function(e, data){
55220 onEndDrag : function(data, e){
55224 onValidDrop : function(dd, e, id){
55229 beforeInvalidDrop : function(e, id){
55234 * Ext JS Library 1.1.1
55235 * Copyright(c) 2006-2007, Ext JS, LLC.
55237 * Originally Released Under LGPL - original licence link has changed is not relivant.
55240 * <script type="text/javascript">
55245 * @class Roo.grid.ColumnModel
55246 * @extends Roo.util.Observable
55247 * This is the default implementation of a ColumnModel used by the Grid. It defines
55248 * the columns in the grid.
55251 var colModel = new Roo.grid.ColumnModel([
55252 {header: "Ticker", width: 60, sortable: true, locked: true},
55253 {header: "Company Name", width: 150, sortable: true},
55254 {header: "Market Cap.", width: 100, sortable: true},
55255 {header: "$ Sales", width: 100, sortable: true, renderer: money},
55256 {header: "Employees", width: 100, sortable: true, resizable: false}
55261 * The config options listed for this class are options which may appear in each
55262 * individual column definition.
55263 * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
55265 * @param {Object} config An Array of column config objects. See this class's
55266 * config objects for details.
55268 Roo.grid.ColumnModel = function(config){
55270 * The config passed into the constructor
55272 this.config = config;
55275 // if no id, create one
55276 // if the column does not have a dataIndex mapping,
55277 // map it to the order it is in the config
55278 for(var i = 0, len = config.length; i < len; i++){
55280 if(typeof c.dataIndex == "undefined"){
55283 if(typeof c.renderer == "string"){
55284 c.renderer = Roo.util.Format[c.renderer];
55286 if(typeof c.id == "undefined"){
55289 if(c.editor && c.editor.xtype){
55290 c.editor = Roo.factory(c.editor, Roo.grid);
55292 if(c.editor && c.editor.isFormField){
55293 c.editor = new Roo.grid.GridEditor(c.editor);
55295 this.lookup[c.id] = c;
55299 * The width of columns which have no width specified (defaults to 100)
55302 this.defaultWidth = 100;
55305 * Default sortable of columns which have no sortable specified (defaults to false)
55308 this.defaultSortable = false;
55312 * @event widthchange
55313 * Fires when the width of a column changes.
55314 * @param {ColumnModel} this
55315 * @param {Number} columnIndex The column index
55316 * @param {Number} newWidth The new width
55318 "widthchange": true,
55320 * @event headerchange
55321 * Fires when the text of a header changes.
55322 * @param {ColumnModel} this
55323 * @param {Number} columnIndex The column index
55324 * @param {Number} newText The new header text
55326 "headerchange": true,
55328 * @event hiddenchange
55329 * Fires when a column is hidden or "unhidden".
55330 * @param {ColumnModel} this
55331 * @param {Number} columnIndex The column index
55332 * @param {Boolean} hidden true if hidden, false otherwise
55334 "hiddenchange": true,
55336 * @event columnmoved
55337 * Fires when a column is moved.
55338 * @param {ColumnModel} this
55339 * @param {Number} oldIndex
55340 * @param {Number} newIndex
55342 "columnmoved" : true,
55344 * @event columlockchange
55345 * Fires when a column's locked state is changed
55346 * @param {ColumnModel} this
55347 * @param {Number} colIndex
55348 * @param {Boolean} locked true if locked
55350 "columnlockchange" : true
55352 Roo.grid.ColumnModel.superclass.constructor.call(this);
55354 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
55356 * @cfg {String} header The header text to display in the Grid view.
55359 * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
55360 * {@link Roo.data.Record} definition from which to draw the column's value. If not
55361 * specified, the column's index is used as an index into the Record's data Array.
55364 * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
55365 * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
55368 * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
55369 * Defaults to the value of the {@link #defaultSortable} property.
55370 * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
55373 * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid. Defaults to false.
55376 * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed. Defaults to false.
55379 * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
55382 * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
55385 * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
55386 * given the cell's data value. See {@link #setRenderer}. If not specified, the
55387 * default renderer uses the raw data value. If an object is returned (bootstrap only)
55388 * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
55391 * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor
55394 * @cfg {String} align (Optional) Set the CSS text-align property of the column. Defaults to undefined.
55397 * @cfg {String} cursor (Optional)
55400 * @cfg {String} tooltip (Optional)
55403 * Returns the id of the column at the specified index.
55404 * @param {Number} index The column index
55405 * @return {String} the id
55407 getColumnId : function(index){
55408 return this.config[index].id;
55412 * Returns the column for a specified id.
55413 * @param {String} id The column id
55414 * @return {Object} the column
55416 getColumnById : function(id){
55417 return this.lookup[id];
55422 * Returns the column for a specified dataIndex.
55423 * @param {String} dataIndex The column dataIndex
55424 * @return {Object|Boolean} the column or false if not found
55426 getColumnByDataIndex: function(dataIndex){
55427 var index = this.findColumnIndex(dataIndex);
55428 return index > -1 ? this.config[index] : false;
55432 * Returns the index for a specified column id.
55433 * @param {String} id The column id
55434 * @return {Number} the index, or -1 if not found
55436 getIndexById : function(id){
55437 for(var i = 0, len = this.config.length; i < len; i++){
55438 if(this.config[i].id == id){
55446 * Returns the index for a specified column dataIndex.
55447 * @param {String} dataIndex The column dataIndex
55448 * @return {Number} the index, or -1 if not found
55451 findColumnIndex : function(dataIndex){
55452 for(var i = 0, len = this.config.length; i < len; i++){
55453 if(this.config[i].dataIndex == dataIndex){
55461 moveColumn : function(oldIndex, newIndex){
55462 var c = this.config[oldIndex];
55463 this.config.splice(oldIndex, 1);
55464 this.config.splice(newIndex, 0, c);
55465 this.dataMap = null;
55466 this.fireEvent("columnmoved", this, oldIndex, newIndex);
55469 isLocked : function(colIndex){
55470 return this.config[colIndex].locked === true;
55473 setLocked : function(colIndex, value, suppressEvent){
55474 if(this.isLocked(colIndex) == value){
55477 this.config[colIndex].locked = value;
55478 if(!suppressEvent){
55479 this.fireEvent("columnlockchange", this, colIndex, value);
55483 getTotalLockedWidth : function(){
55484 var totalWidth = 0;
55485 for(var i = 0; i < this.config.length; i++){
55486 if(this.isLocked(i) && !this.isHidden(i)){
55487 this.totalWidth += this.getColumnWidth(i);
55493 getLockedCount : function(){
55494 for(var i = 0, len = this.config.length; i < len; i++){
55495 if(!this.isLocked(i)){
55502 * Returns the number of columns.
55505 getColumnCount : function(visibleOnly){
55506 if(visibleOnly === true){
55508 for(var i = 0, len = this.config.length; i < len; i++){
55509 if(!this.isHidden(i)){
55515 return this.config.length;
55519 * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
55520 * @param {Function} fn
55521 * @param {Object} scope (optional)
55522 * @return {Array} result
55524 getColumnsBy : function(fn, scope){
55526 for(var i = 0, len = this.config.length; i < len; i++){
55527 var c = this.config[i];
55528 if(fn.call(scope||this, c, i) === true){
55536 * Returns true if the specified column is sortable.
55537 * @param {Number} col The column index
55538 * @return {Boolean}
55540 isSortable : function(col){
55541 if(typeof this.config[col].sortable == "undefined"){
55542 return this.defaultSortable;
55544 return this.config[col].sortable;
55548 * Returns the rendering (formatting) function defined for the column.
55549 * @param {Number} col The column index.
55550 * @return {Function} The function used to render the cell. See {@link #setRenderer}.
55552 getRenderer : function(col){
55553 if(!this.config[col].renderer){
55554 return Roo.grid.ColumnModel.defaultRenderer;
55556 return this.config[col].renderer;
55560 * Sets the rendering (formatting) function for a column.
55561 * @param {Number} col The column index
55562 * @param {Function} fn The function to use to process the cell's raw data
55563 * to return HTML markup for the grid view. The render function is called with
55564 * the following parameters:<ul>
55565 * <li>Data value.</li>
55566 * <li>Cell metadata. An object in which you may set the following attributes:<ul>
55567 * <li>css A CSS style string to apply to the table cell.</li>
55568 * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
55569 * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
55570 * <li>Row index</li>
55571 * <li>Column index</li>
55572 * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
55574 setRenderer : function(col, fn){
55575 this.config[col].renderer = fn;
55579 * Returns the width for the specified column.
55580 * @param {Number} col The column index
55583 getColumnWidth : function(col){
55584 return this.config[col].width * 1 || this.defaultWidth;
55588 * Sets the width for a column.
55589 * @param {Number} col The column index
55590 * @param {Number} width The new width
55592 setColumnWidth : function(col, width, suppressEvent){
55593 this.config[col].width = width;
55594 this.totalWidth = null;
55595 if(!suppressEvent){
55596 this.fireEvent("widthchange", this, col, width);
55601 * Returns the total width of all columns.
55602 * @param {Boolean} includeHidden True to include hidden column widths
55605 getTotalWidth : function(includeHidden){
55606 if(!this.totalWidth){
55607 this.totalWidth = 0;
55608 for(var i = 0, len = this.config.length; i < len; i++){
55609 if(includeHidden || !this.isHidden(i)){
55610 this.totalWidth += this.getColumnWidth(i);
55614 return this.totalWidth;
55618 * Returns the header for the specified column.
55619 * @param {Number} col The column index
55622 getColumnHeader : function(col){
55623 return this.config[col].header;
55627 * Sets the header for a column.
55628 * @param {Number} col The column index
55629 * @param {String} header The new header
55631 setColumnHeader : function(col, header){
55632 this.config[col].header = header;
55633 this.fireEvent("headerchange", this, col, header);
55637 * Returns the tooltip for the specified column.
55638 * @param {Number} col The column index
55641 getColumnTooltip : function(col){
55642 return this.config[col].tooltip;
55645 * Sets the tooltip for a column.
55646 * @param {Number} col The column index
55647 * @param {String} tooltip The new tooltip
55649 setColumnTooltip : function(col, tooltip){
55650 this.config[col].tooltip = tooltip;
55654 * Returns the dataIndex for the specified column.
55655 * @param {Number} col The column index
55658 getDataIndex : function(col){
55659 return this.config[col].dataIndex;
55663 * Sets the dataIndex for a column.
55664 * @param {Number} col The column index
55665 * @param {Number} dataIndex The new dataIndex
55667 setDataIndex : function(col, dataIndex){
55668 this.config[col].dataIndex = dataIndex;
55674 * Returns true if the cell is editable.
55675 * @param {Number} colIndex The column index
55676 * @param {Number} rowIndex The row index
55677 * @return {Boolean}
55679 isCellEditable : function(colIndex, rowIndex){
55680 return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
55684 * Returns the editor defined for the cell/column.
55685 * return false or null to disable editing.
55686 * @param {Number} colIndex The column index
55687 * @param {Number} rowIndex The row index
55690 getCellEditor : function(colIndex, rowIndex){
55691 return this.config[colIndex].editor;
55695 * Sets if a column is editable.
55696 * @param {Number} col The column index
55697 * @param {Boolean} editable True if the column is editable
55699 setEditable : function(col, editable){
55700 this.config[col].editable = editable;
55705 * Returns true if the column is hidden.
55706 * @param {Number} colIndex The column index
55707 * @return {Boolean}
55709 isHidden : function(colIndex){
55710 return this.config[colIndex].hidden;
55715 * Returns true if the column width cannot be changed
55717 isFixed : function(colIndex){
55718 return this.config[colIndex].fixed;
55722 * Returns true if the column can be resized
55723 * @return {Boolean}
55725 isResizable : function(colIndex){
55726 return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
55729 * Sets if a column is hidden.
55730 * @param {Number} colIndex The column index
55731 * @param {Boolean} hidden True if the column is hidden
55733 setHidden : function(colIndex, hidden){
55734 this.config[colIndex].hidden = hidden;
55735 this.totalWidth = null;
55736 this.fireEvent("hiddenchange", this, colIndex, hidden);
55740 * Sets the editor for a column.
55741 * @param {Number} col The column index
55742 * @param {Object} editor The editor object
55744 setEditor : function(col, editor){
55745 this.config[col].editor = editor;
55749 Roo.grid.ColumnModel.defaultRenderer = function(value){
55750 if(typeof value == "string" && value.length < 1){
55756 // Alias for backwards compatibility
55757 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
55760 * Ext JS Library 1.1.1
55761 * Copyright(c) 2006-2007, Ext JS, LLC.
55763 * Originally Released Under LGPL - original licence link has changed is not relivant.
55766 * <script type="text/javascript">
55770 * @class Roo.grid.AbstractSelectionModel
55771 * @extends Roo.util.Observable
55772 * Abstract base class for grid SelectionModels. It provides the interface that should be
55773 * implemented by descendant classes. This class should not be directly instantiated.
55776 Roo.grid.AbstractSelectionModel = function(){
55777 this.locked = false;
55778 Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
55781 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable, {
55782 /** @ignore Called by the grid automatically. Do not call directly. */
55783 init : function(grid){
55789 * Locks the selections.
55792 this.locked = true;
55796 * Unlocks the selections.
55798 unlock : function(){
55799 this.locked = false;
55803 * Returns true if the selections are locked.
55804 * @return {Boolean}
55806 isLocked : function(){
55807 return this.locked;
55811 * Ext JS Library 1.1.1
55812 * Copyright(c) 2006-2007, Ext JS, LLC.
55814 * Originally Released Under LGPL - original licence link has changed is not relivant.
55817 * <script type="text/javascript">
55820 * @extends Roo.grid.AbstractSelectionModel
55821 * @class Roo.grid.RowSelectionModel
55822 * The default SelectionModel used by {@link Roo.grid.Grid}.
55823 * It supports multiple selections and keyboard selection/navigation.
55825 * @param {Object} config
55827 Roo.grid.RowSelectionModel = function(config){
55828 Roo.apply(this, config);
55829 this.selections = new Roo.util.MixedCollection(false, function(o){
55834 this.lastActive = false;
55838 * @event selectionchange
55839 * Fires when the selection changes
55840 * @param {SelectionModel} this
55842 "selectionchange" : true,
55844 * @event afterselectionchange
55845 * Fires after the selection changes (eg. by key press or clicking)
55846 * @param {SelectionModel} this
55848 "afterselectionchange" : true,
55850 * @event beforerowselect
55851 * Fires when a row is selected being selected, return false to cancel.
55852 * @param {SelectionModel} this
55853 * @param {Number} rowIndex The selected index
55854 * @param {Boolean} keepExisting False if other selections will be cleared
55856 "beforerowselect" : true,
55859 * Fires when a row is selected.
55860 * @param {SelectionModel} this
55861 * @param {Number} rowIndex The selected index
55862 * @param {Roo.data.Record} r The record
55864 "rowselect" : true,
55866 * @event rowdeselect
55867 * Fires when a row is deselected.
55868 * @param {SelectionModel} this
55869 * @param {Number} rowIndex The selected index
55871 "rowdeselect" : true
55873 Roo.grid.RowSelectionModel.superclass.constructor.call(this);
55874 this.locked = false;
55877 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel, {
55879 * @cfg {Boolean} singleSelect
55880 * True to allow selection of only one row at a time (defaults to false)
55882 singleSelect : false,
55885 initEvents : function(){
55887 if(!this.grid.enableDragDrop && !this.grid.enableDrag){
55888 this.grid.on("mousedown", this.handleMouseDown, this);
55889 }else{ // allow click to work like normal
55890 this.grid.on("rowclick", this.handleDragableRowClick, this);
55893 this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
55894 "up" : function(e){
55896 this.selectPrevious(e.shiftKey);
55897 }else if(this.last !== false && this.lastActive !== false){
55898 var last = this.last;
55899 this.selectRange(this.last, this.lastActive-1);
55900 this.grid.getView().focusRow(this.lastActive);
55901 if(last !== false){
55905 this.selectFirstRow();
55907 this.fireEvent("afterselectionchange", this);
55909 "down" : function(e){
55911 this.selectNext(e.shiftKey);
55912 }else if(this.last !== false && this.lastActive !== false){
55913 var last = this.last;
55914 this.selectRange(this.last, this.lastActive+1);
55915 this.grid.getView().focusRow(this.lastActive);
55916 if(last !== false){
55920 this.selectFirstRow();
55922 this.fireEvent("afterselectionchange", this);
55927 var view = this.grid.view;
55928 view.on("refresh", this.onRefresh, this);
55929 view.on("rowupdated", this.onRowUpdated, this);
55930 view.on("rowremoved", this.onRemove, this);
55934 onRefresh : function(){
55935 var ds = this.grid.dataSource, i, v = this.grid.view;
55936 var s = this.selections;
55937 s.each(function(r){
55938 if((i = ds.indexOfId(r.id)) != -1){
55940 s.add(ds.getAt(i)); // updating the selection relate data
55948 onRemove : function(v, index, r){
55949 this.selections.remove(r);
55953 onRowUpdated : function(v, index, r){
55954 if(this.isSelected(r)){
55955 v.onRowSelect(index);
55961 * @param {Array} records The records to select
55962 * @param {Boolean} keepExisting (optional) True to keep existing selections
55964 selectRecords : function(records, keepExisting){
55966 this.clearSelections();
55968 var ds = this.grid.dataSource;
55969 for(var i = 0, len = records.length; i < len; i++){
55970 this.selectRow(ds.indexOf(records[i]), true);
55975 * Gets the number of selected rows.
55978 getCount : function(){
55979 return this.selections.length;
55983 * Selects the first row in the grid.
55985 selectFirstRow : function(){
55990 * Select the last row.
55991 * @param {Boolean} keepExisting (optional) True to keep existing selections
55993 selectLastRow : function(keepExisting){
55994 this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
55998 * Selects the row immediately following the last selected row.
55999 * @param {Boolean} keepExisting (optional) True to keep existing selections
56001 selectNext : function(keepExisting){
56002 if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
56003 this.selectRow(this.last+1, keepExisting);
56004 this.grid.getView().focusRow(this.last);
56009 * Selects the row that precedes the last selected row.
56010 * @param {Boolean} keepExisting (optional) True to keep existing selections
56012 selectPrevious : function(keepExisting){
56014 this.selectRow(this.last-1, keepExisting);
56015 this.grid.getView().focusRow(this.last);
56020 * Returns the selected records
56021 * @return {Array} Array of selected records
56023 getSelections : function(){
56024 return [].concat(this.selections.items);
56028 * Returns the first selected record.
56031 getSelected : function(){
56032 return this.selections.itemAt(0);
56037 * Clears all selections.
56039 clearSelections : function(fast){
56040 if(this.locked) return;
56042 var ds = this.grid.dataSource;
56043 var s = this.selections;
56044 s.each(function(r){
56045 this.deselectRow(ds.indexOfId(r.id));
56049 this.selections.clear();
56056 * Selects all rows.
56058 selectAll : function(){
56059 if(this.locked) return;
56060 this.selections.clear();
56061 for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
56062 this.selectRow(i, true);
56067 * Returns True if there is a selection.
56068 * @return {Boolean}
56070 hasSelection : function(){
56071 return this.selections.length > 0;
56075 * Returns True if the specified row is selected.
56076 * @param {Number/Record} record The record or index of the record to check
56077 * @return {Boolean}
56079 isSelected : function(index){
56080 var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
56081 return (r && this.selections.key(r.id) ? true : false);
56085 * Returns True if the specified record id is selected.
56086 * @param {String} id The id of record to check
56087 * @return {Boolean}
56089 isIdSelected : function(id){
56090 return (this.selections.key(id) ? true : false);
56094 handleMouseDown : function(e, t){
56095 var view = this.grid.getView(), rowIndex;
56096 if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
56099 if(e.shiftKey && this.last !== false){
56100 var last = this.last;
56101 this.selectRange(last, rowIndex, e.ctrlKey);
56102 this.last = last; // reset the last
56103 view.focusRow(rowIndex);
56105 var isSelected = this.isSelected(rowIndex);
56106 if(e.button !== 0 && isSelected){
56107 view.focusRow(rowIndex);
56108 }else if(e.ctrlKey && isSelected){
56109 this.deselectRow(rowIndex);
56110 }else if(!isSelected){
56111 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
56112 view.focusRow(rowIndex);
56115 this.fireEvent("afterselectionchange", this);
56118 handleDragableRowClick : function(grid, rowIndex, e)
56120 if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
56121 this.selectRow(rowIndex, false);
56122 grid.view.focusRow(rowIndex);
56123 this.fireEvent("afterselectionchange", this);
56128 * Selects multiple rows.
56129 * @param {Array} rows Array of the indexes of the row to select
56130 * @param {Boolean} keepExisting (optional) True to keep existing selections
56132 selectRows : function(rows, keepExisting){
56134 this.clearSelections();
56136 for(var i = 0, len = rows.length; i < len; i++){
56137 this.selectRow(rows[i], true);
56142 * Selects a range of rows. All rows in between startRow and endRow are also selected.
56143 * @param {Number} startRow The index of the first row in the range
56144 * @param {Number} endRow The index of the last row in the range
56145 * @param {Boolean} keepExisting (optional) True to retain existing selections
56147 selectRange : function(startRow, endRow, keepExisting){
56148 if(this.locked) return;
56150 this.clearSelections();
56152 if(startRow <= endRow){
56153 for(var i = startRow; i <= endRow; i++){
56154 this.selectRow(i, true);
56157 for(var i = startRow; i >= endRow; i--){
56158 this.selectRow(i, true);
56164 * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
56165 * @param {Number} startRow The index of the first row in the range
56166 * @param {Number} endRow The index of the last row in the range
56168 deselectRange : function(startRow, endRow, preventViewNotify){
56169 if(this.locked) return;
56170 for(var i = startRow; i <= endRow; i++){
56171 this.deselectRow(i, preventViewNotify);
56177 * @param {Number} row The index of the row to select
56178 * @param {Boolean} keepExisting (optional) True to keep existing selections
56180 selectRow : function(index, keepExisting, preventViewNotify){
56181 if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
56182 if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
56183 if(!keepExisting || this.singleSelect){
56184 this.clearSelections();
56186 var r = this.grid.dataSource.getAt(index);
56187 this.selections.add(r);
56188 this.last = this.lastActive = index;
56189 if(!preventViewNotify){
56190 this.grid.getView().onRowSelect(index);
56192 this.fireEvent("rowselect", this, index, r);
56193 this.fireEvent("selectionchange", this);
56199 * @param {Number} row The index of the row to deselect
56201 deselectRow : function(index, preventViewNotify){
56202 if(this.locked) return;
56203 if(this.last == index){
56206 if(this.lastActive == index){
56207 this.lastActive = false;
56209 var r = this.grid.dataSource.getAt(index);
56210 this.selections.remove(r);
56211 if(!preventViewNotify){
56212 this.grid.getView().onRowDeselect(index);
56214 this.fireEvent("rowdeselect", this, index);
56215 this.fireEvent("selectionchange", this);
56219 restoreLast : function(){
56221 this.last = this._last;
56226 acceptsNav : function(row, col, cm){
56227 return !cm.isHidden(col) && cm.isCellEditable(col, row);
56231 onEditorKey : function(field, e){
56232 var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
56237 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
56239 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56241 }else if(k == e.ENTER && !e.ctrlKey){
56245 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
56247 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
56249 }else if(k == e.ESC){
56253 g.startEditing(newCell[0], newCell[1]);
56258 * Ext JS Library 1.1.1
56259 * Copyright(c) 2006-2007, Ext JS, LLC.
56261 * Originally Released Under LGPL - original licence link has changed is not relivant.
56264 * <script type="text/javascript">
56267 * @class Roo.grid.CellSelectionModel
56268 * @extends Roo.grid.AbstractSelectionModel
56269 * This class provides the basic implementation for cell selection in a grid.
56271 * @param {Object} config The object containing the configuration of this model.
56272 * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
56274 Roo.grid.CellSelectionModel = function(config){
56275 Roo.apply(this, config);
56277 this.selection = null;
56281 * @event beforerowselect
56282 * Fires before a cell is selected.
56283 * @param {SelectionModel} this
56284 * @param {Number} rowIndex The selected row index
56285 * @param {Number} colIndex The selected cell index
56287 "beforecellselect" : true,
56289 * @event cellselect
56290 * Fires when a cell is selected.
56291 * @param {SelectionModel} this
56292 * @param {Number} rowIndex The selected row index
56293 * @param {Number} colIndex The selected cell index
56295 "cellselect" : true,
56297 * @event selectionchange
56298 * Fires when the active selection changes.
56299 * @param {SelectionModel} this
56300 * @param {Object} selection null for no selection or an object (o) with two properties
56302 <li>o.record: the record object for the row the selection is in</li>
56303 <li>o.cell: An array of [rowIndex, columnIndex]</li>
56306 "selectionchange" : true,
56309 * Fires when the tab (or enter) was pressed on the last editable cell
56310 * You can use this to trigger add new row.
56311 * @param {SelectionModel} this
56315 * @event beforeeditnext
56316 * Fires before the next editable sell is made active
56317 * You can use this to skip to another cell or fire the tabend
56318 * if you set cell to false
56319 * @param {Object} eventdata object : { cell : [ row, col ] }
56321 "beforeeditnext" : true
56323 Roo.grid.CellSelectionModel.superclass.constructor.call(this);
56326 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel, {
56328 enter_is_tab: false,
56331 initEvents : function(){
56332 this.grid.on("mousedown", this.handleMouseDown, this);
56333 this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
56334 var view = this.grid.view;
56335 view.on("refresh", this.onViewChange, this);
56336 view.on("rowupdated", this.onRowUpdated, this);
56337 view.on("beforerowremoved", this.clearSelections, this);
56338 view.on("beforerowsinserted", this.clearSelections, this);
56339 if(this.grid.isEditor){
56340 this.grid.on("beforeedit", this.beforeEdit, this);
56345 beforeEdit : function(e){
56346 this.select(e.row, e.column, false, true, e.record);
56350 onRowUpdated : function(v, index, r){
56351 if(this.selection && this.selection.record == r){
56352 v.onCellSelect(index, this.selection.cell[1]);
56357 onViewChange : function(){
56358 this.clearSelections(true);
56362 * Returns the currently selected cell,.
56363 * @return {Array} The selected cell (row, column) or null if none selected.
56365 getSelectedCell : function(){
56366 return this.selection ? this.selection.cell : null;
56370 * Clears all selections.
56371 * @param {Boolean} true to prevent the gridview from being notified about the change.
56373 clearSelections : function(preventNotify){
56374 var s = this.selection;
56376 if(preventNotify !== true){
56377 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
56379 this.selection = null;
56380 this.fireEvent("selectionchange", this, null);
56385 * Returns true if there is a selection.
56386 * @return {Boolean}
56388 hasSelection : function(){
56389 return this.selection ? true : false;
56393 handleMouseDown : function(e, t){
56394 var v = this.grid.getView();
56395 if(this.isLocked()){
56398 var row = v.findRowIndex(t);
56399 var cell = v.findCellIndex(t);
56400 if(row !== false && cell !== false){
56401 this.select(row, cell);
56407 * @param {Number} rowIndex
56408 * @param {Number} collIndex
56410 select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
56411 if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
56412 this.clearSelections();
56413 r = r || this.grid.dataSource.getAt(rowIndex);
56416 cell : [rowIndex, colIndex]
56418 if(!preventViewNotify){
56419 var v = this.grid.getView();
56420 v.onCellSelect(rowIndex, colIndex);
56421 if(preventFocus !== true){
56422 v.focusCell(rowIndex, colIndex);
56425 this.fireEvent("cellselect", this, rowIndex, colIndex);
56426 this.fireEvent("selectionchange", this, this.selection);
56431 isSelectable : function(rowIndex, colIndex, cm){
56432 return !cm.isHidden(colIndex);
56436 handleKeyDown : function(e){
56437 //Roo.log('Cell Sel Model handleKeyDown');
56438 if(!e.isNavKeyPress()){
56441 var g = this.grid, s = this.selection;
56444 var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
56446 this.select(cell[0], cell[1]);
56451 var walk = function(row, col, step){
56452 return g.walkCells(row, col, step, sm.isSelectable, sm);
56454 var k = e.getKey(), r = s.cell[0], c = s.cell[1];
56461 // handled by onEditorKey
56462 if (g.isEditor && g.editing) {
56466 newCell = walk(r, c-1, -1);
56468 newCell = walk(r, c+1, 1);
56473 newCell = walk(r+1, c, 1);
56477 newCell = walk(r-1, c, -1);
56481 newCell = walk(r, c+1, 1);
56485 newCell = walk(r, c-1, -1);
56490 if(g.isEditor && !g.editing){
56491 g.startEditing(r, c);
56500 this.select(newCell[0], newCell[1]);
56506 acceptsNav : function(row, col, cm){
56507 return !cm.isHidden(col) && cm.isCellEditable(col, row);
56511 * @param {Number} field (not used) - as it's normally used as a listener
56512 * @param {Number} e - event - fake it by using
56514 * var e = Roo.EventObjectImpl.prototype;
56515 * e.keyCode = e.TAB
56519 onEditorKey : function(field, e){
56521 var k = e.getKey(),
56524 ed = g.activeEditor,
56526 ///Roo.log('onEditorKey' + k);
56529 if (this.enter_is_tab && k == e.ENTER) {
56535 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
56537 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56543 } else if(k == e.ENTER && !e.ctrlKey){
56546 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
56548 } else if(k == e.ESC){
56553 var ecall = { cell : newCell, forward : forward };
56554 this.fireEvent('beforeeditnext', ecall );
56555 newCell = ecall.cell;
56556 forward = ecall.forward;
56560 //Roo.log('next cell after edit');
56561 g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
56562 } else if (forward) {
56563 // tabbed past last
56564 this.fireEvent.defer(100, this, ['tabend',this]);
56569 * Ext JS Library 1.1.1
56570 * Copyright(c) 2006-2007, Ext JS, LLC.
56572 * Originally Released Under LGPL - original licence link has changed is not relivant.
56575 * <script type="text/javascript">
56579 * @class Roo.grid.EditorGrid
56580 * @extends Roo.grid.Grid
56581 * Class for creating and editable grid.
56582 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
56583 * The container MUST have some type of size defined for the grid to fill. The container will be
56584 * automatically set to position relative if it isn't already.
56585 * @param {Object} dataSource The data model to bind to
56586 * @param {Object} colModel The column model with info about this grid's columns
56588 Roo.grid.EditorGrid = function(container, config){
56589 Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
56590 this.getGridEl().addClass("xedit-grid");
56592 if(!this.selModel){
56593 this.selModel = new Roo.grid.CellSelectionModel();
56596 this.activeEditor = null;
56600 * @event beforeedit
56601 * Fires before cell editing is triggered. The edit event object has the following properties <br />
56602 * <ul style="padding:5px;padding-left:16px;">
56603 * <li>grid - This grid</li>
56604 * <li>record - The record being edited</li>
56605 * <li>field - The field name being edited</li>
56606 * <li>value - The value for the field being edited.</li>
56607 * <li>row - The grid row index</li>
56608 * <li>column - The grid column index</li>
56609 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
56611 * @param {Object} e An edit event (see above for description)
56613 "beforeedit" : true,
56616 * Fires after a cell is edited. <br />
56617 * <ul style="padding:5px;padding-left:16px;">
56618 * <li>grid - This grid</li>
56619 * <li>record - The record being edited</li>
56620 * <li>field - The field name being edited</li>
56621 * <li>value - The value being set</li>
56622 * <li>originalValue - The original value for the field, before the edit.</li>
56623 * <li>row - The grid row index</li>
56624 * <li>column - The grid column index</li>
56626 * @param {Object} e An edit event (see above for description)
56628 "afteredit" : true,
56630 * @event validateedit
56631 * Fires after a cell is edited, but before the value is set in the record.
56632 * You can use this to modify the value being set in the field, Return false
56633 * to cancel the change. The edit event object has the following properties <br />
56634 * <ul style="padding:5px;padding-left:16px;">
56635 * <li>editor - This editor</li>
56636 * <li>grid - This grid</li>
56637 * <li>record - The record being edited</li>
56638 * <li>field - The field name being edited</li>
56639 * <li>value - The value being set</li>
56640 * <li>originalValue - The original value for the field, before the edit.</li>
56641 * <li>row - The grid row index</li>
56642 * <li>column - The grid column index</li>
56643 * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
56645 * @param {Object} e An edit event (see above for description)
56647 "validateedit" : true
56649 this.on("bodyscroll", this.stopEditing, this);
56650 this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this);
56653 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
56655 * @cfg {Number} clicksToEdit
56656 * The number of clicks on a cell required to display the cell's editor (defaults to 2)
56663 trackMouseOver: false, // causes very odd FF errors
56665 onCellDblClick : function(g, row, col){
56666 this.startEditing(row, col);
56669 onEditComplete : function(ed, value, startValue){
56670 this.editing = false;
56671 this.activeEditor = null;
56672 ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
56674 var field = this.colModel.getDataIndex(ed.col);
56679 originalValue: startValue,
56686 var cell = Roo.get(this.view.getCell(ed.row,ed.col))
56689 if(String(value) !== String(startValue)){
56691 if(this.fireEvent("validateedit", e) !== false && !e.cancel){
56692 r.set(field, e.value);
56693 // if we are dealing with a combo box..
56694 // then we also set the 'name' colum to be the displayField
56695 if (ed.field.displayField && ed.field.name) {
56696 r.set(ed.field.name, ed.field.el.dom.value);
56699 delete e.cancel; //?? why!!!
56700 this.fireEvent("afteredit", e);
56703 this.fireEvent("afteredit", e); // always fire it!
56705 this.view.focusCell(ed.row, ed.col);
56709 * Starts editing the specified for the specified row/column
56710 * @param {Number} rowIndex
56711 * @param {Number} colIndex
56713 startEditing : function(row, col){
56714 this.stopEditing();
56715 if(this.colModel.isCellEditable(col, row)){
56716 this.view.ensureVisible(row, col, true);
56718 var r = this.dataSource.getAt(row);
56719 var field = this.colModel.getDataIndex(col);
56720 var cell = Roo.get(this.view.getCell(row,col));
56725 value: r.data[field],
56730 if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
56731 this.editing = true;
56732 var ed = this.colModel.getCellEditor(col, row);
56738 ed.render(ed.parentEl || document.body);
56744 (function(){ // complex but required for focus issues in safari, ie and opera
56748 ed.on("complete", this.onEditComplete, this, {single: true});
56749 ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
56750 this.activeEditor = ed;
56751 var v = r.data[field];
56752 ed.startEdit(this.view.getCell(row, col), v);
56753 // combo's with 'displayField and name set
56754 if (ed.field.displayField && ed.field.name) {
56755 ed.field.el.dom.value = r.data[ed.field.name];
56759 }).defer(50, this);
56765 * Stops any active editing
56767 stopEditing : function(){
56768 if(this.activeEditor){
56769 this.activeEditor.completeEdit();
56771 this.activeEditor = null;
56775 * Called to get grid's drag proxy text, by default returns this.ddText.
56778 getDragDropText : function(){
56779 var count = this.selModel.getSelectedCell() ? 1 : 0;
56780 return String.format(this.ddText, count, count == 1 ? '' : 's');
56785 * Ext JS Library 1.1.1
56786 * Copyright(c) 2006-2007, Ext JS, LLC.
56788 * Originally Released Under LGPL - original licence link has changed is not relivant.
56791 * <script type="text/javascript">
56794 // private - not really -- you end up using it !
56795 // This is a support class used internally by the Grid components
56798 * @class Roo.grid.GridEditor
56799 * @extends Roo.Editor
56800 * Class for creating and editable grid elements.
56801 * @param {Object} config any settings (must include field)
56803 Roo.grid.GridEditor = function(field, config){
56804 if (!config && field.field) {
56806 field = Roo.factory(config.field, Roo.form);
56808 Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
56809 field.monitorTab = false;
56812 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
56815 * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
56818 alignment: "tl-tl",
56821 cls: "x-small-editor x-grid-editor",
56826 * Ext JS Library 1.1.1
56827 * Copyright(c) 2006-2007, Ext JS, LLC.
56829 * Originally Released Under LGPL - original licence link has changed is not relivant.
56832 * <script type="text/javascript">
56837 Roo.grid.PropertyRecord = Roo.data.Record.create([
56838 {name:'name',type:'string'}, 'value'
56842 Roo.grid.PropertyStore = function(grid, source){
56844 this.store = new Roo.data.Store({
56845 recordType : Roo.grid.PropertyRecord
56847 this.store.on('update', this.onUpdate, this);
56849 this.setSource(source);
56851 Roo.grid.PropertyStore.superclass.constructor.call(this);
56856 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
56857 setSource : function(o){
56859 this.store.removeAll();
56862 if(this.isEditableValue(o[k])){
56863 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
56866 this.store.loadRecords({records: data}, {}, true);
56869 onUpdate : function(ds, record, type){
56870 if(type == Roo.data.Record.EDIT){
56871 var v = record.data['value'];
56872 var oldValue = record.modified['value'];
56873 if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
56874 this.source[record.id] = v;
56876 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
56883 getProperty : function(row){
56884 return this.store.getAt(row);
56887 isEditableValue: function(val){
56888 if(val && val instanceof Date){
56890 }else if(typeof val == 'object' || typeof val == 'function'){
56896 setValue : function(prop, value){
56897 this.source[prop] = value;
56898 this.store.getById(prop).set('value', value);
56901 getSource : function(){
56902 return this.source;
56906 Roo.grid.PropertyColumnModel = function(grid, store){
56909 g.PropertyColumnModel.superclass.constructor.call(this, [
56910 {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
56911 {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
56913 this.store = store;
56914 this.bselect = Roo.DomHelper.append(document.body, {
56915 tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
56916 {tag: 'option', value: 'true', html: 'true'},
56917 {tag: 'option', value: 'false', html: 'false'}
56920 Roo.id(this.bselect);
56923 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
56924 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
56925 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
56926 'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
56927 'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
56929 this.renderCellDelegate = this.renderCell.createDelegate(this);
56930 this.renderPropDelegate = this.renderProp.createDelegate(this);
56933 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
56937 valueText : 'Value',
56939 dateFormat : 'm/j/Y',
56942 renderDate : function(dateVal){
56943 return dateVal.dateFormat(this.dateFormat);
56946 renderBool : function(bVal){
56947 return bVal ? 'true' : 'false';
56950 isCellEditable : function(colIndex, rowIndex){
56951 return colIndex == 1;
56954 getRenderer : function(col){
56956 this.renderCellDelegate : this.renderPropDelegate;
56959 renderProp : function(v){
56960 return this.getPropertyName(v);
56963 renderCell : function(val){
56965 if(val instanceof Date){
56966 rv = this.renderDate(val);
56967 }else if(typeof val == 'boolean'){
56968 rv = this.renderBool(val);
56970 return Roo.util.Format.htmlEncode(rv);
56973 getPropertyName : function(name){
56974 var pn = this.grid.propertyNames;
56975 return pn && pn[name] ? pn[name] : name;
56978 getCellEditor : function(colIndex, rowIndex){
56979 var p = this.store.getProperty(rowIndex);
56980 var n = p.data['name'], val = p.data['value'];
56982 if(typeof(this.grid.customEditors[n]) == 'string'){
56983 return this.editors[this.grid.customEditors[n]];
56985 if(typeof(this.grid.customEditors[n]) != 'undefined'){
56986 return this.grid.customEditors[n];
56988 if(val instanceof Date){
56989 return this.editors['date'];
56990 }else if(typeof val == 'number'){
56991 return this.editors['number'];
56992 }else if(typeof val == 'boolean'){
56993 return this.editors['boolean'];
56995 return this.editors['string'];
57001 * @class Roo.grid.PropertyGrid
57002 * @extends Roo.grid.EditorGrid
57003 * This class represents the interface of a component based property grid control.
57004 * <br><br>Usage:<pre><code>
57005 var grid = new Roo.grid.PropertyGrid("my-container-id", {
57013 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
57014 * The container MUST have some type of size defined for the grid to fill. The container will be
57015 * automatically set to position relative if it isn't already.
57016 * @param {Object} config A config object that sets properties on this grid.
57018 Roo.grid.PropertyGrid = function(container, config){
57019 config = config || {};
57020 var store = new Roo.grid.PropertyStore(this);
57021 this.store = store;
57022 var cm = new Roo.grid.PropertyColumnModel(this, store);
57023 store.store.sort('name', 'ASC');
57024 Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
57027 enableColLock:false,
57028 enableColumnMove:false,
57030 trackMouseOver: false,
57033 this.getGridEl().addClass('x-props-grid');
57034 this.lastEditRow = null;
57035 this.on('columnresize', this.onColumnResize, this);
57038 * @event beforepropertychange
57039 * Fires before a property changes (return false to stop?)
57040 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
57041 * @param {String} id Record Id
57042 * @param {String} newval New Value
57043 * @param {String} oldval Old Value
57045 "beforepropertychange": true,
57047 * @event propertychange
57048 * Fires after a property changes
57049 * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
57050 * @param {String} id Record Id
57051 * @param {String} newval New Value
57052 * @param {String} oldval Old Value
57054 "propertychange": true
57056 this.customEditors = this.customEditors || {};
57058 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
57061 * @cfg {Object} customEditors map of colnames=> custom editors.
57062 * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
57063 * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
57064 * false disables editing of the field.
57068 * @cfg {Object} propertyNames map of property Names to their displayed value
57071 render : function(){
57072 Roo.grid.PropertyGrid.superclass.render.call(this);
57073 this.autoSize.defer(100, this);
57076 autoSize : function(){
57077 Roo.grid.PropertyGrid.superclass.autoSize.call(this);
57079 this.view.fitColumns();
57083 onColumnResize : function(){
57084 this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
57088 * Sets the data for the Grid
57089 * accepts a Key => Value object of all the elements avaiable.
57090 * @param {Object} data to appear in grid.
57092 setSource : function(source){
57093 this.store.setSource(source);
57097 * Gets all the data from the grid.
57098 * @return {Object} data data stored in grid
57100 getSource : function(){
57101 return this.store.getSource();
57110 * @class Roo.grid.Calendar
57111 * @extends Roo.util.Grid
57112 * This class extends the Grid to provide a calendar widget
57113 * <br><br>Usage:<pre><code>
57114 var grid = new Roo.grid.Calendar("my-container-id", {
57117 selModel: mySelectionModel,
57118 autoSizeColumns: true,
57119 monitorWindowResize: false,
57120 trackMouseOver: true
57121 eventstore : real data store..
57127 * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
57128 * The container MUST have some type of size defined for the grid to fill. The container will be
57129 * automatically set to position relative if it isn't already.
57130 * @param {Object} config A config object that sets properties on this grid.
57132 Roo.grid.Calendar = function(container, config){
57133 // initialize the container
57134 this.container = Roo.get(container);
57135 this.container.update("");
57136 this.container.setStyle("overflow", "hidden");
57137 this.container.addClass('x-grid-container');
57139 this.id = this.container.id;
57141 Roo.apply(this, config);
57142 // check and correct shorthanded configs
57146 for (var r = 0;r < 6;r++) {
57149 for (var c =0;c < 7;c++) {
57153 if (this.eventStore) {
57154 this.eventStore= Roo.factory(this.eventStore, Roo.data);
57155 this.eventStore.on('load',this.onLoad, this);
57156 this.eventStore.on('beforeload',this.clearEvents, this);
57160 this.dataSource = new Roo.data.Store({
57161 proxy: new Roo.data.MemoryProxy(rows),
57162 reader: new Roo.data.ArrayReader({}, [
57163 'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
57166 this.dataSource.load();
57167 this.ds = this.dataSource;
57168 this.ds.xmodule = this.xmodule || false;
57171 var cellRender = function(v,x,r)
57173 return String.format(
57174 '<div class="fc-day fc-widget-content"><div>' +
57175 '<div class="fc-event-container"></div>' +
57176 '<div class="fc-day-number">{0}</div>'+
57178 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
57179 '</div></div>', v);
57184 this.colModel = new Roo.grid.ColumnModel( [
57186 xtype: 'ColumnModel',
57188 dataIndex : 'weekday0',
57190 renderer : cellRender
57193 xtype: 'ColumnModel',
57195 dataIndex : 'weekday1',
57197 renderer : cellRender
57200 xtype: 'ColumnModel',
57202 dataIndex : 'weekday2',
57203 header : 'Tuesday',
57204 renderer : cellRender
57207 xtype: 'ColumnModel',
57209 dataIndex : 'weekday3',
57210 header : 'Wednesday',
57211 renderer : cellRender
57214 xtype: 'ColumnModel',
57216 dataIndex : 'weekday4',
57217 header : 'Thursday',
57218 renderer : cellRender
57221 xtype: 'ColumnModel',
57223 dataIndex : 'weekday5',
57225 renderer : cellRender
57228 xtype: 'ColumnModel',
57230 dataIndex : 'weekday6',
57231 header : 'Saturday',
57232 renderer : cellRender
57235 this.cm = this.colModel;
57236 this.cm.xmodule = this.xmodule || false;
57240 //this.selModel = new Roo.grid.CellSelectionModel();
57241 //this.sm = this.selModel;
57242 //this.selModel.init(this);
57246 this.container.setWidth(this.width);
57250 this.container.setHeight(this.height);
57257 * The raw click event for the entire grid.
57258 * @param {Roo.EventObject} e
57263 * The raw dblclick event for the entire grid.
57264 * @param {Roo.EventObject} e
57268 * @event contextmenu
57269 * The raw contextmenu event for the entire grid.
57270 * @param {Roo.EventObject} e
57272 "contextmenu" : true,
57275 * The raw mousedown event for the entire grid.
57276 * @param {Roo.EventObject} e
57278 "mousedown" : true,
57281 * The raw mouseup event for the entire grid.
57282 * @param {Roo.EventObject} e
57287 * The raw mouseover event for the entire grid.
57288 * @param {Roo.EventObject} e
57290 "mouseover" : true,
57293 * The raw mouseout event for the entire grid.
57294 * @param {Roo.EventObject} e
57299 * The raw keypress event for the entire grid.
57300 * @param {Roo.EventObject} e
57305 * The raw keydown event for the entire grid.
57306 * @param {Roo.EventObject} e
57314 * Fires when a cell is clicked
57315 * @param {Grid} this
57316 * @param {Number} rowIndex
57317 * @param {Number} columnIndex
57318 * @param {Roo.EventObject} e
57320 "cellclick" : true,
57322 * @event celldblclick
57323 * Fires when a cell is double clicked
57324 * @param {Grid} this
57325 * @param {Number} rowIndex
57326 * @param {Number} columnIndex
57327 * @param {Roo.EventObject} e
57329 "celldblclick" : true,
57332 * Fires when a row is clicked
57333 * @param {Grid} this
57334 * @param {Number} rowIndex
57335 * @param {Roo.EventObject} e
57339 * @event rowdblclick
57340 * Fires when a row is double clicked
57341 * @param {Grid} this
57342 * @param {Number} rowIndex
57343 * @param {Roo.EventObject} e
57345 "rowdblclick" : true,
57347 * @event headerclick
57348 * Fires when a header is clicked
57349 * @param {Grid} this
57350 * @param {Number} columnIndex
57351 * @param {Roo.EventObject} e
57353 "headerclick" : true,
57355 * @event headerdblclick
57356 * Fires when a header cell is double clicked
57357 * @param {Grid} this
57358 * @param {Number} columnIndex
57359 * @param {Roo.EventObject} e
57361 "headerdblclick" : true,
57363 * @event rowcontextmenu
57364 * Fires when a row is right clicked
57365 * @param {Grid} this
57366 * @param {Number} rowIndex
57367 * @param {Roo.EventObject} e
57369 "rowcontextmenu" : true,
57371 * @event cellcontextmenu
57372 * Fires when a cell is right clicked
57373 * @param {Grid} this
57374 * @param {Number} rowIndex
57375 * @param {Number} cellIndex
57376 * @param {Roo.EventObject} e
57378 "cellcontextmenu" : true,
57380 * @event headercontextmenu
57381 * Fires when a header is right clicked
57382 * @param {Grid} this
57383 * @param {Number} columnIndex
57384 * @param {Roo.EventObject} e
57386 "headercontextmenu" : true,
57388 * @event bodyscroll
57389 * Fires when the body element is scrolled
57390 * @param {Number} scrollLeft
57391 * @param {Number} scrollTop
57393 "bodyscroll" : true,
57395 * @event columnresize
57396 * Fires when the user resizes a column
57397 * @param {Number} columnIndex
57398 * @param {Number} newSize
57400 "columnresize" : true,
57402 * @event columnmove
57403 * Fires when the user moves a column
57404 * @param {Number} oldIndex
57405 * @param {Number} newIndex
57407 "columnmove" : true,
57410 * Fires when row(s) start being dragged
57411 * @param {Grid} this
57412 * @param {Roo.GridDD} dd The drag drop object
57413 * @param {event} e The raw browser event
57415 "startdrag" : true,
57418 * Fires when a drag operation is complete
57419 * @param {Grid} this
57420 * @param {Roo.GridDD} dd The drag drop object
57421 * @param {event} e The raw browser event
57426 * Fires when dragged row(s) are dropped on a valid DD target
57427 * @param {Grid} this
57428 * @param {Roo.GridDD} dd The drag drop object
57429 * @param {String} targetId The target drag drop object
57430 * @param {event} e The raw browser event
57435 * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
57436 * @param {Grid} this
57437 * @param {Roo.GridDD} dd The drag drop object
57438 * @param {String} targetId The target drag drop object
57439 * @param {event} e The raw browser event
57444 * Fires when the dragged row(s) first cross another DD target while being dragged
57445 * @param {Grid} this
57446 * @param {Roo.GridDD} dd The drag drop object
57447 * @param {String} targetId The target drag drop object
57448 * @param {event} e The raw browser event
57450 "dragenter" : true,
57453 * Fires when the dragged row(s) leave another DD target while being dragged
57454 * @param {Grid} this
57455 * @param {Roo.GridDD} dd The drag drop object
57456 * @param {String} targetId The target drag drop object
57457 * @param {event} e The raw browser event
57462 * Fires when a row is rendered, so you can change add a style to it.
57463 * @param {GridView} gridview The grid view
57464 * @param {Object} rowcfg contains record rowIndex and rowClass - set rowClass to add a style.
57470 * Fires when the grid is rendered
57471 * @param {Grid} grid
57476 * Fires when a date is selected
57477 * @param {DatePicker} this
57478 * @param {Date} date The selected date
57482 * @event monthchange
57483 * Fires when the displayed month changes
57484 * @param {DatePicker} this
57485 * @param {Date} date The selected month
57487 'monthchange': true,
57489 * @event evententer
57490 * Fires when mouse over an event
57491 * @param {Calendar} this
57492 * @param {event} Event
57494 'evententer': true,
57496 * @event eventleave
57497 * Fires when the mouse leaves an
57498 * @param {Calendar} this
57501 'eventleave': true,
57503 * @event eventclick
57504 * Fires when the mouse click an
57505 * @param {Calendar} this
57508 'eventclick': true,
57510 * @event eventrender
57511 * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
57512 * @param {Calendar} this
57513 * @param {data} data to be modified
57515 'eventrender': true
57519 Roo.grid.Grid.superclass.constructor.call(this);
57520 this.on('render', function() {
57521 this.view.el.addClass('x-grid-cal');
57523 (function() { this.setDate(new Date()); }).defer(100,this); //default today..
57527 if (!Roo.grid.Calendar.style) {
57528 Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
57531 '.x-grid-cal .x-grid-col' : {
57532 height: 'auto !important',
57533 'vertical-align': 'top'
57535 '.x-grid-cal .fc-event-hori' : {
57546 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
57548 * @cfg {Store} eventStore The store that loads events.
57553 activeDate : false,
57556 monitorWindowResize : false,
57559 resizeColumns : function() {
57560 var col = (this.view.el.getWidth() / 7) - 3;
57561 // loop through cols, and setWidth
57562 for(var i =0 ; i < 7 ; i++){
57563 this.cm.setColumnWidth(i, col);
57566 setDate :function(date) {
57568 Roo.log('setDate?');
57570 this.resizeColumns();
57571 var vd = this.activeDate;
57572 this.activeDate = date;
57573 // if(vd && this.el){
57574 // var t = date.getTime();
57575 // if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
57576 // Roo.log('using add remove');
57578 // this.fireEvent('monthchange', this, date);
57580 // this.cells.removeClass("fc-state-highlight");
57581 // this.cells.each(function(c){
57582 // if(c.dateValue == t){
57583 // c.addClass("fc-state-highlight");
57584 // setTimeout(function(){
57585 // try{c.dom.firstChild.focus();}catch(e){}
57595 var days = date.getDaysInMonth();
57597 var firstOfMonth = date.getFirstDateOfMonth();
57598 var startingPos = firstOfMonth.getDay()-this.startDay;
57600 if(startingPos < this.startDay){
57604 var pm = date.add(Date.MONTH, -1);
57605 var prevStart = pm.getDaysInMonth()-startingPos;
57609 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
57611 this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
57612 //this.cells.addClassOnOver('fc-state-hover');
57614 var cells = this.cells.elements;
57615 var textEls = this.textNodes;
57617 //Roo.each(cells, function(cell){
57618 // cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
57621 days += startingPos;
57623 // convert everything to numbers so it's fast
57624 var day = 86400000;
57625 var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
57628 //Roo.log(prevStart);
57630 var today = new Date().clearTime().getTime();
57631 var sel = date.clearTime().getTime();
57632 var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
57633 var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
57634 var ddMatch = this.disabledDatesRE;
57635 var ddText = this.disabledDatesText;
57636 var ddays = this.disabledDays ? this.disabledDays.join("") : false;
57637 var ddaysText = this.disabledDaysText;
57638 var format = this.format;
57640 var setCellClass = function(cal, cell){
57642 //Roo.log('set Cell Class');
57644 var t = d.getTime();
57649 cell.dateValue = t;
57651 cell.className += " fc-today";
57652 cell.className += " fc-state-highlight";
57653 cell.title = cal.todayText;
57656 // disable highlight in other month..
57657 cell.className += " fc-state-highlight";
57662 //cell.className = " fc-state-disabled";
57663 cell.title = cal.minText;
57667 //cell.className = " fc-state-disabled";
57668 cell.title = cal.maxText;
57672 if(ddays.indexOf(d.getDay()) != -1){
57673 // cell.title = ddaysText;
57674 // cell.className = " fc-state-disabled";
57677 if(ddMatch && format){
57678 var fvalue = d.dateFormat(format);
57679 if(ddMatch.test(fvalue)){
57680 cell.title = ddText.replace("%0", fvalue);
57681 cell.className = " fc-state-disabled";
57685 if (!cell.initialClassName) {
57686 cell.initialClassName = cell.dom.className;
57689 cell.dom.className = cell.initialClassName + ' ' + cell.className;
57694 for(; i < startingPos; i++) {
57695 cells[i].dayName = (++prevStart);
57696 Roo.log(textEls[i]);
57697 d.setDate(d.getDate()+1);
57699 //cells[i].className = "fc-past fc-other-month";
57700 setCellClass(this, cells[i]);
57705 for(; i < days; i++){
57706 intDay = i - startingPos + 1;
57707 cells[i].dayName = (intDay);
57708 d.setDate(d.getDate()+1);
57710 cells[i].className = ''; // "x-date-active";
57711 setCellClass(this, cells[i]);
57715 for(; i < 42; i++) {
57716 //textEls[i].innerHTML = (++extraDays);
57718 d.setDate(d.getDate()+1);
57719 cells[i].dayName = (++extraDays);
57720 cells[i].className = "fc-future fc-other-month";
57721 setCellClass(this, cells[i]);
57724 //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
57726 var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
57728 // this will cause all the cells to mis
57731 for (var r = 0;r < 6;r++) {
57732 for (var c =0;c < 7;c++) {
57733 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
57737 this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
57738 for(i=0;i<cells.length;i++) {
57740 this.cells.elements[i].dayName = cells[i].dayName ;
57741 this.cells.elements[i].className = cells[i].className;
57742 this.cells.elements[i].initialClassName = cells[i].initialClassName ;
57743 this.cells.elements[i].title = cells[i].title ;
57744 this.cells.elements[i].dateValue = cells[i].dateValue ;
57750 //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
57751 //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
57753 ////if(totalRows != 6){
57754 //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
57755 // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
57758 this.fireEvent('monthchange', this, date);
57763 * Returns the grid's SelectionModel.
57764 * @return {SelectionModel}
57766 getSelectionModel : function(){
57767 if(!this.selModel){
57768 this.selModel = new Roo.grid.CellSelectionModel();
57770 return this.selModel;
57774 this.eventStore.load()
57780 findCell : function(dt) {
57781 dt = dt.clearTime().getTime();
57783 this.cells.each(function(c){
57784 //Roo.log("check " +c.dateValue + '?=' + dt);
57785 if(c.dateValue == dt){
57795 findCells : function(rec) {
57796 var s = rec.data.start_dt.clone().clearTime().getTime();
57798 var e= rec.data.end_dt.clone().clearTime().getTime();
57801 this.cells.each(function(c){
57802 ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
57804 if(c.dateValue > e){
57807 if(c.dateValue < s){
57816 findBestRow: function(cells)
57820 for (var i =0 ; i < cells.length;i++) {
57821 ret = Math.max(cells[i].rows || 0,ret);
57828 addItem : function(rec)
57830 // look for vertical location slot in
57831 var cells = this.findCells(rec);
57833 rec.row = this.findBestRow(cells);
57835 // work out the location.
57839 for(var i =0; i < cells.length; i++) {
57847 if (crow.start.getY() == cells[i].getY()) {
57849 crow.end = cells[i];
57865 for (var i = 0; i < cells.length;i++) {
57866 cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
57873 clearEvents: function() {
57875 if (!this.eventStore.getCount()) {
57878 // reset number of rows in cells.
57879 Roo.each(this.cells.elements, function(c){
57883 this.eventStore.each(function(e) {
57884 this.clearEvent(e);
57889 clearEvent : function(ev)
57892 Roo.each(ev.els, function(el) {
57893 el.un('mouseenter' ,this.onEventEnter, this);
57894 el.un('mouseleave' ,this.onEventLeave, this);
57902 renderEvent : function(ev,ctr) {
57904 ctr = this.view.el.select('.fc-event-container',true).first();
57908 this.clearEvent(ev);
57914 var cells = ev.cells;
57915 var rows = ev.rows;
57916 this.fireEvent('eventrender', this, ev);
57918 for(var i =0; i < rows.length; i++) {
57922 cls += ' fc-event-start';
57924 if ((i+1) == rows.length) {
57925 cls += ' fc-event-end';
57928 //Roo.log(ev.data);
57929 // how many rows should it span..
57930 var cg = this.eventTmpl.append(ctr,Roo.apply({
57933 }, ev.data) , true);
57936 cg.on('mouseenter' ,this.onEventEnter, this, ev);
57937 cg.on('mouseleave' ,this.onEventLeave, this, ev);
57938 cg.on('click', this.onEventClick, this, ev);
57942 var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
57943 var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
57946 cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);
57947 cg.setWidth(ebox.right - sbox.x -2);
57951 renderEvents: function()
57953 // first make sure there is enough space..
57955 if (!this.eventTmpl) {
57956 this.eventTmpl = new Roo.Template(
57957 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}" style="position: absolute" unselectable="on">' +
57958 '<div class="fc-event-inner">' +
57959 '<span class="fc-event-time">{time}</span>' +
57960 '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
57962 '<div class="ui-resizable-heandle ui-resizable-e"> </div>' +
57970 this.cells.each(function(c) {
57971 //Roo.log(c.select('.fc-day-content div',true).first());
57972 c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
57975 var ctr = this.view.el.select('.fc-event-container',true).first();
57978 this.eventStore.each(function(ev){
57980 this.renderEvent(ev);
57984 this.view.layout();
57988 onEventEnter: function (e, el,event,d) {
57989 this.fireEvent('evententer', this, el, event);
57992 onEventLeave: function (e, el,event,d) {
57993 this.fireEvent('eventleave', this, el, event);
57996 onEventClick: function (e, el,event,d) {
57997 this.fireEvent('eventclick', this, el, event);
58000 onMonthChange: function () {
58004 onLoad: function () {
58006 //Roo.log('calendar onload');
58008 if(this.eventStore.getCount() > 0){
58012 this.eventStore.each(function(d){
58017 if (typeof(add.end_dt) == 'undefined') {
58018 Roo.log("Missing End time in calendar data: ");
58022 if (typeof(add.start_dt) == 'undefined') {
58023 Roo.log("Missing Start time in calendar data: ");
58027 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
58028 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
58029 add.id = add.id || d.id;
58030 add.title = add.title || '??';
58038 this.renderEvents();
58048 render : function ()
58052 if (!this.view.el.hasClass('course-timesheet')) {
58053 this.view.el.addClass('course-timesheet');
58055 if (this.tsStyle) {
58060 Roo.log(_this.grid.view.el.getWidth());
58063 this.tsStyle = Roo.util.CSS.createStyleSheet({
58064 '.course-timesheet .x-grid-row' : {
58067 '.x-grid-row td' : {
58068 'vertical-align' : 0
58070 '.course-edit-link' : {
58072 'text-overflow' : 'ellipsis',
58073 'overflow' : 'hidden',
58074 'white-space' : 'nowrap',
58075 'cursor' : 'pointer'
58080 '.de-act-sup-link' : {
58081 'color' : 'purple',
58082 'text-decoration' : 'line-through'
58086 'text-decoration' : 'line-through'
58088 '.course-timesheet .course-highlight' : {
58089 'border-top-style': 'dashed !important',
58090 'border-bottom-bottom': 'dashed !important'
58092 '.course-timesheet .course-item' : {
58093 'font-family' : 'tahoma, arial, helvetica',
58094 'font-size' : '11px',
58095 'overflow' : 'hidden',
58096 'padding-left' : '10px',
58097 'padding-right' : '10px',
58098 'padding-top' : '10px'
58106 monitorWindowResize : false,
58107 cellrenderer : function(v,x,r)
58112 xtype: 'CellSelectionModel',
58119 beforeload : function (_self, options)
58121 options.params = options.params || {};
58122 options.params._month = _this.monthField.getValue();
58123 options.params.limit = 9999;
58124 options.params['sort'] = 'when_dt';
58125 options.params['dir'] = 'ASC';
58126 this.proxy.loadResponse = this.loadResponse;
58128 //this.addColumns();
58130 load : function (_self, records, options)
58132 _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
58133 // if you click on the translation.. you can edit it...
58134 var el = Roo.get(this);
58135 var id = el.dom.getAttribute('data-id');
58136 var d = el.dom.getAttribute('data-date');
58137 var t = el.dom.getAttribute('data-time');
58138 //var id = this.child('span').dom.textContent;
58141 Pman.Dialog.CourseCalendar.show({
58145 productitem_active : id ? 1 : 0
58147 _this.grid.ds.load({});
58152 _this.panel.fireEvent('resize', [ '', '' ]);
58155 loadResponse : function(o, success, response){
58156 // this is overridden on before load..
58158 Roo.log("our code?");
58159 //Roo.log(success);
58160 //Roo.log(response)
58161 delete this.activeRequest;
58163 this.fireEvent("loadexception", this, o, response);
58164 o.request.callback.call(o.request.scope, null, o.request.arg, false);
58169 result = o.reader.read(response);
58171 Roo.log("load exception?");
58172 this.fireEvent("loadexception", this, o, response, e);
58173 o.request.callback.call(o.request.scope, null, o.request.arg, false);
58176 Roo.log("ready...");
58177 // loop through result.records;
58178 // and set this.tdate[date] = [] << array of records..
58180 Roo.each(result.records, function(r){
58182 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
58183 _this.tdata[r.data.when_dt.format('j')] = [];
58185 _this.tdata[r.data.when_dt.format('j')].push(r.data);
58188 //Roo.log(_this.tdata);
58190 result.records = [];
58191 result.totalRecords = 6;
58193 // let's generate some duumy records for the rows.
58194 //var st = _this.dateField.getValue();
58196 // work out monday..
58197 //st = st.add(Date.DAY, -1 * st.format('w'));
58199 var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58201 var firstOfMonth = date.getFirstDayOfMonth();
58202 var days = date.getDaysInMonth();
58204 var firstAdded = false;
58205 for (var i = 0; i < result.totalRecords ; i++) {
58206 //var d= st.add(Date.DAY, i);
58209 for(var w = 0 ; w < 7 ; w++){
58210 if(!firstAdded && firstOfMonth != w){
58217 var dd = (d > 0 && d < 10) ? "0"+d : d;
58218 row['weekday'+w] = String.format(
58219 '<span style="font-size: 16px;"><b>{0}</b></span>'+
58220 '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
58222 date.format('Y-m-')+dd
58225 if(typeof(_this.tdata[d]) != 'undefined'){
58226 Roo.each(_this.tdata[d], function(r){
58230 var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
58231 if(r.parent_id*1>0){
58232 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
58235 if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
58236 deactive = 'de-act-link';
58239 row['weekday'+w] += String.format(
58240 '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
58242 r.product_id_name, //1
58243 r.when_dt.format('h:ia'), //2
58253 // only do this if something added..
58255 result.records.push(_this.grid.dataSource.reader.newRow(row));
58259 // push it twice. (second one with an hour..
58263 this.fireEvent("load", this, o, o.request.arg);
58264 o.request.callback.call(o.request.scope, result, o.request.arg, true);
58266 sortInfo : {field: 'when_dt', direction : 'ASC' },
58268 xtype: 'HttpProxy',
58271 url : baseURL + '/Roo/Shop_course.php'
58274 xtype: 'JsonReader',
58291 'name': 'parent_id',
58295 'name': 'product_id',
58299 'name': 'productitem_id',
58317 click : function (_self, e)
58319 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58320 sd.setMonth(sd.getMonth()-1);
58321 _this.monthField.setValue(sd.format('Y-m-d'));
58322 _this.grid.ds.load({});
58328 xtype: 'Separator',
58332 xtype: 'MonthField',
58335 render : function (_self)
58337 _this.monthField = _self;
58338 // _this.monthField.set today
58340 select : function (combo, date)
58342 _this.grid.ds.load({});
58345 value : (function() { return new Date(); })()
58348 xtype: 'Separator',
58354 text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
58364 click : function (_self, e)
58366 var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
58367 sd.setMonth(sd.getMonth()+1);
58368 _this.monthField.setValue(sd.format('Y-m-d'));
58369 _this.grid.ds.load({});
58382 * Ext JS Library 1.1.1
58383 * Copyright(c) 2006-2007, Ext JS, LLC.
58385 * Originally Released Under LGPL - original licence link has changed is not relivant.
58388 * <script type="text/javascript">
58392 * @class Roo.LoadMask
58393 * A simple utility class for generically masking elements while loading data. If the element being masked has
58394 * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
58395 * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
58396 * element's UpdateManager load indicator and will be destroyed after the initial load.
58398 * Create a new LoadMask
58399 * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
58400 * @param {Object} config The config object
58402 Roo.LoadMask = function(el, config){
58403 this.el = Roo.get(el);
58404 Roo.apply(this, config);
58406 this.store.on('beforeload', this.onBeforeLoad, this);
58407 this.store.on('load', this.onLoad, this);
58408 this.store.on('loadexception', this.onLoadException, this);
58409 this.removeMask = false;
58411 var um = this.el.getUpdateManager();
58412 um.showLoadIndicator = false; // disable the default indicator
58413 um.on('beforeupdate', this.onBeforeLoad, this);
58414 um.on('update', this.onLoad, this);
58415 um.on('failure', this.onLoad, this);
58416 this.removeMask = true;
58420 Roo.LoadMask.prototype = {
58422 * @cfg {Boolean} removeMask
58423 * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
58424 * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
58427 * @cfg {String} msg
58428 * The text to display in a centered loading message box (defaults to 'Loading...')
58430 msg : 'Loading...',
58432 * @cfg {String} msgCls
58433 * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
58435 msgCls : 'x-mask-loading',
58438 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
58444 * Disables the mask to prevent it from being displayed
58446 disable : function(){
58447 this.disabled = true;
58451 * Enables the mask so that it can be displayed
58453 enable : function(){
58454 this.disabled = false;
58457 onLoadException : function()
58459 Roo.log(arguments);
58461 if (typeof(arguments[3]) != 'undefined') {
58462 Roo.MessageBox.alert("Error loading",arguments[3]);
58466 if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
58467 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
58476 this.el.unmask(this.removeMask);
58479 onLoad : function()
58481 this.el.unmask(this.removeMask);
58485 onBeforeLoad : function(){
58486 if(!this.disabled){
58487 this.el.mask(this.msg, this.msgCls);
58492 destroy : function(){
58494 this.store.un('beforeload', this.onBeforeLoad, this);
58495 this.store.un('load', this.onLoad, this);
58496 this.store.un('loadexception', this.onLoadException, this);
58498 var um = this.el.getUpdateManager();
58499 um.un('beforeupdate', this.onBeforeLoad, this);
58500 um.un('update', this.onLoad, this);
58501 um.un('failure', this.onLoad, this);
58506 * Ext JS Library 1.1.1
58507 * Copyright(c) 2006-2007, Ext JS, LLC.
58509 * Originally Released Under LGPL - original licence link has changed is not relivant.
58512 * <script type="text/javascript">
58517 * @class Roo.XTemplate
58518 * @extends Roo.Template
58519 * Provides a template that can have nested templates for loops or conditionals. The syntax is:
58521 var t = new Roo.XTemplate(
58522 '<select name="{name}">',
58523 '<tpl for="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
58527 // then append, applying the master template values
58530 * Supported features:
58535 {a_variable} - output encoded.
58536 {a_variable.format:("Y-m-d")} - call a method on the variable
58537 {a_variable:raw} - unencoded output
58538 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
58539 {a_variable:this.method_on_template(...)} - call a method on the template object.
58544 <tpl for="a_variable or condition.."></tpl>
58545 <tpl if="a_variable or condition"></tpl>
58546 <tpl exec="some javascript"></tpl>
58547 <tpl name="named_template"></tpl> (experimental)
58549 <tpl for="."></tpl> - just iterate the property..
58550 <tpl for=".."></tpl> - iterates with the parent (probably the template)
58554 Roo.XTemplate = function()
58556 Roo.XTemplate.superclass.constructor.apply(this, arguments);
58563 Roo.extend(Roo.XTemplate, Roo.Template, {
58566 * The various sub templates
58571 * basic tag replacing syntax
58574 * // you can fake an object call by doing this
58578 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
58581 * compile the template
58583 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
58586 compile: function()
58590 s = ['<tpl>', s, '</tpl>'].join('');
58592 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
58593 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
58594 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
58595 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
58596 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
58601 while(true == !!(m = s.match(re))){
58602 var forMatch = m[0].match(nameRe),
58603 ifMatch = m[0].match(ifRe),
58604 execMatch = m[0].match(execRe),
58605 namedMatch = m[0].match(namedRe),
58610 name = forMatch && forMatch[1] ? forMatch[1] : '';
58613 // if - puts fn into test..
58614 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
58616 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
58621 // exec - calls a function... returns empty if true is returned.
58622 exp = execMatch && execMatch[1] ? execMatch[1] : null;
58624 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
58632 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
58633 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
58634 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
58637 var uid = namedMatch ? namedMatch[1] : id;
58641 id: namedMatch ? namedMatch[1] : id,
58648 s = s.replace(m[0], '');
58650 s = s.replace(m[0], '{xtpl'+ id + '}');
58655 for(var i = tpls.length-1; i >= 0; --i){
58656 this.compileTpl(tpls[i]);
58657 this.tpls[tpls[i].id] = tpls[i];
58659 this.master = tpls[tpls.length-1];
58663 * same as applyTemplate, except it's done to one of the subTemplates
58664 * when using named templates, you can do:
58666 * var str = pl.applySubTemplate('your-name', values);
58669 * @param {Number} id of the template
58670 * @param {Object} values to apply to template
58671 * @param {Object} parent (normaly the instance of this object)
58673 applySubTemplate : function(id, values, parent)
58677 var t = this.tpls[id];
58681 if(t.test && !t.test.call(this, values, parent)){
58685 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
58686 Roo.log(e.toString());
58692 if(t.exec && t.exec.call(this, values, parent)){
58696 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
58697 Roo.log(e.toString());
58702 var vs = t.target ? t.target.call(this, values, parent) : values;
58703 parent = t.target ? values : parent;
58704 if(t.target && vs instanceof Array){
58706 for(var i = 0, len = vs.length; i < len; i++){
58707 buf[buf.length] = t.compiled.call(this, vs[i], parent);
58709 return buf.join('');
58711 return t.compiled.call(this, vs, parent);
58713 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
58714 Roo.log(e.toString());
58715 Roo.log(t.compiled);
58720 compileTpl : function(tpl)
58722 var fm = Roo.util.Format;
58723 var useF = this.disableFormats !== true;
58724 var sep = Roo.isGecko ? "+" : ",";
58725 var undef = function(str) {
58726 Roo.log("Property not found :" + str);
58730 var fn = function(m, name, format, args)
58732 //Roo.log(arguments);
58733 args = args ? args.replace(/\\'/g,"'") : args;
58734 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
58735 if (typeof(format) == 'undefined') {
58736 format= 'htmlEncode';
58738 if (format == 'raw' ) {
58742 if(name.substr(0, 4) == 'xtpl'){
58743 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
58746 // build an array of options to determine if value is undefined..
58748 // basically get 'xxxx.yyyy' then do
58749 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
58750 // (function () { Roo.log("Property not found"); return ''; })() :
58755 Roo.each(name.split('.'), function(st) {
58756 lookfor += (lookfor.length ? '.': '') + st;
58757 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
58760 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
58763 if(format && useF){
58765 args = args ? ',' + args : "";
58767 if(format.substr(0, 5) != "this."){
58768 format = "fm." + format + '(';
58770 format = 'this.call("'+ format.substr(5) + '", ';
58774 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
58778 // called with xxyx.yuu:(test,test)
58780 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
58782 // raw.. - :raw modifier..
58783 return "'"+ sep + udef_st + name + ")"+sep+"'";
58787 // branched to use + in gecko and [].join() in others
58789 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
58790 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
58793 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
58794 body.push(tpl.body.replace(/(\r\n|\n)/g,
58795 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
58796 body.push("'].join('');};};");
58797 body = body.join('');
58800 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
58802 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
58808 applyTemplate : function(values){
58809 return this.master.compiled.call(this, values, {});
58810 //var s = this.subs;
58813 apply : function(){
58814 return this.applyTemplate.apply(this, arguments);
58819 Roo.XTemplate.from = function(el){
58820 el = Roo.getDom(el);
58821 return new Roo.XTemplate(el.value || el.innerHTML);