roojs-ui.js
[roojs1] / roojs-ui-debug.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13
14 /*
15  * These classes are derivatives of the similarly named classes in the YUI Library.
16  * The original license:
17  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
18  * Code licensed under the BSD License:
19  * http://developer.yahoo.net/yui/license.txt
20  */
21
22 (function() {
23
24 var Event=Roo.EventManager;
25 var Dom=Roo.lib.Dom;
26
27 /**
28  * @class Roo.dd.DragDrop
29  * @extends Roo.util.Observable
30  * Defines the interface and base operation of items that that can be
31  * dragged or can be drop targets.  It was designed to be extended, overriding
32  * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
33  * Up to three html elements can be associated with a DragDrop instance:
34  * <ul>
35  * <li>linked element: the element that is passed into the constructor.
36  * This is the element which defines the boundaries for interaction with
37  * other DragDrop objects.</li>
38  * <li>handle element(s): The drag operation only occurs if the element that
39  * was clicked matches a handle element.  By default this is the linked
40  * element, but there are times that you will want only a portion of the
41  * linked element to initiate the drag operation, and the setHandleElId()
42  * method provides a way to define this.</li>
43  * <li>drag element: this represents the element that would be moved along
44  * with the cursor during a drag operation.  By default, this is the linked
45  * element itself as in {@link Roo.dd.DD}.  setDragElId() lets you define
46  * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
47  * </li>
48  * </ul>
49  * This class should not be instantiated until the onload event to ensure that
50  * the associated elements are available.
51  * The following would define a DragDrop obj that would interact with any
52  * other DragDrop obj in the "group1" group:
53  * <pre>
54  *  dd = new Roo.dd.DragDrop("div1", "group1");
55  * </pre>
56  * Since none of the event handlers have been implemented, nothing would
57  * actually happen if you were to run the code above.  Normally you would
58  * override this class or one of the default implementations, but you can
59  * also override the methods you want on an instance of the class...
60  * <pre>
61  *  dd.onDragDrop = function(e, id) {
62  *  &nbsp;&nbsp;alert("dd was dropped on " + id);
63  *  }
64  * </pre>
65  * @constructor
66  * @param {String} id of the element that is linked to this instance
67  * @param {String} sGroup the group of related DragDrop objects
68  * @param {object} config an object containing configurable attributes
69  *                Valid properties for DragDrop:
70  *                    padding, isTarget, maintainOffset, primaryButtonOnly
71  */
72 Roo.dd.DragDrop = function(id, sGroup, config) {
73     if (id) {
74         this.init(id, sGroup, config);
75     }
76     
77 };
78
79 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
80
81     /**
82      * The id of the element associated with this object.  This is what we
83      * refer to as the "linked element" because the size and position of
84      * this element is used to determine when the drag and drop objects have
85      * interacted.
86      * @property id
87      * @type String
88      */
89     id: null,
90
91     /**
92      * Configuration attributes passed into the constructor
93      * @property config
94      * @type object
95      */
96     config: null,
97
98     /**
99      * The id of the element that will be dragged.  By default this is same
100      * as the linked element , but could be changed to another element. Ex:
101      * Roo.dd.DDProxy
102      * @property dragElId
103      * @type String
104      * @private
105      */
106     dragElId: null,
107
108     /**
109      * the id of the element that initiates the drag operation.  By default
110      * this is the linked element, but could be changed to be a child of this
111      * element.  This lets us do things like only starting the drag when the
112      * header element within the linked html element is clicked.
113      * @property handleElId
114      * @type String
115      * @private
116      */
117     handleElId: null,
118
119     /**
120      * An associative array of HTML tags that will be ignored if clicked.
121      * @property invalidHandleTypes
122      * @type {string: string}
123      */
124     invalidHandleTypes: null,
125
126     /**
127      * An associative array of ids for elements that will be ignored if clicked
128      * @property invalidHandleIds
129      * @type {string: string}
130      */
131     invalidHandleIds: null,
132
133     /**
134      * An indexted array of css class names for elements that will be ignored
135      * if clicked.
136      * @property invalidHandleClasses
137      * @type string[]
138      */
139     invalidHandleClasses: null,
140
141     /**
142      * The linked element's absolute X position at the time the drag was
143      * started
144      * @property startPageX
145      * @type int
146      * @private
147      */
148     startPageX: 0,
149
150     /**
151      * The linked element's absolute X position at the time the drag was
152      * started
153      * @property startPageY
154      * @type int
155      * @private
156      */
157     startPageY: 0,
158
159     /**
160      * The group defines a logical collection of DragDrop objects that are
161      * related.  Instances only get events when interacting with other
162      * DragDrop object in the same group.  This lets us define multiple
163      * groups using a single DragDrop subclass if we want.
164      * @property groups
165      * @type {string: string}
166      */
167     groups: null,
168
169     /**
170      * Individual drag/drop instances can be locked.  This will prevent
171      * onmousedown start drag.
172      * @property locked
173      * @type boolean
174      * @private
175      */
176     locked: false,
177
178     /**
179      * Lock this instance
180      * @method lock
181      */
182     lock: function() { this.locked = true; },
183
184     /**
185      * Unlock this instace
186      * @method unlock
187      */
188     unlock: function() { this.locked = false; },
189
190     /**
191      * By default, all insances can be a drop target.  This can be disabled by
192      * setting isTarget to false.
193      * @method isTarget
194      * @type boolean
195      */
196     isTarget: true,
197
198     /**
199      * The padding configured for this drag and drop object for calculating
200      * the drop zone intersection with this object.
201      * @method padding
202      * @type int[]
203      */
204     padding: null,
205
206     /**
207      * Cached reference to the linked element
208      * @property _domRef
209      * @private
210      */
211     _domRef: null,
212
213     /**
214      * Internal typeof flag
215      * @property __ygDragDrop
216      * @private
217      */
218     __ygDragDrop: true,
219
220     /**
221      * Set to true when horizontal contraints are applied
222      * @property constrainX
223      * @type boolean
224      * @private
225      */
226     constrainX: false,
227
228     /**
229      * Set to true when vertical contraints are applied
230      * @property constrainY
231      * @type boolean
232      * @private
233      */
234     constrainY: false,
235
236     /**
237      * The left constraint
238      * @property minX
239      * @type int
240      * @private
241      */
242     minX: 0,
243
244     /**
245      * The right constraint
246      * @property maxX
247      * @type int
248      * @private
249      */
250     maxX: 0,
251
252     /**
253      * The up constraint
254      * @property minY
255      * @type int
256      * @type int
257      * @private
258      */
259     minY: 0,
260
261     /**
262      * The down constraint
263      * @property maxY
264      * @type int
265      * @private
266      */
267     maxY: 0,
268
269     /**
270      * Maintain offsets when we resetconstraints.  Set to true when you want
271      * the position of the element relative to its parent to stay the same
272      * when the page changes
273      *
274      * @property maintainOffset
275      * @type boolean
276      */
277     maintainOffset: false,
278
279     /**
280      * Array of pixel locations the element will snap to if we specified a
281      * horizontal graduation/interval.  This array is generated automatically
282      * when you define a tick interval.
283      * @property xTicks
284      * @type int[]
285      */
286     xTicks: null,
287
288     /**
289      * Array of pixel locations the element will snap to if we specified a
290      * vertical graduation/interval.  This array is generated automatically
291      * when you define a tick interval.
292      * @property yTicks
293      * @type int[]
294      */
295     yTicks: null,
296
297     /**
298      * By default the drag and drop instance will only respond to the primary
299      * button click (left button for a right-handed mouse).  Set to true to
300      * allow drag and drop to start with any mouse click that is propogated
301      * by the browser
302      * @property primaryButtonOnly
303      * @type boolean
304      */
305     primaryButtonOnly: true,
306
307     /**
308      * The availabe property is false until the linked dom element is accessible.
309      * @property available
310      * @type boolean
311      */
312     available: false,
313
314     /**
315      * By default, drags can only be initiated if the mousedown occurs in the
316      * region the linked element is.  This is done in part to work around a
317      * bug in some browsers that mis-report the mousedown if the previous
318      * mouseup happened outside of the window.  This property is set to true
319      * if outer handles are defined.
320      *
321      * @property hasOuterHandles
322      * @type boolean
323      * @default false
324      */
325     hasOuterHandles: false,
326
327     /**
328      * Code that executes immediately before the startDrag event
329      * @method b4StartDrag
330      * @private
331      */
332     b4StartDrag: function(x, y) { },
333
334     /**
335      * Abstract method called after a drag/drop object is clicked
336      * and the drag or mousedown time thresholds have beeen met.
337      * @method startDrag
338      * @param {int} X click location
339      * @param {int} Y click location
340      */
341     startDrag: function(x, y) { /* override this */ },
342
343     /**
344      * Code that executes immediately before the onDrag event
345      * @method b4Drag
346      * @private
347      */
348     b4Drag: function(e) { },
349
350     /**
351      * Abstract method called during the onMouseMove event while dragging an
352      * object.
353      * @method onDrag
354      * @param {Event} e the mousemove event
355      */
356     onDrag: function(e) { /* override this */ },
357
358     /**
359      * Abstract method called when this element fist begins hovering over
360      * another DragDrop obj
361      * @method onDragEnter
362      * @param {Event} e the mousemove event
363      * @param {String|DragDrop[]} id In POINT mode, the element
364      * id this is hovering over.  In INTERSECT mode, an array of one or more
365      * dragdrop items being hovered over.
366      */
367     onDragEnter: function(e, id) { /* override this */ },
368
369     /**
370      * Code that executes immediately before the onDragOver event
371      * @method b4DragOver
372      * @private
373      */
374     b4DragOver: function(e) { },
375
376     /**
377      * Abstract method called when this element is hovering over another
378      * DragDrop obj
379      * @method onDragOver
380      * @param {Event} e the mousemove event
381      * @param {String|DragDrop[]} id In POINT mode, the element
382      * id this is hovering over.  In INTERSECT mode, an array of dd items
383      * being hovered over.
384      */
385     onDragOver: function(e, id) { /* override this */ },
386
387     /**
388      * Code that executes immediately before the onDragOut event
389      * @method b4DragOut
390      * @private
391      */
392     b4DragOut: function(e) { },
393
394     /**
395      * Abstract method called when we are no longer hovering over an element
396      * @method onDragOut
397      * @param {Event} e the mousemove event
398      * @param {String|DragDrop[]} id In POINT mode, the element
399      * id this was hovering over.  In INTERSECT mode, an array of dd items
400      * that the mouse is no longer over.
401      */
402     onDragOut: function(e, id) { /* override this */ },
403
404     /**
405      * Code that executes immediately before the onDragDrop event
406      * @method b4DragDrop
407      * @private
408      */
409     b4DragDrop: function(e) { },
410
411     /**
412      * Abstract method called when this item is dropped on another DragDrop
413      * obj
414      * @method onDragDrop
415      * @param {Event} e the mouseup event
416      * @param {String|DragDrop[]} id In POINT mode, the element
417      * id this was dropped on.  In INTERSECT mode, an array of dd items this
418      * was dropped on.
419      */
420     onDragDrop: function(e, id) { /* override this */ },
421
422     /**
423      * Abstract method called when this item is dropped on an area with no
424      * drop target
425      * @method onInvalidDrop
426      * @param {Event} e the mouseup event
427      */
428     onInvalidDrop: function(e) { /* override this */ },
429
430     /**
431      * Code that executes immediately before the endDrag event
432      * @method b4EndDrag
433      * @private
434      */
435     b4EndDrag: function(e) { },
436
437     /**
438      * Fired when we are done dragging the object
439      * @method endDrag
440      * @param {Event} e the mouseup event
441      */
442     endDrag: function(e) { /* override this */ },
443
444     /**
445      * Code executed immediately before the onMouseDown event
446      * @method b4MouseDown
447      * @param {Event} e the mousedown event
448      * @private
449      */
450     b4MouseDown: function(e) {  },
451
452     /**
453      * Event handler that fires when a drag/drop obj gets a mousedown
454      * @method onMouseDown
455      * @param {Event} e the mousedown event
456      */
457     onMouseDown: function(e) { /* override this */ },
458
459     /**
460      * Event handler that fires when a drag/drop obj gets a mouseup
461      * @method onMouseUp
462      * @param {Event} e the mouseup event
463      */
464     onMouseUp: function(e) { /* override this */ },
465
466     /**
467      * Override the onAvailable method to do what is needed after the initial
468      * position was determined.
469      * @method onAvailable
470      */
471     onAvailable: function () {
472     },
473
474     /*
475      * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
476      * @type Object
477      */
478     defaultPadding : {left:0, right:0, top:0, bottom:0},
479
480     /*
481      * Initializes the drag drop object's constraints to restrict movement to a certain element.
482  *
483  * Usage:
484  <pre><code>
485  var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
486                 { dragElId: "existingProxyDiv" });
487  dd.startDrag = function(){
488      this.constrainTo("parent-id");
489  };
490  </code></pre>
491  * Or you can initalize it using the {@link Roo.Element} object:
492  <pre><code>
493  Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
494      startDrag : function(){
495          this.constrainTo("parent-id");
496      }
497  });
498  </code></pre>
499      * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
500      * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
501      * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
502      * an object containing the sides to pad. For example: {right:10, bottom:10}
503      * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
504      */
505     constrainTo : function(constrainTo, pad, inContent){
506         if(typeof pad == "number"){
507             pad = {left: pad, right:pad, top:pad, bottom:pad};
508         }
509         pad = pad || this.defaultPadding;
510         var b = Roo.get(this.getEl()).getBox();
511         var ce = Roo.get(constrainTo);
512         var s = ce.getScroll();
513         var c, cd = ce.dom;
514         if(cd == document.body){
515             c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
516         }else{
517             xy = ce.getXY();
518             c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
519         }
520
521
522         var topSpace = b.y - c.y;
523         var leftSpace = b.x - c.x;
524
525         this.resetConstraints();
526         this.setXConstraint(leftSpace - (pad.left||0), // left
527                 c.width - leftSpace - b.width - (pad.right||0) //right
528         );
529         this.setYConstraint(topSpace - (pad.top||0), //top
530                 c.height - topSpace - b.height - (pad.bottom||0) //bottom
531         );
532     },
533
534     /**
535      * Returns a reference to the linked element
536      * @method getEl
537      * @return {HTMLElement} the html element
538      */
539     getEl: function() {
540         if (!this._domRef) {
541             this._domRef = Roo.getDom(this.id);
542         }
543
544         return this._domRef;
545     },
546
547     /**
548      * Returns a reference to the actual element to drag.  By default this is
549      * the same as the html element, but it can be assigned to another
550      * element. An example of this can be found in Roo.dd.DDProxy
551      * @method getDragEl
552      * @return {HTMLElement} the html element
553      */
554     getDragEl: function() {
555         return Roo.getDom(this.dragElId);
556     },
557
558     /**
559      * Sets up the DragDrop object.  Must be called in the constructor of any
560      * Roo.dd.DragDrop subclass
561      * @method init
562      * @param id the id of the linked element
563      * @param {String} sGroup the group of related items
564      * @param {object} config configuration attributes
565      */
566     init: function(id, sGroup, config) {
567         this.initTarget(id, sGroup, config);
568         if (!Roo.isTouch) {
569             Event.on(this.id, "mousedown", this.handleMouseDown, this);
570         }
571         Event.on(this.id, "touchstart", this.handleMouseDown, this);
572         // Event.on(this.id, "selectstart", Event.preventDefault);
573     },
574
575     /**
576      * Initializes Targeting functionality only... the object does not
577      * get a mousedown handler.
578      * @method initTarget
579      * @param id the id of the linked element
580      * @param {String} sGroup the group of related items
581      * @param {object} config configuration attributes
582      */
583     initTarget: function(id, sGroup, config) {
584
585         // configuration attributes
586         this.config = config || {};
587
588         // create a local reference to the drag and drop manager
589         this.DDM = Roo.dd.DDM;
590         // initialize the groups array
591         this.groups = {};
592
593         // assume that we have an element reference instead of an id if the
594         // parameter is not a string
595         if (typeof id !== "string") {
596             id = Roo.id(id);
597         }
598
599         // set the id
600         this.id = id;
601
602         // add to an interaction group
603         this.addToGroup((sGroup) ? sGroup : "default");
604
605         // We don't want to register this as the handle with the manager
606         // so we just set the id rather than calling the setter.
607         this.handleElId = id;
608
609         // the linked element is the element that gets dragged by default
610         this.setDragElId(id);
611
612         // by default, clicked anchors will not start drag operations.
613         this.invalidHandleTypes = { A: "A" };
614         this.invalidHandleIds = {};
615         this.invalidHandleClasses = [];
616
617         this.applyConfig();
618
619         this.handleOnAvailable();
620     },
621
622     /**
623      * Applies the configuration parameters that were passed into the constructor.
624      * This is supposed to happen at each level through the inheritance chain.  So
625      * a DDProxy implentation will execute apply config on DDProxy, DD, and
626      * DragDrop in order to get all of the parameters that are available in
627      * each object.
628      * @method applyConfig
629      */
630     applyConfig: function() {
631
632         // configurable properties:
633         //    padding, isTarget, maintainOffset, primaryButtonOnly
634         this.padding           = this.config.padding || [0, 0, 0, 0];
635         this.isTarget          = (this.config.isTarget !== false);
636         this.maintainOffset    = (this.config.maintainOffset);
637         this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
638
639     },
640
641     /**
642      * Executed when the linked element is available
643      * @method handleOnAvailable
644      * @private
645      */
646     handleOnAvailable: function() {
647         this.available = true;
648         this.resetConstraints();
649         this.onAvailable();
650     },
651
652      /**
653      * Configures the padding for the target zone in px.  Effectively expands
654      * (or reduces) the virtual object size for targeting calculations.
655      * Supports css-style shorthand; if only one parameter is passed, all sides
656      * will have that padding, and if only two are passed, the top and bottom
657      * will have the first param, the left and right the second.
658      * @method setPadding
659      * @param {int} iTop    Top pad
660      * @param {int} iRight  Right pad
661      * @param {int} iBot    Bot pad
662      * @param {int} iLeft   Left pad
663      */
664     setPadding: function(iTop, iRight, iBot, iLeft) {
665         // this.padding = [iLeft, iRight, iTop, iBot];
666         if (!iRight && 0 !== iRight) {
667             this.padding = [iTop, iTop, iTop, iTop];
668         } else if (!iBot && 0 !== iBot) {
669             this.padding = [iTop, iRight, iTop, iRight];
670         } else {
671             this.padding = [iTop, iRight, iBot, iLeft];
672         }
673     },
674
675     /**
676      * Stores the initial placement of the linked element.
677      * @method setInitialPosition
678      * @param {int} diffX   the X offset, default 0
679      * @param {int} diffY   the Y offset, default 0
680      */
681     setInitPosition: function(diffX, diffY) {
682         var el = this.getEl();
683
684         if (!this.DDM.verifyEl(el)) {
685             return;
686         }
687
688         var dx = diffX || 0;
689         var dy = diffY || 0;
690
691         var p = Dom.getXY( el );
692
693         this.initPageX = p[0] - dx;
694         this.initPageY = p[1] - dy;
695
696         this.lastPageX = p[0];
697         this.lastPageY = p[1];
698
699
700         this.setStartPosition(p);
701     },
702
703     /**
704      * Sets the start position of the element.  This is set when the obj
705      * is initialized, the reset when a drag is started.
706      * @method setStartPosition
707      * @param pos current position (from previous lookup)
708      * @private
709      */
710     setStartPosition: function(pos) {
711         var p = pos || Dom.getXY( this.getEl() );
712         this.deltaSetXY = null;
713
714         this.startPageX = p[0];
715         this.startPageY = p[1];
716     },
717
718     /**
719      * Add this instance to a group of related drag/drop objects.  All
720      * instances belong to at least one group, and can belong to as many
721      * groups as needed.
722      * @method addToGroup
723      * @param sGroup {string} the name of the group
724      */
725     addToGroup: function(sGroup) {
726         this.groups[sGroup] = true;
727         this.DDM.regDragDrop(this, sGroup);
728     },
729
730     /**
731      * Remove's this instance from the supplied interaction group
732      * @method removeFromGroup
733      * @param {string}  sGroup  The group to drop
734      */
735     removeFromGroup: function(sGroup) {
736         if (this.groups[sGroup]) {
737             delete this.groups[sGroup];
738         }
739
740         this.DDM.removeDDFromGroup(this, sGroup);
741     },
742
743     /**
744      * Allows you to specify that an element other than the linked element
745      * will be moved with the cursor during a drag
746      * @method setDragElId
747      * @param id {string} the id of the element that will be used to initiate the drag
748      */
749     setDragElId: function(id) {
750         this.dragElId = id;
751     },
752
753     /**
754      * Allows you to specify a child of the linked element that should be
755      * used to initiate the drag operation.  An example of this would be if
756      * you have a content div with text and links.  Clicking anywhere in the
757      * content area would normally start the drag operation.  Use this method
758      * to specify that an element inside of the content div is the element
759      * that starts the drag operation.
760      * @method setHandleElId
761      * @param id {string} the id of the element that will be used to
762      * initiate the drag.
763      */
764     setHandleElId: function(id) {
765         if (typeof id !== "string") {
766             id = Roo.id(id);
767         }
768         this.handleElId = id;
769         this.DDM.regHandle(this.id, id);
770     },
771
772     /**
773      * Allows you to set an element outside of the linked element as a drag
774      * handle
775      * @method setOuterHandleElId
776      * @param id the id of the element that will be used to initiate the drag
777      */
778     setOuterHandleElId: function(id) {
779         if (typeof id !== "string") {
780             id = Roo.id(id);
781         }
782         Event.on(id, "mousedown",
783                 this.handleMouseDown, this);
784         this.setHandleElId(id);
785
786         this.hasOuterHandles = true;
787     },
788
789     /**
790      * Remove all drag and drop hooks for this element
791      * @method unreg
792      */
793     unreg: function() {
794         Event.un(this.id, "mousedown",
795                 this.handleMouseDown);
796         Event.un(this.id, "touchstart",
797                 this.handleMouseDown);
798         this._domRef = null;
799         this.DDM._remove(this);
800     },
801
802     destroy : function(){
803         this.unreg();
804     },
805
806     /**
807      * Returns true if this instance is locked, or the drag drop mgr is locked
808      * (meaning that all drag/drop is disabled on the page.)
809      * @method isLocked
810      * @return {boolean} true if this obj or all drag/drop is locked, else
811      * false
812      */
813     isLocked: function() {
814         return (this.DDM.isLocked() || this.locked);
815     },
816
817     /**
818      * Fired when this object is clicked
819      * @method handleMouseDown
820      * @param {Event} e
821      * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
822      * @private
823      */
824     handleMouseDown: function(e, oDD){
825      
826         if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
827             //Roo.log('not touch/ button !=0');
828             return;
829         }
830         if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
831             return; // double touch..
832         }
833         
834
835         if (this.isLocked()) {
836             //Roo.log('locked');
837             return;
838         }
839
840         this.DDM.refreshCache(this.groups);
841 //        Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
842         var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
843         if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) )  {
844             //Roo.log('no outer handes or not over target');
845                 // do nothing.
846         } else {
847 //            Roo.log('check validator');
848             if (this.clickValidator(e)) {
849 //                Roo.log('validate success');
850                 // set the initial element position
851                 this.setStartPosition();
852
853
854                 this.b4MouseDown(e);
855                 this.onMouseDown(e);
856
857                 this.DDM.handleMouseDown(e, this);
858
859                 this.DDM.stopEvent(e);
860             } else {
861
862
863             }
864         }
865     },
866
867     clickValidator: function(e) {
868         var target = e.getTarget();
869         return ( this.isValidHandleChild(target) &&
870                     (this.id == this.handleElId ||
871                         this.DDM.handleWasClicked(target, this.id)) );
872     },
873
874     /**
875      * Allows you to specify a tag name that should not start a drag operation
876      * when clicked.  This is designed to facilitate embedding links within a
877      * drag handle that do something other than start the drag.
878      * @method addInvalidHandleType
879      * @param {string} tagName the type of element to exclude
880      */
881     addInvalidHandleType: function(tagName) {
882         var type = tagName.toUpperCase();
883         this.invalidHandleTypes[type] = type;
884     },
885
886     /**
887      * Lets you to specify an element id for a child of a drag handle
888      * that should not initiate a drag
889      * @method addInvalidHandleId
890      * @param {string} id the element id of the element you wish to ignore
891      */
892     addInvalidHandleId: function(id) {
893         if (typeof id !== "string") {
894             id = Roo.id(id);
895         }
896         this.invalidHandleIds[id] = id;
897     },
898
899     /**
900      * Lets you specify a css class of elements that will not initiate a drag
901      * @method addInvalidHandleClass
902      * @param {string} cssClass the class of the elements you wish to ignore
903      */
904     addInvalidHandleClass: function(cssClass) {
905         this.invalidHandleClasses.push(cssClass);
906     },
907
908     /**
909      * Unsets an excluded tag name set by addInvalidHandleType
910      * @method removeInvalidHandleType
911      * @param {string} tagName the type of element to unexclude
912      */
913     removeInvalidHandleType: function(tagName) {
914         var type = tagName.toUpperCase();
915         // this.invalidHandleTypes[type] = null;
916         delete this.invalidHandleTypes[type];
917     },
918
919     /**
920      * Unsets an invalid handle id
921      * @method removeInvalidHandleId
922      * @param {string} id the id of the element to re-enable
923      */
924     removeInvalidHandleId: function(id) {
925         if (typeof id !== "string") {
926             id = Roo.id(id);
927         }
928         delete this.invalidHandleIds[id];
929     },
930
931     /**
932      * Unsets an invalid css class
933      * @method removeInvalidHandleClass
934      * @param {string} cssClass the class of the element(s) you wish to
935      * re-enable
936      */
937     removeInvalidHandleClass: function(cssClass) {
938         for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
939             if (this.invalidHandleClasses[i] == cssClass) {
940                 delete this.invalidHandleClasses[i];
941             }
942         }
943     },
944
945     /**
946      * Checks the tag exclusion list to see if this click should be ignored
947      * @method isValidHandleChild
948      * @param {HTMLElement} node the HTMLElement to evaluate
949      * @return {boolean} true if this is a valid tag type, false if not
950      */
951     isValidHandleChild: function(node) {
952
953         var valid = true;
954         // var n = (node.nodeName == "#text") ? node.parentNode : node;
955         var nodeName;
956         try {
957             nodeName = node.nodeName.toUpperCase();
958         } catch(e) {
959             nodeName = node.nodeName;
960         }
961         valid = valid && !this.invalidHandleTypes[nodeName];
962         valid = valid && !this.invalidHandleIds[node.id];
963
964         for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
965             valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
966         }
967
968
969         return valid;
970
971     },
972
973     /**
974      * Create the array of horizontal tick marks if an interval was specified
975      * in setXConstraint().
976      * @method setXTicks
977      * @private
978      */
979     setXTicks: function(iStartX, iTickSize) {
980         this.xTicks = [];
981         this.xTickSize = iTickSize;
982
983         var tickMap = {};
984
985         for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
986             if (!tickMap[i]) {
987                 this.xTicks[this.xTicks.length] = i;
988                 tickMap[i] = true;
989             }
990         }
991
992         for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
993             if (!tickMap[i]) {
994                 this.xTicks[this.xTicks.length] = i;
995                 tickMap[i] = true;
996             }
997         }
998
999         this.xTicks.sort(this.DDM.numericSort) ;
1000     },
1001
1002     /**
1003      * Create the array of vertical tick marks if an interval was specified in
1004      * setYConstraint().
1005      * @method setYTicks
1006      * @private
1007      */
1008     setYTicks: function(iStartY, iTickSize) {
1009         this.yTicks = [];
1010         this.yTickSize = iTickSize;
1011
1012         var tickMap = {};
1013
1014         for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
1015             if (!tickMap[i]) {
1016                 this.yTicks[this.yTicks.length] = i;
1017                 tickMap[i] = true;
1018             }
1019         }
1020
1021         for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
1022             if (!tickMap[i]) {
1023                 this.yTicks[this.yTicks.length] = i;
1024                 tickMap[i] = true;
1025             }
1026         }
1027
1028         this.yTicks.sort(this.DDM.numericSort) ;
1029     },
1030
1031     /**
1032      * By default, the element can be dragged any place on the screen.  Use
1033      * this method to limit the horizontal travel of the element.  Pass in
1034      * 0,0 for the parameters if you want to lock the drag to the y axis.
1035      * @method setXConstraint
1036      * @param {int} iLeft the number of pixels the element can move to the left
1037      * @param {int} iRight the number of pixels the element can move to the
1038      * right
1039      * @param {int} iTickSize optional parameter for specifying that the
1040      * element
1041      * should move iTickSize pixels at a time.
1042      */
1043     setXConstraint: function(iLeft, iRight, iTickSize) {
1044         this.leftConstraint = iLeft;
1045         this.rightConstraint = iRight;
1046
1047         this.minX = this.initPageX - iLeft;
1048         this.maxX = this.initPageX + iRight;
1049         if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
1050
1051         this.constrainX = true;
1052     },
1053
1054     /**
1055      * Clears any constraints applied to this instance.  Also clears ticks
1056      * since they can't exist independent of a constraint at this time.
1057      * @method clearConstraints
1058      */
1059     clearConstraints: function() {
1060         this.constrainX = false;
1061         this.constrainY = false;
1062         this.clearTicks();
1063     },
1064
1065     /**
1066      * Clears any tick interval defined for this instance
1067      * @method clearTicks
1068      */
1069     clearTicks: function() {
1070         this.xTicks = null;
1071         this.yTicks = null;
1072         this.xTickSize = 0;
1073         this.yTickSize = 0;
1074     },
1075
1076     /**
1077      * By default, the element can be dragged any place on the screen.  Set
1078      * this to limit the vertical travel of the element.  Pass in 0,0 for the
1079      * parameters if you want to lock the drag to the x axis.
1080      * @method setYConstraint
1081      * @param {int} iUp the number of pixels the element can move up
1082      * @param {int} iDown the number of pixels the element can move down
1083      * @param {int} iTickSize optional parameter for specifying that the
1084      * element should move iTickSize pixels at a time.
1085      */
1086     setYConstraint: function(iUp, iDown, iTickSize) {
1087         this.topConstraint = iUp;
1088         this.bottomConstraint = iDown;
1089
1090         this.minY = this.initPageY - iUp;
1091         this.maxY = this.initPageY + iDown;
1092         if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
1093
1094         this.constrainY = true;
1095
1096     },
1097
1098     /**
1099      * resetConstraints must be called if you manually reposition a dd element.
1100      * @method resetConstraints
1101      * @param {boolean} maintainOffset
1102      */
1103     resetConstraints: function() {
1104
1105
1106         // Maintain offsets if necessary
1107         if (this.initPageX || this.initPageX === 0) {
1108             // figure out how much this thing has moved
1109             var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
1110             var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
1111
1112             this.setInitPosition(dx, dy);
1113
1114         // This is the first time we have detected the element's position
1115         } else {
1116             this.setInitPosition();
1117         }
1118
1119         if (this.constrainX) {
1120             this.setXConstraint( this.leftConstraint,
1121                                  this.rightConstraint,
1122                                  this.xTickSize        );
1123         }
1124
1125         if (this.constrainY) {
1126             this.setYConstraint( this.topConstraint,
1127                                  this.bottomConstraint,
1128                                  this.yTickSize         );
1129         }
1130     },
1131
1132     /**
1133      * Normally the drag element is moved pixel by pixel, but we can specify
1134      * that it move a number of pixels at a time.  This method resolves the
1135      * location when we have it set up like this.
1136      * @method getTick
1137      * @param {int} val where we want to place the object
1138      * @param {int[]} tickArray sorted array of valid points
1139      * @return {int} the closest tick
1140      * @private
1141      */
1142     getTick: function(val, tickArray) {
1143
1144         if (!tickArray) {
1145             // If tick interval is not defined, it is effectively 1 pixel,
1146             // so we return the value passed to us.
1147             return val;
1148         } else if (tickArray[0] >= val) {
1149             // The value is lower than the first tick, so we return the first
1150             // tick.
1151             return tickArray[0];
1152         } else {
1153             for (var i=0, len=tickArray.length; i<len; ++i) {
1154                 var next = i + 1;
1155                 if (tickArray[next] && tickArray[next] >= val) {
1156                     var diff1 = val - tickArray[i];
1157                     var diff2 = tickArray[next] - val;
1158                     return (diff2 > diff1) ? tickArray[i] : tickArray[next];
1159                 }
1160             }
1161
1162             // The value is larger than the last tick, so we return the last
1163             // tick.
1164             return tickArray[tickArray.length - 1];
1165         }
1166     },
1167
1168     /**
1169      * toString method
1170      * @method toString
1171      * @return {string} string representation of the dd obj
1172      */
1173     toString: function() {
1174         return ("DragDrop " + this.id);
1175     }
1176
1177 });
1178
1179 })();
1180 /*
1181  * Based on:
1182  * Ext JS Library 1.1.1
1183  * Copyright(c) 2006-2007, Ext JS, LLC.
1184  *
1185  * Originally Released Under LGPL - original licence link has changed is not relivant.
1186  *
1187  * Fork - LGPL
1188  * <script type="text/javascript">
1189  */
1190
1191
1192 /**
1193  * The drag and drop utility provides a framework for building drag and drop
1194  * applications.  In addition to enabling drag and drop for specific elements,
1195  * the drag and drop elements are tracked by the manager class, and the
1196  * interactions between the various elements are tracked during the drag and
1197  * the implementing code is notified about these important moments.
1198  */
1199
1200 // Only load the library once.  Rewriting the manager class would orphan
1201 // existing drag and drop instances.
1202 if (!Roo.dd.DragDropMgr) {
1203
1204 /**
1205  * @class Roo.dd.DragDropMgr
1206  * DragDropMgr is a singleton that tracks the element interaction for
1207  * all DragDrop items in the window.  Generally, you will not call
1208  * this class directly, but it does have helper methods that could
1209  * be useful in your DragDrop implementations.
1210  * @singleton
1211  */
1212 Roo.dd.DragDropMgr = function() {
1213
1214     var Event = Roo.EventManager;
1215
1216     return {
1217
1218         /**
1219          * Two dimensional Array of registered DragDrop objects.  The first
1220          * dimension is the DragDrop item group, the second the DragDrop
1221          * object.
1222          * @property ids
1223          * @type {string: string}
1224          * @private
1225          * @static
1226          */
1227         ids: {},
1228
1229         /**
1230          * Array of element ids defined as drag handles.  Used to determine
1231          * if the element that generated the mousedown event is actually the
1232          * handle and not the html element itself.
1233          * @property handleIds
1234          * @type {string: string}
1235          * @private
1236          * @static
1237          */
1238         handleIds: {},
1239
1240         /**
1241          * the DragDrop object that is currently being dragged
1242          * @property dragCurrent
1243          * @type DragDrop
1244          * @private
1245          * @static
1246          **/
1247         dragCurrent: null,
1248
1249         /**
1250          * the DragDrop object(s) that are being hovered over
1251          * @property dragOvers
1252          * @type Array
1253          * @private
1254          * @static
1255          */
1256         dragOvers: {},
1257
1258         /**
1259          * the X distance between the cursor and the object being dragged
1260          * @property deltaX
1261          * @type int
1262          * @private
1263          * @static
1264          */
1265         deltaX: 0,
1266
1267         /**
1268          * the Y distance between the cursor and the object being dragged
1269          * @property deltaY
1270          * @type int
1271          * @private
1272          * @static
1273          */
1274         deltaY: 0,
1275
1276         /**
1277          * Flag to determine if we should prevent the default behavior of the
1278          * events we define. By default this is true, but this can be set to
1279          * false if you need the default behavior (not recommended)
1280          * @property preventDefault
1281          * @type boolean
1282          * @static
1283          */
1284         preventDefault: true,
1285
1286         /**
1287          * Flag to determine if we should stop the propagation of the events
1288          * we generate. This is true by default but you may want to set it to
1289          * false if the html element contains other features that require the
1290          * mouse click.
1291          * @property stopPropagation
1292          * @type boolean
1293          * @static
1294          */
1295         stopPropagation: true,
1296
1297         /**
1298          * Internal flag that is set to true when drag and drop has been
1299          * intialized
1300          * @property initialized
1301          * @private
1302          * @static
1303          */
1304         initalized: false,
1305
1306         /**
1307          * All drag and drop can be disabled.
1308          * @property locked
1309          * @private
1310          * @static
1311          */
1312         locked: false,
1313
1314         /**
1315          * Called the first time an element is registered.
1316          * @method init
1317          * @private
1318          * @static
1319          */
1320         init: function() {
1321             this.initialized = true;
1322         },
1323
1324         /**
1325          * In point mode, drag and drop interaction is defined by the
1326          * location of the cursor during the drag/drop
1327          * @property POINT
1328          * @type int
1329          * @static
1330          */
1331         POINT: 0,
1332
1333         /**
1334          * In intersect mode, drag and drop interactio nis defined by the
1335          * overlap of two or more drag and drop objects.
1336          * @property INTERSECT
1337          * @type int
1338          * @static
1339          */
1340         INTERSECT: 1,
1341
1342         /**
1343          * The current drag and drop mode.  Default: POINT
1344          * @property mode
1345          * @type int
1346          * @static
1347          */
1348         mode: 0,
1349
1350         /**
1351          * Runs method on all drag and drop objects
1352          * @method _execOnAll
1353          * @private
1354          * @static
1355          */
1356         _execOnAll: function(sMethod, args) {
1357             for (var i in this.ids) {
1358                 for (var j in this.ids[i]) {
1359                     var oDD = this.ids[i][j];
1360                     if (! this.isTypeOfDD(oDD)) {
1361                         continue;
1362                     }
1363                     oDD[sMethod].apply(oDD, args);
1364                 }
1365             }
1366         },
1367
1368         /**
1369          * Drag and drop initialization.  Sets up the global event handlers
1370          * @method _onLoad
1371          * @private
1372          * @static
1373          */
1374         _onLoad: function() {
1375
1376             this.init();
1377
1378             if (!Roo.isTouch) {
1379                 Event.on(document, "mouseup",   this.handleMouseUp, this, true);
1380                 Event.on(document, "mousemove", this.handleMouseMove, this, true);
1381             }
1382             Event.on(document, "touchend",   this.handleMouseUp, this, true);
1383             Event.on(document, "touchmove", this.handleMouseMove, this, true);
1384             
1385             Event.on(window,   "unload",    this._onUnload, this, true);
1386             Event.on(window,   "resize",    this._onResize, this, true);
1387             // Event.on(window,   "mouseout",    this._test);
1388
1389         },
1390
1391         /**
1392          * Reset constraints on all drag and drop objs
1393          * @method _onResize
1394          * @private
1395          * @static
1396          */
1397         _onResize: function(e) {
1398             this._execOnAll("resetConstraints", []);
1399         },
1400
1401         /**
1402          * Lock all drag and drop functionality
1403          * @method lock
1404          * @static
1405          */
1406         lock: function() { this.locked = true; },
1407
1408         /**
1409          * Unlock all drag and drop functionality
1410          * @method unlock
1411          * @static
1412          */
1413         unlock: function() { this.locked = false; },
1414
1415         /**
1416          * Is drag and drop locked?
1417          * @method isLocked
1418          * @return {boolean} True if drag and drop is locked, false otherwise.
1419          * @static
1420          */
1421         isLocked: function() { return this.locked; },
1422
1423         /**
1424          * Location cache that is set for all drag drop objects when a drag is
1425          * initiated, cleared when the drag is finished.
1426          * @property locationCache
1427          * @private
1428          * @static
1429          */
1430         locationCache: {},
1431
1432         /**
1433          * Set useCache to false if you want to force object the lookup of each
1434          * drag and drop linked element constantly during a drag.
1435          * @property useCache
1436          * @type boolean
1437          * @static
1438          */
1439         useCache: true,
1440
1441         /**
1442          * The number of pixels that the mouse needs to move after the
1443          * mousedown before the drag is initiated.  Default=3;
1444          * @property clickPixelThresh
1445          * @type int
1446          * @static
1447          */
1448         clickPixelThresh: 3,
1449
1450         /**
1451          * The number of milliseconds after the mousedown event to initiate the
1452          * drag if we don't get a mouseup event. Default=1000
1453          * @property clickTimeThresh
1454          * @type int
1455          * @static
1456          */
1457         clickTimeThresh: 350,
1458
1459         /**
1460          * Flag that indicates that either the drag pixel threshold or the
1461          * mousdown time threshold has been met
1462          * @property dragThreshMet
1463          * @type boolean
1464          * @private
1465          * @static
1466          */
1467         dragThreshMet: false,
1468
1469         /**
1470          * Timeout used for the click time threshold
1471          * @property clickTimeout
1472          * @type Object
1473          * @private
1474          * @static
1475          */
1476         clickTimeout: null,
1477
1478         /**
1479          * The X position of the mousedown event stored for later use when a
1480          * drag threshold is met.
1481          * @property startX
1482          * @type int
1483          * @private
1484          * @static
1485          */
1486         startX: 0,
1487
1488         /**
1489          * The Y position of the mousedown event stored for later use when a
1490          * drag threshold is met.
1491          * @property startY
1492          * @type int
1493          * @private
1494          * @static
1495          */
1496         startY: 0,
1497
1498         /**
1499          * Each DragDrop instance must be registered with the DragDropMgr.
1500          * This is executed in DragDrop.init()
1501          * @method regDragDrop
1502          * @param {DragDrop} oDD the DragDrop object to register
1503          * @param {String} sGroup the name of the group this element belongs to
1504          * @static
1505          */
1506         regDragDrop: function(oDD, sGroup) {
1507             if (!this.initialized) { this.init(); }
1508
1509             if (!this.ids[sGroup]) {
1510                 this.ids[sGroup] = {};
1511             }
1512             this.ids[sGroup][oDD.id] = oDD;
1513         },
1514
1515         /**
1516          * Removes the supplied dd instance from the supplied group. Executed
1517          * by DragDrop.removeFromGroup, so don't call this function directly.
1518          * @method removeDDFromGroup
1519          * @private
1520          * @static
1521          */
1522         removeDDFromGroup: function(oDD, sGroup) {
1523             if (!this.ids[sGroup]) {
1524                 this.ids[sGroup] = {};
1525             }
1526
1527             var obj = this.ids[sGroup];
1528             if (obj && obj[oDD.id]) {
1529                 delete obj[oDD.id];
1530             }
1531         },
1532
1533         /**
1534          * Unregisters a drag and drop item.  This is executed in
1535          * DragDrop.unreg, use that method instead of calling this directly.
1536          * @method _remove
1537          * @private
1538          * @static
1539          */
1540         _remove: function(oDD) {
1541             for (var g in oDD.groups) {
1542                 if (g && this.ids[g][oDD.id]) {
1543                     delete this.ids[g][oDD.id];
1544                 }
1545             }
1546             delete this.handleIds[oDD.id];
1547         },
1548
1549         /**
1550          * Each DragDrop handle element must be registered.  This is done
1551          * automatically when executing DragDrop.setHandleElId()
1552          * @method regHandle
1553          * @param {String} sDDId the DragDrop id this element is a handle for
1554          * @param {String} sHandleId the id of the element that is the drag
1555          * handle
1556          * @static
1557          */
1558         regHandle: function(sDDId, sHandleId) {
1559             if (!this.handleIds[sDDId]) {
1560                 this.handleIds[sDDId] = {};
1561             }
1562             this.handleIds[sDDId][sHandleId] = sHandleId;
1563         },
1564
1565         /**
1566          * Utility function to determine if a given element has been
1567          * registered as a drag drop item.
1568          * @method isDragDrop
1569          * @param {String} id the element id to check
1570          * @return {boolean} true if this element is a DragDrop item,
1571          * false otherwise
1572          * @static
1573          */
1574         isDragDrop: function(id) {
1575             return ( this.getDDById(id) ) ? true : false;
1576         },
1577
1578         /**
1579          * Returns the drag and drop instances that are in all groups the
1580          * passed in instance belongs to.
1581          * @method getRelated
1582          * @param {DragDrop} p_oDD the obj to get related data for
1583          * @param {boolean} bTargetsOnly if true, only return targetable objs
1584          * @return {DragDrop[]} the related instances
1585          * @static
1586          */
1587         getRelated: function(p_oDD, bTargetsOnly) {
1588             var oDDs = [];
1589             for (var i in p_oDD.groups) {
1590                 for (j in this.ids[i]) {
1591                     var dd = this.ids[i][j];
1592                     if (! this.isTypeOfDD(dd)) {
1593                         continue;
1594                     }
1595                     if (!bTargetsOnly || dd.isTarget) {
1596                         oDDs[oDDs.length] = dd;
1597                     }
1598                 }
1599             }
1600
1601             return oDDs;
1602         },
1603
1604         /**
1605          * Returns true if the specified dd target is a legal target for
1606          * the specifice drag obj
1607          * @method isLegalTarget
1608          * @param {DragDrop} the drag obj
1609          * @param {DragDrop} the target
1610          * @return {boolean} true if the target is a legal target for the
1611          * dd obj
1612          * @static
1613          */
1614         isLegalTarget: function (oDD, oTargetDD) {
1615             var targets = this.getRelated(oDD, true);
1616             for (var i=0, len=targets.length;i<len;++i) {
1617                 if (targets[i].id == oTargetDD.id) {
1618                     return true;
1619                 }
1620             }
1621
1622             return false;
1623         },
1624
1625         /**
1626          * My goal is to be able to transparently determine if an object is
1627          * typeof DragDrop, and the exact subclass of DragDrop.  typeof
1628          * returns "object", oDD.constructor.toString() always returns
1629          * "DragDrop" and not the name of the subclass.  So for now it just
1630          * evaluates a well-known variable in DragDrop.
1631          * @method isTypeOfDD
1632          * @param {Object} the object to evaluate
1633          * @return {boolean} true if typeof oDD = DragDrop
1634          * @static
1635          */
1636         isTypeOfDD: function (oDD) {
1637             return (oDD && oDD.__ygDragDrop);
1638         },
1639
1640         /**
1641          * Utility function to determine if a given element has been
1642          * registered as a drag drop handle for the given Drag Drop object.
1643          * @method isHandle
1644          * @param {String} id the element id to check
1645          * @return {boolean} true if this element is a DragDrop handle, false
1646          * otherwise
1647          * @static
1648          */
1649         isHandle: function(sDDId, sHandleId) {
1650             return ( this.handleIds[sDDId] &&
1651                             this.handleIds[sDDId][sHandleId] );
1652         },
1653
1654         /**
1655          * Returns the DragDrop instance for a given id
1656          * @method getDDById
1657          * @param {String} id the id of the DragDrop object
1658          * @return {DragDrop} the drag drop object, null if it is not found
1659          * @static
1660          */
1661         getDDById: function(id) {
1662             for (var i in this.ids) {
1663                 if (this.ids[i][id]) {
1664                     return this.ids[i][id];
1665                 }
1666             }
1667             return null;
1668         },
1669
1670         /**
1671          * Fired after a registered DragDrop object gets the mousedown event.
1672          * Sets up the events required to track the object being dragged
1673          * @method handleMouseDown
1674          * @param {Event} e the event
1675          * @param oDD the DragDrop object being dragged
1676          * @private
1677          * @static
1678          */
1679         handleMouseDown: function(e, oDD) {
1680             if(Roo.QuickTips){
1681                 Roo.QuickTips.disable();
1682             }
1683             this.currentTarget = e.getTarget();
1684
1685             this.dragCurrent = oDD;
1686
1687             var el = oDD.getEl();
1688
1689             // track start position
1690             this.startX = e.getPageX();
1691             this.startY = e.getPageY();
1692
1693             this.deltaX = this.startX - el.offsetLeft;
1694             this.deltaY = this.startY - el.offsetTop;
1695
1696             this.dragThreshMet = false;
1697
1698             this.clickTimeout = setTimeout(
1699                     function() {
1700                         var DDM = Roo.dd.DDM;
1701                         DDM.startDrag(DDM.startX, DDM.startY);
1702                     },
1703                     this.clickTimeThresh );
1704         },
1705
1706         /**
1707          * Fired when either the drag pixel threshol or the mousedown hold
1708          * time threshold has been met.
1709          * @method startDrag
1710          * @param x {int} the X position of the original mousedown
1711          * @param y {int} the Y position of the original mousedown
1712          * @static
1713          */
1714         startDrag: function(x, y) {
1715             clearTimeout(this.clickTimeout);
1716             if (this.dragCurrent) {
1717                 this.dragCurrent.b4StartDrag(x, y);
1718                 this.dragCurrent.startDrag(x, y);
1719             }
1720             this.dragThreshMet = true;
1721         },
1722
1723         /**
1724          * Internal function to handle the mouseup event.  Will be invoked
1725          * from the context of the document.
1726          * @method handleMouseUp
1727          * @param {Event} e the event
1728          * @private
1729          * @static
1730          */
1731         handleMouseUp: function(e) {
1732
1733             if(Roo.QuickTips){
1734                 Roo.QuickTips.enable();
1735             }
1736             if (! this.dragCurrent) {
1737                 return;
1738             }
1739
1740             clearTimeout(this.clickTimeout);
1741
1742             if (this.dragThreshMet) {
1743                 this.fireEvents(e, true);
1744             } else {
1745             }
1746
1747             this.stopDrag(e);
1748
1749             this.stopEvent(e);
1750         },
1751
1752         /**
1753          * Utility to stop event propagation and event default, if these
1754          * features are turned on.
1755          * @method stopEvent
1756          * @param {Event} e the event as returned by this.getEvent()
1757          * @static
1758          */
1759         stopEvent: function(e){
1760             if(this.stopPropagation) {
1761                 e.stopPropagation();
1762             }
1763
1764             if (this.preventDefault) {
1765                 e.preventDefault();
1766             }
1767         },
1768
1769         /**
1770          * Internal function to clean up event handlers after the drag
1771          * operation is complete
1772          * @method stopDrag
1773          * @param {Event} e the event
1774          * @private
1775          * @static
1776          */
1777         stopDrag: function(e) {
1778             // Fire the drag end event for the item that was dragged
1779             if (this.dragCurrent) {
1780                 if (this.dragThreshMet) {
1781                     this.dragCurrent.b4EndDrag(e);
1782                     this.dragCurrent.endDrag(e);
1783                 }
1784
1785                 this.dragCurrent.onMouseUp(e);
1786             }
1787
1788             this.dragCurrent = null;
1789             this.dragOvers = {};
1790         },
1791
1792         /**
1793          * Internal function to handle the mousemove event.  Will be invoked
1794          * from the context of the html element.
1795          *
1796          * @TODO figure out what we can do about mouse events lost when the
1797          * user drags objects beyond the window boundary.  Currently we can
1798          * detect this in internet explorer by verifying that the mouse is
1799          * down during the mousemove event.  Firefox doesn't give us the
1800          * button state on the mousemove event.
1801          * @method handleMouseMove
1802          * @param {Event} e the event
1803          * @private
1804          * @static
1805          */
1806         handleMouseMove: function(e) {
1807             if (! this.dragCurrent) {
1808                 return true;
1809             }
1810
1811             // var button = e.which || e.button;
1812
1813             // check for IE mouseup outside of page boundary
1814             if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
1815                 this.stopEvent(e);
1816                 return this.handleMouseUp(e);
1817             }
1818
1819             if (!this.dragThreshMet) {
1820                 var diffX = Math.abs(this.startX - e.getPageX());
1821                 var diffY = Math.abs(this.startY - e.getPageY());
1822                 if (diffX > this.clickPixelThresh ||
1823                             diffY > this.clickPixelThresh) {
1824                     this.startDrag(this.startX, this.startY);
1825                 }
1826             }
1827
1828             if (this.dragThreshMet) {
1829                 this.dragCurrent.b4Drag(e);
1830                 this.dragCurrent.onDrag(e);
1831                 if(!this.dragCurrent.moveOnly){
1832                     this.fireEvents(e, false);
1833                 }
1834             }
1835
1836             this.stopEvent(e);
1837
1838             return true;
1839         },
1840
1841         /**
1842          * Iterates over all of the DragDrop elements to find ones we are
1843          * hovering over or dropping on
1844          * @method fireEvents
1845          * @param {Event} e the event
1846          * @param {boolean} isDrop is this a drop op or a mouseover op?
1847          * @private
1848          * @static
1849          */
1850         fireEvents: function(e, isDrop) {
1851             var dc = this.dragCurrent;
1852
1853             // If the user did the mouse up outside of the window, we could
1854             // get here even though we have ended the drag.
1855             if (!dc || dc.isLocked()) {
1856                 return;
1857             }
1858
1859             var pt = e.getPoint();
1860
1861             // cache the previous dragOver array
1862             var oldOvers = [];
1863
1864             var outEvts   = [];
1865             var overEvts  = [];
1866             var dropEvts  = [];
1867             var enterEvts = [];
1868
1869             // Check to see if the object(s) we were hovering over is no longer
1870             // being hovered over so we can fire the onDragOut event
1871             for (var i in this.dragOvers) {
1872
1873                 var ddo = this.dragOvers[i];
1874
1875                 if (! this.isTypeOfDD(ddo)) {
1876                     continue;
1877                 }
1878
1879                 if (! this.isOverTarget(pt, ddo, this.mode)) {
1880                     outEvts.push( ddo );
1881                 }
1882
1883                 oldOvers[i] = true;
1884                 delete this.dragOvers[i];
1885             }
1886
1887             for (var sGroup in dc.groups) {
1888
1889                 if ("string" != typeof sGroup) {
1890                     continue;
1891                 }
1892
1893                 for (i in this.ids[sGroup]) {
1894                     var oDD = this.ids[sGroup][i];
1895                     if (! this.isTypeOfDD(oDD)) {
1896                         continue;
1897                     }
1898
1899                     if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
1900                         if (this.isOverTarget(pt, oDD, this.mode)) {
1901                             // look for drop interactions
1902                             if (isDrop) {
1903                                 dropEvts.push( oDD );
1904                             // look for drag enter and drag over interactions
1905                             } else {
1906
1907                                 // initial drag over: dragEnter fires
1908                                 if (!oldOvers[oDD.id]) {
1909                                     enterEvts.push( oDD );
1910                                 // subsequent drag overs: dragOver fires
1911                                 } else {
1912                                     overEvts.push( oDD );
1913                                 }
1914
1915                                 this.dragOvers[oDD.id] = oDD;
1916                             }
1917                         }
1918                     }
1919                 }
1920             }
1921
1922             if (this.mode) {
1923                 if (outEvts.length) {
1924                     dc.b4DragOut(e, outEvts);
1925                     dc.onDragOut(e, outEvts);
1926                 }
1927
1928                 if (enterEvts.length) {
1929                     dc.onDragEnter(e, enterEvts);
1930                 }
1931
1932                 if (overEvts.length) {
1933                     dc.b4DragOver(e, overEvts);
1934                     dc.onDragOver(e, overEvts);
1935                 }
1936
1937                 if (dropEvts.length) {
1938                     dc.b4DragDrop(e, dropEvts);
1939                     dc.onDragDrop(e, dropEvts);
1940                 }
1941
1942             } else {
1943                 // fire dragout events
1944                 var len = 0;
1945                 for (i=0, len=outEvts.length; i<len; ++i) {
1946                     dc.b4DragOut(e, outEvts[i].id);
1947                     dc.onDragOut(e, outEvts[i].id);
1948                 }
1949
1950                 // fire enter events
1951                 for (i=0,len=enterEvts.length; i<len; ++i) {
1952                     // dc.b4DragEnter(e, oDD.id);
1953                     dc.onDragEnter(e, enterEvts[i].id);
1954                 }
1955
1956                 // fire over events
1957                 for (i=0,len=overEvts.length; i<len; ++i) {
1958                     dc.b4DragOver(e, overEvts[i].id);
1959                     dc.onDragOver(e, overEvts[i].id);
1960                 }
1961
1962                 // fire drop events
1963                 for (i=0, len=dropEvts.length; i<len; ++i) {
1964                     dc.b4DragDrop(e, dropEvts[i].id);
1965                     dc.onDragDrop(e, dropEvts[i].id);
1966                 }
1967
1968             }
1969
1970             // notify about a drop that did not find a target
1971             if (isDrop && !dropEvts.length) {
1972                 dc.onInvalidDrop(e);
1973             }
1974
1975         },
1976
1977         /**
1978          * Helper function for getting the best match from the list of drag
1979          * and drop objects returned by the drag and drop events when we are
1980          * in INTERSECT mode.  It returns either the first object that the
1981          * cursor is over, or the object that has the greatest overlap with
1982          * the dragged element.
1983          * @method getBestMatch
1984          * @param  {DragDrop[]} dds The array of drag and drop objects
1985          * targeted
1986          * @return {DragDrop}       The best single match
1987          * @static
1988          */
1989         getBestMatch: function(dds) {
1990             var winner = null;
1991             // Return null if the input is not what we expect
1992             //if (!dds || !dds.length || dds.length == 0) {
1993                // winner = null;
1994             // If there is only one item, it wins
1995             //} else if (dds.length == 1) {
1996
1997             var len = dds.length;
1998
1999             if (len == 1) {
2000                 winner = dds[0];
2001             } else {
2002                 // Loop through the targeted items
2003                 for (var i=0; i<len; ++i) {
2004                     var dd = dds[i];
2005                     // If the cursor is over the object, it wins.  If the
2006                     // cursor is over multiple matches, the first one we come
2007                     // to wins.
2008                     if (dd.cursorIsOver) {
2009                         winner = dd;
2010                         break;
2011                     // Otherwise the object with the most overlap wins
2012                     } else {
2013                         if (!winner ||
2014                             winner.overlap.getArea() < dd.overlap.getArea()) {
2015                             winner = dd;
2016                         }
2017                     }
2018                 }
2019             }
2020
2021             return winner;
2022         },
2023
2024         /**
2025          * Refreshes the cache of the top-left and bottom-right points of the
2026          * drag and drop objects in the specified group(s).  This is in the
2027          * format that is stored in the drag and drop instance, so typical
2028          * usage is:
2029          * <code>
2030          * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
2031          * </code>
2032          * Alternatively:
2033          * <code>
2034          * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
2035          * </code>
2036          * @TODO this really should be an indexed array.  Alternatively this
2037          * method could accept both.
2038          * @method refreshCache
2039          * @param {Object} groups an associative array of groups to refresh
2040          * @static
2041          */
2042         refreshCache: function(groups) {
2043             for (var sGroup in groups) {
2044                 if ("string" != typeof sGroup) {
2045                     continue;
2046                 }
2047                 for (var i in this.ids[sGroup]) {
2048                     var oDD = this.ids[sGroup][i];
2049
2050                     if (this.isTypeOfDD(oDD)) {
2051                     // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
2052                         var loc = this.getLocation(oDD);
2053                         if (loc) {
2054                             this.locationCache[oDD.id] = loc;
2055                         } else {
2056                             delete this.locationCache[oDD.id];
2057                             // this will unregister the drag and drop object if
2058                             // the element is not in a usable state
2059                             // oDD.unreg();
2060                         }
2061                     }
2062                 }
2063             }
2064         },
2065
2066         /**
2067          * This checks to make sure an element exists and is in the DOM.  The
2068          * main purpose is to handle cases where innerHTML is used to remove
2069          * drag and drop objects from the DOM.  IE provides an 'unspecified
2070          * error' when trying to access the offsetParent of such an element
2071          * @method verifyEl
2072          * @param {HTMLElement} el the element to check
2073          * @return {boolean} true if the element looks usable
2074          * @static
2075          */
2076         verifyEl: function(el) {
2077             if (el) {
2078                 var parent;
2079                 if(Roo.isIE){
2080                     try{
2081                         parent = el.offsetParent;
2082                     }catch(e){}
2083                 }else{
2084                     parent = el.offsetParent;
2085                 }
2086                 if (parent) {
2087                     return true;
2088                 }
2089             }
2090
2091             return false;
2092         },
2093
2094         /**
2095          * Returns a Region object containing the drag and drop element's position
2096          * and size, including the padding configured for it
2097          * @method getLocation
2098          * @param {DragDrop} oDD the drag and drop object to get the
2099          *                       location for
2100          * @return {Roo.lib.Region} a Region object representing the total area
2101          *                             the element occupies, including any padding
2102          *                             the instance is configured for.
2103          * @static
2104          */
2105         getLocation: function(oDD) {
2106             if (! this.isTypeOfDD(oDD)) {
2107                 return null;
2108             }
2109
2110             var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
2111
2112             try {
2113                 pos= Roo.lib.Dom.getXY(el);
2114             } catch (e) { }
2115
2116             if (!pos) {
2117                 return null;
2118             }
2119
2120             x1 = pos[0];
2121             x2 = x1 + el.offsetWidth;
2122             y1 = pos[1];
2123             y2 = y1 + el.offsetHeight;
2124
2125             t = y1 - oDD.padding[0];
2126             r = x2 + oDD.padding[1];
2127             b = y2 + oDD.padding[2];
2128             l = x1 - oDD.padding[3];
2129
2130             return new Roo.lib.Region( t, r, b, l );
2131         },
2132
2133         /**
2134          * Checks the cursor location to see if it over the target
2135          * @method isOverTarget
2136          * @param {Roo.lib.Point} pt The point to evaluate
2137          * @param {DragDrop} oTarget the DragDrop object we are inspecting
2138          * @return {boolean} true if the mouse is over the target
2139          * @private
2140          * @static
2141          */
2142         isOverTarget: function(pt, oTarget, intersect) {
2143             // use cache if available
2144             var loc = this.locationCache[oTarget.id];
2145             if (!loc || !this.useCache) {
2146                 loc = this.getLocation(oTarget);
2147                 this.locationCache[oTarget.id] = loc;
2148
2149             }
2150
2151             if (!loc) {
2152                 return false;
2153             }
2154
2155             oTarget.cursorIsOver = loc.contains( pt );
2156
2157             // DragDrop is using this as a sanity check for the initial mousedown
2158             // in this case we are done.  In POINT mode, if the drag obj has no
2159             // contraints, we are also done. Otherwise we need to evaluate the
2160             // location of the target as related to the actual location of the
2161             // dragged element.
2162             var dc = this.dragCurrent;
2163             if (!dc || !dc.getTargetCoord ||
2164                     (!intersect && !dc.constrainX && !dc.constrainY)) {
2165                 return oTarget.cursorIsOver;
2166             }
2167
2168             oTarget.overlap = null;
2169
2170             // Get the current location of the drag element, this is the
2171             // location of the mouse event less the delta that represents
2172             // where the original mousedown happened on the element.  We
2173             // need to consider constraints and ticks as well.
2174             var pos = dc.getTargetCoord(pt.x, pt.y);
2175
2176             var el = dc.getDragEl();
2177             var curRegion = new Roo.lib.Region( pos.y,
2178                                                    pos.x + el.offsetWidth,
2179                                                    pos.y + el.offsetHeight,
2180                                                    pos.x );
2181
2182             var overlap = curRegion.intersect(loc);
2183
2184             if (overlap) {
2185                 oTarget.overlap = overlap;
2186                 return (intersect) ? true : oTarget.cursorIsOver;
2187             } else {
2188                 return false;
2189             }
2190         },
2191
2192         /**
2193          * unload event handler
2194          * @method _onUnload
2195          * @private
2196          * @static
2197          */
2198         _onUnload: function(e, me) {
2199             Roo.dd.DragDropMgr.unregAll();
2200         },
2201
2202         /**
2203          * Cleans up the drag and drop events and objects.
2204          * @method unregAll
2205          * @private
2206          * @static
2207          */
2208         unregAll: function() {
2209
2210             if (this.dragCurrent) {
2211                 this.stopDrag();
2212                 this.dragCurrent = null;
2213             }
2214
2215             this._execOnAll("unreg", []);
2216
2217             for (i in this.elementCache) {
2218                 delete this.elementCache[i];
2219             }
2220
2221             this.elementCache = {};
2222             this.ids = {};
2223         },
2224
2225         /**
2226          * A cache of DOM elements
2227          * @property elementCache
2228          * @private
2229          * @static
2230          */
2231         elementCache: {},
2232
2233         /**
2234          * Get the wrapper for the DOM element specified
2235          * @method getElWrapper
2236          * @param {String} id the id of the element to get
2237          * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
2238          * @private
2239          * @deprecated This wrapper isn't that useful
2240          * @static
2241          */
2242         getElWrapper: function(id) {
2243             var oWrapper = this.elementCache[id];
2244             if (!oWrapper || !oWrapper.el) {
2245                 oWrapper = this.elementCache[id] =
2246                     new this.ElementWrapper(Roo.getDom(id));
2247             }
2248             return oWrapper;
2249         },
2250
2251         /**
2252          * Returns the actual DOM element
2253          * @method getElement
2254          * @param {String} id the id of the elment to get
2255          * @return {Object} The element
2256          * @deprecated use Roo.getDom instead
2257          * @static
2258          */
2259         getElement: function(id) {
2260             return Roo.getDom(id);
2261         },
2262
2263         /**
2264          * Returns the style property for the DOM element (i.e.,
2265          * document.getElById(id).style)
2266          * @method getCss
2267          * @param {String} id the id of the elment to get
2268          * @return {Object} The style property of the element
2269          * @deprecated use Roo.getDom instead
2270          * @static
2271          */
2272         getCss: function(id) {
2273             var el = Roo.getDom(id);
2274             return (el) ? el.style : null;
2275         },
2276
2277         /**
2278          * Inner class for cached elements
2279          * @class DragDropMgr.ElementWrapper
2280          * @for DragDropMgr
2281          * @private
2282          * @deprecated
2283          */
2284         ElementWrapper: function(el) {
2285                 /**
2286                  * The element
2287                  * @property el
2288                  */
2289                 this.el = el || null;
2290                 /**
2291                  * The element id
2292                  * @property id
2293                  */
2294                 this.id = this.el && el.id;
2295                 /**
2296                  * A reference to the style property
2297                  * @property css
2298                  */
2299                 this.css = this.el && el.style;
2300             },
2301
2302         /**
2303          * Returns the X position of an html element
2304          * @method getPosX
2305          * @param el the element for which to get the position
2306          * @return {int} the X coordinate
2307          * @for DragDropMgr
2308          * @deprecated use Roo.lib.Dom.getX instead
2309          * @static
2310          */
2311         getPosX: function(el) {
2312             return Roo.lib.Dom.getX(el);
2313         },
2314
2315         /**
2316          * Returns the Y position of an html element
2317          * @method getPosY
2318          * @param el the element for which to get the position
2319          * @return {int} the Y coordinate
2320          * @deprecated use Roo.lib.Dom.getY instead
2321          * @static
2322          */
2323         getPosY: function(el) {
2324             return Roo.lib.Dom.getY(el);
2325         },
2326
2327         /**
2328          * Swap two nodes.  In IE, we use the native method, for others we
2329          * emulate the IE behavior
2330          * @method swapNode
2331          * @param n1 the first node to swap
2332          * @param n2 the other node to swap
2333          * @static
2334          */
2335         swapNode: function(n1, n2) {
2336             if (n1.swapNode) {
2337                 n1.swapNode(n2);
2338             } else {
2339                 var p = n2.parentNode;
2340                 var s = n2.nextSibling;
2341
2342                 if (s == n1) {
2343                     p.insertBefore(n1, n2);
2344                 } else if (n2 == n1.nextSibling) {
2345                     p.insertBefore(n2, n1);
2346                 } else {
2347                     n1.parentNode.replaceChild(n2, n1);
2348                     p.insertBefore(n1, s);
2349                 }
2350             }
2351         },
2352
2353         /**
2354          * Returns the current scroll position
2355          * @method getScroll
2356          * @private
2357          * @static
2358          */
2359         getScroll: function () {
2360             var t, l, dde=document.documentElement, db=document.body;
2361             if (dde && (dde.scrollTop || dde.scrollLeft)) {
2362                 t = dde.scrollTop;
2363                 l = dde.scrollLeft;
2364             } else if (db) {
2365                 t = db.scrollTop;
2366                 l = db.scrollLeft;
2367             } else {
2368
2369             }
2370             return { top: t, left: l };
2371         },
2372
2373         /**
2374          * Returns the specified element style property
2375          * @method getStyle
2376          * @param {HTMLElement} el          the element
2377          * @param {string}      styleProp   the style property
2378          * @return {string} The value of the style property
2379          * @deprecated use Roo.lib.Dom.getStyle
2380          * @static
2381          */
2382         getStyle: function(el, styleProp) {
2383             return Roo.fly(el).getStyle(styleProp);
2384         },
2385
2386         /**
2387          * Gets the scrollTop
2388          * @method getScrollTop
2389          * @return {int} the document's scrollTop
2390          * @static
2391          */
2392         getScrollTop: function () { return this.getScroll().top; },
2393
2394         /**
2395          * Gets the scrollLeft
2396          * @method getScrollLeft
2397          * @return {int} the document's scrollTop
2398          * @static
2399          */
2400         getScrollLeft: function () { return this.getScroll().left; },
2401
2402         /**
2403          * Sets the x/y position of an element to the location of the
2404          * target element.
2405          * @method moveToEl
2406          * @param {HTMLElement} moveEl      The element to move
2407          * @param {HTMLElement} targetEl    The position reference element
2408          * @static
2409          */
2410         moveToEl: function (moveEl, targetEl) {
2411             var aCoord = Roo.lib.Dom.getXY(targetEl);
2412             Roo.lib.Dom.setXY(moveEl, aCoord);
2413         },
2414
2415         /**
2416          * Numeric array sort function
2417          * @method numericSort
2418          * @static
2419          */
2420         numericSort: function(a, b) { return (a - b); },
2421
2422         /**
2423          * Internal counter
2424          * @property _timeoutCount
2425          * @private
2426          * @static
2427          */
2428         _timeoutCount: 0,
2429
2430         /**
2431          * Trying to make the load order less important.  Without this we get
2432          * an error if this file is loaded before the Event Utility.
2433          * @method _addListeners
2434          * @private
2435          * @static
2436          */
2437         _addListeners: function() {
2438             var DDM = Roo.dd.DDM;
2439             if ( Roo.lib.Event && document ) {
2440                 DDM._onLoad();
2441             } else {
2442                 if (DDM._timeoutCount > 2000) {
2443                 } else {
2444                     setTimeout(DDM._addListeners, 10);
2445                     if (document && document.body) {
2446                         DDM._timeoutCount += 1;
2447                     }
2448                 }
2449             }
2450         },
2451
2452         /**
2453          * Recursively searches the immediate parent and all child nodes for
2454          * the handle element in order to determine wheter or not it was
2455          * clicked.
2456          * @method handleWasClicked
2457          * @param node the html element to inspect
2458          * @static
2459          */
2460         handleWasClicked: function(node, id) {
2461             if (this.isHandle(id, node.id)) {
2462                 return true;
2463             } else {
2464                 // check to see if this is a text node child of the one we want
2465                 var p = node.parentNode;
2466
2467                 while (p) {
2468                     if (this.isHandle(id, p.id)) {
2469                         return true;
2470                     } else {
2471                         p = p.parentNode;
2472                     }
2473                 }
2474             }
2475
2476             return false;
2477         }
2478
2479     };
2480
2481 }();
2482
2483 // shorter alias, save a few bytes
2484 Roo.dd.DDM = Roo.dd.DragDropMgr;
2485 Roo.dd.DDM._addListeners();
2486
2487 }/*
2488  * Based on:
2489  * Ext JS Library 1.1.1
2490  * Copyright(c) 2006-2007, Ext JS, LLC.
2491  *
2492  * Originally Released Under LGPL - original licence link has changed is not relivant.
2493  *
2494  * Fork - LGPL
2495  * <script type="text/javascript">
2496  */
2497
2498 /**
2499  * @class Roo.dd.DD
2500  * A DragDrop implementation where the linked element follows the
2501  * mouse cursor during a drag.
2502  * @extends Roo.dd.DragDrop
2503  * @constructor
2504  * @param {String} id the id of the linked element
2505  * @param {String} sGroup the group of related DragDrop items
2506  * @param {object} config an object containing configurable attributes
2507  *                Valid properties for DD:
2508  *                    scroll
2509  */
2510 Roo.dd.DD = function(id, sGroup, config) {
2511     if (id) {
2512         this.init(id, sGroup, config);
2513     }
2514 };
2515
2516 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
2517
2518     /**
2519      * When set to true, the utility automatically tries to scroll the browser
2520      * window wehn a drag and drop element is dragged near the viewport boundary.
2521      * Defaults to true.
2522      * @property scroll
2523      * @type boolean
2524      */
2525     scroll: true,
2526
2527     /**
2528      * Sets the pointer offset to the distance between the linked element's top
2529      * left corner and the location the element was clicked
2530      * @method autoOffset
2531      * @param {int} iPageX the X coordinate of the click
2532      * @param {int} iPageY the Y coordinate of the click
2533      */
2534     autoOffset: function(iPageX, iPageY) {
2535         var x = iPageX - this.startPageX;
2536         var y = iPageY - this.startPageY;
2537         this.setDelta(x, y);
2538     },
2539
2540     /**
2541      * Sets the pointer offset.  You can call this directly to force the
2542      * offset to be in a particular location (e.g., pass in 0,0 to set it
2543      * to the center of the object)
2544      * @method setDelta
2545      * @param {int} iDeltaX the distance from the left
2546      * @param {int} iDeltaY the distance from the top
2547      */
2548     setDelta: function(iDeltaX, iDeltaY) {
2549         this.deltaX = iDeltaX;
2550         this.deltaY = iDeltaY;
2551     },
2552
2553     /**
2554      * Sets the drag element to the location of the mousedown or click event,
2555      * maintaining the cursor location relative to the location on the element
2556      * that was clicked.  Override this if you want to place the element in a
2557      * location other than where the cursor is.
2558      * @method setDragElPos
2559      * @param {int} iPageX the X coordinate of the mousedown or drag event
2560      * @param {int} iPageY the Y coordinate of the mousedown or drag event
2561      */
2562     setDragElPos: function(iPageX, iPageY) {
2563         // the first time we do this, we are going to check to make sure
2564         // the element has css positioning
2565
2566         var el = this.getDragEl();
2567         this.alignElWithMouse(el, iPageX, iPageY);
2568     },
2569
2570     /**
2571      * Sets the element to the location of the mousedown or click event,
2572      * maintaining the cursor location relative to the location on the element
2573      * that was clicked.  Override this if you want to place the element in a
2574      * location other than where the cursor is.
2575      * @method alignElWithMouse
2576      * @param {HTMLElement} el the element to move
2577      * @param {int} iPageX the X coordinate of the mousedown or drag event
2578      * @param {int} iPageY the Y coordinate of the mousedown or drag event
2579      */
2580     alignElWithMouse: function(el, iPageX, iPageY) {
2581         var oCoord = this.getTargetCoord(iPageX, iPageY);
2582         var fly = el.dom ? el : Roo.fly(el);
2583         if (!this.deltaSetXY) {
2584             var aCoord = [oCoord.x, oCoord.y];
2585             fly.setXY(aCoord);
2586             var newLeft = fly.getLeft(true);
2587             var newTop  = fly.getTop(true);
2588             this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
2589         } else {
2590             fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
2591         }
2592
2593         this.cachePosition(oCoord.x, oCoord.y);
2594         this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
2595         return oCoord;
2596     },
2597
2598     /**
2599      * Saves the most recent position so that we can reset the constraints and
2600      * tick marks on-demand.  We need to know this so that we can calculate the
2601      * number of pixels the element is offset from its original position.
2602      * @method cachePosition
2603      * @param iPageX the current x position (optional, this just makes it so we
2604      * don't have to look it up again)
2605      * @param iPageY the current y position (optional, this just makes it so we
2606      * don't have to look it up again)
2607      */
2608     cachePosition: function(iPageX, iPageY) {
2609         if (iPageX) {
2610             this.lastPageX = iPageX;
2611             this.lastPageY = iPageY;
2612         } else {
2613             var aCoord = Roo.lib.Dom.getXY(this.getEl());
2614             this.lastPageX = aCoord[0];
2615             this.lastPageY = aCoord[1];
2616         }
2617     },
2618
2619     /**
2620      * Auto-scroll the window if the dragged object has been moved beyond the
2621      * visible window boundary.
2622      * @method autoScroll
2623      * @param {int} x the drag element's x position
2624      * @param {int} y the drag element's y position
2625      * @param {int} h the height of the drag element
2626      * @param {int} w the width of the drag element
2627      * @private
2628      */
2629     autoScroll: function(x, y, h, w) {
2630
2631         if (this.scroll) {
2632             // The client height
2633             var clientH = Roo.lib.Dom.getViewWidth();
2634
2635             // The client width
2636             var clientW = Roo.lib.Dom.getViewHeight();
2637
2638             // The amt scrolled down
2639             var st = this.DDM.getScrollTop();
2640
2641             // The amt scrolled right
2642             var sl = this.DDM.getScrollLeft();
2643
2644             // Location of the bottom of the element
2645             var bot = h + y;
2646
2647             // Location of the right of the element
2648             var right = w + x;
2649
2650             // The distance from the cursor to the bottom of the visible area,
2651             // adjusted so that we don't scroll if the cursor is beyond the
2652             // element drag constraints
2653             var toBot = (clientH + st - y - this.deltaY);
2654
2655             // The distance from the cursor to the right of the visible area
2656             var toRight = (clientW + sl - x - this.deltaX);
2657
2658
2659             // How close to the edge the cursor must be before we scroll
2660             // var thresh = (document.all) ? 100 : 40;
2661             var thresh = 40;
2662
2663             // How many pixels to scroll per autoscroll op.  This helps to reduce
2664             // clunky scrolling. IE is more sensitive about this ... it needs this
2665             // value to be higher.
2666             var scrAmt = (document.all) ? 80 : 30;
2667
2668             // Scroll down if we are near the bottom of the visible page and the
2669             // obj extends below the crease
2670             if ( bot > clientH && toBot < thresh ) {
2671                 window.scrollTo(sl, st + scrAmt);
2672             }
2673
2674             // Scroll up if the window is scrolled down and the top of the object
2675             // goes above the top border
2676             if ( y < st && st > 0 && y - st < thresh ) {
2677                 window.scrollTo(sl, st - scrAmt);
2678             }
2679
2680             // Scroll right if the obj is beyond the right border and the cursor is
2681             // near the border.
2682             if ( right > clientW && toRight < thresh ) {
2683                 window.scrollTo(sl + scrAmt, st);
2684             }
2685
2686             // Scroll left if the window has been scrolled to the right and the obj
2687             // extends past the left border
2688             if ( x < sl && sl > 0 && x - sl < thresh ) {
2689                 window.scrollTo(sl - scrAmt, st);
2690             }
2691         }
2692     },
2693
2694     /**
2695      * Finds the location the element should be placed if we want to move
2696      * it to where the mouse location less the click offset would place us.
2697      * @method getTargetCoord
2698      * @param {int} iPageX the X coordinate of the click
2699      * @param {int} iPageY the Y coordinate of the click
2700      * @return an object that contains the coordinates (Object.x and Object.y)
2701      * @private
2702      */
2703     getTargetCoord: function(iPageX, iPageY) {
2704
2705
2706         var x = iPageX - this.deltaX;
2707         var y = iPageY - this.deltaY;
2708
2709         if (this.constrainX) {
2710             if (x < this.minX) { x = this.minX; }
2711             if (x > this.maxX) { x = this.maxX; }
2712         }
2713
2714         if (this.constrainY) {
2715             if (y < this.minY) { y = this.minY; }
2716             if (y > this.maxY) { y = this.maxY; }
2717         }
2718
2719         x = this.getTick(x, this.xTicks);
2720         y = this.getTick(y, this.yTicks);
2721
2722
2723         return {x:x, y:y};
2724     },
2725
2726     /*
2727      * Sets up config options specific to this class. Overrides
2728      * Roo.dd.DragDrop, but all versions of this method through the
2729      * inheritance chain are called
2730      */
2731     applyConfig: function() {
2732         Roo.dd.DD.superclass.applyConfig.call(this);
2733         this.scroll = (this.config.scroll !== false);
2734     },
2735
2736     /*
2737      * Event that fires prior to the onMouseDown event.  Overrides
2738      * Roo.dd.DragDrop.
2739      */
2740     b4MouseDown: function(e) {
2741         // this.resetConstraints();
2742         this.autoOffset(e.getPageX(),
2743                             e.getPageY());
2744     },
2745
2746     /*
2747      * Event that fires prior to the onDrag event.  Overrides
2748      * Roo.dd.DragDrop.
2749      */
2750     b4Drag: function(e) {
2751         this.setDragElPos(e.getPageX(),
2752                             e.getPageY());
2753     },
2754
2755     toString: function() {
2756         return ("DD " + this.id);
2757     }
2758
2759     //////////////////////////////////////////////////////////////////////////
2760     // Debugging ygDragDrop events that can be overridden
2761     //////////////////////////////////////////////////////////////////////////
2762     /*
2763     startDrag: function(x, y) {
2764     },
2765
2766     onDrag: function(e) {
2767     },
2768
2769     onDragEnter: function(e, id) {
2770     },
2771
2772     onDragOver: function(e, id) {
2773     },
2774
2775     onDragOut: function(e, id) {
2776     },
2777
2778     onDragDrop: function(e, id) {
2779     },
2780
2781     endDrag: function(e) {
2782     }
2783
2784     */
2785
2786 });/*
2787  * Based on:
2788  * Ext JS Library 1.1.1
2789  * Copyright(c) 2006-2007, Ext JS, LLC.
2790  *
2791  * Originally Released Under LGPL - original licence link has changed is not relivant.
2792  *
2793  * Fork - LGPL
2794  * <script type="text/javascript">
2795  */
2796
2797 /**
2798  * @class Roo.dd.DDProxy
2799  * A DragDrop implementation that inserts an empty, bordered div into
2800  * the document that follows the cursor during drag operations.  At the time of
2801  * the click, the frame div is resized to the dimensions of the linked html
2802  * element, and moved to the exact location of the linked element.
2803  *
2804  * References to the "frame" element refer to the single proxy element that
2805  * was created to be dragged in place of all DDProxy elements on the
2806  * page.
2807  *
2808  * @extends Roo.dd.DD
2809  * @constructor
2810  * @param {String} id the id of the linked html element
2811  * @param {String} sGroup the group of related DragDrop objects
2812  * @param {object} config an object containing configurable attributes
2813  *                Valid properties for DDProxy in addition to those in DragDrop:
2814  *                   resizeFrame, centerFrame, dragElId
2815  */
2816 Roo.dd.DDProxy = function(id, sGroup, config) {
2817     if (id) {
2818         this.init(id, sGroup, config);
2819         this.initFrame();
2820     }
2821 };
2822
2823 /**
2824  * The default drag frame div id
2825  * @property Roo.dd.DDProxy.dragElId
2826  * @type String
2827  * @static
2828  */
2829 Roo.dd.DDProxy.dragElId = "ygddfdiv";
2830
2831 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
2832
2833     /**
2834      * By default we resize the drag frame to be the same size as the element
2835      * we want to drag (this is to get the frame effect).  We can turn it off
2836      * if we want a different behavior.
2837      * @property resizeFrame
2838      * @type boolean
2839      */
2840     resizeFrame: true,
2841
2842     /**
2843      * By default the frame is positioned exactly where the drag element is, so
2844      * we use the cursor offset provided by Roo.dd.DD.  Another option that works only if
2845      * you do not have constraints on the obj is to have the drag frame centered
2846      * around the cursor.  Set centerFrame to true for this effect.
2847      * @property centerFrame
2848      * @type boolean
2849      */
2850     centerFrame: false,
2851
2852     /**
2853      * Creates the proxy element if it does not yet exist
2854      * @method createFrame
2855      */
2856     createFrame: function() {
2857         var self = this;
2858         var body = document.body;
2859
2860         if (!body || !body.firstChild) {
2861             setTimeout( function() { self.createFrame(); }, 50 );
2862             return;
2863         }
2864
2865         var div = this.getDragEl();
2866
2867         if (!div) {
2868             div    = document.createElement("div");
2869             div.id = this.dragElId;
2870             var s  = div.style;
2871
2872             s.position   = "absolute";
2873             s.visibility = "hidden";
2874             s.cursor     = "move";
2875             s.border     = "2px solid #aaa";
2876             s.zIndex     = 999;
2877
2878             // appendChild can blow up IE if invoked prior to the window load event
2879             // while rendering a table.  It is possible there are other scenarios
2880             // that would cause this to happen as well.
2881             body.insertBefore(div, body.firstChild);
2882         }
2883     },
2884
2885     /**
2886      * Initialization for the drag frame element.  Must be called in the
2887      * constructor of all subclasses
2888      * @method initFrame
2889      */
2890     initFrame: function() {
2891         this.createFrame();
2892     },
2893
2894     applyConfig: function() {
2895         Roo.dd.DDProxy.superclass.applyConfig.call(this);
2896
2897         this.resizeFrame = (this.config.resizeFrame !== false);
2898         this.centerFrame = (this.config.centerFrame);
2899         this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
2900     },
2901
2902     /**
2903      * Resizes the drag frame to the dimensions of the clicked object, positions
2904      * it over the object, and finally displays it
2905      * @method showFrame
2906      * @param {int} iPageX X click position
2907      * @param {int} iPageY Y click position
2908      * @private
2909      */
2910     showFrame: function(iPageX, iPageY) {
2911         var el = this.getEl();
2912         var dragEl = this.getDragEl();
2913         var s = dragEl.style;
2914
2915         this._resizeProxy();
2916
2917         if (this.centerFrame) {
2918             this.setDelta( Math.round(parseInt(s.width,  10)/2),
2919                            Math.round(parseInt(s.height, 10)/2) );
2920         }
2921
2922         this.setDragElPos(iPageX, iPageY);
2923
2924         Roo.fly(dragEl).show();
2925     },
2926
2927     /**
2928      * The proxy is automatically resized to the dimensions of the linked
2929      * element when a drag is initiated, unless resizeFrame is set to false
2930      * @method _resizeProxy
2931      * @private
2932      */
2933     _resizeProxy: function() {
2934         if (this.resizeFrame) {
2935             var el = this.getEl();
2936             Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
2937         }
2938     },
2939
2940     // overrides Roo.dd.DragDrop
2941     b4MouseDown: function(e) {
2942         var x = e.getPageX();
2943         var y = e.getPageY();
2944         this.autoOffset(x, y);
2945         this.setDragElPos(x, y);
2946     },
2947
2948     // overrides Roo.dd.DragDrop
2949     b4StartDrag: function(x, y) {
2950         // show the drag frame
2951         this.showFrame(x, y);
2952     },
2953
2954     // overrides Roo.dd.DragDrop
2955     b4EndDrag: function(e) {
2956         Roo.fly(this.getDragEl()).hide();
2957     },
2958
2959     // overrides Roo.dd.DragDrop
2960     // By default we try to move the element to the last location of the frame.
2961     // This is so that the default behavior mirrors that of Roo.dd.DD.
2962     endDrag: function(e) {
2963
2964         var lel = this.getEl();
2965         var del = this.getDragEl();
2966
2967         // Show the drag frame briefly so we can get its position
2968         del.style.visibility = "";
2969
2970         this.beforeMove();
2971         // Hide the linked element before the move to get around a Safari
2972         // rendering bug.
2973         lel.style.visibility = "hidden";
2974         Roo.dd.DDM.moveToEl(lel, del);
2975         del.style.visibility = "hidden";
2976         lel.style.visibility = "";
2977
2978         this.afterDrag();
2979     },
2980
2981     beforeMove : function(){
2982
2983     },
2984
2985     afterDrag : function(){
2986
2987     },
2988
2989     toString: function() {
2990         return ("DDProxy " + this.id);
2991     }
2992
2993 });
2994 /*
2995  * Based on:
2996  * Ext JS Library 1.1.1
2997  * Copyright(c) 2006-2007, Ext JS, LLC.
2998  *
2999  * Originally Released Under LGPL - original licence link has changed is not relivant.
3000  *
3001  * Fork - LGPL
3002  * <script type="text/javascript">
3003  */
3004
3005  /**
3006  * @class Roo.dd.DDTarget
3007  * A DragDrop implementation that does not move, but can be a drop
3008  * target.  You would get the same result by simply omitting implementation
3009  * for the event callbacks, but this way we reduce the processing cost of the
3010  * event listener and the callbacks.
3011  * @extends Roo.dd.DragDrop
3012  * @constructor
3013  * @param {String} id the id of the element that is a drop target
3014  * @param {String} sGroup the group of related DragDrop objects
3015  * @param {object} config an object containing configurable attributes
3016  *                 Valid properties for DDTarget in addition to those in
3017  *                 DragDrop:
3018  *                    none
3019  */
3020 Roo.dd.DDTarget = function(id, sGroup, config) {
3021     if (id) {
3022         this.initTarget(id, sGroup, config);
3023     }
3024     if (config.listeners || config.events) { 
3025        Roo.dd.DragDrop.superclass.constructor.call(this,  { 
3026             listeners : config.listeners || {}, 
3027             events : config.events || {} 
3028         });    
3029     }
3030 };
3031
3032 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
3033 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
3034     toString: function() {
3035         return ("DDTarget " + this.id);
3036     }
3037 });
3038 /*
3039  * Based on:
3040  * Ext JS Library 1.1.1
3041  * Copyright(c) 2006-2007, Ext JS, LLC.
3042  *
3043  * Originally Released Under LGPL - original licence link has changed is not relivant.
3044  *
3045  * Fork - LGPL
3046  * <script type="text/javascript">
3047  */
3048  
3049
3050 /**
3051  * @class Roo.dd.ScrollManager
3052  * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
3053  * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
3054  * @singleton
3055  */
3056 Roo.dd.ScrollManager = function(){
3057     var ddm = Roo.dd.DragDropMgr;
3058     var els = {};
3059     var dragEl = null;
3060     var proc = {};
3061     
3062     
3063     
3064     var onStop = function(e){
3065         dragEl = null;
3066         clearProc();
3067     };
3068     
3069     var triggerRefresh = function(){
3070         if(ddm.dragCurrent){
3071              ddm.refreshCache(ddm.dragCurrent.groups);
3072         }
3073     };
3074     
3075     var doScroll = function(){
3076         if(ddm.dragCurrent){
3077             var dds = Roo.dd.ScrollManager;
3078             if(!dds.animate){
3079                 if(proc.el.scroll(proc.dir, dds.increment)){
3080                     triggerRefresh();
3081                 }
3082             }else{
3083                 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
3084             }
3085         }
3086     };
3087     
3088     var clearProc = function(){
3089         if(proc.id){
3090             clearInterval(proc.id);
3091         }
3092         proc.id = 0;
3093         proc.el = null;
3094         proc.dir = "";
3095     };
3096     
3097     var startProc = function(el, dir){
3098          Roo.log('scroll startproc');
3099         clearProc();
3100         proc.el = el;
3101         proc.dir = dir;
3102         proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
3103     };
3104     
3105     var onFire = function(e, isDrop){
3106        
3107         if(isDrop || !ddm.dragCurrent){ return; }
3108         var dds = Roo.dd.ScrollManager;
3109         if(!dragEl || dragEl != ddm.dragCurrent){
3110             dragEl = ddm.dragCurrent;
3111             // refresh regions on drag start
3112             dds.refreshCache();
3113         }
3114         
3115         var xy = Roo.lib.Event.getXY(e);
3116         var pt = new Roo.lib.Point(xy[0], xy[1]);
3117         for(var id in els){
3118             var el = els[id], r = el._region;
3119             if(r && r.contains(pt) && el.isScrollable()){
3120                 if(r.bottom - pt.y <= dds.thresh){
3121                     if(proc.el != el){
3122                         startProc(el, "down");
3123                     }
3124                     return;
3125                 }else if(r.right - pt.x <= dds.thresh){
3126                     if(proc.el != el){
3127                         startProc(el, "left");
3128                     }
3129                     return;
3130                 }else if(pt.y - r.top <= dds.thresh){
3131                     if(proc.el != el){
3132                         startProc(el, "up");
3133                     }
3134                     return;
3135                 }else if(pt.x - r.left <= dds.thresh){
3136                     if(proc.el != el){
3137                         startProc(el, "right");
3138                     }
3139                     return;
3140                 }
3141             }
3142         }
3143         clearProc();
3144     };
3145     
3146     ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
3147     ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
3148     
3149     return {
3150         /**
3151          * Registers new overflow element(s) to auto scroll
3152          * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
3153          */
3154         register : function(el){
3155             if(el instanceof Array){
3156                 for(var i = 0, len = el.length; i < len; i++) {
3157                         this.register(el[i]);
3158                 }
3159             }else{
3160                 el = Roo.get(el);
3161                 els[el.id] = el;
3162             }
3163             Roo.dd.ScrollManager.els = els;
3164         },
3165         
3166         /**
3167          * Unregisters overflow element(s) so they are no longer scrolled
3168          * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
3169          */
3170         unregister : function(el){
3171             if(el instanceof Array){
3172                 for(var i = 0, len = el.length; i < len; i++) {
3173                         this.unregister(el[i]);
3174                 }
3175             }else{
3176                 el = Roo.get(el);
3177                 delete els[el.id];
3178             }
3179         },
3180         
3181         /**
3182          * The number of pixels from the edge of a container the pointer needs to be to 
3183          * trigger scrolling (defaults to 25)
3184          * @type Number
3185          */
3186         thresh : 25,
3187         
3188         /**
3189          * The number of pixels to scroll in each scroll increment (defaults to 50)
3190          * @type Number
3191          */
3192         increment : 100,
3193         
3194         /**
3195          * The frequency of scrolls in milliseconds (defaults to 500)
3196          * @type Number
3197          */
3198         frequency : 500,
3199         
3200         /**
3201          * True to animate the scroll (defaults to true)
3202          * @type Boolean
3203          */
3204         animate: true,
3205         
3206         /**
3207          * The animation duration in seconds - 
3208          * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
3209          * @type Number
3210          */
3211         animDuration: .4,
3212         
3213         /**
3214          * Manually trigger a cache refresh.
3215          */
3216         refreshCache : function(){
3217             for(var id in els){
3218                 if(typeof els[id] == 'object'){ // for people extending the object prototype
3219                     els[id]._region = els[id].getRegion();
3220                 }
3221             }
3222         }
3223     };
3224 }();/*
3225  * Based on:
3226  * Ext JS Library 1.1.1
3227  * Copyright(c) 2006-2007, Ext JS, LLC.
3228  *
3229  * Originally Released Under LGPL - original licence link has changed is not relivant.
3230  *
3231  * Fork - LGPL
3232  * <script type="text/javascript">
3233  */
3234  
3235
3236 /**
3237  * @class Roo.dd.Registry
3238  * Provides easy access to all drag drop components that are registered on a page.  Items can be retrieved either
3239  * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
3240  * @singleton
3241  */
3242 Roo.dd.Registry = function(){
3243     var elements = {}; 
3244     var handles = {}; 
3245     var autoIdSeed = 0;
3246
3247     var getId = function(el, autogen){
3248         if(typeof el == "string"){
3249             return el;
3250         }
3251         var id = el.id;
3252         if(!id && autogen !== false){
3253             id = "roodd-" + (++autoIdSeed);
3254             el.id = id;
3255         }
3256         return id;
3257     };
3258     
3259     return {
3260     /**
3261      * Register a drag drop element
3262      * @param {String|HTMLElement} element The id or DOM node to register
3263      * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
3264      * in drag drop operations.  You can populate this object with any arbitrary properties that your own code
3265      * knows how to interpret, plus there are some specific properties known to the Registry that should be
3266      * populated in the data object (if applicable):
3267      * <pre>
3268 Value      Description<br />
3269 ---------  ------------------------------------------<br />
3270 handles    Array of DOM nodes that trigger dragging<br />
3271            for the element being registered<br />
3272 isHandle   True if the element passed in triggers<br />
3273            dragging itself, else false
3274 </pre>
3275      */
3276         register : function(el, data){
3277             data = data || {};
3278             if(typeof el == "string"){
3279                 el = document.getElementById(el);
3280             }
3281             data.ddel = el;
3282             elements[getId(el)] = data;
3283             if(data.isHandle !== false){
3284                 handles[data.ddel.id] = data;
3285             }
3286             if(data.handles){
3287                 var hs = data.handles;
3288                 for(var i = 0, len = hs.length; i < len; i++){
3289                         handles[getId(hs[i])] = data;
3290                 }
3291             }
3292         },
3293
3294     /**
3295      * Unregister a drag drop element
3296      * @param {String|HTMLElement}  element The id or DOM node to unregister
3297      */
3298         unregister : function(el){
3299             var id = getId(el, false);
3300             var data = elements[id];
3301             if(data){
3302                 delete elements[id];
3303                 if(data.handles){
3304                     var hs = data.handles;
3305                     for(var i = 0, len = hs.length; i < len; i++){
3306                         delete handles[getId(hs[i], false)];
3307                     }
3308                 }
3309             }
3310         },
3311
3312     /**
3313      * Returns the handle registered for a DOM Node by id
3314      * @param {String|HTMLElement} id The DOM node or id to look up
3315      * @return {Object} handle The custom handle data
3316      */
3317         getHandle : function(id){
3318             if(typeof id != "string"){ // must be element?
3319                 id = id.id;
3320             }
3321             return handles[id];
3322         },
3323
3324     /**
3325      * Returns the handle that is registered for the DOM node that is the target of the event
3326      * @param {Event} e The event
3327      * @return {Object} handle The custom handle data
3328      */
3329         getHandleFromEvent : function(e){
3330             var t = Roo.lib.Event.getTarget(e);
3331             return t ? handles[t.id] : null;
3332         },
3333
3334     /**
3335      * Returns a custom data object that is registered for a DOM node by id
3336      * @param {String|HTMLElement} id The DOM node or id to look up
3337      * @return {Object} data The custom data
3338      */
3339         getTarget : function(id){
3340             if(typeof id != "string"){ // must be element?
3341                 id = id.id;
3342             }
3343             return elements[id];
3344         },
3345
3346     /**
3347      * Returns a custom data object that is registered for the DOM node that is the target of the event
3348      * @param {Event} e The event
3349      * @return {Object} data The custom data
3350      */
3351         getTargetFromEvent : function(e){
3352             var t = Roo.lib.Event.getTarget(e);
3353             return t ? elements[t.id] || handles[t.id] : null;
3354         }
3355     };
3356 }();/*
3357  * Based on:
3358  * Ext JS Library 1.1.1
3359  * Copyright(c) 2006-2007, Ext JS, LLC.
3360  *
3361  * Originally Released Under LGPL - original licence link has changed is not relivant.
3362  *
3363  * Fork - LGPL
3364  * <script type="text/javascript">
3365  */
3366  
3367
3368 /**
3369  * @class Roo.dd.StatusProxy
3370  * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair.  This is the
3371  * default drag proxy used by all Roo.dd components.
3372  * @constructor
3373  * @param {Object} config
3374  */
3375 Roo.dd.StatusProxy = function(config){
3376     Roo.apply(this, config);
3377     this.id = this.id || Roo.id();
3378     this.el = new Roo.Layer({
3379         dh: {
3380             id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
3381                 {tag: "div", cls: "x-dd-drop-icon"},
3382                 {tag: "div", cls: "x-dd-drag-ghost"}
3383             ]
3384         }, 
3385         shadow: !config || config.shadow !== false
3386     });
3387     this.ghost = Roo.get(this.el.dom.childNodes[1]);
3388     this.dropStatus = this.dropNotAllowed;
3389 };
3390
3391 Roo.dd.StatusProxy.prototype = {
3392     /**
3393      * @cfg {String} dropAllowed
3394      * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
3395      */
3396     dropAllowed : "x-dd-drop-ok",
3397     /**
3398      * @cfg {String} dropNotAllowed
3399      * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
3400      */
3401     dropNotAllowed : "x-dd-drop-nodrop",
3402
3403     /**
3404      * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
3405      * over the current target element.
3406      * @param {String} cssClass The css class for the new drop status indicator image
3407      */
3408     setStatus : function(cssClass){
3409         cssClass = cssClass || this.dropNotAllowed;
3410         if(this.dropStatus != cssClass){
3411             this.el.replaceClass(this.dropStatus, cssClass);
3412             this.dropStatus = cssClass;
3413         }
3414     },
3415
3416     /**
3417      * Resets the status indicator to the default dropNotAllowed value
3418      * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
3419      */
3420     reset : function(clearGhost){
3421         this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
3422         this.dropStatus = this.dropNotAllowed;
3423         if(clearGhost){
3424             this.ghost.update("");
3425         }
3426     },
3427
3428     /**
3429      * Updates the contents of the ghost element
3430      * @param {String} html The html that will replace the current innerHTML of the ghost element
3431      */
3432     update : function(html){
3433         if(typeof html == "string"){
3434             this.ghost.update(html);
3435         }else{
3436             this.ghost.update("");
3437             html.style.margin = "0";
3438             this.ghost.dom.appendChild(html);
3439         }
3440         // ensure float = none set?? cant remember why though.
3441         var el = this.ghost.dom.firstChild;
3442                 if(el){
3443                         Roo.fly(el).setStyle('float', 'none');
3444                 }
3445     },
3446     
3447     /**
3448      * Returns the underlying proxy {@link Roo.Layer}
3449      * @return {Roo.Layer} el
3450     */
3451     getEl : function(){
3452         return this.el;
3453     },
3454
3455     /**
3456      * Returns the ghost element
3457      * @return {Roo.Element} el
3458      */
3459     getGhost : function(){
3460         return this.ghost;
3461     },
3462
3463     /**
3464      * Hides the proxy
3465      * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
3466      */
3467     hide : function(clear){
3468         this.el.hide();
3469         if(clear){
3470             this.reset(true);
3471         }
3472     },
3473
3474     /**
3475      * Stops the repair animation if it's currently running
3476      */
3477     stop : function(){
3478         if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
3479             this.anim.stop();
3480         }
3481     },
3482
3483     /**
3484      * Displays this proxy
3485      */
3486     show : function(){
3487         this.el.show();
3488     },
3489
3490     /**
3491      * Force the Layer to sync its shadow and shim positions to the element
3492      */
3493     sync : function(){
3494         this.el.sync();
3495     },
3496
3497     /**
3498      * Causes the proxy to return to its position of origin via an animation.  Should be called after an
3499      * invalid drop operation by the item being dragged.
3500      * @param {Array} xy The XY position of the element ([x, y])
3501      * @param {Function} callback The function to call after the repair is complete
3502      * @param {Object} scope The scope in which to execute the callback
3503      */
3504     repair : function(xy, callback, scope){
3505         this.callback = callback;
3506         this.scope = scope;
3507         if(xy && this.animRepair !== false){
3508             this.el.addClass("x-dd-drag-repair");
3509             this.el.hideUnders(true);
3510             this.anim = this.el.shift({
3511                 duration: this.repairDuration || .5,
3512                 easing: 'easeOut',
3513                 xy: xy,
3514                 stopFx: true,
3515                 callback: this.afterRepair,
3516                 scope: this
3517             });
3518         }else{
3519             this.afterRepair();
3520         }
3521     },
3522
3523     // private
3524     afterRepair : function(){
3525         this.hide(true);
3526         if(typeof this.callback == "function"){
3527             this.callback.call(this.scope || this);
3528         }
3529         this.callback = null;
3530         this.scope = null;
3531     }
3532 };/*
3533  * Based on:
3534  * Ext JS Library 1.1.1
3535  * Copyright(c) 2006-2007, Ext JS, LLC.
3536  *
3537  * Originally Released Under LGPL - original licence link has changed is not relivant.
3538  *
3539  * Fork - LGPL
3540  * <script type="text/javascript">
3541  */
3542
3543 /**
3544  * @class Roo.dd.DragSource
3545  * @extends Roo.dd.DDProxy
3546  * A simple class that provides the basic implementation needed to make any element draggable.
3547  * @constructor
3548  * @param {String/HTMLElement/Element} el The container element
3549  * @param {Object} config
3550  */
3551 Roo.dd.DragSource = function(el, config){
3552     this.el = Roo.get(el);
3553     this.dragData = {};
3554     
3555     Roo.apply(this, config);
3556     
3557     if(!this.proxy){
3558         this.proxy = new Roo.dd.StatusProxy();
3559     }
3560
3561     Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
3562           {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
3563     
3564     this.dragging = false;
3565 };
3566
3567 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
3568     /**
3569      * @cfg {String} dropAllowed
3570      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
3571      */
3572     dropAllowed : "x-dd-drop-ok",
3573     /**
3574      * @cfg {String} dropNotAllowed
3575      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
3576      */
3577     dropNotAllowed : "x-dd-drop-nodrop",
3578
3579     /**
3580      * Returns the data object associated with this drag source
3581      * @return {Object} data An object containing arbitrary data
3582      */
3583     getDragData : function(e){
3584         return this.dragData;
3585     },
3586
3587     // private
3588     onDragEnter : function(e, id){
3589         var target = Roo.dd.DragDropMgr.getDDById(id);
3590         this.cachedTarget = target;
3591         if(this.beforeDragEnter(target, e, id) !== false){
3592             if(target.isNotifyTarget){
3593                 var status = target.notifyEnter(this, e, this.dragData);
3594                 this.proxy.setStatus(status);
3595             }else{
3596                 this.proxy.setStatus(this.dropAllowed);
3597             }
3598             
3599             if(this.afterDragEnter){
3600                 /**
3601                  * An empty function by default, but provided so that you can perform a custom action
3602                  * when the dragged item enters the drop target by providing an implementation.
3603                  * @param {Roo.dd.DragDrop} target The drop target
3604                  * @param {Event} e The event object
3605                  * @param {String} id The id of the dragged element
3606                  * @method afterDragEnter
3607                  */
3608                 this.afterDragEnter(target, e, id);
3609             }
3610         }
3611     },
3612
3613     /**
3614      * An empty function by default, but provided so that you can perform a custom action
3615      * before the dragged item enters the drop target and optionally cancel the onDragEnter.
3616      * @param {Roo.dd.DragDrop} target The drop target
3617      * @param {Event} e The event object
3618      * @param {String} id The id of the dragged element
3619      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3620      */
3621     beforeDragEnter : function(target, e, id){
3622         return true;
3623     },
3624
3625     // private
3626     alignElWithMouse: function() {
3627         Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
3628         this.proxy.sync();
3629     },
3630
3631     // private
3632     onDragOver : function(e, id){
3633         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3634         if(this.beforeDragOver(target, e, id) !== false){
3635             if(target.isNotifyTarget){
3636                 var status = target.notifyOver(this, e, this.dragData);
3637                 this.proxy.setStatus(status);
3638             }
3639
3640             if(this.afterDragOver){
3641                 /**
3642                  * An empty function by default, but provided so that you can perform a custom action
3643                  * while the dragged item is over the drop target by providing an implementation.
3644                  * @param {Roo.dd.DragDrop} target The drop target
3645                  * @param {Event} e The event object
3646                  * @param {String} id The id of the dragged element
3647                  * @method afterDragOver
3648                  */
3649                 this.afterDragOver(target, e, id);
3650             }
3651         }
3652     },
3653
3654     /**
3655      * An empty function by default, but provided so that you can perform a custom action
3656      * while the dragged item is over the drop target and optionally cancel the onDragOver.
3657      * @param {Roo.dd.DragDrop} target The drop target
3658      * @param {Event} e The event object
3659      * @param {String} id The id of the dragged element
3660      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3661      */
3662     beforeDragOver : function(target, e, id){
3663         return true;
3664     },
3665
3666     // private
3667     onDragOut : function(e, id){
3668         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3669         if(this.beforeDragOut(target, e, id) !== false){
3670             if(target.isNotifyTarget){
3671                 target.notifyOut(this, e, this.dragData);
3672             }
3673             this.proxy.reset();
3674             if(this.afterDragOut){
3675                 /**
3676                  * An empty function by default, but provided so that you can perform a custom action
3677                  * after the dragged item is dragged out of the target without dropping.
3678                  * @param {Roo.dd.DragDrop} target The drop target
3679                  * @param {Event} e The event object
3680                  * @param {String} id The id of the dragged element
3681                  * @method afterDragOut
3682                  */
3683                 this.afterDragOut(target, e, id);
3684             }
3685         }
3686         this.cachedTarget = null;
3687     },
3688
3689     /**
3690      * An empty function by default, but provided so that you can perform a custom action before the dragged
3691      * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
3692      * @param {Roo.dd.DragDrop} target The drop target
3693      * @param {Event} e The event object
3694      * @param {String} id The id of the dragged element
3695      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3696      */
3697     beforeDragOut : function(target, e, id){
3698         return true;
3699     },
3700     
3701     // private
3702     onDragDrop : function(e, id){
3703         var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
3704         if(this.beforeDragDrop(target, e, id) !== false){
3705             if(target.isNotifyTarget){
3706                 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
3707                     this.onValidDrop(target, e, id);
3708                 }else{
3709                     this.onInvalidDrop(target, e, id);
3710                 }
3711             }else{
3712                 this.onValidDrop(target, e, id);
3713             }
3714             
3715             if(this.afterDragDrop){
3716                 /**
3717                  * An empty function by default, but provided so that you can perform a custom action
3718                  * after a valid drag drop has occurred by providing an implementation.
3719                  * @param {Roo.dd.DragDrop} target The drop target
3720                  * @param {Event} e The event object
3721                  * @param {String} id The id of the dropped element
3722                  * @method afterDragDrop
3723                  */
3724                 this.afterDragDrop(target, e, id);
3725             }
3726         }
3727         delete this.cachedTarget;
3728     },
3729
3730     /**
3731      * An empty function by default, but provided so that you can perform a custom action before the dragged
3732      * item is dropped onto the target and optionally cancel the onDragDrop.
3733      * @param {Roo.dd.DragDrop} target The drop target
3734      * @param {Event} e The event object
3735      * @param {String} id The id of the dragged element
3736      * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
3737      */
3738     beforeDragDrop : function(target, e, id){
3739         return true;
3740     },
3741
3742     // private
3743     onValidDrop : function(target, e, id){
3744         this.hideProxy();
3745         if(this.afterValidDrop){
3746             /**
3747              * An empty function by default, but provided so that you can perform a custom action
3748              * after a valid drop has occurred by providing an implementation.
3749              * @param {Object} target The target DD 
3750              * @param {Event} e The event object
3751              * @param {String} id The id of the dropped element
3752              * @method afterInvalidDrop
3753              */
3754             this.afterValidDrop(target, e, id);
3755         }
3756     },
3757
3758     // private
3759     getRepairXY : function(e, data){
3760         return this.el.getXY();  
3761     },
3762
3763     // private
3764     onInvalidDrop : function(target, e, id){
3765         this.beforeInvalidDrop(target, e, id);
3766         if(this.cachedTarget){
3767             if(this.cachedTarget.isNotifyTarget){
3768                 this.cachedTarget.notifyOut(this, e, this.dragData);
3769             }
3770             this.cacheTarget = null;
3771         }
3772         this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
3773
3774         if(this.afterInvalidDrop){
3775             /**
3776              * An empty function by default, but provided so that you can perform a custom action
3777              * after an invalid drop has occurred by providing an implementation.
3778              * @param {Event} e The event object
3779              * @param {String} id The id of the dropped element
3780              * @method afterInvalidDrop
3781              */
3782             this.afterInvalidDrop(e, id);
3783         }
3784     },
3785
3786     // private
3787     afterRepair : function(){
3788         if(Roo.enableFx){
3789             this.el.highlight(this.hlColor || "c3daf9");
3790         }
3791         this.dragging = false;
3792     },
3793
3794     /**
3795      * An empty function by default, but provided so that you can perform a custom action after an invalid
3796      * drop has occurred.
3797      * @param {Roo.dd.DragDrop} target The drop target
3798      * @param {Event} e The event object
3799      * @param {String} id The id of the dragged element
3800      * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
3801      */
3802     beforeInvalidDrop : function(target, e, id){
3803         return true;
3804     },
3805
3806     // private
3807     handleMouseDown : function(e){
3808         if(this.dragging) {
3809             return;
3810         }
3811         var data = this.getDragData(e);
3812         if(data && this.onBeforeDrag(data, e) !== false){
3813             this.dragData = data;
3814             this.proxy.stop();
3815             Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
3816         } 
3817     },
3818
3819     /**
3820      * An empty function by default, but provided so that you can perform a custom action before the initial
3821      * drag event begins and optionally cancel it.
3822      * @param {Object} data An object containing arbitrary data to be shared with drop targets
3823      * @param {Event} e The event object
3824      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
3825      */
3826     onBeforeDrag : function(data, e){
3827         return true;
3828     },
3829
3830     /**
3831      * An empty function by default, but provided so that you can perform a custom action once the initial
3832      * drag event has begun.  The drag cannot be canceled from this function.
3833      * @param {Number} x The x position of the click on the dragged object
3834      * @param {Number} y The y position of the click on the dragged object
3835      */
3836     onStartDrag : Roo.emptyFn,
3837
3838     // private - YUI override
3839     startDrag : function(x, y){
3840         this.proxy.reset();
3841         this.dragging = true;
3842         this.proxy.update("");
3843         this.onInitDrag(x, y);
3844         this.proxy.show();
3845     },
3846
3847     // private
3848     onInitDrag : function(x, y){
3849         var clone = this.el.dom.cloneNode(true);
3850         clone.id = Roo.id(); // prevent duplicate ids
3851         this.proxy.update(clone);
3852         this.onStartDrag(x, y);
3853         return true;
3854     },
3855
3856     /**
3857      * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
3858      * @return {Roo.dd.StatusProxy} proxy The StatusProxy
3859      */
3860     getProxy : function(){
3861         return this.proxy;  
3862     },
3863
3864     /**
3865      * Hides the drag source's {@link Roo.dd.StatusProxy}
3866      */
3867     hideProxy : function(){
3868         this.proxy.hide();  
3869         this.proxy.reset(true);
3870         this.dragging = false;
3871     },
3872
3873     // private
3874     triggerCacheRefresh : function(){
3875         Roo.dd.DDM.refreshCache(this.groups);
3876     },
3877
3878     // private - override to prevent hiding
3879     b4EndDrag: function(e) {
3880     },
3881
3882     // private - override to prevent moving
3883     endDrag : function(e){
3884         this.onEndDrag(this.dragData, e);
3885     },
3886
3887     // private
3888     onEndDrag : function(data, e){
3889     },
3890     
3891     // private - pin to cursor
3892     autoOffset : function(x, y) {
3893         this.setDelta(-12, -20);
3894     }    
3895 });/*
3896  * Based on:
3897  * Ext JS Library 1.1.1
3898  * Copyright(c) 2006-2007, Ext JS, LLC.
3899  *
3900  * Originally Released Under LGPL - original licence link has changed is not relivant.
3901  *
3902  * Fork - LGPL
3903  * <script type="text/javascript">
3904  */
3905
3906
3907 /**
3908  * @class Roo.dd.DropTarget
3909  * @extends Roo.dd.DDTarget
3910  * A simple class that provides the basic implementation needed to make any element a drop target that can have
3911  * draggable items dropped onto it.  The drop has no effect until an implementation of notifyDrop is provided.
3912  * @constructor
3913  * @param {String/HTMLElement/Element} el The container element
3914  * @param {Object} config
3915  */
3916 Roo.dd.DropTarget = function(el, config){
3917     this.el = Roo.get(el);
3918     
3919     var listeners = false; ;
3920     if (config && config.listeners) {
3921         listeners= config.listeners;
3922         delete config.listeners;
3923     }
3924     Roo.apply(this, config);
3925     
3926     if(this.containerScroll){
3927         Roo.dd.ScrollManager.register(this.el);
3928     }
3929     this.addEvents( {
3930          /**
3931          * @scope Roo.dd.DropTarget
3932          */
3933          
3934          /**
3935          * @event enter
3936          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
3937          * target.  This default implementation adds the CSS class specified by overClass (if any) to the drop element
3938          * and returns the dropAllowed config value.  This method should be overridden if drop validation is required.
3939          * 
3940          * IMPORTANT : it should set this.overClass and this.dropAllowed
3941          * 
3942          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3943          * @param {Event} e The event
3944          * @param {Object} data An object containing arbitrary data supplied by the drag source
3945          */
3946         "enter" : true,
3947         
3948          /**
3949          * @event over
3950          * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
3951          * This method will be called on every mouse movement while the drag source is over the drop target.
3952          * This default implementation simply returns the dropAllowed config value.
3953          * 
3954          * IMPORTANT : it should set this.dropAllowed
3955          * 
3956          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3957          * @param {Event} e The event
3958          * @param {Object} data An object containing arbitrary data supplied by the drag source
3959          
3960          */
3961         "over" : true,
3962         /**
3963          * @event out
3964          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
3965          * out of the target without dropping.  This default implementation simply removes the CSS class specified by
3966          * overClass (if any) from the drop element.
3967          * 
3968          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3969          * @param {Event} e The event
3970          * @param {Object} data An object containing arbitrary data supplied by the drag source
3971          */
3972          "out" : true,
3973          
3974         /**
3975          * @event drop
3976          * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
3977          * been dropped on it.  This method has no default implementation and returns false, so you must provide an
3978          * implementation that does something to process the drop event and returns true so that the drag source's
3979          * repair action does not run.
3980          * 
3981          * IMPORTANT : it should set this.success
3982          * 
3983          * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
3984          * @param {Event} e The event
3985          * @param {Object} data An object containing arbitrary data supplied by the drag source
3986         */
3987          "drop" : true
3988     });
3989             
3990      
3991     Roo.dd.DropTarget.superclass.constructor.call(  this, 
3992         this.el.dom, 
3993         this.ddGroup || this.group,
3994         {
3995             isTarget: true,
3996             listeners : listeners || {} 
3997            
3998         
3999         }
4000     );
4001
4002 };
4003
4004 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
4005     /**
4006      * @cfg {String} overClass
4007      * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
4008      */
4009      /**
4010      * @cfg {String} ddGroup
4011      * The drag drop group to handle drop events for
4012      */
4013      
4014     /**
4015      * @cfg {String} dropAllowed
4016      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
4017      */
4018     dropAllowed : "x-dd-drop-ok",
4019     /**
4020      * @cfg {String} dropNotAllowed
4021      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
4022      */
4023     dropNotAllowed : "x-dd-drop-nodrop",
4024     /**
4025      * @cfg {boolean} success
4026      * set this after drop listener.. 
4027      */
4028     success : false,
4029     /**
4030      * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
4031      * if the drop point is valid for over/enter..
4032      */
4033     valid : false,
4034     // private
4035     isTarget : true,
4036
4037     // private
4038     isNotifyTarget : true,
4039     
4040     /**
4041      * @hide
4042      */
4043     notifyEnter : function(dd, e, data)
4044     {
4045         this.valid = true;
4046         this.fireEvent('enter', dd, e, data);
4047         if(this.overClass){
4048             this.el.addClass(this.overClass);
4049         }
4050         return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
4051             this.valid ? this.dropAllowed : this.dropNotAllowed
4052         );
4053     },
4054
4055     /**
4056      * @hide
4057      */
4058     notifyOver : function(dd, e, data)
4059     {
4060         this.valid = true;
4061         this.fireEvent('over', dd, e, data);
4062         return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
4063             this.valid ? this.dropAllowed : this.dropNotAllowed
4064         );
4065     },
4066
4067     /**
4068      * @hide
4069      */
4070     notifyOut : function(dd, e, data)
4071     {
4072         this.fireEvent('out', dd, e, data);
4073         if(this.overClass){
4074             this.el.removeClass(this.overClass);
4075         }
4076     },
4077
4078     /**
4079      * @hide
4080      */
4081     notifyDrop : function(dd, e, data)
4082     {
4083         this.success = false;
4084         this.fireEvent('drop', dd, e, data);
4085         return this.success;
4086     }
4087 });/*
4088  * Based on:
4089  * Ext JS Library 1.1.1
4090  * Copyright(c) 2006-2007, Ext JS, LLC.
4091  *
4092  * Originally Released Under LGPL - original licence link has changed is not relivant.
4093  *
4094  * Fork - LGPL
4095  * <script type="text/javascript">
4096  */
4097
4098
4099 /**
4100  * @class Roo.dd.DragZone
4101  * @extends Roo.dd.DragSource
4102  * This class provides a container DD instance that proxies for multiple child node sources.<br />
4103  * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
4104  * @constructor
4105  * @param {String/HTMLElement/Element} el The container element
4106  * @param {Object} config
4107  */
4108 Roo.dd.DragZone = function(el, config){
4109     Roo.dd.DragZone.superclass.constructor.call(this, el, config);
4110     if(this.containerScroll){
4111         Roo.dd.ScrollManager.register(this.el);
4112     }
4113 };
4114
4115 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
4116     /**
4117      * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
4118      * for auto scrolling during drag operations.
4119      */
4120     /**
4121      * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
4122      * method after a failed drop (defaults to "c3daf9" - light blue)
4123      */
4124
4125     /**
4126      * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
4127      * for a valid target to drag based on the mouse down. Override this method
4128      * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
4129      * object has a "ddel" attribute (with an HTML Element) for other functions to work.
4130      * @param {EventObject} e The mouse down event
4131      * @return {Object} The dragData
4132      */
4133     getDragData : function(e){
4134         return Roo.dd.Registry.getHandleFromEvent(e);
4135     },
4136     
4137     /**
4138      * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
4139      * this.dragData.ddel
4140      * @param {Number} x The x position of the click on the dragged object
4141      * @param {Number} y The y position of the click on the dragged object
4142      * @return {Boolean} true to continue the drag, false to cancel
4143      */
4144     onInitDrag : function(x, y){
4145         this.proxy.update(this.dragData.ddel.cloneNode(true));
4146         this.onStartDrag(x, y);
4147         return true;
4148     },
4149     
4150     /**
4151      * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel 
4152      */
4153     afterRepair : function(){
4154         if(Roo.enableFx){
4155             Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
4156         }
4157         this.dragging = false;
4158     },
4159
4160     /**
4161      * Called before a repair of an invalid drop to get the XY to animate to. By default returns
4162      * the XY of this.dragData.ddel
4163      * @param {EventObject} e The mouse up event
4164      * @return {Array} The xy location (e.g. [100, 200])
4165      */
4166     getRepairXY : function(e){
4167         return Roo.Element.fly(this.dragData.ddel).getXY();  
4168     }
4169 });/*
4170  * Based on:
4171  * Ext JS Library 1.1.1
4172  * Copyright(c) 2006-2007, Ext JS, LLC.
4173  *
4174  * Originally Released Under LGPL - original licence link has changed is not relivant.
4175  *
4176  * Fork - LGPL
4177  * <script type="text/javascript">
4178  */
4179 /**
4180  * @class Roo.dd.DropZone
4181  * @extends Roo.dd.DropTarget
4182  * This class provides a container DD instance that proxies for multiple child node targets.<br />
4183  * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
4184  * @constructor
4185  * @param {String/HTMLElement/Element} el The container element
4186  * @param {Object} config
4187  */
4188 Roo.dd.DropZone = function(el, config){
4189     Roo.dd.DropZone.superclass.constructor.call(this, el, config);
4190 };
4191
4192 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
4193     /**
4194      * Returns a custom data object associated with the DOM node that is the target of the event.  By default
4195      * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
4196      * provide your own custom lookup.
4197      * @param {Event} e The event
4198      * @return {Object} data The custom data
4199      */
4200     getTargetFromEvent : function(e){
4201         return Roo.dd.Registry.getTargetFromEvent(e);
4202     },
4203
4204     /**
4205      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
4206      * that it has registered.  This method has no default implementation and should be overridden to provide
4207      * node-specific processing if necessary.
4208      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from 
4209      * {@link #getTargetFromEvent} for this node)
4210      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4211      * @param {Event} e The event
4212      * @param {Object} data An object containing arbitrary data supplied by the drag source
4213      */
4214     onNodeEnter : function(n, dd, e, data){
4215         
4216     },
4217
4218     /**
4219      * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
4220      * that it has registered.  The default implementation returns this.dropNotAllowed, so it should be
4221      * overridden to provide the proper feedback.
4222      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4223      * {@link #getTargetFromEvent} for this node)
4224      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4225      * @param {Event} e The event
4226      * @param {Object} data An object containing arbitrary data supplied by the drag source
4227      * @return {String} status The CSS class that communicates the drop status back to the source so that the
4228      * underlying {@link Roo.dd.StatusProxy} can be updated
4229      */
4230     onNodeOver : function(n, dd, e, data){
4231         return this.dropAllowed;
4232     },
4233
4234     /**
4235      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
4236      * the drop node without dropping.  This method has no default implementation and should be overridden to provide
4237      * node-specific processing if necessary.
4238      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4239      * {@link #getTargetFromEvent} for this node)
4240      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4241      * @param {Event} e The event
4242      * @param {Object} data An object containing arbitrary data supplied by the drag source
4243      */
4244     onNodeOut : function(n, dd, e, data){
4245         
4246     },
4247
4248     /**
4249      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
4250      * the drop node.  The default implementation returns false, so it should be overridden to provide the
4251      * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
4252      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
4253      * {@link #getTargetFromEvent} for this node)
4254      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4255      * @param {Event} e The event
4256      * @param {Object} data An object containing arbitrary data supplied by the drag source
4257      * @return {Boolean} True if the drop was valid, else false
4258      */
4259     onNodeDrop : function(n, dd, e, data){
4260         return false;
4261     },
4262
4263     /**
4264      * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
4265      * but not over any of its registered drop nodes.  The default implementation returns this.dropNotAllowed, so
4266      * it should be overridden to provide the proper feedback if necessary.
4267      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4268      * @param {Event} e The event
4269      * @param {Object} data An object containing arbitrary data supplied by the drag source
4270      * @return {String} status The CSS class that communicates the drop status back to the source so that the
4271      * underlying {@link Roo.dd.StatusProxy} can be updated
4272      */
4273     onContainerOver : function(dd, e, data){
4274         return this.dropNotAllowed;
4275     },
4276
4277     /**
4278      * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
4279      * but not on any of its registered drop nodes.  The default implementation returns false, so it should be
4280      * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
4281      * be able to accept drops.  It should return true when valid so that the drag source's repair action does not run.
4282      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4283      * @param {Event} e The event
4284      * @param {Object} data An object containing arbitrary data supplied by the drag source
4285      * @return {Boolean} True if the drop was valid, else false
4286      */
4287     onContainerDrop : function(dd, e, data){
4288         return false;
4289     },
4290
4291     /**
4292      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
4293      * the zone.  The default implementation returns this.dropNotAllowed and expects that only registered drop
4294      * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
4295      * you should override this method and provide a custom implementation.
4296      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4297      * @param {Event} e The event
4298      * @param {Object} data An object containing arbitrary data supplied by the drag source
4299      * @return {String} status The CSS class that communicates the drop status back to the source so that the
4300      * underlying {@link Roo.dd.StatusProxy} can be updated
4301      */
4302     notifyEnter : function(dd, e, data){
4303         return this.dropNotAllowed;
4304     },
4305
4306     /**
4307      * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
4308      * This method will be called on every mouse movement while the drag source is over the drop zone.
4309      * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
4310      * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
4311      * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
4312      * registered node, it will call {@link #onContainerOver}.
4313      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4314      * @param {Event} e The event
4315      * @param {Object} data An object containing arbitrary data supplied by the drag source
4316      * @return {String} status The CSS class that communicates the drop status back to the source so that the
4317      * underlying {@link Roo.dd.StatusProxy} can be updated
4318      */
4319     notifyOver : function(dd, e, data){
4320         var n = this.getTargetFromEvent(e);
4321         if(!n){ // not over valid drop target
4322             if(this.lastOverNode){
4323                 this.onNodeOut(this.lastOverNode, dd, e, data);
4324                 this.lastOverNode = null;
4325             }
4326             return this.onContainerOver(dd, e, data);
4327         }
4328         if(this.lastOverNode != n){
4329             if(this.lastOverNode){
4330                 this.onNodeOut(this.lastOverNode, dd, e, data);
4331             }
4332             this.onNodeEnter(n, dd, e, data);
4333             this.lastOverNode = n;
4334         }
4335         return this.onNodeOver(n, dd, e, data);
4336     },
4337
4338     /**
4339      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
4340      * out of the zone without dropping.  If the drag source is currently over a registered node, the notification
4341      * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
4342      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
4343      * @param {Event} e The event
4344      * @param {Object} data An object containing arbitrary data supplied by the drag zone
4345      */
4346     notifyOut : function(dd, e, data){
4347         if(this.lastOverNode){
4348             this.onNodeOut(this.lastOverNode, dd, e, data);
4349             this.lastOverNode = null;
4350         }
4351     },
4352
4353     /**
4354      * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
4355      * been dropped on it.  The drag zone will look up the target node based on the event passed in, and if there
4356      * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
4357      * otherwise it will call {@link #onContainerDrop}.
4358      * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
4359      * @param {Event} e The event
4360      * @param {Object} data An object containing arbitrary data supplied by the drag source
4361      * @return {Boolean} True if the drop was valid, else false
4362      */
4363     notifyDrop : function(dd, e, data){
4364         if(this.lastOverNode){
4365             this.onNodeOut(this.lastOverNode, dd, e, data);
4366             this.lastOverNode = null;
4367         }
4368         var n = this.getTargetFromEvent(e);
4369         return n ?
4370             this.onNodeDrop(n, dd, e, data) :
4371             this.onContainerDrop(dd, e, data);
4372     },
4373
4374     // private
4375     triggerCacheRefresh : function(){
4376         Roo.dd.DDM.refreshCache(this.groups);
4377     }  
4378 });/*
4379  * Based on:
4380  * Ext JS Library 1.1.1
4381  * Copyright(c) 2006-2007, Ext JS, LLC.
4382  *
4383  * Originally Released Under LGPL - original licence link has changed is not relivant.
4384  *
4385  * Fork - LGPL
4386  * <script type="text/javascript">
4387  */
4388
4389
4390 /**
4391  * @class Roo.data.SortTypes
4392  * @singleton
4393  * Defines the default sorting (casting?) comparison functions used when sorting data.
4394  */
4395 Roo.data.SortTypes = {
4396     /**
4397      * Default sort that does nothing
4398      * @param {Mixed} s The value being converted
4399      * @return {Mixed} The comparison value
4400      */
4401     none : function(s){
4402         return s;
4403     },
4404     
4405     /**
4406      * The regular expression used to strip tags
4407      * @type {RegExp}
4408      * @property
4409      */
4410     stripTagsRE : /<\/?[^>]+>/gi,
4411     
4412     /**
4413      * Strips all HTML tags to sort on text only
4414      * @param {Mixed} s The value being converted
4415      * @return {String} The comparison value
4416      */
4417     asText : function(s){
4418         return String(s).replace(this.stripTagsRE, "");
4419     },
4420     
4421     /**
4422      * Strips all HTML tags to sort on text only - Case insensitive
4423      * @param {Mixed} s The value being converted
4424      * @return {String} The comparison value
4425      */
4426     asUCText : function(s){
4427         return String(s).toUpperCase().replace(this.stripTagsRE, "");
4428     },
4429     
4430     /**
4431      * Case insensitive string
4432      * @param {Mixed} s The value being converted
4433      * @return {String} The comparison value
4434      */
4435     asUCString : function(s) {
4436         return String(s).toUpperCase();
4437     },
4438     
4439     /**
4440      * Date sorting
4441      * @param {Mixed} s The value being converted
4442      * @return {Number} The comparison value
4443      */
4444     asDate : function(s) {
4445         if(!s){
4446             return 0;
4447         }
4448         if(s instanceof Date){
4449             return s.getTime();
4450         }
4451         return Date.parse(String(s));
4452     },
4453     
4454     /**
4455      * Float sorting
4456      * @param {Mixed} s The value being converted
4457      * @return {Float} The comparison value
4458      */
4459     asFloat : function(s) {
4460         var val = parseFloat(String(s).replace(/,/g, ""));
4461         if(isNaN(val)) val = 0;
4462         return val;
4463     },
4464     
4465     /**
4466      * Integer sorting
4467      * @param {Mixed} s The value being converted
4468      * @return {Number} The comparison value
4469      */
4470     asInt : function(s) {
4471         var val = parseInt(String(s).replace(/,/g, ""));
4472         if(isNaN(val)) val = 0;
4473         return val;
4474     }
4475 };/*
4476  * Based on:
4477  * Ext JS Library 1.1.1
4478  * Copyright(c) 2006-2007, Ext JS, LLC.
4479  *
4480  * Originally Released Under LGPL - original licence link has changed is not relivant.
4481  *
4482  * Fork - LGPL
4483  * <script type="text/javascript">
4484  */
4485
4486 /**
4487 * @class Roo.data.Record
4488  * Instances of this class encapsulate both record <em>definition</em> information, and record
4489  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
4490  * to access Records cached in an {@link Roo.data.Store} object.<br>
4491  * <p>
4492  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
4493  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
4494  * objects.<br>
4495  * <p>
4496  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
4497  * @constructor
4498  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
4499  * {@link #create}. The parameters are the same.
4500  * @param {Array} data An associative Array of data values keyed by the field name.
4501  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
4502  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
4503  * not specified an integer id is generated.
4504  */
4505 Roo.data.Record = function(data, id){
4506     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
4507     this.data = data;
4508 };
4509
4510 /**
4511  * Generate a constructor for a specific record layout.
4512  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
4513  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
4514  * Each field definition object may contain the following properties: <ul>
4515  * <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,
4516  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
4517  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
4518  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
4519  * is being used, then this is a string containing the javascript expression to reference the data relative to 
4520  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
4521  * to the data item relative to the record element. If the mapping expression is the same as the field name,
4522  * this may be omitted.</p></li>
4523  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
4524  * <ul><li>auto (Default, implies no conversion)</li>
4525  * <li>string</li>
4526  * <li>int</li>
4527  * <li>float</li>
4528  * <li>boolean</li>
4529  * <li>date</li></ul></p></li>
4530  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
4531  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
4532  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
4533  * by the Reader into an object that will be stored in the Record. It is passed the
4534  * following parameters:<ul>
4535  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
4536  * </ul></p></li>
4537  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
4538  * </ul>
4539  * <br>usage:<br><pre><code>
4540 var TopicRecord = Roo.data.Record.create(
4541     {name: 'title', mapping: 'topic_title'},
4542     {name: 'author', mapping: 'username'},
4543     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
4544     {name: 'lastPost', mapping: 'post_time', type: 'date'},
4545     {name: 'lastPoster', mapping: 'user2'},
4546     {name: 'excerpt', mapping: 'post_text'}
4547 );
4548
4549 var myNewRecord = new TopicRecord({
4550     title: 'Do my job please',
4551     author: 'noobie',
4552     totalPosts: 1,
4553     lastPost: new Date(),
4554     lastPoster: 'Animal',
4555     excerpt: 'No way dude!'
4556 });
4557 myStore.add(myNewRecord);
4558 </code></pre>
4559  * @method create
4560  * @static
4561  */
4562 Roo.data.Record.create = function(o){
4563     var f = function(){
4564         f.superclass.constructor.apply(this, arguments);
4565     };
4566     Roo.extend(f, Roo.data.Record);
4567     var p = f.prototype;
4568     p.fields = new Roo.util.MixedCollection(false, function(field){
4569         return field.name;
4570     });
4571     for(var i = 0, len = o.length; i < len; i++){
4572         p.fields.add(new Roo.data.Field(o[i]));
4573     }
4574     f.getField = function(name){
4575         return p.fields.get(name);  
4576     };
4577     return f;
4578 };
4579
4580 Roo.data.Record.AUTO_ID = 1000;
4581 Roo.data.Record.EDIT = 'edit';
4582 Roo.data.Record.REJECT = 'reject';
4583 Roo.data.Record.COMMIT = 'commit';
4584
4585 Roo.data.Record.prototype = {
4586     /**
4587      * Readonly flag - true if this record has been modified.
4588      * @type Boolean
4589      */
4590     dirty : false,
4591     editing : false,
4592     error: null,
4593     modified: null,
4594
4595     // private
4596     join : function(store){
4597         this.store = store;
4598     },
4599
4600     /**
4601      * Set the named field to the specified value.
4602      * @param {String} name The name of the field to set.
4603      * @param {Object} value The value to set the field to.
4604      */
4605     set : function(name, value){
4606         if(this.data[name] == value){
4607             return;
4608         }
4609         this.dirty = true;
4610         if(!this.modified){
4611             this.modified = {};
4612         }
4613         if(typeof this.modified[name] == 'undefined'){
4614             this.modified[name] = this.data[name];
4615         }
4616         this.data[name] = value;
4617         if(!this.editing && this.store){
4618             this.store.afterEdit(this);
4619         }       
4620     },
4621
4622     /**
4623      * Get the value of the named field.
4624      * @param {String} name The name of the field to get the value of.
4625      * @return {Object} The value of the field.
4626      */
4627     get : function(name){
4628         return this.data[name]; 
4629     },
4630
4631     // private
4632     beginEdit : function(){
4633         this.editing = true;
4634         this.modified = {}; 
4635     },
4636
4637     // private
4638     cancelEdit : function(){
4639         this.editing = false;
4640         delete this.modified;
4641     },
4642
4643     // private
4644     endEdit : function(){
4645         this.editing = false;
4646         if(this.dirty && this.store){
4647             this.store.afterEdit(this);
4648         }
4649     },
4650
4651     /**
4652      * Usually called by the {@link Roo.data.Store} which owns the Record.
4653      * Rejects all changes made to the Record since either creation, or the last commit operation.
4654      * Modified fields are reverted to their original values.
4655      * <p>
4656      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
4657      * of reject operations.
4658      */
4659     reject : function(){
4660         var m = this.modified;
4661         for(var n in m){
4662             if(typeof m[n] != "function"){
4663                 this.data[n] = m[n];
4664             }
4665         }
4666         this.dirty = false;
4667         delete this.modified;
4668         this.editing = false;
4669         if(this.store){
4670             this.store.afterReject(this);
4671         }
4672     },
4673
4674     /**
4675      * Usually called by the {@link Roo.data.Store} which owns the Record.
4676      * Commits all changes made to the Record since either creation, or the last commit operation.
4677      * <p>
4678      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
4679      * of commit operations.
4680      */
4681     commit : function(){
4682         this.dirty = false;
4683         delete this.modified;
4684         this.editing = false;
4685         if(this.store){
4686             this.store.afterCommit(this);
4687         }
4688     },
4689
4690     // private
4691     hasError : function(){
4692         return this.error != null;
4693     },
4694
4695     // private
4696     clearError : function(){
4697         this.error = null;
4698     },
4699
4700     /**
4701      * Creates a copy of this record.
4702      * @param {String} id (optional) A new record id if you don't want to use this record's id
4703      * @return {Record}
4704      */
4705     copy : function(newId) {
4706         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
4707     }
4708 };/*
4709  * Based on:
4710  * Ext JS Library 1.1.1
4711  * Copyright(c) 2006-2007, Ext JS, LLC.
4712  *
4713  * Originally Released Under LGPL - original licence link has changed is not relivant.
4714  *
4715  * Fork - LGPL
4716  * <script type="text/javascript">
4717  */
4718
4719
4720
4721 /**
4722  * @class Roo.data.Store
4723  * @extends Roo.util.Observable
4724  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
4725  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
4726  * <p>
4727  * 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
4728  * has no knowledge of the format of the data returned by the Proxy.<br>
4729  * <p>
4730  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
4731  * instances from the data object. These records are cached and made available through accessor functions.
4732  * @constructor
4733  * Creates a new Store.
4734  * @param {Object} config A config object containing the objects needed for the Store to access data,
4735  * and read the data into Records.
4736  */
4737 Roo.data.Store = function(config){
4738     this.data = new Roo.util.MixedCollection(false);
4739     this.data.getKey = function(o){
4740         return o.id;
4741     };
4742     this.baseParams = {};
4743     // private
4744     this.paramNames = {
4745         "start" : "start",
4746         "limit" : "limit",
4747         "sort" : "sort",
4748         "dir" : "dir",
4749         "multisort" : "_multisort"
4750     };
4751
4752     if(config && config.data){
4753         this.inlineData = config.data;
4754         delete config.data;
4755     }
4756
4757     Roo.apply(this, config);
4758     
4759     if(this.reader){ // reader passed
4760         this.reader = Roo.factory(this.reader, Roo.data);
4761         this.reader.xmodule = this.xmodule || false;
4762         if(!this.recordType){
4763             this.recordType = this.reader.recordType;
4764         }
4765         if(this.reader.onMetaChange){
4766             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
4767         }
4768     }
4769
4770     if(this.recordType){
4771         this.fields = this.recordType.prototype.fields;
4772     }
4773     this.modified = [];
4774
4775     this.addEvents({
4776         /**
4777          * @event datachanged
4778          * Fires when the data cache has changed, and a widget which is using this Store
4779          * as a Record cache should refresh its view.
4780          * @param {Store} this
4781          */
4782         datachanged : true,
4783         /**
4784          * @event metachange
4785          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
4786          * @param {Store} this
4787          * @param {Object} meta The JSON metadata
4788          */
4789         metachange : true,
4790         /**
4791          * @event add
4792          * Fires when Records have been added to the Store
4793          * @param {Store} this
4794          * @param {Roo.data.Record[]} records The array of Records added
4795          * @param {Number} index The index at which the record(s) were added
4796          */
4797         add : true,
4798         /**
4799          * @event remove
4800          * Fires when a Record has been removed from the Store
4801          * @param {Store} this
4802          * @param {Roo.data.Record} record The Record that was removed
4803          * @param {Number} index The index at which the record was removed
4804          */
4805         remove : true,
4806         /**
4807          * @event update
4808          * Fires when a Record has been updated
4809          * @param {Store} this
4810          * @param {Roo.data.Record} record The Record that was updated
4811          * @param {String} operation The update operation being performed.  Value may be one of:
4812          * <pre><code>
4813  Roo.data.Record.EDIT
4814  Roo.data.Record.REJECT
4815  Roo.data.Record.COMMIT
4816          * </code></pre>
4817          */
4818         update : true,
4819         /**
4820          * @event clear
4821          * Fires when the data cache has been cleared.
4822          * @param {Store} this
4823          */
4824         clear : true,
4825         /**
4826          * @event beforeload
4827          * Fires before a request is made for a new data object.  If the beforeload handler returns false
4828          * the load action will be canceled.
4829          * @param {Store} this
4830          * @param {Object} options The loading options that were specified (see {@link #load} for details)
4831          */
4832         beforeload : true,
4833         /**
4834          * @event beforeloadadd
4835          * Fires after a new set of Records has been loaded.
4836          * @param {Store} this
4837          * @param {Roo.data.Record[]} records The Records that were loaded
4838          * @param {Object} options The loading options that were specified (see {@link #load} for details)
4839          */
4840         beforeloadadd : true,
4841         /**
4842          * @event load
4843          * Fires after a new set of Records has been loaded, before they are added to the store.
4844          * @param {Store} this
4845          * @param {Roo.data.Record[]} records The Records that were loaded
4846          * @param {Object} options The loading options that were specified (see {@link #load} for details)
4847          * @params {Object} return from reader
4848          */
4849         load : true,
4850         /**
4851          * @event loadexception
4852          * Fires if an exception occurs in the Proxy during loading.
4853          * Called with the signature of the Proxy's "loadexception" event.
4854          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
4855          * 
4856          * @param {Proxy} 
4857          * @param {Object} return from JsonData.reader() - success, totalRecords, records
4858          * @param {Object} load options 
4859          * @param {Object} jsonData from your request (normally this contains the Exception)
4860          */
4861         loadexception : true
4862     });
4863     
4864     if(this.proxy){
4865         this.proxy = Roo.factory(this.proxy, Roo.data);
4866         this.proxy.xmodule = this.xmodule || false;
4867         this.relayEvents(this.proxy,  ["loadexception"]);
4868     }
4869     this.sortToggle = {};
4870     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
4871
4872     Roo.data.Store.superclass.constructor.call(this);
4873
4874     if(this.inlineData){
4875         this.loadData(this.inlineData);
4876         delete this.inlineData;
4877     }
4878 };
4879
4880 Roo.extend(Roo.data.Store, Roo.util.Observable, {
4881      /**
4882     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
4883     * without a remote query - used by combo/forms at present.
4884     */
4885     
4886     /**
4887     * @cfg {Roo.data.DataProxy} proxy The Proxy object which provides access to a data object.
4888     */
4889     /**
4890     * @cfg {Array} data Inline data to be loaded when the store is initialized.
4891     */
4892     /**
4893     * @cfg {Roo.data.Reader} reader The Reader object which processes the data object and returns
4894     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
4895     */
4896     /**
4897     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
4898     * on any HTTP request
4899     */
4900     /**
4901     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
4902     */
4903     /**
4904     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
4905     */
4906     multiSort: false,
4907     /**
4908     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
4909     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
4910     */
4911     remoteSort : false,
4912
4913     /**
4914     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
4915      * loaded or when a record is removed. (defaults to false).
4916     */
4917     pruneModifiedRecords : false,
4918
4919     // private
4920     lastOptions : null,
4921
4922     /**
4923      * Add Records to the Store and fires the add event.
4924      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
4925      */
4926     add : function(records){
4927         records = [].concat(records);
4928         for(var i = 0, len = records.length; i < len; i++){
4929             records[i].join(this);
4930         }
4931         var index = this.data.length;
4932         this.data.addAll(records);
4933         this.fireEvent("add", this, records, index);
4934     },
4935
4936     /**
4937      * Remove a Record from the Store and fires the remove event.
4938      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
4939      */
4940     remove : function(record){
4941         var index = this.data.indexOf(record);
4942         this.data.removeAt(index);
4943         if(this.pruneModifiedRecords){
4944             this.modified.remove(record);
4945         }
4946         this.fireEvent("remove", this, record, index);
4947     },
4948
4949     /**
4950      * Remove all Records from the Store and fires the clear event.
4951      */
4952     removeAll : function(){
4953         this.data.clear();
4954         if(this.pruneModifiedRecords){
4955             this.modified = [];
4956         }
4957         this.fireEvent("clear", this);
4958     },
4959
4960     /**
4961      * Inserts Records to the Store at the given index and fires the add event.
4962      * @param {Number} index The start index at which to insert the passed Records.
4963      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
4964      */
4965     insert : function(index, records){
4966         records = [].concat(records);
4967         for(var i = 0, len = records.length; i < len; i++){
4968             this.data.insert(index, records[i]);
4969             records[i].join(this);
4970         }
4971         this.fireEvent("add", this, records, index);
4972     },
4973
4974     /**
4975      * Get the index within the cache of the passed Record.
4976      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
4977      * @return {Number} The index of the passed Record. Returns -1 if not found.
4978      */
4979     indexOf : function(record){
4980         return this.data.indexOf(record);
4981     },
4982
4983     /**
4984      * Get the index within the cache of the Record with the passed id.
4985      * @param {String} id The id of the Record to find.
4986      * @return {Number} The index of the Record. Returns -1 if not found.
4987      */
4988     indexOfId : function(id){
4989         return this.data.indexOfKey(id);
4990     },
4991
4992     /**
4993      * Get the Record with the specified id.
4994      * @param {String} id The id of the Record to find.
4995      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
4996      */
4997     getById : function(id){
4998         return this.data.key(id);
4999     },
5000
5001     /**
5002      * Get the Record at the specified index.
5003      * @param {Number} index The index of the Record to find.
5004      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
5005      */
5006     getAt : function(index){
5007         return this.data.itemAt(index);
5008     },
5009
5010     /**
5011      * Returns a range of Records between specified indices.
5012      * @param {Number} startIndex (optional) The starting index (defaults to 0)
5013      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
5014      * @return {Roo.data.Record[]} An array of Records
5015      */
5016     getRange : function(start, end){
5017         return this.data.getRange(start, end);
5018     },
5019
5020     // private
5021     storeOptions : function(o){
5022         o = Roo.apply({}, o);
5023         delete o.callback;
5024         delete o.scope;
5025         this.lastOptions = o;
5026     },
5027
5028     /**
5029      * Loads the Record cache from the configured Proxy using the configured Reader.
5030      * <p>
5031      * If using remote paging, then the first load call must specify the <em>start</em>
5032      * and <em>limit</em> properties in the options.params property to establish the initial
5033      * position within the dataset, and the number of Records to cache on each read from the Proxy.
5034      * <p>
5035      * <strong>It is important to note that for remote data sources, loading is asynchronous,
5036      * and this call will return before the new data has been loaded. Perform any post-processing
5037      * in a callback function, or in a "load" event handler.</strong>
5038      * <p>
5039      * @param {Object} options An object containing properties which control loading options:<ul>
5040      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
5041      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
5042      * passed the following arguments:<ul>
5043      * <li>r : Roo.data.Record[]</li>
5044      * <li>options: Options object from the load call</li>
5045      * <li>success: Boolean success indicator</li></ul></li>
5046      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
5047      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
5048      * </ul>
5049      */
5050     load : function(options){
5051         options = options || {};
5052         if(this.fireEvent("beforeload", this, options) !== false){
5053             this.storeOptions(options);
5054             var p = Roo.apply(options.params || {}, this.baseParams);
5055             // if meta was not loaded from remote source.. try requesting it.
5056             if (!this.reader.metaFromRemote) {
5057                 p._requestMeta = 1;
5058             }
5059             if(this.sortInfo && this.remoteSort){
5060                 var pn = this.paramNames;
5061                 p[pn["sort"]] = this.sortInfo.field;
5062                 p[pn["dir"]] = this.sortInfo.direction;
5063             }
5064             if (this.multiSort) {
5065                 var pn = this.paramNames;
5066                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
5067             }
5068             
5069             this.proxy.load(p, this.reader, this.loadRecords, this, options);
5070         }
5071     },
5072
5073     /**
5074      * Reloads the Record cache from the configured Proxy using the configured Reader and
5075      * the options from the last load operation performed.
5076      * @param {Object} options (optional) An object containing properties which may override the options
5077      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
5078      * the most recently used options are reused).
5079      */
5080     reload : function(options){
5081         this.load(Roo.applyIf(options||{}, this.lastOptions));
5082     },
5083
5084     // private
5085     // Called as a callback by the Reader during a load operation.
5086     loadRecords : function(o, options, success){
5087         if(!o || success === false){
5088             if(success !== false){
5089                 this.fireEvent("load", this, [], options, o);
5090             }
5091             if(options.callback){
5092                 options.callback.call(options.scope || this, [], options, false);
5093             }
5094             return;
5095         }
5096         // if data returned failure - throw an exception.
5097         if (o.success === false) {
5098             // show a message if no listener is registered.
5099             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
5100                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
5101             }
5102             // loadmask wil be hooked into this..
5103             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
5104             return;
5105         }
5106         var r = o.records, t = o.totalRecords || r.length;
5107         
5108         this.fireEvent("beforeloadadd", this, r, options, o);
5109         
5110         if(!options || options.add !== true){
5111             if(this.pruneModifiedRecords){
5112                 this.modified = [];
5113             }
5114             for(var i = 0, len = r.length; i < len; i++){
5115                 r[i].join(this);
5116             }
5117             if(this.snapshot){
5118                 this.data = this.snapshot;
5119                 delete this.snapshot;
5120             }
5121             this.data.clear();
5122             this.data.addAll(r);
5123             this.totalLength = t;
5124             this.applySort();
5125             this.fireEvent("datachanged", this);
5126         }else{
5127             this.totalLength = Math.max(t, this.data.length+r.length);
5128             this.add(r);
5129         }
5130         this.fireEvent("load", this, r, options, o);
5131         if(options.callback){
5132             options.callback.call(options.scope || this, r, options, true);
5133         }
5134     },
5135
5136
5137     /**
5138      * Loads data from a passed data block. A Reader which understands the format of the data
5139      * must have been configured in the constructor.
5140      * @param {Object} data The data block from which to read the Records.  The format of the data expected
5141      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
5142      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
5143      */
5144     loadData : function(o, append){
5145         var r = this.reader.readRecords(o);
5146         this.loadRecords(r, {add: append}, true);
5147     },
5148
5149     /**
5150      * Gets the number of cached records.
5151      * <p>
5152      * <em>If using paging, this may not be the total size of the dataset. If the data object
5153      * used by the Reader contains the dataset size, then the getTotalCount() function returns
5154      * the data set size</em>
5155      */
5156     getCount : function(){
5157         return this.data.length || 0;
5158     },
5159
5160     /**
5161      * Gets the total number of records in the dataset as returned by the server.
5162      * <p>
5163      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
5164      * the dataset size</em>
5165      */
5166     getTotalCount : function(){
5167         return this.totalLength || 0;
5168     },
5169
5170     /**
5171      * Returns the sort state of the Store as an object with two properties:
5172      * <pre><code>
5173  field {String} The name of the field by which the Records are sorted
5174  direction {String} The sort order, "ASC" or "DESC"
5175      * </code></pre>
5176      */
5177     getSortState : function(){
5178         return this.sortInfo;
5179     },
5180
5181     // private
5182     applySort : function(){
5183         if(this.sortInfo && !this.remoteSort){
5184             var s = this.sortInfo, f = s.field;
5185             var st = this.fields.get(f).sortType;
5186             var fn = function(r1, r2){
5187                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
5188                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
5189             };
5190             this.data.sort(s.direction, fn);
5191             if(this.snapshot && this.snapshot != this.data){
5192                 this.snapshot.sort(s.direction, fn);
5193             }
5194         }
5195     },
5196
5197     /**
5198      * Sets the default sort column and order to be used by the next load operation.
5199      * @param {String} fieldName The name of the field to sort by.
5200      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
5201      */
5202     setDefaultSort : function(field, dir){
5203         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
5204     },
5205
5206     /**
5207      * Sort the Records.
5208      * If remote sorting is used, the sort is performed on the server, and the cache is
5209      * reloaded. If local sorting is used, the cache is sorted internally.
5210      * @param {String} fieldName The name of the field to sort by.
5211      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
5212      */
5213     sort : function(fieldName, dir){
5214         var f = this.fields.get(fieldName);
5215         if(!dir){
5216             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
5217             
5218             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
5219                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
5220             }else{
5221                 dir = f.sortDir;
5222             }
5223         }
5224         this.sortToggle[f.name] = dir;
5225         this.sortInfo = {field: f.name, direction: dir};
5226         if(!this.remoteSort){
5227             this.applySort();
5228             this.fireEvent("datachanged", this);
5229         }else{
5230             this.load(this.lastOptions);
5231         }
5232     },
5233
5234     /**
5235      * Calls the specified function for each of the Records in the cache.
5236      * @param {Function} fn The function to call. The Record is passed as the first parameter.
5237      * Returning <em>false</em> aborts and exits the iteration.
5238      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
5239      */
5240     each : function(fn, scope){
5241         this.data.each(fn, scope);
5242     },
5243
5244     /**
5245      * Gets all records modified since the last commit.  Modified records are persisted across load operations
5246      * (e.g., during paging).
5247      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
5248      */
5249     getModifiedRecords : function(){
5250         return this.modified;
5251     },
5252
5253     // private
5254     createFilterFn : function(property, value, anyMatch){
5255         if(!value.exec){ // not a regex
5256             value = String(value);
5257             if(value.length == 0){
5258                 return false;
5259             }
5260             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
5261         }
5262         return function(r){
5263             return value.test(r.data[property]);
5264         };
5265     },
5266
5267     /**
5268      * Sums the value of <i>property</i> for each record between start and end and returns the result.
5269      * @param {String} property A field on your records
5270      * @param {Number} start The record index to start at (defaults to 0)
5271      * @param {Number} end The last record index to include (defaults to length - 1)
5272      * @return {Number} The sum
5273      */
5274     sum : function(property, start, end){
5275         var rs = this.data.items, v = 0;
5276         start = start || 0;
5277         end = (end || end === 0) ? end : rs.length-1;
5278
5279         for(var i = start; i <= end; i++){
5280             v += (rs[i].data[property] || 0);
5281         }
5282         return v;
5283     },
5284
5285     /**
5286      * Filter the records by a specified property.
5287      * @param {String} field A field on your records
5288      * @param {String/RegExp} value Either a string that the field
5289      * should start with or a RegExp to test against the field
5290      * @param {Boolean} anyMatch True to match any part not just the beginning
5291      */
5292     filter : function(property, value, anyMatch){
5293         var fn = this.createFilterFn(property, value, anyMatch);
5294         return fn ? this.filterBy(fn) : this.clearFilter();
5295     },
5296
5297     /**
5298      * Filter by a function. The specified function will be called with each
5299      * record in this data source. If the function returns true the record is included,
5300      * otherwise it is filtered.
5301      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
5302      * @param {Object} scope (optional) The scope of the function (defaults to this)
5303      */
5304     filterBy : function(fn, scope){
5305         this.snapshot = this.snapshot || this.data;
5306         this.data = this.queryBy(fn, scope||this);
5307         this.fireEvent("datachanged", this);
5308     },
5309
5310     /**
5311      * Query the records by a specified property.
5312      * @param {String} field A field on your records
5313      * @param {String/RegExp} value Either a string that the field
5314      * should start with or a RegExp to test against the field
5315      * @param {Boolean} anyMatch True to match any part not just the beginning
5316      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
5317      */
5318     query : function(property, value, anyMatch){
5319         var fn = this.createFilterFn(property, value, anyMatch);
5320         return fn ? this.queryBy(fn) : this.data.clone();
5321     },
5322
5323     /**
5324      * Query by a function. The specified function will be called with each
5325      * record in this data source. If the function returns true the record is included
5326      * in the results.
5327      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
5328      * @param {Object} scope (optional) The scope of the function (defaults to this)
5329       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
5330      **/
5331     queryBy : function(fn, scope){
5332         var data = this.snapshot || this.data;
5333         return data.filterBy(fn, scope||this);
5334     },
5335
5336     /**
5337      * Collects unique values for a particular dataIndex from this store.
5338      * @param {String} dataIndex The property to collect
5339      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
5340      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
5341      * @return {Array} An array of the unique values
5342      **/
5343     collect : function(dataIndex, allowNull, bypassFilter){
5344         var d = (bypassFilter === true && this.snapshot) ?
5345                 this.snapshot.items : this.data.items;
5346         var v, sv, r = [], l = {};
5347         for(var i = 0, len = d.length; i < len; i++){
5348             v = d[i].data[dataIndex];
5349             sv = String(v);
5350             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
5351                 l[sv] = true;
5352                 r[r.length] = v;
5353             }
5354         }
5355         return r;
5356     },
5357
5358     /**
5359      * Revert to a view of the Record cache with no filtering applied.
5360      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
5361      */
5362     clearFilter : function(suppressEvent){
5363         if(this.snapshot && this.snapshot != this.data){
5364             this.data = this.snapshot;
5365             delete this.snapshot;
5366             if(suppressEvent !== true){
5367                 this.fireEvent("datachanged", this);
5368             }
5369         }
5370     },
5371
5372     // private
5373     afterEdit : function(record){
5374         if(this.modified.indexOf(record) == -1){
5375             this.modified.push(record);
5376         }
5377         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
5378     },
5379     
5380     // private
5381     afterReject : function(record){
5382         this.modified.remove(record);
5383         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
5384     },
5385
5386     // private
5387     afterCommit : function(record){
5388         this.modified.remove(record);
5389         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
5390     },
5391
5392     /**
5393      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
5394      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
5395      */
5396     commitChanges : function(){
5397         var m = this.modified.slice(0);
5398         this.modified = [];
5399         for(var i = 0, len = m.length; i < len; i++){
5400             m[i].commit();
5401         }
5402     },
5403
5404     /**
5405      * Cancel outstanding changes on all changed records.
5406      */
5407     rejectChanges : function(){
5408         var m = this.modified.slice(0);
5409         this.modified = [];
5410         for(var i = 0, len = m.length; i < len; i++){
5411             m[i].reject();
5412         }
5413     },
5414
5415     onMetaChange : function(meta, rtype, o){
5416         this.recordType = rtype;
5417         this.fields = rtype.prototype.fields;
5418         delete this.snapshot;
5419         this.sortInfo = meta.sortInfo || this.sortInfo;
5420         this.modified = [];
5421         this.fireEvent('metachange', this, this.reader.meta);
5422     }
5423 });/*
5424  * Based on:
5425  * Ext JS Library 1.1.1
5426  * Copyright(c) 2006-2007, Ext JS, LLC.
5427  *
5428  * Originally Released Under LGPL - original licence link has changed is not relivant.
5429  *
5430  * Fork - LGPL
5431  * <script type="text/javascript">
5432  */
5433
5434 /**
5435  * @class Roo.data.SimpleStore
5436  * @extends Roo.data.Store
5437  * Small helper class to make creating Stores from Array data easier.
5438  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
5439  * @cfg {Array} fields An array of field definition objects, or field name strings.
5440  * @cfg {Array} data The multi-dimensional array of data
5441  * @constructor
5442  * @param {Object} config
5443  */
5444 Roo.data.SimpleStore = function(config){
5445     Roo.data.SimpleStore.superclass.constructor.call(this, {
5446         isLocal : true,
5447         reader: new Roo.data.ArrayReader({
5448                 id: config.id
5449             },
5450             Roo.data.Record.create(config.fields)
5451         ),
5452         proxy : new Roo.data.MemoryProxy(config.data)
5453     });
5454     this.load();
5455 };
5456 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
5457  * Based on:
5458  * Ext JS Library 1.1.1
5459  * Copyright(c) 2006-2007, Ext JS, LLC.
5460  *
5461  * Originally Released Under LGPL - original licence link has changed is not relivant.
5462  *
5463  * Fork - LGPL
5464  * <script type="text/javascript">
5465  */
5466
5467 /**
5468 /**
5469  * @extends Roo.data.Store
5470  * @class Roo.data.JsonStore
5471  * Small helper class to make creating Stores for JSON data easier. <br/>
5472 <pre><code>
5473 var store = new Roo.data.JsonStore({
5474     url: 'get-images.php',
5475     root: 'images',
5476     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
5477 });
5478 </code></pre>
5479  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
5480  * JsonReader and HttpProxy (unless inline data is provided).</b>
5481  * @cfg {Array} fields An array of field definition objects, or field name strings.
5482  * @constructor
5483  * @param {Object} config
5484  */
5485 Roo.data.JsonStore = function(c){
5486     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
5487         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
5488         reader: new Roo.data.JsonReader(c, c.fields)
5489     }));
5490 };
5491 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
5492  * Based on:
5493  * Ext JS Library 1.1.1
5494  * Copyright(c) 2006-2007, Ext JS, LLC.
5495  *
5496  * Originally Released Under LGPL - original licence link has changed is not relivant.
5497  *
5498  * Fork - LGPL
5499  * <script type="text/javascript">
5500  */
5501
5502  
5503 Roo.data.Field = function(config){
5504     if(typeof config == "string"){
5505         config = {name: config};
5506     }
5507     Roo.apply(this, config);
5508     
5509     if(!this.type){
5510         this.type = "auto";
5511     }
5512     
5513     var st = Roo.data.SortTypes;
5514     // named sortTypes are supported, here we look them up
5515     if(typeof this.sortType == "string"){
5516         this.sortType = st[this.sortType];
5517     }
5518     
5519     // set default sortType for strings and dates
5520     if(!this.sortType){
5521         switch(this.type){
5522             case "string":
5523                 this.sortType = st.asUCString;
5524                 break;
5525             case "date":
5526                 this.sortType = st.asDate;
5527                 break;
5528             default:
5529                 this.sortType = st.none;
5530         }
5531     }
5532
5533     // define once
5534     var stripRe = /[\$,%]/g;
5535
5536     // prebuilt conversion function for this field, instead of
5537     // switching every time we're reading a value
5538     if(!this.convert){
5539         var cv, dateFormat = this.dateFormat;
5540         switch(this.type){
5541             case "":
5542             case "auto":
5543             case undefined:
5544                 cv = function(v){ return v; };
5545                 break;
5546             case "string":
5547                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
5548                 break;
5549             case "int":
5550                 cv = function(v){
5551                     return v !== undefined && v !== null && v !== '' ?
5552                            parseInt(String(v).replace(stripRe, ""), 10) : '';
5553                     };
5554                 break;
5555             case "float":
5556                 cv = function(v){
5557                     return v !== undefined && v !== null && v !== '' ?
5558                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
5559                     };
5560                 break;
5561             case "bool":
5562             case "boolean":
5563                 cv = function(v){ return v === true || v === "true" || v == 1; };
5564                 break;
5565             case "date":
5566                 cv = function(v){
5567                     if(!v){
5568                         return '';
5569                     }
5570                     if(v instanceof Date){
5571                         return v;
5572                     }
5573                     if(dateFormat){
5574                         if(dateFormat == "timestamp"){
5575                             return new Date(v*1000);
5576                         }
5577                         return Date.parseDate(v, dateFormat);
5578                     }
5579                     var parsed = Date.parse(v);
5580                     return parsed ? new Date(parsed) : null;
5581                 };
5582              break;
5583             
5584         }
5585         this.convert = cv;
5586     }
5587 };
5588
5589 Roo.data.Field.prototype = {
5590     dateFormat: null,
5591     defaultValue: "",
5592     mapping: null,
5593     sortType : null,
5594     sortDir : "ASC"
5595 };/*
5596  * Based on:
5597  * Ext JS Library 1.1.1
5598  * Copyright(c) 2006-2007, Ext JS, LLC.
5599  *
5600  * Originally Released Under LGPL - original licence link has changed is not relivant.
5601  *
5602  * Fork - LGPL
5603  * <script type="text/javascript">
5604  */
5605  
5606 // Base class for reading structured data from a data source.  This class is intended to be
5607 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
5608
5609 /**
5610  * @class Roo.data.DataReader
5611  * Base class for reading structured data from a data source.  This class is intended to be
5612  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
5613  */
5614
5615 Roo.data.DataReader = function(meta, recordType){
5616     
5617     this.meta = meta;
5618     
5619     this.recordType = recordType instanceof Array ? 
5620         Roo.data.Record.create(recordType) : recordType;
5621 };
5622
5623 Roo.data.DataReader.prototype = {
5624      /**
5625      * Create an empty record
5626      * @param {Object} data (optional) - overlay some values
5627      * @return {Roo.data.Record} record created.
5628      */
5629     newRow :  function(d) {
5630         var da =  {};
5631         this.recordType.prototype.fields.each(function(c) {
5632             switch( c.type) {
5633                 case 'int' : da[c.name] = 0; break;
5634                 case 'date' : da[c.name] = new Date(); break;
5635                 case 'float' : da[c.name] = 0.0; break;
5636                 case 'boolean' : da[c.name] = false; break;
5637                 default : da[c.name] = ""; break;
5638             }
5639             
5640         });
5641         return new this.recordType(Roo.apply(da, d));
5642     }
5643     
5644 };/*
5645  * Based on:
5646  * Ext JS Library 1.1.1
5647  * Copyright(c) 2006-2007, Ext JS, LLC.
5648  *
5649  * Originally Released Under LGPL - original licence link has changed is not relivant.
5650  *
5651  * Fork - LGPL
5652  * <script type="text/javascript">
5653  */
5654
5655 /**
5656  * @class Roo.data.DataProxy
5657  * @extends Roo.data.Observable
5658  * This class is an abstract base class for implementations which provide retrieval of
5659  * unformatted data objects.<br>
5660  * <p>
5661  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
5662  * (of the appropriate type which knows how to parse the data object) to provide a block of
5663  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
5664  * <p>
5665  * Custom implementations must implement the load method as described in
5666  * {@link Roo.data.HttpProxy#load}.
5667  */
5668 Roo.data.DataProxy = function(){
5669     this.addEvents({
5670         /**
5671          * @event beforeload
5672          * Fires before a network request is made to retrieve a data object.
5673          * @param {Object} This DataProxy object.
5674          * @param {Object} params The params parameter to the load function.
5675          */
5676         beforeload : true,
5677         /**
5678          * @event load
5679          * Fires before the load method's callback is called.
5680          * @param {Object} This DataProxy object.
5681          * @param {Object} o The data object.
5682          * @param {Object} arg The callback argument object passed to the load function.
5683          */
5684         load : true,
5685         /**
5686          * @event loadexception
5687          * Fires if an Exception occurs during data retrieval.
5688          * @param {Object} This DataProxy object.
5689          * @param {Object} o The data object.
5690          * @param {Object} arg The callback argument object passed to the load function.
5691          * @param {Object} e The Exception.
5692          */
5693         loadexception : true
5694     });
5695     Roo.data.DataProxy.superclass.constructor.call(this);
5696 };
5697
5698 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
5699
5700     /**
5701      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
5702      */
5703 /*
5704  * Based on:
5705  * Ext JS Library 1.1.1
5706  * Copyright(c) 2006-2007, Ext JS, LLC.
5707  *
5708  * Originally Released Under LGPL - original licence link has changed is not relivant.
5709  *
5710  * Fork - LGPL
5711  * <script type="text/javascript">
5712  */
5713 /**
5714  * @class Roo.data.MemoryProxy
5715  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
5716  * to the Reader when its load method is called.
5717  * @constructor
5718  * @param {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
5719  */
5720 Roo.data.MemoryProxy = function(data){
5721     if (data.data) {
5722         data = data.data;
5723     }
5724     Roo.data.MemoryProxy.superclass.constructor.call(this);
5725     this.data = data;
5726 };
5727
5728 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
5729     /**
5730      * Load data from the requested source (in this case an in-memory
5731      * data object passed to the constructor), read the data object into
5732      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
5733      * process that block using the passed callback.
5734      * @param {Object} params This parameter is not used by the MemoryProxy class.
5735      * @param {Roo.data.DataReader} reader The Reader object which converts the data
5736      * object into a block of Roo.data.Records.
5737      * @param {Function} callback The function into which to pass the block of Roo.data.records.
5738      * The function must be passed <ul>
5739      * <li>The Record block object</li>
5740      * <li>The "arg" argument from the load function</li>
5741      * <li>A boolean success indicator</li>
5742      * </ul>
5743      * @param {Object} scope The scope in which to call the callback
5744      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
5745      */
5746     load : function(params, reader, callback, scope, arg){
5747         params = params || {};
5748         var result;
5749         try {
5750             result = reader.readRecords(this.data);
5751         }catch(e){
5752             this.fireEvent("loadexception", this, arg, null, e);
5753             callback.call(scope, null, arg, false);
5754             return;
5755         }
5756         callback.call(scope, result, arg, true);
5757     },
5758     
5759     // private
5760     update : function(params, records){
5761         
5762     }
5763 });/*
5764  * Based on:
5765  * Ext JS Library 1.1.1
5766  * Copyright(c) 2006-2007, Ext JS, LLC.
5767  *
5768  * Originally Released Under LGPL - original licence link has changed is not relivant.
5769  *
5770  * Fork - LGPL
5771  * <script type="text/javascript">
5772  */
5773 /**
5774  * @class Roo.data.HttpProxy
5775  * @extends Roo.data.DataProxy
5776  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
5777  * configured to reference a certain URL.<br><br>
5778  * <p>
5779  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
5780  * from which the running page was served.<br><br>
5781  * <p>
5782  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
5783  * <p>
5784  * Be aware that to enable the browser to parse an XML document, the server must set
5785  * the Content-Type header in the HTTP response to "text/xml".
5786  * @constructor
5787  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
5788  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
5789  * will be used to make the request.
5790  */
5791 Roo.data.HttpProxy = function(conn){
5792     Roo.data.HttpProxy.superclass.constructor.call(this);
5793     // is conn a conn config or a real conn?
5794     this.conn = conn;
5795     this.useAjax = !conn || !conn.events;
5796   
5797 };
5798
5799 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
5800     // thse are take from connection...
5801     
5802     /**
5803      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
5804      */
5805     /**
5806      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
5807      * extra parameters to each request made by this object. (defaults to undefined)
5808      */
5809     /**
5810      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
5811      *  to each request made by this object. (defaults to undefined)
5812      */
5813     /**
5814      * @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)
5815      */
5816     /**
5817      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
5818      */
5819      /**
5820      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
5821      * @type Boolean
5822      */
5823   
5824
5825     /**
5826      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
5827      * @type Boolean
5828      */
5829     /**
5830      * Return the {@link Roo.data.Connection} object being used by this Proxy.
5831      * @return {Connection} The Connection object. This object may be used to subscribe to events on
5832      * a finer-grained basis than the DataProxy events.
5833      */
5834     getConnection : function(){
5835         return this.useAjax ? Roo.Ajax : this.conn;
5836     },
5837
5838     /**
5839      * Load data from the configured {@link Roo.data.Connection}, read the data object into
5840      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
5841      * process that block using the passed callback.
5842      * @param {Object} params An object containing properties which are to be used as HTTP parameters
5843      * for the request to the remote server.
5844      * @param {Roo.data.DataReader} reader The Reader object which converts the data
5845      * object into a block of Roo.data.Records.
5846      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
5847      * The function must be passed <ul>
5848      * <li>The Record block object</li>
5849      * <li>The "arg" argument from the load function</li>
5850      * <li>A boolean success indicator</li>
5851      * </ul>
5852      * @param {Object} scope The scope in which to call the callback
5853      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
5854      */
5855     load : function(params, reader, callback, scope, arg){
5856         if(this.fireEvent("beforeload", this, params) !== false){
5857             var  o = {
5858                 params : params || {},
5859                 request: {
5860                     callback : callback,
5861                     scope : scope,
5862                     arg : arg
5863                 },
5864                 reader: reader,
5865                 callback : this.loadResponse,
5866                 scope: this
5867             };
5868             if(this.useAjax){
5869                 Roo.applyIf(o, this.conn);
5870                 if(this.activeRequest){
5871                     Roo.Ajax.abort(this.activeRequest);
5872                 }
5873                 this.activeRequest = Roo.Ajax.request(o);
5874             }else{
5875                 this.conn.request(o);
5876             }
5877         }else{
5878             callback.call(scope||this, null, arg, false);
5879         }
5880     },
5881
5882     // private
5883     loadResponse : function(o, success, response){
5884         delete this.activeRequest;
5885         if(!success){
5886             this.fireEvent("loadexception", this, o, response);
5887             o.request.callback.call(o.request.scope, null, o.request.arg, false);
5888             return;
5889         }
5890         var result;
5891         try {
5892             result = o.reader.read(response);
5893         }catch(e){
5894             this.fireEvent("loadexception", this, o, response, e);
5895             o.request.callback.call(o.request.scope, null, o.request.arg, false);
5896             return;
5897         }
5898         
5899         this.fireEvent("load", this, o, o.request.arg);
5900         o.request.callback.call(o.request.scope, result, o.request.arg, true);
5901     },
5902
5903     // private
5904     update : function(dataSet){
5905
5906     },
5907
5908     // private
5909     updateResponse : function(dataSet){
5910
5911     }
5912 });/*
5913  * Based on:
5914  * Ext JS Library 1.1.1
5915  * Copyright(c) 2006-2007, Ext JS, LLC.
5916  *
5917  * Originally Released Under LGPL - original licence link has changed is not relivant.
5918  *
5919  * Fork - LGPL
5920  * <script type="text/javascript">
5921  */
5922
5923 /**
5924  * @class Roo.data.ScriptTagProxy
5925  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
5926  * other than the originating domain of the running page.<br><br>
5927  * <p>
5928  * <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
5929  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
5930  * <p>
5931  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
5932  * source code that is used as the source inside a &lt;script> tag.<br><br>
5933  * <p>
5934  * In order for the browser to process the returned data, the server must wrap the data object
5935  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
5936  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
5937  * depending on whether the callback name was passed:
5938  * <p>
5939  * <pre><code>
5940 boolean scriptTag = false;
5941 String cb = request.getParameter("callback");
5942 if (cb != null) {
5943     scriptTag = true;
5944     response.setContentType("text/javascript");
5945 } else {
5946     response.setContentType("application/x-json");
5947 }
5948 Writer out = response.getWriter();
5949 if (scriptTag) {
5950     out.write(cb + "(");
5951 }
5952 out.print(dataBlock.toJsonString());
5953 if (scriptTag) {
5954     out.write(");");
5955 }
5956 </pre></code>
5957  *
5958  * @constructor
5959  * @param {Object} config A configuration object.
5960  */
5961 Roo.data.ScriptTagProxy = function(config){
5962     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
5963     Roo.apply(this, config);
5964     this.head = document.getElementsByTagName("head")[0];
5965 };
5966
5967 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
5968
5969 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
5970     /**
5971      * @cfg {String} url The URL from which to request the data object.
5972      */
5973     /**
5974      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
5975      */
5976     timeout : 30000,
5977     /**
5978      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
5979      * the server the name of the callback function set up by the load call to process the returned data object.
5980      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
5981      * javascript output which calls this named function passing the data object as its only parameter.
5982      */
5983     callbackParam : "callback",
5984     /**
5985      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
5986      * name to the request.
5987      */
5988     nocache : true,
5989
5990     /**
5991      * Load data from the configured URL, read the data object into
5992      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
5993      * process that block using the passed callback.
5994      * @param {Object} params An object containing properties which are to be used as HTTP parameters
5995      * for the request to the remote server.
5996      * @param {Roo.data.DataReader} reader The Reader object which converts the data
5997      * object into a block of Roo.data.Records.
5998      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
5999      * The function must be passed <ul>
6000      * <li>The Record block object</li>
6001      * <li>The "arg" argument from the load function</li>
6002      * <li>A boolean success indicator</li>
6003      * </ul>
6004      * @param {Object} scope The scope in which to call the callback
6005      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
6006      */
6007     load : function(params, reader, callback, scope, arg){
6008         if(this.fireEvent("beforeload", this, params) !== false){
6009
6010             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
6011
6012             var url = this.url;
6013             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
6014             if(this.nocache){
6015                 url += "&_dc=" + (new Date().getTime());
6016             }
6017             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
6018             var trans = {
6019                 id : transId,
6020                 cb : "stcCallback"+transId,
6021                 scriptId : "stcScript"+transId,
6022                 params : params,
6023                 arg : arg,
6024                 url : url,
6025                 callback : callback,
6026                 scope : scope,
6027                 reader : reader
6028             };
6029             var conn = this;
6030
6031             window[trans.cb] = function(o){
6032                 conn.handleResponse(o, trans);
6033             };
6034
6035             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
6036
6037             if(this.autoAbort !== false){
6038                 this.abort();
6039             }
6040
6041             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
6042
6043             var script = document.createElement("script");
6044             script.setAttribute("src", url);
6045             script.setAttribute("type", "text/javascript");
6046             script.setAttribute("id", trans.scriptId);
6047             this.head.appendChild(script);
6048
6049             this.trans = trans;
6050         }else{
6051             callback.call(scope||this, null, arg, false);
6052         }
6053     },
6054
6055     // private
6056     isLoading : function(){
6057         return this.trans ? true : false;
6058     },
6059
6060     /**
6061      * Abort the current server request.
6062      */
6063     abort : function(){
6064         if(this.isLoading()){
6065             this.destroyTrans(this.trans);
6066         }
6067     },
6068
6069     // private
6070     destroyTrans : function(trans, isLoaded){
6071         this.head.removeChild(document.getElementById(trans.scriptId));
6072         clearTimeout(trans.timeoutId);
6073         if(isLoaded){
6074             window[trans.cb] = undefined;
6075             try{
6076                 delete window[trans.cb];
6077             }catch(e){}
6078         }else{
6079             // if hasn't been loaded, wait for load to remove it to prevent script error
6080             window[trans.cb] = function(){
6081                 window[trans.cb] = undefined;
6082                 try{
6083                     delete window[trans.cb];
6084                 }catch(e){}
6085             };
6086         }
6087     },
6088
6089     // private
6090     handleResponse : function(o, trans){
6091         this.trans = false;
6092         this.destroyTrans(trans, true);
6093         var result;
6094         try {
6095             result = trans.reader.readRecords(o);
6096         }catch(e){
6097             this.fireEvent("loadexception", this, o, trans.arg, e);
6098             trans.callback.call(trans.scope||window, null, trans.arg, false);
6099             return;
6100         }
6101         this.fireEvent("load", this, o, trans.arg);
6102         trans.callback.call(trans.scope||window, result, trans.arg, true);
6103     },
6104
6105     // private
6106     handleFailure : function(trans){
6107         this.trans = false;
6108         this.destroyTrans(trans, false);
6109         this.fireEvent("loadexception", this, null, trans.arg);
6110         trans.callback.call(trans.scope||window, null, trans.arg, false);
6111     }
6112 });/*
6113  * Based on:
6114  * Ext JS Library 1.1.1
6115  * Copyright(c) 2006-2007, Ext JS, LLC.
6116  *
6117  * Originally Released Under LGPL - original licence link has changed is not relivant.
6118  *
6119  * Fork - LGPL
6120  * <script type="text/javascript">
6121  */
6122
6123 /**
6124  * @class Roo.data.JsonReader
6125  * @extends Roo.data.DataReader
6126  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
6127  * based on mappings in a provided Roo.data.Record constructor.
6128  * 
6129  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
6130  * in the reply previously. 
6131  * 
6132  * <p>
6133  * Example code:
6134  * <pre><code>
6135 var RecordDef = Roo.data.Record.create([
6136     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
6137     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
6138 ]);
6139 var myReader = new Roo.data.JsonReader({
6140     totalProperty: "results",    // The property which contains the total dataset size (optional)
6141     root: "rows",                // The property which contains an Array of row objects
6142     id: "id"                     // The property within each row object that provides an ID for the record (optional)
6143 }, RecordDef);
6144 </code></pre>
6145  * <p>
6146  * This would consume a JSON file like this:
6147  * <pre><code>
6148 { 'results': 2, 'rows': [
6149     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
6150     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
6151 }
6152 </code></pre>
6153  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
6154  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
6155  * paged from the remote server.
6156  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
6157  * @cfg {String} root name of the property which contains the Array of row objects.
6158  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
6159  * @constructor
6160  * Create a new JsonReader
6161  * @param {Object} meta Metadata configuration options
6162  * @param {Object} recordType Either an Array of field definition objects,
6163  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
6164  */
6165 Roo.data.JsonReader = function(meta, recordType){
6166     
6167     meta = meta || {};
6168     // set some defaults:
6169     Roo.applyIf(meta, {
6170         totalProperty: 'total',
6171         successProperty : 'success',
6172         root : 'data',
6173         id : 'id'
6174     });
6175     
6176     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
6177 };
6178 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
6179     
6180     /**
6181      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
6182      * Used by Store query builder to append _requestMeta to params.
6183      * 
6184      */
6185     metaFromRemote : false,
6186     /**
6187      * This method is only used by a DataProxy which has retrieved data from a remote server.
6188      * @param {Object} response The XHR object which contains the JSON data in its responseText.
6189      * @return {Object} data A data block which is used by an Roo.data.Store object as
6190      * a cache of Roo.data.Records.
6191      */
6192     read : function(response){
6193         var json = response.responseText;
6194        
6195         var o = /* eval:var:o */ eval("("+json+")");
6196         if(!o) {
6197             throw {message: "JsonReader.read: Json object not found"};
6198         }
6199         
6200         if(o.metaData){
6201             
6202             delete this.ef;
6203             this.metaFromRemote = true;
6204             this.meta = o.metaData;
6205             this.recordType = Roo.data.Record.create(o.metaData.fields);
6206             this.onMetaChange(this.meta, this.recordType, o);
6207         }
6208         return this.readRecords(o);
6209     },
6210
6211     // private function a store will implement
6212     onMetaChange : function(meta, recordType, o){
6213
6214     },
6215
6216     /**
6217          * @ignore
6218          */
6219     simpleAccess: function(obj, subsc) {
6220         return obj[subsc];
6221     },
6222
6223         /**
6224          * @ignore
6225          */
6226     getJsonAccessor: function(){
6227         var re = /[\[\.]/;
6228         return function(expr) {
6229             try {
6230                 return(re.test(expr))
6231                     ? new Function("obj", "return obj." + expr)
6232                     : function(obj){
6233                         return obj[expr];
6234                     };
6235             } catch(e){}
6236             return Roo.emptyFn;
6237         };
6238     }(),
6239
6240     /**
6241      * Create a data block containing Roo.data.Records from an XML document.
6242      * @param {Object} o An object which contains an Array of row objects in the property specified
6243      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
6244      * which contains the total size of the dataset.
6245      * @return {Object} data A data block which is used by an Roo.data.Store object as
6246      * a cache of Roo.data.Records.
6247      */
6248     readRecords : function(o){
6249         /**
6250          * After any data loads, the raw JSON data is available for further custom processing.
6251          * @type Object
6252          */
6253         this.o = o;
6254         var s = this.meta, Record = this.recordType,
6255             f = Record.prototype.fields, fi = f.items, fl = f.length;
6256
6257 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
6258         if (!this.ef) {
6259             if(s.totalProperty) {
6260                     this.getTotal = this.getJsonAccessor(s.totalProperty);
6261                 }
6262                 if(s.successProperty) {
6263                     this.getSuccess = this.getJsonAccessor(s.successProperty);
6264                 }
6265                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
6266                 if (s.id) {
6267                         var g = this.getJsonAccessor(s.id);
6268                         this.getId = function(rec) {
6269                                 var r = g(rec);
6270                                 return (r === undefined || r === "") ? null : r;
6271                         };
6272                 } else {
6273                         this.getId = function(){return null;};
6274                 }
6275             this.ef = [];
6276             for(var jj = 0; jj < fl; jj++){
6277                 f = fi[jj];
6278                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
6279                 this.ef[jj] = this.getJsonAccessor(map);
6280             }
6281         }
6282
6283         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
6284         if(s.totalProperty){
6285             var vt = parseInt(this.getTotal(o), 10);
6286             if(!isNaN(vt)){
6287                 totalRecords = vt;
6288             }
6289         }
6290         if(s.successProperty){
6291             var vs = this.getSuccess(o);
6292             if(vs === false || vs === 'false'){
6293                 success = false;
6294             }
6295         }
6296         var records = [];
6297             for(var i = 0; i < c; i++){
6298                     var n = root[i];
6299                 var values = {};
6300                 var id = this.getId(n);
6301                 for(var j = 0; j < fl; j++){
6302                     f = fi[j];
6303                 var v = this.ef[j](n);
6304                 if (!f.convert) {
6305                     Roo.log('missing convert for ' + f.name);
6306                     Roo.log(f);
6307                     continue;
6308                 }
6309                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
6310                 }
6311                 var record = new Record(values, id);
6312                 record.json = n;
6313                 records[i] = record;
6314             }
6315             return {
6316             raw : o,
6317                 success : success,
6318                 records : records,
6319                 totalRecords : totalRecords
6320             };
6321     }
6322 });/*
6323  * Based on:
6324  * Ext JS Library 1.1.1
6325  * Copyright(c) 2006-2007, Ext JS, LLC.
6326  *
6327  * Originally Released Under LGPL - original licence link has changed is not relivant.
6328  *
6329  * Fork - LGPL
6330  * <script type="text/javascript">
6331  */
6332
6333 /**
6334  * @class Roo.data.XmlReader
6335  * @extends Roo.data.DataReader
6336  * Data reader class to create an Array of {@link Roo.data.Record} objects from an XML document
6337  * based on mappings in a provided Roo.data.Record constructor.<br><br>
6338  * <p>
6339  * <em>Note that in order for the browser to parse a returned XML document, the Content-Type
6340  * header in the HTTP response must be set to "text/xml".</em>
6341  * <p>
6342  * Example code:
6343  * <pre><code>
6344 var RecordDef = Roo.data.Record.create([
6345    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
6346    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
6347 ]);
6348 var myReader = new Roo.data.XmlReader({
6349    totalRecords: "results", // The element which contains the total dataset size (optional)
6350    record: "row",           // The repeated element which contains row information
6351    id: "id"                 // The element within the row that provides an ID for the record (optional)
6352 }, RecordDef);
6353 </code></pre>
6354  * <p>
6355  * This would consume an XML file like this:
6356  * <pre><code>
6357 &lt;?xml?>
6358 &lt;dataset>
6359  &lt;results>2&lt;/results>
6360  &lt;row>
6361    &lt;id>1&lt;/id>
6362    &lt;name>Bill&lt;/name>
6363    &lt;occupation>Gardener&lt;/occupation>
6364  &lt;/row>
6365  &lt;row>
6366    &lt;id>2&lt;/id>
6367    &lt;name>Ben&lt;/name>
6368    &lt;occupation>Horticulturalist&lt;/occupation>
6369  &lt;/row>
6370 &lt;/dataset>
6371 </code></pre>
6372  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
6373  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
6374  * paged from the remote server.
6375  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
6376  * @cfg {String} success The DomQuery path to the success attribute used by forms.
6377  * @cfg {String} id The DomQuery path relative from the record element to the element that contains
6378  * a record identifier value.
6379  * @constructor
6380  * Create a new XmlReader
6381  * @param {Object} meta Metadata configuration options
6382  * @param {Mixed} recordType The definition of the data record type to produce.  This can be either a valid
6383  * Record subclass created with {@link Roo.data.Record#create}, or an array of objects with which to call
6384  * Roo.data.Record.create.  See the {@link Roo.data.Record} class for more details.
6385  */
6386 Roo.data.XmlReader = function(meta, recordType){
6387     meta = meta || {};
6388     Roo.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
6389 };
6390 Roo.extend(Roo.data.XmlReader, Roo.data.DataReader, {
6391     /**
6392      * This method is only used by a DataProxy which has retrieved data from a remote server.
6393          * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
6394          * to contain a method called 'responseXML' that returns an XML document object.
6395      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
6396      * a cache of Roo.data.Records.
6397      */
6398     read : function(response){
6399         var doc = response.responseXML;
6400         if(!doc) {
6401             throw {message: "XmlReader.read: XML Document not available"};
6402         }
6403         return this.readRecords(doc);
6404     },
6405
6406     /**
6407      * Create a data block containing Roo.data.Records from an XML document.
6408          * @param {Object} doc A parsed XML document.
6409      * @return {Object} records A data block which is used by an {@link Roo.data.Store} as
6410      * a cache of Roo.data.Records.
6411      */
6412     readRecords : function(doc){
6413         /**
6414          * After any data loads/reads, the raw XML Document is available for further custom processing.
6415          * @type XMLDocument
6416          */
6417         this.xmlData = doc;
6418         var root = doc.documentElement || doc;
6419         var q = Roo.DomQuery;
6420         var recordType = this.recordType, fields = recordType.prototype.fields;
6421         var sid = this.meta.id;
6422         var totalRecords = 0, success = true;
6423         if(this.meta.totalRecords){
6424             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
6425         }
6426         
6427         if(this.meta.success){
6428             var sv = q.selectValue(this.meta.success, root, true);
6429             success = sv !== false && sv !== 'false';
6430         }
6431         var records = [];
6432         var ns = q.select(this.meta.record, root);
6433         for(var i = 0, len = ns.length; i < len; i++) {
6434                 var n = ns[i];
6435                 var values = {};
6436                 var id = sid ? q.selectValue(sid, n) : undefined;
6437                 for(var j = 0, jlen = fields.length; j < jlen; j++){
6438                     var f = fields.items[j];
6439                 var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
6440                     v = f.convert(v);
6441                     values[f.name] = v;
6442                 }
6443                 var record = new recordType(values, id);
6444                 record.node = n;
6445                 records[records.length] = record;
6446             }
6447
6448             return {
6449                 success : success,
6450                 records : records,
6451                 totalRecords : totalRecords || records.length
6452             };
6453     }
6454 });/*
6455  * Based on:
6456  * Ext JS Library 1.1.1
6457  * Copyright(c) 2006-2007, Ext JS, LLC.
6458  *
6459  * Originally Released Under LGPL - original licence link has changed is not relivant.
6460  *
6461  * Fork - LGPL
6462  * <script type="text/javascript">
6463  */
6464
6465 /**
6466  * @class Roo.data.ArrayReader
6467  * @extends Roo.data.DataReader
6468  * Data reader class to create an Array of Roo.data.Record objects from an Array.
6469  * Each element of that Array represents a row of data fields. The
6470  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
6471  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
6472  * <p>
6473  * Example code:.
6474  * <pre><code>
6475 var RecordDef = Roo.data.Record.create([
6476     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
6477     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
6478 ]);
6479 var myReader = new Roo.data.ArrayReader({
6480     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
6481 }, RecordDef);
6482 </code></pre>
6483  * <p>
6484  * This would consume an Array like this:
6485  * <pre><code>
6486 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
6487   </code></pre>
6488  * @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
6489  * @constructor
6490  * Create a new JsonReader
6491  * @param {Object} meta Metadata configuration options.
6492  * @param {Object} recordType Either an Array of field definition objects
6493  * as specified to {@link Roo.data.Record#create},
6494  * or an {@link Roo.data.Record} object
6495  * created using {@link Roo.data.Record#create}.
6496  */
6497 Roo.data.ArrayReader = function(meta, recordType){
6498     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
6499 };
6500
6501 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
6502     /**
6503      * Create a data block containing Roo.data.Records from an XML document.
6504      * @param {Object} o An Array of row objects which represents the dataset.
6505      * @return {Object} data A data block which is used by an Roo.data.Store object as
6506      * a cache of Roo.data.Records.
6507      */
6508     readRecords : function(o){
6509         var sid = this.meta ? this.meta.id : null;
6510         var recordType = this.recordType, fields = recordType.prototype.fields;
6511         var records = [];
6512         var root = o;
6513             for(var i = 0; i < root.length; i++){
6514                     var n = root[i];
6515                 var values = {};
6516                 var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
6517                 for(var j = 0, jlen = fields.length; j < jlen; j++){
6518                 var f = fields.items[j];
6519                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
6520                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
6521                 v = f.convert(v);
6522                 values[f.name] = v;
6523             }
6524                 var record = new recordType(values, id);
6525                 record.json = n;
6526                 records[records.length] = record;
6527             }
6528             return {
6529                 records : records,
6530                 totalRecords : records.length
6531             };
6532     }
6533 });/*
6534  * Based on:
6535  * Ext JS Library 1.1.1
6536  * Copyright(c) 2006-2007, Ext JS, LLC.
6537  *
6538  * Originally Released Under LGPL - original licence link has changed is not relivant.
6539  *
6540  * Fork - LGPL
6541  * <script type="text/javascript">
6542  */
6543
6544
6545 /**
6546  * @class Roo.data.Tree
6547  * @extends Roo.util.Observable
6548  * Represents a tree data structure and bubbles all the events for its nodes. The nodes
6549  * in the tree have most standard DOM functionality.
6550  * @constructor
6551  * @param {Node} root (optional) The root node
6552  */
6553 Roo.data.Tree = function(root){
6554    this.nodeHash = {};
6555    /**
6556     * The root node for this tree
6557     * @type Node
6558     */
6559    this.root = null;
6560    if(root){
6561        this.setRootNode(root);
6562    }
6563    this.addEvents({
6564        /**
6565         * @event append
6566         * Fires when a new child node is appended to a node in this tree.
6567         * @param {Tree} tree The owner tree
6568         * @param {Node} parent The parent node
6569         * @param {Node} node The newly appended node
6570         * @param {Number} index The index of the newly appended node
6571         */
6572        "append" : true,
6573        /**
6574         * @event remove
6575         * Fires when a child node is removed from a node in this tree.
6576         * @param {Tree} tree The owner tree
6577         * @param {Node} parent The parent node
6578         * @param {Node} node The child node removed
6579         */
6580        "remove" : true,
6581        /**
6582         * @event move
6583         * Fires when a node is moved to a new location in the tree
6584         * @param {Tree} tree The owner tree
6585         * @param {Node} node The node moved
6586         * @param {Node} oldParent The old parent of this node
6587         * @param {Node} newParent The new parent of this node
6588         * @param {Number} index The index it was moved to
6589         */
6590        "move" : true,
6591        /**
6592         * @event insert
6593         * Fires when a new child node is inserted in a node in this tree.
6594         * @param {Tree} tree The owner tree
6595         * @param {Node} parent The parent node
6596         * @param {Node} node The child node inserted
6597         * @param {Node} refNode The child node the node was inserted before
6598         */
6599        "insert" : true,
6600        /**
6601         * @event beforeappend
6602         * Fires before a new child is appended to a node in this tree, return false to cancel the append.
6603         * @param {Tree} tree The owner tree
6604         * @param {Node} parent The parent node
6605         * @param {Node} node The child node to be appended
6606         */
6607        "beforeappend" : true,
6608        /**
6609         * @event beforeremove
6610         * Fires before a child is removed from a node in this tree, return false to cancel the remove.
6611         * @param {Tree} tree The owner tree
6612         * @param {Node} parent The parent node
6613         * @param {Node} node The child node to be removed
6614         */
6615        "beforeremove" : true,
6616        /**
6617         * @event beforemove
6618         * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
6619         * @param {Tree} tree The owner tree
6620         * @param {Node} node The node being moved
6621         * @param {Node} oldParent The parent of the node
6622         * @param {Node} newParent The new parent the node is moving to
6623         * @param {Number} index The index it is being moved to
6624         */
6625        "beforemove" : true,
6626        /**
6627         * @event beforeinsert
6628         * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
6629         * @param {Tree} tree The owner tree
6630         * @param {Node} parent The parent node
6631         * @param {Node} node The child node to be inserted
6632         * @param {Node} refNode The child node the node is being inserted before
6633         */
6634        "beforeinsert" : true
6635    });
6636
6637     Roo.data.Tree.superclass.constructor.call(this);
6638 };
6639
6640 Roo.extend(Roo.data.Tree, Roo.util.Observable, {
6641     pathSeparator: "/",
6642
6643     proxyNodeEvent : function(){
6644         return this.fireEvent.apply(this, arguments);
6645     },
6646
6647     /**
6648      * Returns the root node for this tree.
6649      * @return {Node}
6650      */
6651     getRootNode : function(){
6652         return this.root;
6653     },
6654
6655     /**
6656      * Sets the root node for this tree.
6657      * @param {Node} node
6658      * @return {Node}
6659      */
6660     setRootNode : function(node){
6661         this.root = node;
6662         node.ownerTree = this;
6663         node.isRoot = true;
6664         this.registerNode(node);
6665         return node;
6666     },
6667
6668     /**
6669      * Gets a node in this tree by its id.
6670      * @param {String} id
6671      * @return {Node}
6672      */
6673     getNodeById : function(id){
6674         return this.nodeHash[id];
6675     },
6676
6677     registerNode : function(node){
6678         this.nodeHash[node.id] = node;
6679     },
6680
6681     unregisterNode : function(node){
6682         delete this.nodeHash[node.id];
6683     },
6684
6685     toString : function(){
6686         return "[Tree"+(this.id?" "+this.id:"")+"]";
6687     }
6688 });
6689
6690 /**
6691  * @class Roo.data.Node
6692  * @extends Roo.util.Observable
6693  * @cfg {Boolean} leaf true if this node is a leaf and does not have children
6694  * @cfg {String} id The id for this node. If one is not specified, one is generated.
6695  * @constructor
6696  * @param {Object} attributes The attributes/config for the node
6697  */
6698 Roo.data.Node = function(attributes){
6699     /**
6700      * The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
6701      * @type {Object}
6702      */
6703     this.attributes = attributes || {};
6704     this.leaf = this.attributes.leaf;
6705     /**
6706      * The node id. @type String
6707      */
6708     this.id = this.attributes.id;
6709     if(!this.id){
6710         this.id = Roo.id(null, "ynode-");
6711         this.attributes.id = this.id;
6712     }
6713      
6714     
6715     /**
6716      * All child nodes of this node. @type Array
6717      */
6718     this.childNodes = [];
6719     if(!this.childNodes.indexOf){ // indexOf is a must
6720         this.childNodes.indexOf = function(o){
6721             for(var i = 0, len = this.length; i < len; i++){
6722                 if(this[i] == o) {
6723                     return i;
6724                 }
6725             }
6726             return -1;
6727         };
6728     }
6729     /**
6730      * The parent node for this node. @type Node
6731      */
6732     this.parentNode = null;
6733     /**
6734      * The first direct child node of this node, or null if this node has no child nodes. @type Node
6735      */
6736     this.firstChild = null;
6737     /**
6738      * The last direct child node of this node, or null if this node has no child nodes. @type Node
6739      */
6740     this.lastChild = null;
6741     /**
6742      * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
6743      */
6744     this.previousSibling = null;
6745     /**
6746      * The node immediately following this node in the tree, or null if there is no sibling node. @type Node
6747      */
6748     this.nextSibling = null;
6749
6750     this.addEvents({
6751        /**
6752         * @event append
6753         * Fires when a new child node is appended
6754         * @param {Tree} tree The owner tree
6755         * @param {Node} this This node
6756         * @param {Node} node The newly appended node
6757         * @param {Number} index The index of the newly appended node
6758         */
6759        "append" : true,
6760        /**
6761         * @event remove
6762         * Fires when a child node is removed
6763         * @param {Tree} tree The owner tree
6764         * @param {Node} this This node
6765         * @param {Node} node The removed node
6766         */
6767        "remove" : true,
6768        /**
6769         * @event move
6770         * Fires when this node is moved to a new location in the tree
6771         * @param {Tree} tree The owner tree
6772         * @param {Node} this This node
6773         * @param {Node} oldParent The old parent of this node
6774         * @param {Node} newParent The new parent of this node
6775         * @param {Number} index The index it was moved to
6776         */
6777        "move" : true,
6778        /**
6779         * @event insert
6780         * Fires when a new child node is inserted.
6781         * @param {Tree} tree The owner tree
6782         * @param {Node} this This node
6783         * @param {Node} node The child node inserted
6784         * @param {Node} refNode The child node the node was inserted before
6785         */
6786        "insert" : true,
6787        /**
6788         * @event beforeappend
6789         * Fires before a new child is appended, return false to cancel the append.
6790         * @param {Tree} tree The owner tree
6791         * @param {Node} this This node
6792         * @param {Node} node The child node to be appended
6793         */
6794        "beforeappend" : true,
6795        /**
6796         * @event beforeremove
6797         * Fires before a child is removed, return false to cancel the remove.
6798         * @param {Tree} tree The owner tree
6799         * @param {Node} this This node
6800         * @param {Node} node The child node to be removed
6801         */
6802        "beforeremove" : true,
6803        /**
6804         * @event beforemove
6805         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
6806         * @param {Tree} tree The owner tree
6807         * @param {Node} this This node
6808         * @param {Node} oldParent The parent of this node
6809         * @param {Node} newParent The new parent this node is moving to
6810         * @param {Number} index The index it is being moved to
6811         */
6812        "beforemove" : true,
6813        /**
6814         * @event beforeinsert
6815         * Fires before a new child is inserted, return false to cancel the insert.
6816         * @param {Tree} tree The owner tree
6817         * @param {Node} this This node
6818         * @param {Node} node The child node to be inserted
6819         * @param {Node} refNode The child node the node is being inserted before
6820         */
6821        "beforeinsert" : true
6822    });
6823     this.listeners = this.attributes.listeners;
6824     Roo.data.Node.superclass.constructor.call(this);
6825 };
6826
6827 Roo.extend(Roo.data.Node, Roo.util.Observable, {
6828     fireEvent : function(evtName){
6829         // first do standard event for this node
6830         if(Roo.data.Node.superclass.fireEvent.apply(this, arguments) === false){
6831             return false;
6832         }
6833         // then bubble it up to the tree if the event wasn't cancelled
6834         var ot = this.getOwnerTree();
6835         if(ot){
6836             if(ot.proxyNodeEvent.apply(ot, arguments) === false){
6837                 return false;
6838             }
6839         }
6840         return true;
6841     },
6842
6843     /**
6844      * Returns true if this node is a leaf
6845      * @return {Boolean}
6846      */
6847     isLeaf : function(){
6848         return this.leaf === true;
6849     },
6850
6851     // private
6852     setFirstChild : function(node){
6853         this.firstChild = node;
6854     },
6855
6856     //private
6857     setLastChild : function(node){
6858         this.lastChild = node;
6859     },
6860
6861
6862     /**
6863      * Returns true if this node is the last child of its parent
6864      * @return {Boolean}
6865      */
6866     isLast : function(){
6867        return (!this.parentNode ? true : this.parentNode.lastChild == this);
6868     },
6869
6870     /**
6871      * Returns true if this node is the first child of its parent
6872      * @return {Boolean}
6873      */
6874     isFirst : function(){
6875        return (!this.parentNode ? true : this.parentNode.firstChild == this);
6876     },
6877
6878     hasChildNodes : function(){
6879         return !this.isLeaf() && this.childNodes.length > 0;
6880     },
6881
6882     /**
6883      * Insert node(s) as the last child node of this node.
6884      * @param {Node/Array} node The node or Array of nodes to append
6885      * @return {Node} The appended node if single append, or null if an array was passed
6886      */
6887     appendChild : function(node){
6888         var multi = false;
6889         if(node instanceof Array){
6890             multi = node;
6891         }else if(arguments.length > 1){
6892             multi = arguments;
6893         }
6894         // if passed an array or multiple args do them one by one
6895         if(multi){
6896             for(var i = 0, len = multi.length; i < len; i++) {
6897                 this.appendChild(multi[i]);
6898             }
6899         }else{
6900             if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
6901                 return false;
6902             }
6903             var index = this.childNodes.length;
6904             var oldParent = node.parentNode;
6905             // it's a move, make sure we move it cleanly
6906             if(oldParent){
6907                 if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
6908                     return false;
6909                 }
6910                 oldParent.removeChild(node);
6911             }
6912             index = this.childNodes.length;
6913             if(index == 0){
6914                 this.setFirstChild(node);
6915             }
6916             this.childNodes.push(node);
6917             node.parentNode = this;
6918             var ps = this.childNodes[index-1];
6919             if(ps){
6920                 node.previousSibling = ps;
6921                 ps.nextSibling = node;
6922             }else{
6923                 node.previousSibling = null;
6924             }
6925             node.nextSibling = null;
6926             this.setLastChild(node);
6927             node.setOwnerTree(this.getOwnerTree());
6928             this.fireEvent("append", this.ownerTree, this, node, index);
6929             if(oldParent){
6930                 node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
6931             }
6932             return node;
6933         }
6934     },
6935
6936     /**
6937      * Removes a child node from this node.
6938      * @param {Node} node The node to remove
6939      * @return {Node} The removed node
6940      */
6941     removeChild : function(node){
6942         var index = this.childNodes.indexOf(node);
6943         if(index == -1){
6944             return false;
6945         }
6946         if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
6947             return false;
6948         }
6949
6950         // remove it from childNodes collection
6951         this.childNodes.splice(index, 1);
6952
6953         // update siblings
6954         if(node.previousSibling){
6955             node.previousSibling.nextSibling = node.nextSibling;
6956         }
6957         if(node.nextSibling){
6958             node.nextSibling.previousSibling = node.previousSibling;
6959         }
6960
6961         // update child refs
6962         if(this.firstChild == node){
6963             this.setFirstChild(node.nextSibling);
6964         }
6965         if(this.lastChild == node){
6966             this.setLastChild(node.previousSibling);
6967         }
6968
6969         node.setOwnerTree(null);
6970         // clear any references from the node
6971         node.parentNode = null;
6972         node.previousSibling = null;
6973         node.nextSibling = null;
6974         this.fireEvent("remove", this.ownerTree, this, node);
6975         return node;
6976     },
6977
6978     /**
6979      * Inserts the first node before the second node in this nodes childNodes collection.
6980      * @param {Node} node The node to insert
6981      * @param {Node} refNode The node to insert before (if null the node is appended)
6982      * @return {Node} The inserted node
6983      */
6984     insertBefore : function(node, refNode){
6985         if(!refNode){ // like standard Dom, refNode can be null for append
6986             return this.appendChild(node);
6987         }
6988         // nothing to do
6989         if(node == refNode){
6990             return false;
6991         }
6992
6993         if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
6994             return false;
6995         }
6996         var index = this.childNodes.indexOf(refNode);
6997         var oldParent = node.parentNode;
6998         var refIndex = index;
6999
7000         // when moving internally, indexes will change after remove
7001         if(oldParent == this && this.childNodes.indexOf(node) < index){
7002             refIndex--;
7003         }
7004
7005         // it's a move, make sure we move it cleanly
7006         if(oldParent){
7007             if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
7008                 return false;
7009             }
7010             oldParent.removeChild(node);
7011         }
7012         if(refIndex == 0){
7013             this.setFirstChild(node);
7014         }
7015         this.childNodes.splice(refIndex, 0, node);
7016         node.parentNode = this;
7017         var ps = this.childNodes[refIndex-1];
7018         if(ps){
7019             node.previousSibling = ps;
7020             ps.nextSibling = node;
7021         }else{
7022             node.previousSibling = null;
7023         }
7024         node.nextSibling = refNode;
7025         refNode.previousSibling = node;
7026         node.setOwnerTree(this.getOwnerTree());
7027         this.fireEvent("insert", this.ownerTree, this, node, refNode);
7028         if(oldParent){
7029             node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
7030         }
7031         return node;
7032     },
7033
7034     /**
7035      * Returns the child node at the specified index.
7036      * @param {Number} index
7037      * @return {Node}
7038      */
7039     item : function(index){
7040         return this.childNodes[index];
7041     },
7042
7043     /**
7044      * Replaces one child node in this node with another.
7045      * @param {Node} newChild The replacement node
7046      * @param {Node} oldChild The node to replace
7047      * @return {Node} The replaced node
7048      */
7049     replaceChild : function(newChild, oldChild){
7050         this.insertBefore(newChild, oldChild);
7051         this.removeChild(oldChild);
7052         return oldChild;
7053     },
7054
7055     /**
7056      * Returns the index of a child node
7057      * @param {Node} node
7058      * @return {Number} The index of the node or -1 if it was not found
7059      */
7060     indexOf : function(child){
7061         return this.childNodes.indexOf(child);
7062     },
7063
7064     /**
7065      * Returns the tree this node is in.
7066      * @return {Tree}
7067      */
7068     getOwnerTree : function(){
7069         // if it doesn't have one, look for one
7070         if(!this.ownerTree){
7071             var p = this;
7072             while(p){
7073                 if(p.ownerTree){
7074                     this.ownerTree = p.ownerTree;
7075                     break;
7076                 }
7077                 p = p.parentNode;
7078             }
7079         }
7080         return this.ownerTree;
7081     },
7082
7083     /**
7084      * Returns depth of this node (the root node has a depth of 0)
7085      * @return {Number}
7086      */
7087     getDepth : function(){
7088         var depth = 0;
7089         var p = this;
7090         while(p.parentNode){
7091             ++depth;
7092             p = p.parentNode;
7093         }
7094         return depth;
7095     },
7096
7097     // private
7098     setOwnerTree : function(tree){
7099         // if it's move, we need to update everyone
7100         if(tree != this.ownerTree){
7101             if(this.ownerTree){
7102                 this.ownerTree.unregisterNode(this);
7103             }
7104             this.ownerTree = tree;
7105             var cs = this.childNodes;
7106             for(var i = 0, len = cs.length; i < len; i++) {
7107                 cs[i].setOwnerTree(tree);
7108             }
7109             if(tree){
7110                 tree.registerNode(this);
7111             }
7112         }
7113     },
7114
7115     /**
7116      * Returns the path for this node. The path can be used to expand or select this node programmatically.
7117      * @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
7118      * @return {String} The path
7119      */
7120     getPath : function(attr){
7121         attr = attr || "id";
7122         var p = this.parentNode;
7123         var b = [this.attributes[attr]];
7124         while(p){
7125             b.unshift(p.attributes[attr]);
7126             p = p.parentNode;
7127         }
7128         var sep = this.getOwnerTree().pathSeparator;
7129         return sep + b.join(sep);
7130     },
7131
7132     /**
7133      * Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
7134      * function call will be the scope provided or the current node. The arguments to the function
7135      * will be the args provided or the current node. If the function returns false at any point,
7136      * the bubble is stopped.
7137      * @param {Function} fn The function to call
7138      * @param {Object} scope (optional) The scope of the function (defaults to current node)
7139      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7140      */
7141     bubble : function(fn, scope, args){
7142         var p = this;
7143         while(p){
7144             if(fn.call(scope || p, args || p) === false){
7145                 break;
7146             }
7147             p = p.parentNode;
7148         }
7149     },
7150
7151     /**
7152      * Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
7153      * function call will be the scope provided or the current node. The arguments to the function
7154      * will be the args provided or the current node. If the function returns false at any point,
7155      * the cascade is stopped on that branch.
7156      * @param {Function} fn The function to call
7157      * @param {Object} scope (optional) The scope of the function (defaults to current node)
7158      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7159      */
7160     cascade : function(fn, scope, args){
7161         if(fn.call(scope || this, args || this) !== false){
7162             var cs = this.childNodes;
7163             for(var i = 0, len = cs.length; i < len; i++) {
7164                 cs[i].cascade(fn, scope, args);
7165             }
7166         }
7167     },
7168
7169     /**
7170      * Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
7171      * function call will be the scope provided or the current node. The arguments to the function
7172      * will be the args provided or the current node. If the function returns false at any point,
7173      * the iteration stops.
7174      * @param {Function} fn The function to call
7175      * @param {Object} scope (optional) The scope of the function (defaults to current node)
7176      * @param {Array} args (optional) The args to call the function with (default to passing the current node)
7177      */
7178     eachChild : function(fn, scope, args){
7179         var cs = this.childNodes;
7180         for(var i = 0, len = cs.length; i < len; i++) {
7181                 if(fn.call(scope || this, args || cs[i]) === false){
7182                     break;
7183                 }
7184         }
7185     },
7186
7187     /**
7188      * Finds the first child that has the attribute with the specified value.
7189      * @param {String} attribute The attribute name
7190      * @param {Mixed} value The value to search for
7191      * @return {Node} The found child or null if none was found
7192      */
7193     findChild : function(attribute, value){
7194         var cs = this.childNodes;
7195         for(var i = 0, len = cs.length; i < len; i++) {
7196                 if(cs[i].attributes[attribute] == value){
7197                     return cs[i];
7198                 }
7199         }
7200         return null;
7201     },
7202
7203     /**
7204      * Finds the first child by a custom function. The child matches if the function passed
7205      * returns true.
7206      * @param {Function} fn
7207      * @param {Object} scope (optional)
7208      * @return {Node} The found child or null if none was found
7209      */
7210     findChildBy : function(fn, scope){
7211         var cs = this.childNodes;
7212         for(var i = 0, len = cs.length; i < len; i++) {
7213                 if(fn.call(scope||cs[i], cs[i]) === true){
7214                     return cs[i];
7215                 }
7216         }
7217         return null;
7218     },
7219
7220     /**
7221      * Sorts this nodes children using the supplied sort function
7222      * @param {Function} fn
7223      * @param {Object} scope (optional)
7224      */
7225     sort : function(fn, scope){
7226         var cs = this.childNodes;
7227         var len = cs.length;
7228         if(len > 0){
7229             var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
7230             cs.sort(sortFn);
7231             for(var i = 0; i < len; i++){
7232                 var n = cs[i];
7233                 n.previousSibling = cs[i-1];
7234                 n.nextSibling = cs[i+1];
7235                 if(i == 0){
7236                     this.setFirstChild(n);
7237                 }
7238                 if(i == len-1){
7239                     this.setLastChild(n);
7240                 }
7241             }
7242         }
7243     },
7244
7245     /**
7246      * Returns true if this node is an ancestor (at any point) of the passed node.
7247      * @param {Node} node
7248      * @return {Boolean}
7249      */
7250     contains : function(node){
7251         return node.isAncestor(this);
7252     },
7253
7254     /**
7255      * Returns true if the passed node is an ancestor (at any point) of this node.
7256      * @param {Node} node
7257      * @return {Boolean}
7258      */
7259     isAncestor : function(node){
7260         var p = this.parentNode;
7261         while(p){
7262             if(p == node){
7263                 return true;
7264             }
7265             p = p.parentNode;
7266         }
7267         return false;
7268     },
7269
7270     toString : function(){
7271         return "[Node"+(this.id?" "+this.id:"")+"]";
7272     }
7273 });/*
7274  * Based on:
7275  * Ext JS Library 1.1.1
7276  * Copyright(c) 2006-2007, Ext JS, LLC.
7277  *
7278  * Originally Released Under LGPL - original licence link has changed is not relivant.
7279  *
7280  * Fork - LGPL
7281  * <script type="text/javascript">
7282  */
7283  (function(){ 
7284 /**
7285  * @class Roo.Layer
7286  * @extends Roo.Element
7287  * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
7288  * automatic maintaining of shadow/shim positions.
7289  * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
7290  * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
7291  * you can pass a string with a CSS class name. False turns off the shadow.
7292  * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
7293  * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
7294  * @cfg {String} cls CSS class to add to the element
7295  * @cfg {Number} zindex Starting z-index (defaults to 11000)
7296  * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
7297  * @constructor
7298  * @param {Object} config An object with config options.
7299  * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
7300  */
7301
7302 Roo.Layer = function(config, existingEl){
7303     config = config || {};
7304     var dh = Roo.DomHelper;
7305     var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
7306     if(existingEl){
7307         this.dom = Roo.getDom(existingEl);
7308     }
7309     if(!this.dom){
7310         var o = config.dh || {tag: "div", cls: "x-layer"};
7311         this.dom = dh.append(pel, o);
7312     }
7313     if(config.cls){
7314         this.addClass(config.cls);
7315     }
7316     this.constrain = config.constrain !== false;
7317     this.visibilityMode = Roo.Element.VISIBILITY;
7318     if(config.id){
7319         this.id = this.dom.id = config.id;
7320     }else{
7321         this.id = Roo.id(this.dom);
7322     }
7323     this.zindex = config.zindex || this.getZIndex();
7324     this.position("absolute", this.zindex);
7325     if(config.shadow){
7326         this.shadowOffset = config.shadowOffset || 4;
7327         this.shadow = new Roo.Shadow({
7328             offset : this.shadowOffset,
7329             mode : config.shadow
7330         });
7331     }else{
7332         this.shadowOffset = 0;
7333     }
7334     this.useShim = config.shim !== false && Roo.useShims;
7335     this.useDisplay = config.useDisplay;
7336     this.hide();
7337 };
7338
7339 var supr = Roo.Element.prototype;
7340
7341 // shims are shared among layer to keep from having 100 iframes
7342 var shims = [];
7343
7344 Roo.extend(Roo.Layer, Roo.Element, {
7345
7346     getZIndex : function(){
7347         return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
7348     },
7349
7350     getShim : function(){
7351         if(!this.useShim){
7352             return null;
7353         }
7354         if(this.shim){
7355             return this.shim;
7356         }
7357         var shim = shims.shift();
7358         if(!shim){
7359             shim = this.createShim();
7360             shim.enableDisplayMode('block');
7361             shim.dom.style.display = 'none';
7362             shim.dom.style.visibility = 'visible';
7363         }
7364         var pn = this.dom.parentNode;
7365         if(shim.dom.parentNode != pn){
7366             pn.insertBefore(shim.dom, this.dom);
7367         }
7368         shim.setStyle('z-index', this.getZIndex()-2);
7369         this.shim = shim;
7370         return shim;
7371     },
7372
7373     hideShim : function(){
7374         if(this.shim){
7375             this.shim.setDisplayed(false);
7376             shims.push(this.shim);
7377             delete this.shim;
7378         }
7379     },
7380
7381     disableShadow : function(){
7382         if(this.shadow){
7383             this.shadowDisabled = true;
7384             this.shadow.hide();
7385             this.lastShadowOffset = this.shadowOffset;
7386             this.shadowOffset = 0;
7387         }
7388     },
7389
7390     enableShadow : function(show){
7391         if(this.shadow){
7392             this.shadowDisabled = false;
7393             this.shadowOffset = this.lastShadowOffset;
7394             delete this.lastShadowOffset;
7395             if(show){
7396                 this.sync(true);
7397             }
7398         }
7399     },
7400
7401     // private
7402     // this code can execute repeatedly in milliseconds (i.e. during a drag) so
7403     // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
7404     sync : function(doShow){
7405         var sw = this.shadow;
7406         if(!this.updating && this.isVisible() && (sw || this.useShim)){
7407             var sh = this.getShim();
7408
7409             var w = this.getWidth(),
7410                 h = this.getHeight();
7411
7412             var l = this.getLeft(true),
7413                 t = this.getTop(true);
7414
7415             if(sw && !this.shadowDisabled){
7416                 if(doShow && !sw.isVisible()){
7417                     sw.show(this);
7418                 }else{
7419                     sw.realign(l, t, w, h);
7420                 }
7421                 if(sh){
7422                     if(doShow){
7423                        sh.show();
7424                     }
7425                     // fit the shim behind the shadow, so it is shimmed too
7426                     var a = sw.adjusts, s = sh.dom.style;
7427                     s.left = (Math.min(l, l+a.l))+"px";
7428                     s.top = (Math.min(t, t+a.t))+"px";
7429                     s.width = (w+a.w)+"px";
7430                     s.height = (h+a.h)+"px";
7431                 }
7432             }else if(sh){
7433                 if(doShow){
7434                    sh.show();
7435                 }
7436                 sh.setSize(w, h);
7437                 sh.setLeftTop(l, t);
7438             }
7439             
7440         }
7441     },
7442
7443     // private
7444     destroy : function(){
7445         this.hideShim();
7446         if(this.shadow){
7447             this.shadow.hide();
7448         }
7449         this.removeAllListeners();
7450         var pn = this.dom.parentNode;
7451         if(pn){
7452             pn.removeChild(this.dom);
7453         }
7454         Roo.Element.uncache(this.id);
7455     },
7456
7457     remove : function(){
7458         this.destroy();
7459     },
7460
7461     // private
7462     beginUpdate : function(){
7463         this.updating = true;
7464     },
7465
7466     // private
7467     endUpdate : function(){
7468         this.updating = false;
7469         this.sync(true);
7470     },
7471
7472     // private
7473     hideUnders : function(negOffset){
7474         if(this.shadow){
7475             this.shadow.hide();
7476         }
7477         this.hideShim();
7478     },
7479
7480     // private
7481     constrainXY : function(){
7482         if(this.constrain){
7483             var vw = Roo.lib.Dom.getViewWidth(),
7484                 vh = Roo.lib.Dom.getViewHeight();
7485             var s = Roo.get(document).getScroll();
7486
7487             var xy = this.getXY();
7488             var x = xy[0], y = xy[1];   
7489             var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
7490             // only move it if it needs it
7491             var moved = false;
7492             // first validate right/bottom
7493             if((x + w) > vw+s.left){
7494                 x = vw - w - this.shadowOffset;
7495                 moved = true;
7496             }
7497             if((y + h) > vh+s.top){
7498                 y = vh - h - this.shadowOffset;
7499                 moved = true;
7500             }
7501             // then make sure top/left isn't negative
7502             if(x < s.left){
7503                 x = s.left;
7504                 moved = true;
7505             }
7506             if(y < s.top){
7507                 y = s.top;
7508                 moved = true;
7509             }
7510             if(moved){
7511                 if(this.avoidY){
7512                     var ay = this.avoidY;
7513                     if(y <= ay && (y+h) >= ay){
7514                         y = ay-h-5;   
7515                     }
7516                 }
7517                 xy = [x, y];
7518                 this.storeXY(xy);
7519                 supr.setXY.call(this, xy);
7520                 this.sync();
7521             }
7522         }
7523     },
7524
7525     isVisible : function(){
7526         return this.visible;    
7527     },
7528
7529     // private
7530     showAction : function(){
7531         this.visible = true; // track visibility to prevent getStyle calls
7532         if(this.useDisplay === true){
7533             this.setDisplayed("");
7534         }else if(this.lastXY){
7535             supr.setXY.call(this, this.lastXY);
7536         }else if(this.lastLT){
7537             supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
7538         }
7539     },
7540
7541     // private
7542     hideAction : function(){
7543         this.visible = false;
7544         if(this.useDisplay === true){
7545             this.setDisplayed(false);
7546         }else{
7547             this.setLeftTop(-10000,-10000);
7548         }
7549     },
7550
7551     // overridden Element method
7552     setVisible : function(v, a, d, c, e){
7553         if(v){
7554             this.showAction();
7555         }
7556         if(a && v){
7557             var cb = function(){
7558                 this.sync(true);
7559                 if(c){
7560                     c();
7561                 }
7562             }.createDelegate(this);
7563             supr.setVisible.call(this, true, true, d, cb, e);
7564         }else{
7565             if(!v){
7566                 this.hideUnders(true);
7567             }
7568             var cb = c;
7569             if(a){
7570                 cb = function(){
7571                     this.hideAction();
7572                     if(c){
7573                         c();
7574                     }
7575                 }.createDelegate(this);
7576             }
7577             supr.setVisible.call(this, v, a, d, cb, e);
7578             if(v){
7579                 this.sync(true);
7580             }else if(!a){
7581                 this.hideAction();
7582             }
7583         }
7584     },
7585
7586     storeXY : function(xy){
7587         delete this.lastLT;
7588         this.lastXY = xy;
7589     },
7590
7591     storeLeftTop : function(left, top){
7592         delete this.lastXY;
7593         this.lastLT = [left, top];
7594     },
7595
7596     // private
7597     beforeFx : function(){
7598         this.beforeAction();
7599         return Roo.Layer.superclass.beforeFx.apply(this, arguments);
7600     },
7601
7602     // private
7603     afterFx : function(){
7604         Roo.Layer.superclass.afterFx.apply(this, arguments);
7605         this.sync(this.isVisible());
7606     },
7607
7608     // private
7609     beforeAction : function(){
7610         if(!this.updating && this.shadow){
7611             this.shadow.hide();
7612         }
7613     },
7614
7615     // overridden Element method
7616     setLeft : function(left){
7617         this.storeLeftTop(left, this.getTop(true));
7618         supr.setLeft.apply(this, arguments);
7619         this.sync();
7620     },
7621
7622     setTop : function(top){
7623         this.storeLeftTop(this.getLeft(true), top);
7624         supr.setTop.apply(this, arguments);
7625         this.sync();
7626     },
7627
7628     setLeftTop : function(left, top){
7629         this.storeLeftTop(left, top);
7630         supr.setLeftTop.apply(this, arguments);
7631         this.sync();
7632     },
7633
7634     setXY : function(xy, a, d, c, e){
7635         this.fixDisplay();
7636         this.beforeAction();
7637         this.storeXY(xy);
7638         var cb = this.createCB(c);
7639         supr.setXY.call(this, xy, a, d, cb, e);
7640         if(!a){
7641             cb();
7642         }
7643     },
7644
7645     // private
7646     createCB : function(c){
7647         var el = this;
7648         return function(){
7649             el.constrainXY();
7650             el.sync(true);
7651             if(c){
7652                 c();
7653             }
7654         };
7655     },
7656
7657     // overridden Element method
7658     setX : function(x, a, d, c, e){
7659         this.setXY([x, this.getY()], a, d, c, e);
7660     },
7661
7662     // overridden Element method
7663     setY : function(y, a, d, c, e){
7664         this.setXY([this.getX(), y], a, d, c, e);
7665     },
7666
7667     // overridden Element method
7668     setSize : function(w, h, a, d, c, e){
7669         this.beforeAction();
7670         var cb = this.createCB(c);
7671         supr.setSize.call(this, w, h, a, d, cb, e);
7672         if(!a){
7673             cb();
7674         }
7675     },
7676
7677     // overridden Element method
7678     setWidth : function(w, a, d, c, e){
7679         this.beforeAction();
7680         var cb = this.createCB(c);
7681         supr.setWidth.call(this, w, a, d, cb, e);
7682         if(!a){
7683             cb();
7684         }
7685     },
7686
7687     // overridden Element method
7688     setHeight : function(h, a, d, c, e){
7689         this.beforeAction();
7690         var cb = this.createCB(c);
7691         supr.setHeight.call(this, h, a, d, cb, e);
7692         if(!a){
7693             cb();
7694         }
7695     },
7696
7697     // overridden Element method
7698     setBounds : function(x, y, w, h, a, d, c, e){
7699         this.beforeAction();
7700         var cb = this.createCB(c);
7701         if(!a){
7702             this.storeXY([x, y]);
7703             supr.setXY.call(this, [x, y]);
7704             supr.setSize.call(this, w, h, a, d, cb, e);
7705             cb();
7706         }else{
7707             supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
7708         }
7709         return this;
7710     },
7711     
7712     /**
7713      * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
7714      * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
7715      * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
7716      * @param {Number} zindex The new z-index to set
7717      * @return {this} The Layer
7718      */
7719     setZIndex : function(zindex){
7720         this.zindex = zindex;
7721         this.setStyle("z-index", zindex + 2);
7722         if(this.shadow){
7723             this.shadow.setZIndex(zindex + 1);
7724         }
7725         if(this.shim){
7726             this.shim.setStyle("z-index", zindex);
7727         }
7728     }
7729 });
7730 })();/*
7731  * Based on:
7732  * Ext JS Library 1.1.1
7733  * Copyright(c) 2006-2007, Ext JS, LLC.
7734  *
7735  * Originally Released Under LGPL - original licence link has changed is not relivant.
7736  *
7737  * Fork - LGPL
7738  * <script type="text/javascript">
7739  */
7740
7741
7742 /**
7743  * @class Roo.Shadow
7744  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
7745  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
7746  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
7747  * @constructor
7748  * Create a new Shadow
7749  * @param {Object} config The config object
7750  */
7751 Roo.Shadow = function(config){
7752     Roo.apply(this, config);
7753     if(typeof this.mode != "string"){
7754         this.mode = this.defaultMode;
7755     }
7756     var o = this.offset, a = {h: 0};
7757     var rad = Math.floor(this.offset/2);
7758     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
7759         case "drop":
7760             a.w = 0;
7761             a.l = a.t = o;
7762             a.t -= 1;
7763             if(Roo.isIE){
7764                 a.l -= this.offset + rad;
7765                 a.t -= this.offset + rad;
7766                 a.w -= rad;
7767                 a.h -= rad;
7768                 a.t += 1;
7769             }
7770         break;
7771         case "sides":
7772             a.w = (o*2);
7773             a.l = -o;
7774             a.t = o-1;
7775             if(Roo.isIE){
7776                 a.l -= (this.offset - rad);
7777                 a.t -= this.offset + rad;
7778                 a.l += 1;
7779                 a.w -= (this.offset - rad)*2;
7780                 a.w -= rad + 1;
7781                 a.h -= 1;
7782             }
7783         break;
7784         case "frame":
7785             a.w = a.h = (o*2);
7786             a.l = a.t = -o;
7787             a.t += 1;
7788             a.h -= 2;
7789             if(Roo.isIE){
7790                 a.l -= (this.offset - rad);
7791                 a.t -= (this.offset - rad);
7792                 a.l += 1;
7793                 a.w -= (this.offset + rad + 1);
7794                 a.h -= (this.offset + rad);
7795                 a.h += 1;
7796             }
7797         break;
7798     };
7799
7800     this.adjusts = a;
7801 };
7802
7803 Roo.Shadow.prototype = {
7804     /**
7805      * @cfg {String} mode
7806      * The shadow display mode.  Supports the following options:<br />
7807      * sides: Shadow displays on both sides and bottom only<br />
7808      * frame: Shadow displays equally on all four sides<br />
7809      * drop: Traditional bottom-right drop shadow (default)
7810      */
7811     /**
7812      * @cfg {String} offset
7813      * The number of pixels to offset the shadow from the element (defaults to 4)
7814      */
7815     offset: 4,
7816
7817     // private
7818     defaultMode: "drop",
7819
7820     /**
7821      * Displays the shadow under the target element
7822      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
7823      */
7824     show : function(target){
7825         target = Roo.get(target);
7826         if(!this.el){
7827             this.el = Roo.Shadow.Pool.pull();
7828             if(this.el.dom.nextSibling != target.dom){
7829                 this.el.insertBefore(target);
7830             }
7831         }
7832         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
7833         if(Roo.isIE){
7834             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
7835         }
7836         this.realign(
7837             target.getLeft(true),
7838             target.getTop(true),
7839             target.getWidth(),
7840             target.getHeight()
7841         );
7842         this.el.dom.style.display = "block";
7843     },
7844
7845     /**
7846      * Returns true if the shadow is visible, else false
7847      */
7848     isVisible : function(){
7849         return this.el ? true : false;  
7850     },
7851
7852     /**
7853      * Direct alignment when values are already available. Show must be called at least once before
7854      * calling this method to ensure it is initialized.
7855      * @param {Number} left The target element left position
7856      * @param {Number} top The target element top position
7857      * @param {Number} width The target element width
7858      * @param {Number} height The target element height
7859      */
7860     realign : function(l, t, w, h){
7861         if(!this.el){
7862             return;
7863         }
7864         var a = this.adjusts, d = this.el.dom, s = d.style;
7865         var iea = 0;
7866         s.left = (l+a.l)+"px";
7867         s.top = (t+a.t)+"px";
7868         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
7869  
7870         if(s.width != sws || s.height != shs){
7871             s.width = sws;
7872             s.height = shs;
7873             if(!Roo.isIE){
7874                 var cn = d.childNodes;
7875                 var sww = Math.max(0, (sw-12))+"px";
7876                 cn[0].childNodes[1].style.width = sww;
7877                 cn[1].childNodes[1].style.width = sww;
7878                 cn[2].childNodes[1].style.width = sww;
7879                 cn[1].style.height = Math.max(0, (sh-12))+"px";
7880             }
7881         }
7882     },
7883
7884     /**
7885      * Hides this shadow
7886      */
7887     hide : function(){
7888         if(this.el){
7889             this.el.dom.style.display = "none";
7890             Roo.Shadow.Pool.push(this.el);
7891             delete this.el;
7892         }
7893     },
7894
7895     /**
7896      * Adjust the z-index of this shadow
7897      * @param {Number} zindex The new z-index
7898      */
7899     setZIndex : function(z){
7900         this.zIndex = z;
7901         if(this.el){
7902             this.el.setStyle("z-index", z);
7903         }
7904     }
7905 };
7906
7907 // Private utility class that manages the internal Shadow cache
7908 Roo.Shadow.Pool = function(){
7909     var p = [];
7910     var markup = Roo.isIE ?
7911                  '<div class="x-ie-shadow"></div>' :
7912                  '<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>';
7913     return {
7914         pull : function(){
7915             var sh = p.shift();
7916             if(!sh){
7917                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
7918                 sh.autoBoxAdjust = false;
7919             }
7920             return sh;
7921         },
7922
7923         push : function(sh){
7924             p.push(sh);
7925         }
7926     };
7927 }();/*
7928  * Based on:
7929  * Ext JS Library 1.1.1
7930  * Copyright(c) 2006-2007, Ext JS, LLC.
7931  *
7932  * Originally Released Under LGPL - original licence link has changed is not relivant.
7933  *
7934  * Fork - LGPL
7935  * <script type="text/javascript">
7936  */
7937
7938
7939 /**
7940  * @class Roo.SplitBar
7941  * @extends Roo.util.Observable
7942  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
7943  * <br><br>
7944  * Usage:
7945  * <pre><code>
7946 var split = new Roo.SplitBar("elementToDrag", "elementToSize",
7947                    Roo.SplitBar.HORIZONTAL, Roo.SplitBar.LEFT);
7948 split.setAdapter(new Roo.SplitBar.AbsoluteLayoutAdapter("container"));
7949 split.minSize = 100;
7950 split.maxSize = 600;
7951 split.animate = true;
7952 split.on('moved', splitterMoved);
7953 </code></pre>
7954  * @constructor
7955  * Create a new SplitBar
7956  * @param {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
7957  * @param {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
7958  * @param {Number} orientation (optional) Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
7959  * @param {Number} placement (optional) Either Roo.SplitBar.LEFT or Roo.SplitBar.RIGHT for horizontal or  
7960                         Roo.SplitBar.TOP or Roo.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
7961                         position of the SplitBar).
7962  */
7963 Roo.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
7964     
7965     /** @private */
7966     this.el = Roo.get(dragElement, true);
7967     this.el.dom.unselectable = "on";
7968     /** @private */
7969     this.resizingEl = Roo.get(resizingElement, true);
7970
7971     /**
7972      * @private
7973      * The orientation of the split. Either Roo.SplitBar.HORIZONTAL or Roo.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
7974      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
7975      * @type Number
7976      */
7977     this.orientation = orientation || Roo.SplitBar.HORIZONTAL;
7978     
7979     /**
7980      * The minimum size of the resizing element. (Defaults to 0)
7981      * @type Number
7982      */
7983     this.minSize = 0;
7984     
7985     /**
7986      * The maximum size of the resizing element. (Defaults to 2000)
7987      * @type Number
7988      */
7989     this.maxSize = 2000;
7990     
7991     /**
7992      * Whether to animate the transition to the new size
7993      * @type Boolean
7994      */
7995     this.animate = false;
7996     
7997     /**
7998      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
7999      * @type Boolean
8000      */
8001     this.useShim = false;
8002     
8003     /** @private */
8004     this.shim = null;
8005     
8006     if(!existingProxy){
8007         /** @private */
8008         this.proxy = Roo.SplitBar.createProxy(this.orientation);
8009     }else{
8010         this.proxy = Roo.get(existingProxy).dom;
8011     }
8012     /** @private */
8013     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
8014     
8015     /** @private */
8016     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
8017     
8018     /** @private */
8019     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
8020     
8021     /** @private */
8022     this.dragSpecs = {};
8023     
8024     /**
8025      * @private The adapter to use to positon and resize elements
8026      */
8027     this.adapter = new Roo.SplitBar.BasicLayoutAdapter();
8028     this.adapter.init(this);
8029     
8030     if(this.orientation == Roo.SplitBar.HORIZONTAL){
8031         /** @private */
8032         this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Roo.SplitBar.LEFT : Roo.SplitBar.RIGHT);
8033         this.el.addClass("x-splitbar-h");
8034     }else{
8035         /** @private */
8036         this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Roo.SplitBar.TOP : Roo.SplitBar.BOTTOM);
8037         this.el.addClass("x-splitbar-v");
8038     }
8039     
8040     this.addEvents({
8041         /**
8042          * @event resize
8043          * Fires when the splitter is moved (alias for {@link #event-moved})
8044          * @param {Roo.SplitBar} this
8045          * @param {Number} newSize the new width or height
8046          */
8047         "resize" : true,
8048         /**
8049          * @event moved
8050          * Fires when the splitter is moved
8051          * @param {Roo.SplitBar} this
8052          * @param {Number} newSize the new width or height
8053          */
8054         "moved" : true,
8055         /**
8056          * @event beforeresize
8057          * Fires before the splitter is dragged
8058          * @param {Roo.SplitBar} this
8059          */
8060         "beforeresize" : true,
8061
8062         "beforeapply" : true
8063     });
8064
8065     Roo.util.Observable.call(this);
8066 };
8067
8068 Roo.extend(Roo.SplitBar, Roo.util.Observable, {
8069     onStartProxyDrag : function(x, y){
8070         this.fireEvent("beforeresize", this);
8071         if(!this.overlay){
8072             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "x-drag-overlay", html: "&#160;"}, true);
8073             o.unselectable();
8074             o.enableDisplayMode("block");
8075             // all splitbars share the same overlay
8076             Roo.SplitBar.prototype.overlay = o;
8077         }
8078         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8079         this.overlay.show();
8080         Roo.get(this.proxy).setDisplayed("block");
8081         var size = this.adapter.getElementSize(this);
8082         this.activeMinSize = this.getMinimumSize();;
8083         this.activeMaxSize = this.getMaximumSize();;
8084         var c1 = size - this.activeMinSize;
8085         var c2 = Math.max(this.activeMaxSize - size, 0);
8086         if(this.orientation == Roo.SplitBar.HORIZONTAL){
8087             this.dd.resetConstraints();
8088             this.dd.setXConstraint(
8089                 this.placement == Roo.SplitBar.LEFT ? c1 : c2, 
8090                 this.placement == Roo.SplitBar.LEFT ? c2 : c1
8091             );
8092             this.dd.setYConstraint(0, 0);
8093         }else{
8094             this.dd.resetConstraints();
8095             this.dd.setXConstraint(0, 0);
8096             this.dd.setYConstraint(
8097                 this.placement == Roo.SplitBar.TOP ? c1 : c2, 
8098                 this.placement == Roo.SplitBar.TOP ? c2 : c1
8099             );
8100          }
8101         this.dragSpecs.startSize = size;
8102         this.dragSpecs.startPoint = [x, y];
8103         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
8104     },
8105     
8106     /** 
8107      * @private Called after the drag operation by the DDProxy
8108      */
8109     onEndProxyDrag : function(e){
8110         Roo.get(this.proxy).setDisplayed(false);
8111         var endPoint = Roo.lib.Event.getXY(e);
8112         if(this.overlay){
8113             this.overlay.hide();
8114         }
8115         var newSize;
8116         if(this.orientation == Roo.SplitBar.HORIZONTAL){
8117             newSize = this.dragSpecs.startSize + 
8118                 (this.placement == Roo.SplitBar.LEFT ?
8119                     endPoint[0] - this.dragSpecs.startPoint[0] :
8120                     this.dragSpecs.startPoint[0] - endPoint[0]
8121                 );
8122         }else{
8123             newSize = this.dragSpecs.startSize + 
8124                 (this.placement == Roo.SplitBar.TOP ?
8125                     endPoint[1] - this.dragSpecs.startPoint[1] :
8126                     this.dragSpecs.startPoint[1] - endPoint[1]
8127                 );
8128         }
8129         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
8130         if(newSize != this.dragSpecs.startSize){
8131             if(this.fireEvent('beforeapply', this, newSize) !== false){
8132                 this.adapter.setElementSize(this, newSize);
8133                 this.fireEvent("moved", this, newSize);
8134                 this.fireEvent("resize", this, newSize);
8135             }
8136         }
8137     },
8138     
8139     /**
8140      * Get the adapter this SplitBar uses
8141      * @return The adapter object
8142      */
8143     getAdapter : function(){
8144         return this.adapter;
8145     },
8146     
8147     /**
8148      * Set the adapter this SplitBar uses
8149      * @param {Object} adapter A SplitBar adapter object
8150      */
8151     setAdapter : function(adapter){
8152         this.adapter = adapter;
8153         this.adapter.init(this);
8154     },
8155     
8156     /**
8157      * Gets the minimum size for the resizing element
8158      * @return {Number} The minimum size
8159      */
8160     getMinimumSize : function(){
8161         return this.minSize;
8162     },
8163     
8164     /**
8165      * Sets the minimum size for the resizing element
8166      * @param {Number} minSize The minimum size
8167      */
8168     setMinimumSize : function(minSize){
8169         this.minSize = minSize;
8170     },
8171     
8172     /**
8173      * Gets the maximum size for the resizing element
8174      * @return {Number} The maximum size
8175      */
8176     getMaximumSize : function(){
8177         return this.maxSize;
8178     },
8179     
8180     /**
8181      * Sets the maximum size for the resizing element
8182      * @param {Number} maxSize The maximum size
8183      */
8184     setMaximumSize : function(maxSize){
8185         this.maxSize = maxSize;
8186     },
8187     
8188     /**
8189      * Sets the initialize size for the resizing element
8190      * @param {Number} size The initial size
8191      */
8192     setCurrentSize : function(size){
8193         var oldAnimate = this.animate;
8194         this.animate = false;
8195         this.adapter.setElementSize(this, size);
8196         this.animate = oldAnimate;
8197     },
8198     
8199     /**
8200      * Destroy this splitbar. 
8201      * @param {Boolean} removeEl True to remove the element
8202      */
8203     destroy : function(removeEl){
8204         if(this.shim){
8205             this.shim.remove();
8206         }
8207         this.dd.unreg();
8208         this.proxy.parentNode.removeChild(this.proxy);
8209         if(removeEl){
8210             this.el.remove();
8211         }
8212     }
8213 });
8214
8215 /**
8216  * @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.
8217  */
8218 Roo.SplitBar.createProxy = function(dir){
8219     var proxy = new Roo.Element(document.createElement("div"));
8220     proxy.unselectable();
8221     var cls = 'x-splitbar-proxy';
8222     proxy.addClass(cls + ' ' + (dir == Roo.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
8223     document.body.appendChild(proxy.dom);
8224     return proxy.dom;
8225 };
8226
8227 /** 
8228  * @class Roo.SplitBar.BasicLayoutAdapter
8229  * Default Adapter. It assumes the splitter and resizing element are not positioned
8230  * elements and only gets/sets the width of the element. Generally used for table based layouts.
8231  */
8232 Roo.SplitBar.BasicLayoutAdapter = function(){
8233 };
8234
8235 Roo.SplitBar.BasicLayoutAdapter.prototype = {
8236     // do nothing for now
8237     init : function(s){
8238     
8239     },
8240     /**
8241      * Called before drag operations to get the current size of the resizing element. 
8242      * @param {Roo.SplitBar} s The SplitBar using this adapter
8243      */
8244      getElementSize : function(s){
8245         if(s.orientation == Roo.SplitBar.HORIZONTAL){
8246             return s.resizingEl.getWidth();
8247         }else{
8248             return s.resizingEl.getHeight();
8249         }
8250     },
8251     
8252     /**
8253      * Called after drag operations to set the size of the resizing element.
8254      * @param {Roo.SplitBar} s The SplitBar using this adapter
8255      * @param {Number} newSize The new size to set
8256      * @param {Function} onComplete A function to be invoked when resizing is complete
8257      */
8258     setElementSize : function(s, newSize, onComplete){
8259         if(s.orientation == Roo.SplitBar.HORIZONTAL){
8260             if(!s.animate){
8261                 s.resizingEl.setWidth(newSize);
8262                 if(onComplete){
8263                     onComplete(s, newSize);
8264                 }
8265             }else{
8266                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
8267             }
8268         }else{
8269             
8270             if(!s.animate){
8271                 s.resizingEl.setHeight(newSize);
8272                 if(onComplete){
8273                     onComplete(s, newSize);
8274                 }
8275             }else{
8276                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
8277             }
8278         }
8279     }
8280 };
8281
8282 /** 
8283  *@class Roo.SplitBar.AbsoluteLayoutAdapter
8284  * @extends Roo.SplitBar.BasicLayoutAdapter
8285  * Adapter that  moves the splitter element to align with the resized sizing element. 
8286  * Used with an absolute positioned SplitBar.
8287  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
8288  * document.body, make sure you assign an id to the body element.
8289  */
8290 Roo.SplitBar.AbsoluteLayoutAdapter = function(container){
8291     this.basic = new Roo.SplitBar.BasicLayoutAdapter();
8292     this.container = Roo.get(container);
8293 };
8294
8295 Roo.SplitBar.AbsoluteLayoutAdapter.prototype = {
8296     init : function(s){
8297         this.basic.init(s);
8298     },
8299     
8300     getElementSize : function(s){
8301         return this.basic.getElementSize(s);
8302     },
8303     
8304     setElementSize : function(s, newSize, onComplete){
8305         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
8306     },
8307     
8308     moveSplitter : function(s){
8309         var yes = Roo.SplitBar;
8310         switch(s.placement){
8311             case yes.LEFT:
8312                 s.el.setX(s.resizingEl.getRight());
8313                 break;
8314             case yes.RIGHT:
8315                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
8316                 break;
8317             case yes.TOP:
8318                 s.el.setY(s.resizingEl.getBottom());
8319                 break;
8320             case yes.BOTTOM:
8321                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
8322                 break;
8323         }
8324     }
8325 };
8326
8327 /**
8328  * Orientation constant - Create a vertical SplitBar
8329  * @static
8330  * @type Number
8331  */
8332 Roo.SplitBar.VERTICAL = 1;
8333
8334 /**
8335  * Orientation constant - Create a horizontal SplitBar
8336  * @static
8337  * @type Number
8338  */
8339 Roo.SplitBar.HORIZONTAL = 2;
8340
8341 /**
8342  * Placement constant - The resizing element is to the left of the splitter element
8343  * @static
8344  * @type Number
8345  */
8346 Roo.SplitBar.LEFT = 1;
8347
8348 /**
8349  * Placement constant - The resizing element is to the right of the splitter element
8350  * @static
8351  * @type Number
8352  */
8353 Roo.SplitBar.RIGHT = 2;
8354
8355 /**
8356  * Placement constant - The resizing element is positioned above the splitter element
8357  * @static
8358  * @type Number
8359  */
8360 Roo.SplitBar.TOP = 3;
8361
8362 /**
8363  * Placement constant - The resizing element is positioned under splitter element
8364  * @static
8365  * @type Number
8366  */
8367 Roo.SplitBar.BOTTOM = 4;
8368 /*
8369  * Based on:
8370  * Ext JS Library 1.1.1
8371  * Copyright(c) 2006-2007, Ext JS, LLC.
8372  *
8373  * Originally Released Under LGPL - original licence link has changed is not relivant.
8374  *
8375  * Fork - LGPL
8376  * <script type="text/javascript">
8377  */
8378
8379 /**
8380  * @class Roo.View
8381  * @extends Roo.util.Observable
8382  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
8383  * This class also supports single and multi selection modes. <br>
8384  * Create a data model bound view:
8385  <pre><code>
8386  var store = new Roo.data.Store(...);
8387
8388  var view = new Roo.View({
8389     el : "my-element",
8390     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
8391  
8392     singleSelect: true,
8393     selectedClass: "ydataview-selected",
8394     store: store
8395  });
8396
8397  // listen for node click?
8398  view.on("click", function(vw, index, node, e){
8399  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
8400  });
8401
8402  // load XML data
8403  dataModel.load("foobar.xml");
8404  </code></pre>
8405  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
8406  * <br><br>
8407  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
8408  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
8409  * 
8410  * Note: old style constructor is still suported (container, template, config)
8411  * 
8412  * @constructor
8413  * Create a new View
8414  * @param {Object} config The config object
8415  * 
8416  */
8417 Roo.View = function(config, depreciated_tpl, depreciated_config){
8418     
8419     if (typeof(depreciated_tpl) == 'undefined') {
8420         // new way.. - universal constructor.
8421         Roo.apply(this, config);
8422         this.el  = Roo.get(this.el);
8423     } else {
8424         // old format..
8425         this.el  = Roo.get(config);
8426         this.tpl = depreciated_tpl;
8427         Roo.apply(this, depreciated_config);
8428     }
8429     this.wrapEl  = this.el.wrap().wrap();
8430     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
8431     
8432     
8433     if(typeof(this.tpl) == "string"){
8434         this.tpl = new Roo.Template(this.tpl);
8435     } else {
8436         // support xtype ctors..
8437         this.tpl = new Roo.factory(this.tpl, Roo);
8438     }
8439     
8440     
8441     this.tpl.compile();
8442    
8443   
8444     
8445      
8446     /** @private */
8447     this.addEvents({
8448         /**
8449          * @event beforeclick
8450          * Fires before a click is processed. Returns false to cancel the default action.
8451          * @param {Roo.View} this
8452          * @param {Number} index The index of the target node
8453          * @param {HTMLElement} node The target node
8454          * @param {Roo.EventObject} e The raw event object
8455          */
8456             "beforeclick" : true,
8457         /**
8458          * @event click
8459          * Fires when a template node is clicked.
8460          * @param {Roo.View} this
8461          * @param {Number} index The index of the target node
8462          * @param {HTMLElement} node The target node
8463          * @param {Roo.EventObject} e The raw event object
8464          */
8465             "click" : true,
8466         /**
8467          * @event dblclick
8468          * Fires when a template node is double clicked.
8469          * @param {Roo.View} this
8470          * @param {Number} index The index of the target node
8471          * @param {HTMLElement} node The target node
8472          * @param {Roo.EventObject} e The raw event object
8473          */
8474             "dblclick" : true,
8475         /**
8476          * @event contextmenu
8477          * Fires when a template node is right clicked.
8478          * @param {Roo.View} this
8479          * @param {Number} index The index of the target node
8480          * @param {HTMLElement} node The target node
8481          * @param {Roo.EventObject} e The raw event object
8482          */
8483             "contextmenu" : true,
8484         /**
8485          * @event selectionchange
8486          * Fires when the selected nodes change.
8487          * @param {Roo.View} this
8488          * @param {Array} selections Array of the selected nodes
8489          */
8490             "selectionchange" : true,
8491     
8492         /**
8493          * @event beforeselect
8494          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
8495          * @param {Roo.View} this
8496          * @param {HTMLElement} node The node to be selected
8497          * @param {Array} selections Array of currently selected nodes
8498          */
8499             "beforeselect" : true,
8500         /**
8501          * @event preparedata
8502          * Fires on every row to render, to allow you to change the data.
8503          * @param {Roo.View} this
8504          * @param {Object} data to be rendered (change this)
8505          */
8506           "preparedata" : true
8507           
8508           
8509         });
8510
8511
8512
8513     this.el.on({
8514         "click": this.onClick,
8515         "dblclick": this.onDblClick,
8516         "contextmenu": this.onContextMenu,
8517         scope:this
8518     });
8519
8520     this.selections = [];
8521     this.nodes = [];
8522     this.cmp = new Roo.CompositeElementLite([]);
8523     if(this.store){
8524         this.store = Roo.factory(this.store, Roo.data);
8525         this.setStore(this.store, true);
8526     }
8527     
8528     if ( this.footer && this.footer.xtype) {
8529            
8530          var fctr = this.wrapEl.appendChild(document.createElement("div"));
8531         
8532         this.footer.dataSource = this.store
8533         this.footer.container = fctr;
8534         this.footer = Roo.factory(this.footer, Roo);
8535         fctr.insertFirst(this.el);
8536         
8537         // this is a bit insane - as the paging toolbar seems to detach the el..
8538 //        dom.parentNode.parentNode.parentNode
8539          // they get detached?
8540     }
8541     
8542     
8543     Roo.View.superclass.constructor.call(this);
8544     
8545     
8546 };
8547
8548 Roo.extend(Roo.View, Roo.util.Observable, {
8549     
8550      /**
8551      * @cfg {Roo.data.Store} store Data store to load data from.
8552      */
8553     store : false,
8554     
8555     /**
8556      * @cfg {String|Roo.Element} el The container element.
8557      */
8558     el : '',
8559     
8560     /**
8561      * @cfg {String|Roo.Template} tpl The template used by this View 
8562      */
8563     tpl : false,
8564     /**
8565      * @cfg {String} dataName the named area of the template to use as the data area
8566      *                          Works with domtemplates roo-name="name"
8567      */
8568     dataName: false,
8569     /**
8570      * @cfg {String} selectedClass The css class to add to selected nodes
8571      */
8572     selectedClass : "x-view-selected",
8573      /**
8574      * @cfg {String} emptyText The empty text to show when nothing is loaded.
8575      */
8576     emptyText : "",
8577     
8578     /**
8579      * @cfg {String} text to display on mask (default Loading)
8580      */
8581     mask : false,
8582     /**
8583      * @cfg {Boolean} multiSelect Allow multiple selection
8584      */
8585     multiSelect : false,
8586     /**
8587      * @cfg {Boolean} singleSelect Allow single selection
8588      */
8589     singleSelect:  false,
8590     
8591     /**
8592      * @cfg {Boolean} toggleSelect - selecting 
8593      */
8594     toggleSelect : false,
8595     
8596     /**
8597      * Returns the element this view is bound to.
8598      * @return {Roo.Element}
8599      */
8600     getEl : function(){
8601         return this.wrapEl;
8602     },
8603     
8604     
8605
8606     /**
8607      * Refreshes the view. - called by datachanged on the store. - do not call directly.
8608      */
8609     refresh : function(){
8610         var t = this.tpl;
8611         
8612         // if we are using something like 'domtemplate', then
8613         // the what gets used is:
8614         // t.applySubtemplate(NAME, data, wrapping data..)
8615         // the outer template then get' applied with
8616         //     the store 'extra data'
8617         // and the body get's added to the
8618         //      roo-name="data" node?
8619         //      <span class='roo-tpl-{name}'></span> ?????
8620         
8621         
8622         
8623         this.clearSelections();
8624         this.el.update("");
8625         var html = [];
8626         var records = this.store.getRange();
8627         if(records.length < 1) {
8628             
8629             // is this valid??  = should it render a template??
8630             
8631             this.el.update(this.emptyText);
8632             return;
8633         }
8634         var el = this.el;
8635         if (this.dataName) {
8636             this.el.update(t.apply(this.store.meta)); //????
8637             el = this.el.child('.roo-tpl-' + this.dataName);
8638         }
8639         
8640         for(var i = 0, len = records.length; i < len; i++){
8641             var data = this.prepareData(records[i].data, i, records[i]);
8642             this.fireEvent("preparedata", this, data, i, records[i]);
8643             html[html.length] = Roo.util.Format.trim(
8644                 this.dataName ?
8645                     t.applySubtemplate(this.dataName, data, this.store.meta) :
8646                     t.apply(data)
8647             );
8648         }
8649         
8650         
8651         
8652         el.update(html.join(""));
8653         this.nodes = el.dom.childNodes;
8654         this.updateIndexes(0);
8655     },
8656
8657     /**
8658      * Function to override to reformat the data that is sent to
8659      * the template for each node.
8660      * DEPRICATED - use the preparedata event handler.
8661      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
8662      * a JSON object for an UpdateManager bound view).
8663      */
8664     prepareData : function(data, index, record)
8665     {
8666         this.fireEvent("preparedata", this, data, index, record);
8667         return data;
8668     },
8669
8670     onUpdate : function(ds, record){
8671         this.clearSelections();
8672         var index = this.store.indexOf(record);
8673         var n = this.nodes[index];
8674         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
8675         n.parentNode.removeChild(n);
8676         this.updateIndexes(index, index);
8677     },
8678
8679     
8680     
8681 // --------- FIXME     
8682     onAdd : function(ds, records, index)
8683     {
8684         this.clearSelections();
8685         if(this.nodes.length == 0){
8686             this.refresh();
8687             return;
8688         }
8689         var n = this.nodes[index];
8690         for(var i = 0, len = records.length; i < len; i++){
8691             var d = this.prepareData(records[i].data, i, records[i]);
8692             if(n){
8693                 this.tpl.insertBefore(n, d);
8694             }else{
8695                 
8696                 this.tpl.append(this.el, d);
8697             }
8698         }
8699         this.updateIndexes(index);
8700     },
8701
8702     onRemove : function(ds, record, index){
8703         this.clearSelections();
8704         var el = this.dataName  ?
8705             this.el.child('.roo-tpl-' + this.dataName) :
8706             this.el; 
8707         el.dom.removeChild(this.nodes[index]);
8708         this.updateIndexes(index);
8709     },
8710
8711     /**
8712      * Refresh an individual node.
8713      * @param {Number} index
8714      */
8715     refreshNode : function(index){
8716         this.onUpdate(this.store, this.store.getAt(index));
8717     },
8718
8719     updateIndexes : function(startIndex, endIndex){
8720         var ns = this.nodes;
8721         startIndex = startIndex || 0;
8722         endIndex = endIndex || ns.length - 1;
8723         for(var i = startIndex; i <= endIndex; i++){
8724             ns[i].nodeIndex = i;
8725         }
8726     },
8727
8728     /**
8729      * Changes the data store this view uses and refresh the view.
8730      * @param {Store} store
8731      */
8732     setStore : function(store, initial){
8733         if(!initial && this.store){
8734             this.store.un("datachanged", this.refresh);
8735             this.store.un("add", this.onAdd);
8736             this.store.un("remove", this.onRemove);
8737             this.store.un("update", this.onUpdate);
8738             this.store.un("clear", this.refresh);
8739             this.store.un("beforeload", this.onBeforeLoad);
8740             this.store.un("load", this.onLoad);
8741             this.store.un("loadexception", this.onLoad);
8742         }
8743         if(store){
8744           
8745             store.on("datachanged", this.refresh, this);
8746             store.on("add", this.onAdd, this);
8747             store.on("remove", this.onRemove, this);
8748             store.on("update", this.onUpdate, this);
8749             store.on("clear", this.refresh, this);
8750             store.on("beforeload", this.onBeforeLoad, this);
8751             store.on("load", this.onLoad, this);
8752             store.on("loadexception", this.onLoad, this);
8753         }
8754         
8755         if(store){
8756             this.refresh();
8757         }
8758     },
8759     /**
8760      * onbeforeLoad - masks the loading area.
8761      *
8762      */
8763     onBeforeLoad : function()
8764     {
8765         this.el.update("");
8766         this.el.mask(this.mask ? this.mask : "Loading" ); 
8767     },
8768     onLoad : function ()
8769     {
8770         this.el.unmask();
8771     },
8772     
8773
8774     /**
8775      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
8776      * @param {HTMLElement} node
8777      * @return {HTMLElement} The template node
8778      */
8779     findItemFromChild : function(node){
8780         var el = this.dataName  ?
8781             this.el.child('.roo-tpl-' + this.dataName,true) :
8782             this.el.dom; 
8783         
8784         if(!node || node.parentNode == el){
8785                     return node;
8786             }
8787             var p = node.parentNode;
8788             while(p && p != el){
8789             if(p.parentNode == el){
8790                 return p;
8791             }
8792             p = p.parentNode;
8793         }
8794             return null;
8795     },
8796
8797     /** @ignore */
8798     onClick : function(e){
8799         var item = this.findItemFromChild(e.getTarget());
8800         if(item){
8801             var index = this.indexOf(item);
8802             if(this.onItemClick(item, index, e) !== false){
8803                 this.fireEvent("click", this, index, item, e);
8804             }
8805         }else{
8806             this.clearSelections();
8807         }
8808     },
8809
8810     /** @ignore */
8811     onContextMenu : function(e){
8812         var item = this.findItemFromChild(e.getTarget());
8813         if(item){
8814             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
8815         }
8816     },
8817
8818     /** @ignore */
8819     onDblClick : function(e){
8820         var item = this.findItemFromChild(e.getTarget());
8821         if(item){
8822             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
8823         }
8824     },
8825
8826     onItemClick : function(item, index, e)
8827     {
8828         if(this.fireEvent("beforeclick", this, index, item, e) === false){
8829             return false;
8830         }
8831         if (this.toggleSelect) {
8832             var m = this.isSelected(item) ? 'unselect' : 'select';
8833             Roo.log(m);
8834             var _t = this;
8835             _t[m](item, true, false);
8836             return true;
8837         }
8838         if(this.multiSelect || this.singleSelect){
8839             if(this.multiSelect && e.shiftKey && this.lastSelection){
8840                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
8841             }else{
8842                 this.select(item, this.multiSelect && e.ctrlKey);
8843                 this.lastSelection = item;
8844             }
8845             e.preventDefault();
8846         }
8847         return true;
8848     },
8849
8850     /**
8851      * Get the number of selected nodes.
8852      * @return {Number}
8853      */
8854     getSelectionCount : function(){
8855         return this.selections.length;
8856     },
8857
8858     /**
8859      * Get the currently selected nodes.
8860      * @return {Array} An array of HTMLElements
8861      */
8862     getSelectedNodes : function(){
8863         return this.selections;
8864     },
8865
8866     /**
8867      * Get the indexes of the selected nodes.
8868      * @return {Array}
8869      */
8870     getSelectedIndexes : function(){
8871         var indexes = [], s = this.selections;
8872         for(var i = 0, len = s.length; i < len; i++){
8873             indexes.push(s[i].nodeIndex);
8874         }
8875         return indexes;
8876     },
8877
8878     /**
8879      * Clear all selections
8880      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
8881      */
8882     clearSelections : function(suppressEvent){
8883         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
8884             this.cmp.elements = this.selections;
8885             this.cmp.removeClass(this.selectedClass);
8886             this.selections = [];
8887             if(!suppressEvent){
8888                 this.fireEvent("selectionchange", this, this.selections);
8889             }
8890         }
8891     },
8892
8893     /**
8894      * Returns true if the passed node is selected
8895      * @param {HTMLElement/Number} node The node or node index
8896      * @return {Boolean}
8897      */
8898     isSelected : function(node){
8899         var s = this.selections;
8900         if(s.length < 1){
8901             return false;
8902         }
8903         node = this.getNode(node);
8904         return s.indexOf(node) !== -1;
8905     },
8906
8907     /**
8908      * Selects nodes.
8909      * @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
8910      * @param {Boolean} keepExisting (optional) true to keep existing selections
8911      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
8912      */
8913     select : function(nodeInfo, keepExisting, suppressEvent){
8914         if(nodeInfo instanceof Array){
8915             if(!keepExisting){
8916                 this.clearSelections(true);
8917             }
8918             for(var i = 0, len = nodeInfo.length; i < len; i++){
8919                 this.select(nodeInfo[i], true, true);
8920             }
8921             return;
8922         } 
8923         var node = this.getNode(nodeInfo);
8924         if(!node || this.isSelected(node)){
8925             return; // already selected.
8926         }
8927         if(!keepExisting){
8928             this.clearSelections(true);
8929         }
8930         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
8931             Roo.fly(node).addClass(this.selectedClass);
8932             this.selections.push(node);
8933             if(!suppressEvent){
8934                 this.fireEvent("selectionchange", this, this.selections);
8935             }
8936         }
8937         
8938         
8939     },
8940       /**
8941      * Unselects nodes.
8942      * @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
8943      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
8944      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
8945      */
8946     unselect : function(nodeInfo, keepExisting, suppressEvent)
8947     {
8948         if(nodeInfo instanceof Array){
8949             Roo.each(this.selections, function(s) {
8950                 this.unselect(s, nodeInfo);
8951             }, this);
8952             return;
8953         }
8954         var node = this.getNode(nodeInfo);
8955         if(!node || !this.isSelected(node)){
8956             Roo.log("not selected");
8957             return; // not selected.
8958         }
8959         // fireevent???
8960         var ns = [];
8961         Roo.each(this.selections, function(s) {
8962             if (s == node ) {
8963                 Roo.fly(node).removeClass(this.selectedClass);
8964
8965                 return;
8966             }
8967             ns.push(s);
8968         },this);
8969         
8970         this.selections= ns;
8971         this.fireEvent("selectionchange", this, this.selections);
8972     },
8973
8974     /**
8975      * Gets a template node.
8976      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
8977      * @return {HTMLElement} The node or null if it wasn't found
8978      */
8979     getNode : function(nodeInfo){
8980         if(typeof nodeInfo == "string"){
8981             return document.getElementById(nodeInfo);
8982         }else if(typeof nodeInfo == "number"){
8983             return this.nodes[nodeInfo];
8984         }
8985         return nodeInfo;
8986     },
8987
8988     /**
8989      * Gets a range template nodes.
8990      * @param {Number} startIndex
8991      * @param {Number} endIndex
8992      * @return {Array} An array of nodes
8993      */
8994     getNodes : function(start, end){
8995         var ns = this.nodes;
8996         start = start || 0;
8997         end = typeof end == "undefined" ? ns.length - 1 : end;
8998         var nodes = [];
8999         if(start <= end){
9000             for(var i = start; i <= end; i++){
9001                 nodes.push(ns[i]);
9002             }
9003         } else{
9004             for(var i = start; i >= end; i--){
9005                 nodes.push(ns[i]);
9006             }
9007         }
9008         return nodes;
9009     },
9010
9011     /**
9012      * Finds the index of the passed node
9013      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
9014      * @return {Number} The index of the node or -1
9015      */
9016     indexOf : function(node){
9017         node = this.getNode(node);
9018         if(typeof node.nodeIndex == "number"){
9019             return node.nodeIndex;
9020         }
9021         var ns = this.nodes;
9022         for(var i = 0, len = ns.length; i < len; i++){
9023             if(ns[i] == node){
9024                 return i;
9025             }
9026         }
9027         return -1;
9028     }
9029 });
9030 /*
9031  * Based on:
9032  * Ext JS Library 1.1.1
9033  * Copyright(c) 2006-2007, Ext JS, LLC.
9034  *
9035  * Originally Released Under LGPL - original licence link has changed is not relivant.
9036  *
9037  * Fork - LGPL
9038  * <script type="text/javascript">
9039  */
9040
9041 /**
9042  * @class Roo.JsonView
9043  * @extends Roo.View
9044  * Shortcut class to create a JSON + {@link Roo.UpdateManager} template view. Usage:
9045 <pre><code>
9046 var view = new Roo.JsonView({
9047     container: "my-element",
9048     tpl: '&lt;div id="{id}"&gt;{foo} - {bar}&lt;/div&gt;', // auto create template
9049     multiSelect: true, 
9050     jsonRoot: "data" 
9051 });
9052
9053 // listen for node click?
9054 view.on("click", function(vw, index, node, e){
9055     alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
9056 });
9057
9058 // direct load of JSON data
9059 view.load("foobar.php");
9060
9061 // Example from my blog list
9062 var tpl = new Roo.Template(
9063     '&lt;div class="entry"&gt;' +
9064     '&lt;a class="entry-title" href="{link}"&gt;{title}&lt;/a&gt;' +
9065     "&lt;h4&gt;{date} by {author} | {comments} Comments&lt;/h4&gt;{description}" +
9066     "&lt;/div&gt;&lt;hr /&gt;"
9067 );
9068
9069 var moreView = new Roo.JsonView({
9070     container :  "entry-list", 
9071     template : tpl,
9072     jsonRoot: "posts"
9073 });
9074 moreView.on("beforerender", this.sortEntries, this);
9075 moreView.load({
9076     url: "/blog/get-posts.php",
9077     params: "allposts=true",
9078     text: "Loading Blog Entries..."
9079 });
9080 </code></pre>
9081
9082 * Note: old code is supported with arguments : (container, template, config)
9083
9084
9085  * @constructor
9086  * Create a new JsonView
9087  * 
9088  * @param {Object} config The config object
9089  * 
9090  */
9091 Roo.JsonView = function(config, depreciated_tpl, depreciated_config){
9092     
9093     
9094     Roo.JsonView.superclass.constructor.call(this, config, depreciated_tpl, depreciated_config);
9095
9096     var um = this.el.getUpdateManager();
9097     um.setRenderer(this);
9098     um.on("update", this.onLoad, this);
9099     um.on("failure", this.onLoadException, this);
9100
9101     /**
9102      * @event beforerender
9103      * Fires before rendering of the downloaded JSON data.
9104      * @param {Roo.JsonView} this
9105      * @param {Object} data The JSON data loaded
9106      */
9107     /**
9108      * @event load
9109      * Fires when data is loaded.
9110      * @param {Roo.JsonView} this
9111      * @param {Object} data The JSON data loaded
9112      * @param {Object} response The raw Connect response object
9113      */
9114     /**
9115      * @event loadexception
9116      * Fires when loading fails.
9117      * @param {Roo.JsonView} this
9118      * @param {Object} response The raw Connect response object
9119      */
9120     this.addEvents({
9121         'beforerender' : true,
9122         'load' : true,
9123         'loadexception' : true
9124     });
9125 };
9126 Roo.extend(Roo.JsonView, Roo.View, {
9127     /**
9128      * @type {String} The root property in the loaded JSON object that contains the data
9129      */
9130     jsonRoot : "",
9131
9132     /**
9133      * Refreshes the view.
9134      */
9135     refresh : function(){
9136         this.clearSelections();
9137         this.el.update("");
9138         var html = [];
9139         var o = this.jsonData;
9140         if(o && o.length > 0){
9141             for(var i = 0, len = o.length; i < len; i++){
9142                 var data = this.prepareData(o[i], i, o);
9143                 html[html.length] = this.tpl.apply(data);
9144             }
9145         }else{
9146             html.push(this.emptyText);
9147         }
9148         this.el.update(html.join(""));
9149         this.nodes = this.el.dom.childNodes;
9150         this.updateIndexes(0);
9151     },
9152
9153     /**
9154      * 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.
9155      * @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:
9156      <pre><code>
9157      view.load({
9158          url: "your-url.php",
9159          params: {param1: "foo", param2: "bar"}, // or a URL encoded string
9160          callback: yourFunction,
9161          scope: yourObject, //(optional scope)
9162          discardUrl: false,
9163          nocache: false,
9164          text: "Loading...",
9165          timeout: 30,
9166          scripts: false
9167      });
9168      </code></pre>
9169      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
9170      * 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.
9171      * @param {String/Object} params (optional) The parameters to pass, as either a URL encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
9172      * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9173      * @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.
9174      */
9175     load : function(){
9176         var um = this.el.getUpdateManager();
9177         um.update.apply(um, arguments);
9178     },
9179
9180     render : function(el, response){
9181         this.clearSelections();
9182         this.el.update("");
9183         var o;
9184         try{
9185             o = Roo.util.JSON.decode(response.responseText);
9186             if(this.jsonRoot){
9187                 
9188                 o = o[this.jsonRoot];
9189             }
9190         } catch(e){
9191         }
9192         /**
9193          * The current JSON data or null
9194          */
9195         this.jsonData = o;
9196         this.beforeRender();
9197         this.refresh();
9198     },
9199
9200 /**
9201  * Get the number of records in the current JSON dataset
9202  * @return {Number}
9203  */
9204     getCount : function(){
9205         return this.jsonData ? this.jsonData.length : 0;
9206     },
9207
9208 /**
9209  * Returns the JSON object for the specified node(s)
9210  * @param {HTMLElement/Array} node The node or an array of nodes
9211  * @return {Object/Array} If you pass in an array, you get an array back, otherwise
9212  * you get the JSON object for the node
9213  */
9214     getNodeData : function(node){
9215         if(node instanceof Array){
9216             var data = [];
9217             for(var i = 0, len = node.length; i < len; i++){
9218                 data.push(this.getNodeData(node[i]));
9219             }
9220             return data;
9221         }
9222         return this.jsonData[this.indexOf(node)] || null;
9223     },
9224
9225     beforeRender : function(){
9226         this.snapshot = this.jsonData;
9227         if(this.sortInfo){
9228             this.sort.apply(this, this.sortInfo);
9229         }
9230         this.fireEvent("beforerender", this, this.jsonData);
9231     },
9232
9233     onLoad : function(el, o){
9234         this.fireEvent("load", this, this.jsonData, o);
9235     },
9236
9237     onLoadException : function(el, o){
9238         this.fireEvent("loadexception", this, o);
9239     },
9240
9241 /**
9242  * Filter the data by a specific property.
9243  * @param {String} property A property on your JSON objects
9244  * @param {String/RegExp} value Either string that the property values
9245  * should start with, or a RegExp to test against the property
9246  */
9247     filter : function(property, value){
9248         if(this.jsonData){
9249             var data = [];
9250             var ss = this.snapshot;
9251             if(typeof value == "string"){
9252                 var vlen = value.length;
9253                 if(vlen == 0){
9254                     this.clearFilter();
9255                     return;
9256                 }
9257                 value = value.toLowerCase();
9258                 for(var i = 0, len = ss.length; i < len; i++){
9259                     var o = ss[i];
9260                     if(o[property].substr(0, vlen).toLowerCase() == value){
9261                         data.push(o);
9262                     }
9263                 }
9264             } else if(value.exec){ // regex?
9265                 for(var i = 0, len = ss.length; i < len; i++){
9266                     var o = ss[i];
9267                     if(value.test(o[property])){
9268                         data.push(o);
9269                     }
9270                 }
9271             } else{
9272                 return;
9273             }
9274             this.jsonData = data;
9275             this.refresh();
9276         }
9277     },
9278
9279 /**
9280  * Filter by a function. The passed function will be called with each
9281  * object in the current dataset. If the function returns true the value is kept,
9282  * otherwise it is filtered.
9283  * @param {Function} fn
9284  * @param {Object} scope (optional) The scope of the function (defaults to this JsonView)
9285  */
9286     filterBy : function(fn, scope){
9287         if(this.jsonData){
9288             var data = [];
9289             var ss = this.snapshot;
9290             for(var i = 0, len = ss.length; i < len; i++){
9291                 var o = ss[i];
9292                 if(fn.call(scope || this, o)){
9293                     data.push(o);
9294                 }
9295             }
9296             this.jsonData = data;
9297             this.refresh();
9298         }
9299     },
9300
9301 /**
9302  * Clears the current filter.
9303  */
9304     clearFilter : function(){
9305         if(this.snapshot && this.jsonData != this.snapshot){
9306             this.jsonData = this.snapshot;
9307             this.refresh();
9308         }
9309     },
9310
9311
9312 /**
9313  * Sorts the data for this view and refreshes it.
9314  * @param {String} property A property on your JSON objects to sort on
9315  * @param {String} direction (optional) "desc" or "asc" (defaults to "asc")
9316  * @param {Function} sortType (optional) A function to call to convert the data to a sortable value.
9317  */
9318     sort : function(property, dir, sortType){
9319         this.sortInfo = Array.prototype.slice.call(arguments, 0);
9320         if(this.jsonData){
9321             var p = property;
9322             var dsc = dir && dir.toLowerCase() == "desc";
9323             var f = function(o1, o2){
9324                 var v1 = sortType ? sortType(o1[p]) : o1[p];
9325                 var v2 = sortType ? sortType(o2[p]) : o2[p];
9326                 ;
9327                 if(v1 < v2){
9328                     return dsc ? +1 : -1;
9329                 } else if(v1 > v2){
9330                     return dsc ? -1 : +1;
9331                 } else{
9332                     return 0;
9333                 }
9334             };
9335             this.jsonData.sort(f);
9336             this.refresh();
9337             if(this.jsonData != this.snapshot){
9338                 this.snapshot.sort(f);
9339             }
9340         }
9341     }
9342 });/*
9343  * Based on:
9344  * Ext JS Library 1.1.1
9345  * Copyright(c) 2006-2007, Ext JS, LLC.
9346  *
9347  * Originally Released Under LGPL - original licence link has changed is not relivant.
9348  *
9349  * Fork - LGPL
9350  * <script type="text/javascript">
9351  */
9352  
9353
9354 /**
9355  * @class Roo.ColorPalette
9356  * @extends Roo.Component
9357  * Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
9358  * Here's an example of typical usage:
9359  * <pre><code>
9360 var cp = new Roo.ColorPalette({value:'993300'});  // initial selected color
9361 cp.render('my-div');
9362
9363 cp.on('select', function(palette, selColor){
9364     // do something with selColor
9365 });
9366 </code></pre>
9367  * @constructor
9368  * Create a new ColorPalette
9369  * @param {Object} config The config object
9370  */
9371 Roo.ColorPalette = function(config){
9372     Roo.ColorPalette.superclass.constructor.call(this, config);
9373     this.addEvents({
9374         /**
9375              * @event select
9376              * Fires when a color is selected
9377              * @param {ColorPalette} this
9378              * @param {String} color The 6-digit color hex code (without the # symbol)
9379              */
9380         select: true
9381     });
9382
9383     if(this.handler){
9384         this.on("select", this.handler, this.scope, true);
9385     }
9386 };
9387 Roo.extend(Roo.ColorPalette, Roo.Component, {
9388     /**
9389      * @cfg {String} itemCls
9390      * The CSS class to apply to the containing element (defaults to "x-color-palette")
9391      */
9392     itemCls : "x-color-palette",
9393     /**
9394      * @cfg {String} value
9395      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
9396      * the hex codes are case-sensitive.
9397      */
9398     value : null,
9399     clickEvent:'click',
9400     // private
9401     ctype: "Roo.ColorPalette",
9402
9403     /**
9404      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the selection event
9405      */
9406     allowReselect : false,
9407
9408     /**
9409      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
9410      * of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
9411      * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
9412      * of colors with the width setting until the box is symmetrical.</p>
9413      * <p>You can override individual colors if needed:</p>
9414      * <pre><code>
9415 var cp = new Roo.ColorPalette();
9416 cp.colors[0] = "FF0000";  // change the first box to red
9417 </code></pre>
9418
9419 Or you can provide a custom array of your own for complete control:
9420 <pre><code>
9421 var cp = new Roo.ColorPalette();
9422 cp.colors = ["000000", "993300", "333300"];
9423 </code></pre>
9424      * @type Array
9425      */
9426     colors : [
9427         "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333",
9428         "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080",
9429         "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696",
9430         "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0",
9431         "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF"
9432     ],
9433
9434     // private
9435     onRender : function(container, position){
9436         var t = new Roo.MasterTemplate(
9437             '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>'
9438         );
9439         var c = this.colors;
9440         for(var i = 0, len = c.length; i < len; i++){
9441             t.add([c[i]]);
9442         }
9443         var el = document.createElement("div");
9444         el.className = this.itemCls;
9445         t.overwrite(el);
9446         container.dom.insertBefore(el, position);
9447         this.el = Roo.get(el);
9448         this.el.on(this.clickEvent, this.handleClick,  this, {delegate: "a"});
9449         if(this.clickEvent != 'click'){
9450             this.el.on('click', Roo.emptyFn,  this, {delegate: "a", preventDefault:true});
9451         }
9452     },
9453
9454     // private
9455     afterRender : function(){
9456         Roo.ColorPalette.superclass.afterRender.call(this);
9457         if(this.value){
9458             var s = this.value;
9459             this.value = null;
9460             this.select(s);
9461         }
9462     },
9463
9464     // private
9465     handleClick : function(e, t){
9466         e.preventDefault();
9467         if(!this.disabled){
9468             var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
9469             this.select(c.toUpperCase());
9470         }
9471     },
9472
9473     /**
9474      * Selects the specified color in the palette (fires the select event)
9475      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
9476      */
9477     select : function(color){
9478         color = color.replace("#", "");
9479         if(color != this.value || this.allowReselect){
9480             var el = this.el;
9481             if(this.value){
9482                 el.child("a.color-"+this.value).removeClass("x-color-palette-sel");
9483             }
9484             el.child("a.color-"+color).addClass("x-color-palette-sel");
9485             this.value = color;
9486             this.fireEvent("select", this, color);
9487         }
9488     }
9489 });/*
9490  * Based on:
9491  * Ext JS Library 1.1.1
9492  * Copyright(c) 2006-2007, Ext JS, LLC.
9493  *
9494  * Originally Released Under LGPL - original licence link has changed is not relivant.
9495  *
9496  * Fork - LGPL
9497  * <script type="text/javascript">
9498  */
9499  
9500 /**
9501  * @class Roo.DatePicker
9502  * @extends Roo.Component
9503  * Simple date picker class.
9504  * @constructor
9505  * Create a new DatePicker
9506  * @param {Object} config The config object
9507  */
9508 Roo.DatePicker = function(config){
9509     Roo.DatePicker.superclass.constructor.call(this, config);
9510
9511     this.value = config && config.value ?
9512                  config.value.clearTime() : new Date().clearTime();
9513
9514     this.addEvents({
9515         /**
9516              * @event select
9517              * Fires when a date is selected
9518              * @param {DatePicker} this
9519              * @param {Date} date The selected date
9520              */
9521         'select': true,
9522         /**
9523              * @event monthchange
9524              * Fires when the displayed month changes 
9525              * @param {DatePicker} this
9526              * @param {Date} date The selected month
9527              */
9528         'monthchange': true
9529     });
9530
9531     if(this.handler){
9532         this.on("select", this.handler,  this.scope || this);
9533     }
9534     // build the disabledDatesRE
9535     if(!this.disabledDatesRE && this.disabledDates){
9536         var dd = this.disabledDates;
9537         var re = "(?:";
9538         for(var i = 0; i < dd.length; i++){
9539             re += dd[i];
9540             if(i != dd.length-1) re += "|";
9541         }
9542         this.disabledDatesRE = new RegExp(re + ")");
9543     }
9544 };
9545
9546 Roo.extend(Roo.DatePicker, Roo.Component, {
9547     /**
9548      * @cfg {String} todayText
9549      * The text to display on the button that selects the current date (defaults to "Today")
9550      */
9551     todayText : "Today",
9552     /**
9553      * @cfg {String} okText
9554      * The text to display on the ok button
9555      */
9556     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
9557     /**
9558      * @cfg {String} cancelText
9559      * The text to display on the cancel button
9560      */
9561     cancelText : "Cancel",
9562     /**
9563      * @cfg {String} todayTip
9564      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
9565      */
9566     todayTip : "{0} (Spacebar)",
9567     /**
9568      * @cfg {Date} minDate
9569      * Minimum allowable date (JavaScript date object, defaults to null)
9570      */
9571     minDate : null,
9572     /**
9573      * @cfg {Date} maxDate
9574      * Maximum allowable date (JavaScript date object, defaults to null)
9575      */
9576     maxDate : null,
9577     /**
9578      * @cfg {String} minText
9579      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
9580      */
9581     minText : "This date is before the minimum date",
9582     /**
9583      * @cfg {String} maxText
9584      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
9585      */
9586     maxText : "This date is after the maximum date",
9587     /**
9588      * @cfg {String} format
9589      * The default date format string which can be overriden for localization support.  The format must be
9590      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
9591      */
9592     format : "m/d/y",
9593     /**
9594      * @cfg {Array} disabledDays
9595      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
9596      */
9597     disabledDays : null,
9598     /**
9599      * @cfg {String} disabledDaysText
9600      * The tooltip to display when the date falls on a disabled day (defaults to "")
9601      */
9602     disabledDaysText : "",
9603     /**
9604      * @cfg {RegExp} disabledDatesRE
9605      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
9606      */
9607     disabledDatesRE : null,
9608     /**
9609      * @cfg {String} disabledDatesText
9610      * The tooltip text to display when the date falls on a disabled date (defaults to "")
9611      */
9612     disabledDatesText : "",
9613     /**
9614      * @cfg {Boolean} constrainToViewport
9615      * True to constrain the date picker to the viewport (defaults to true)
9616      */
9617     constrainToViewport : true,
9618     /**
9619      * @cfg {Array} monthNames
9620      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
9621      */
9622     monthNames : Date.monthNames,
9623     /**
9624      * @cfg {Array} dayNames
9625      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
9626      */
9627     dayNames : Date.dayNames,
9628     /**
9629      * @cfg {String} nextText
9630      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
9631      */
9632     nextText: 'Next Month (Control+Right)',
9633     /**
9634      * @cfg {String} prevText
9635      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
9636      */
9637     prevText: 'Previous Month (Control+Left)',
9638     /**
9639      * @cfg {String} monthYearText
9640      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
9641      */
9642     monthYearText: 'Choose a month (Control+Up/Down to move years)',
9643     /**
9644      * @cfg {Number} startDay
9645      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
9646      */
9647     startDay : 0,
9648     /**
9649      * @cfg {Bool} showClear
9650      * Show a clear button (usefull for date form elements that can be blank.)
9651      */
9652     
9653     showClear: false,
9654     
9655     /**
9656      * Sets the value of the date field
9657      * @param {Date} value The date to set
9658      */
9659     setValue : function(value){
9660         var old = this.value;
9661         
9662         if (typeof(value) == 'string') {
9663          
9664             value = Date.parseDate(value, this.format);
9665         }
9666         if (!value) {
9667             value = new Date();
9668         }
9669         
9670         this.value = value.clearTime(true);
9671         if(this.el){
9672             this.update(this.value);
9673         }
9674     },
9675
9676     /**
9677      * Gets the current selected value of the date field
9678      * @return {Date} The selected date
9679      */
9680     getValue : function(){
9681         return this.value;
9682     },
9683
9684     // private
9685     focus : function(){
9686         if(this.el){
9687             this.update(this.activeDate);
9688         }
9689     },
9690
9691     // privateval
9692     onRender : function(container, position){
9693         
9694         var m = [
9695              '<table cellspacing="0">',
9696                 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
9697                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
9698         var dn = this.dayNames;
9699         for(var i = 0; i < 7; i++){
9700             var d = this.startDay+i;
9701             if(d > 6){
9702                 d = d-7;
9703             }
9704             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
9705         }
9706         m[m.length] = "</tr></thead><tbody><tr>";
9707         for(var i = 0; i < 42; i++) {
9708             if(i % 7 == 0 && i != 0){
9709                 m[m.length] = "</tr><tr>";
9710             }
9711             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
9712         }
9713         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
9714             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
9715
9716         var el = document.createElement("div");
9717         el.className = "x-date-picker";
9718         el.innerHTML = m.join("");
9719
9720         container.dom.insertBefore(el, position);
9721
9722         this.el = Roo.get(el);
9723         this.eventEl = Roo.get(el.firstChild);
9724
9725         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
9726             handler: this.showPrevMonth,
9727             scope: this,
9728             preventDefault:true,
9729             stopDefault:true
9730         });
9731
9732         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
9733             handler: this.showNextMonth,
9734             scope: this,
9735             preventDefault:true,
9736             stopDefault:true
9737         });
9738
9739         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
9740
9741         this.monthPicker = this.el.down('div.x-date-mp');
9742         this.monthPicker.enableDisplayMode('block');
9743         
9744         var kn = new Roo.KeyNav(this.eventEl, {
9745             "left" : function(e){
9746                 e.ctrlKey ?
9747                     this.showPrevMonth() :
9748                     this.update(this.activeDate.add("d", -1));
9749             },
9750
9751             "right" : function(e){
9752                 e.ctrlKey ?
9753                     this.showNextMonth() :
9754                     this.update(this.activeDate.add("d", 1));
9755             },
9756
9757             "up" : function(e){
9758                 e.ctrlKey ?
9759                     this.showNextYear() :
9760                     this.update(this.activeDate.add("d", -7));
9761             },
9762
9763             "down" : function(e){
9764                 e.ctrlKey ?
9765                     this.showPrevYear() :
9766                     this.update(this.activeDate.add("d", 7));
9767             },
9768
9769             "pageUp" : function(e){
9770                 this.showNextMonth();
9771             },
9772
9773             "pageDown" : function(e){
9774                 this.showPrevMonth();
9775             },
9776
9777             "enter" : function(e){
9778                 e.stopPropagation();
9779                 return true;
9780             },
9781
9782             scope : this
9783         });
9784
9785         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
9786
9787         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
9788
9789         this.el.unselectable();
9790         
9791         this.cells = this.el.select("table.x-date-inner tbody td");
9792         this.textNodes = this.el.query("table.x-date-inner tbody span");
9793
9794         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
9795             text: "&#160;",
9796             tooltip: this.monthYearText
9797         });
9798
9799         this.mbtn.on('click', this.showMonthPicker, this);
9800         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
9801
9802
9803         var today = (new Date()).dateFormat(this.format);
9804         
9805         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
9806         if (this.showClear) {
9807             baseTb.add( new Roo.Toolbar.Fill());
9808         }
9809         baseTb.add({
9810             text: String.format(this.todayText, today),
9811             tooltip: String.format(this.todayTip, today),
9812             handler: this.selectToday,
9813             scope: this
9814         });
9815         
9816         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
9817             
9818         //});
9819         if (this.showClear) {
9820             
9821             baseTb.add( new Roo.Toolbar.Fill());
9822             baseTb.add({
9823                 text: '&#160;',
9824                 cls: 'x-btn-icon x-btn-clear',
9825                 handler: function() {
9826                     //this.value = '';
9827                     this.fireEvent("select", this, '');
9828                 },
9829                 scope: this
9830             });
9831         }
9832         
9833         
9834         if(Roo.isIE){
9835             this.el.repaint();
9836         }
9837         this.update(this.value);
9838     },
9839
9840     createMonthPicker : function(){
9841         if(!this.monthPicker.dom.firstChild){
9842             var buf = ['<table border="0" cellspacing="0">'];
9843             for(var i = 0; i < 6; i++){
9844                 buf.push(
9845                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
9846                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
9847                     i == 0 ?
9848                     '<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>' :
9849                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
9850                 );
9851             }
9852             buf.push(
9853                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
9854                     this.okText,
9855                     '</button><button type="button" class="x-date-mp-cancel">',
9856                     this.cancelText,
9857                     '</button></td></tr>',
9858                 '</table>'
9859             );
9860             this.monthPicker.update(buf.join(''));
9861             this.monthPicker.on('click', this.onMonthClick, this);
9862             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
9863
9864             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
9865             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
9866
9867             this.mpMonths.each(function(m, a, i){
9868                 i += 1;
9869                 if((i%2) == 0){
9870                     m.dom.xmonth = 5 + Math.round(i * .5);
9871                 }else{
9872                     m.dom.xmonth = Math.round((i-1) * .5);
9873                 }
9874             });
9875         }
9876     },
9877
9878     showMonthPicker : function(){
9879         this.createMonthPicker();
9880         var size = this.el.getSize();
9881         this.monthPicker.setSize(size);
9882         this.monthPicker.child('table').setSize(size);
9883
9884         this.mpSelMonth = (this.activeDate || this.value).getMonth();
9885         this.updateMPMonth(this.mpSelMonth);
9886         this.mpSelYear = (this.activeDate || this.value).getFullYear();
9887         this.updateMPYear(this.mpSelYear);
9888
9889         this.monthPicker.slideIn('t', {duration:.2});
9890     },
9891
9892     updateMPYear : function(y){
9893         this.mpyear = y;
9894         var ys = this.mpYears.elements;
9895         for(var i = 1; i <= 10; i++){
9896             var td = ys[i-1], y2;
9897             if((i%2) == 0){
9898                 y2 = y + Math.round(i * .5);
9899                 td.firstChild.innerHTML = y2;
9900                 td.xyear = y2;
9901             }else{
9902                 y2 = y - (5-Math.round(i * .5));
9903                 td.firstChild.innerHTML = y2;
9904                 td.xyear = y2;
9905             }
9906             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
9907         }
9908     },
9909
9910     updateMPMonth : function(sm){
9911         this.mpMonths.each(function(m, a, i){
9912             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
9913         });
9914     },
9915
9916     selectMPMonth: function(m){
9917         
9918     },
9919
9920     onMonthClick : function(e, t){
9921         e.stopEvent();
9922         var el = new Roo.Element(t), pn;
9923         if(el.is('button.x-date-mp-cancel')){
9924             this.hideMonthPicker();
9925         }
9926         else if(el.is('button.x-date-mp-ok')){
9927             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
9928             this.hideMonthPicker();
9929         }
9930         else if(pn = el.up('td.x-date-mp-month', 2)){
9931             this.mpMonths.removeClass('x-date-mp-sel');
9932             pn.addClass('x-date-mp-sel');
9933             this.mpSelMonth = pn.dom.xmonth;
9934         }
9935         else if(pn = el.up('td.x-date-mp-year', 2)){
9936             this.mpYears.removeClass('x-date-mp-sel');
9937             pn.addClass('x-date-mp-sel');
9938             this.mpSelYear = pn.dom.xyear;
9939         }
9940         else if(el.is('a.x-date-mp-prev')){
9941             this.updateMPYear(this.mpyear-10);
9942         }
9943         else if(el.is('a.x-date-mp-next')){
9944             this.updateMPYear(this.mpyear+10);
9945         }
9946     },
9947
9948     onMonthDblClick : function(e, t){
9949         e.stopEvent();
9950         var el = new Roo.Element(t), pn;
9951         if(pn = el.up('td.x-date-mp-month', 2)){
9952             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
9953             this.hideMonthPicker();
9954         }
9955         else if(pn = el.up('td.x-date-mp-year', 2)){
9956             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
9957             this.hideMonthPicker();
9958         }
9959     },
9960
9961     hideMonthPicker : function(disableAnim){
9962         if(this.monthPicker){
9963             if(disableAnim === true){
9964                 this.monthPicker.hide();
9965             }else{
9966                 this.monthPicker.slideOut('t', {duration:.2});
9967             }
9968         }
9969     },
9970
9971     // private
9972     showPrevMonth : function(e){
9973         this.update(this.activeDate.add("mo", -1));
9974     },
9975
9976     // private
9977     showNextMonth : function(e){
9978         this.update(this.activeDate.add("mo", 1));
9979     },
9980
9981     // private
9982     showPrevYear : function(){
9983         this.update(this.activeDate.add("y", -1));
9984     },
9985
9986     // private
9987     showNextYear : function(){
9988         this.update(this.activeDate.add("y", 1));
9989     },
9990
9991     // private
9992     handleMouseWheel : function(e){
9993         var delta = e.getWheelDelta();
9994         if(delta > 0){
9995             this.showPrevMonth();
9996             e.stopEvent();
9997         } else if(delta < 0){
9998             this.showNextMonth();
9999             e.stopEvent();
10000         }
10001     },
10002
10003     // private
10004     handleDateClick : function(e, t){
10005         e.stopEvent();
10006         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
10007             this.setValue(new Date(t.dateValue));
10008             this.fireEvent("select", this, this.value);
10009         }
10010     },
10011
10012     // private
10013     selectToday : function(){
10014         this.setValue(new Date().clearTime());
10015         this.fireEvent("select", this, this.value);
10016     },
10017
10018     // private
10019     update : function(date)
10020     {
10021         var vd = this.activeDate;
10022         this.activeDate = date;
10023         if(vd && this.el){
10024             var t = date.getTime();
10025             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
10026                 this.cells.removeClass("x-date-selected");
10027                 this.cells.each(function(c){
10028                    if(c.dom.firstChild.dateValue == t){
10029                        c.addClass("x-date-selected");
10030                        setTimeout(function(){
10031                             try{c.dom.firstChild.focus();}catch(e){}
10032                        }, 50);
10033                        return false;
10034                    }
10035                 });
10036                 return;
10037             }
10038         }
10039         
10040         var days = date.getDaysInMonth();
10041         var firstOfMonth = date.getFirstDateOfMonth();
10042         var startingPos = firstOfMonth.getDay()-this.startDay;
10043
10044         if(startingPos <= this.startDay){
10045             startingPos += 7;
10046         }
10047
10048         var pm = date.add("mo", -1);
10049         var prevStart = pm.getDaysInMonth()-startingPos;
10050
10051         var cells = this.cells.elements;
10052         var textEls = this.textNodes;
10053         days += startingPos;
10054
10055         // convert everything to numbers so it's fast
10056         var day = 86400000;
10057         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
10058         var today = new Date().clearTime().getTime();
10059         var sel = date.clearTime().getTime();
10060         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
10061         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
10062         var ddMatch = this.disabledDatesRE;
10063         var ddText = this.disabledDatesText;
10064         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
10065         var ddaysText = this.disabledDaysText;
10066         var format = this.format;
10067
10068         var setCellClass = function(cal, cell){
10069             cell.title = "";
10070             var t = d.getTime();
10071             cell.firstChild.dateValue = t;
10072             if(t == today){
10073                 cell.className += " x-date-today";
10074                 cell.title = cal.todayText;
10075             }
10076             if(t == sel){
10077                 cell.className += " x-date-selected";
10078                 setTimeout(function(){
10079                     try{cell.firstChild.focus();}catch(e){}
10080                 }, 50);
10081             }
10082             // disabling
10083             if(t < min) {
10084                 cell.className = " x-date-disabled";
10085                 cell.title = cal.minText;
10086                 return;
10087             }
10088             if(t > max) {
10089                 cell.className = " x-date-disabled";
10090                 cell.title = cal.maxText;
10091                 return;
10092             }
10093             if(ddays){
10094                 if(ddays.indexOf(d.getDay()) != -1){
10095                     cell.title = ddaysText;
10096                     cell.className = " x-date-disabled";
10097                 }
10098             }
10099             if(ddMatch && format){
10100                 var fvalue = d.dateFormat(format);
10101                 if(ddMatch.test(fvalue)){
10102                     cell.title = ddText.replace("%0", fvalue);
10103                     cell.className = " x-date-disabled";
10104                 }
10105             }
10106         };
10107
10108         var i = 0;
10109         for(; i < startingPos; i++) {
10110             textEls[i].innerHTML = (++prevStart);
10111             d.setDate(d.getDate()+1);
10112             cells[i].className = "x-date-prevday";
10113             setCellClass(this, cells[i]);
10114         }
10115         for(; i < days; i++){
10116             intDay = i - startingPos + 1;
10117             textEls[i].innerHTML = (intDay);
10118             d.setDate(d.getDate()+1);
10119             cells[i].className = "x-date-active";
10120             setCellClass(this, cells[i]);
10121         }
10122         var extraDays = 0;
10123         for(; i < 42; i++) {
10124              textEls[i].innerHTML = (++extraDays);
10125              d.setDate(d.getDate()+1);
10126              cells[i].className = "x-date-nextday";
10127              setCellClass(this, cells[i]);
10128         }
10129
10130         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
10131         this.fireEvent('monthchange', this, date);
10132         
10133         if(!this.internalRender){
10134             var main = this.el.dom.firstChild;
10135             var w = main.offsetWidth;
10136             this.el.setWidth(w + this.el.getBorderWidth("lr"));
10137             Roo.fly(main).setWidth(w);
10138             this.internalRender = true;
10139             // opera does not respect the auto grow header center column
10140             // then, after it gets a width opera refuses to recalculate
10141             // without a second pass
10142             if(Roo.isOpera && !this.secondPass){
10143                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
10144                 this.secondPass = true;
10145                 this.update.defer(10, this, [date]);
10146             }
10147         }
10148         
10149         
10150     }
10151 });        /*
10152  * Based on:
10153  * Ext JS Library 1.1.1
10154  * Copyright(c) 2006-2007, Ext JS, LLC.
10155  *
10156  * Originally Released Under LGPL - original licence link has changed is not relivant.
10157  *
10158  * Fork - LGPL
10159  * <script type="text/javascript">
10160  */
10161 /**
10162  * @class Roo.TabPanel
10163  * @extends Roo.util.Observable
10164  * A lightweight tab container.
10165  * <br><br>
10166  * Usage:
10167  * <pre><code>
10168 // basic tabs 1, built from existing content
10169 var tabs = new Roo.TabPanel("tabs1");
10170 tabs.addTab("script", "View Script");
10171 tabs.addTab("markup", "View Markup");
10172 tabs.activate("script");
10173
10174 // more advanced tabs, built from javascript
10175 var jtabs = new Roo.TabPanel("jtabs");
10176 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
10177
10178 // set up the UpdateManager
10179 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
10180 var updater = tab2.getUpdateManager();
10181 updater.setDefaultUrl("ajax1.htm");
10182 tab2.on('activate', updater.refresh, updater, true);
10183
10184 // Use setUrl for Ajax loading
10185 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
10186 tab3.setUrl("ajax2.htm", null, true);
10187
10188 // Disabled tab
10189 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
10190 tab4.disable();
10191
10192 jtabs.activate("jtabs-1");
10193  * </code></pre>
10194  * @constructor
10195  * Create a new TabPanel.
10196  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
10197  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
10198  */
10199 Roo.TabPanel = function(container, config){
10200     /**
10201     * The container element for this TabPanel.
10202     * @type Roo.Element
10203     */
10204     this.el = Roo.get(container, true);
10205     if(config){
10206         if(typeof config == "boolean"){
10207             this.tabPosition = config ? "bottom" : "top";
10208         }else{
10209             Roo.apply(this, config);
10210         }
10211     }
10212     if(this.tabPosition == "bottom"){
10213         this.bodyEl = Roo.get(this.createBody(this.el.dom));
10214         this.el.addClass("x-tabs-bottom");
10215     }
10216     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
10217     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
10218     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
10219     if(Roo.isIE){
10220         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
10221     }
10222     if(this.tabPosition != "bottom"){
10223         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
10224          * @type Roo.Element
10225          */
10226         this.bodyEl = Roo.get(this.createBody(this.el.dom));
10227         this.el.addClass("x-tabs-top");
10228     }
10229     this.items = [];
10230
10231     this.bodyEl.setStyle("position", "relative");
10232
10233     this.active = null;
10234     this.activateDelegate = this.activate.createDelegate(this);
10235
10236     this.addEvents({
10237         /**
10238          * @event tabchange
10239          * Fires when the active tab changes
10240          * @param {Roo.TabPanel} this
10241          * @param {Roo.TabPanelItem} activePanel The new active tab
10242          */
10243         "tabchange": true,
10244         /**
10245          * @event beforetabchange
10246          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
10247          * @param {Roo.TabPanel} this
10248          * @param {Object} e Set cancel to true on this object to cancel the tab change
10249          * @param {Roo.TabPanelItem} tab The tab being changed to
10250          */
10251         "beforetabchange" : true
10252     });
10253
10254     Roo.EventManager.onWindowResize(this.onResize, this);
10255     this.cpad = this.el.getPadding("lr");
10256     this.hiddenCount = 0;
10257
10258
10259     // toolbar on the tabbar support...
10260     if (this.toolbar) {
10261         var tcfg = this.toolbar;
10262         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
10263         this.toolbar = new Roo.Toolbar(tcfg);
10264         if (Roo.isSafari) {
10265             var tbl = tcfg.container.child('table', true);
10266             tbl.setAttribute('width', '100%');
10267         }
10268         
10269     }
10270    
10271
10272
10273     Roo.TabPanel.superclass.constructor.call(this);
10274 };
10275
10276 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
10277     /*
10278      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
10279      */
10280     tabPosition : "top",
10281     /*
10282      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
10283      */
10284     currentTabWidth : 0,
10285     /*
10286      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
10287      */
10288     minTabWidth : 40,
10289     /*
10290      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
10291      */
10292     maxTabWidth : 250,
10293     /*
10294      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
10295      */
10296     preferredTabWidth : 175,
10297     /*
10298      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
10299      */
10300     resizeTabs : false,
10301     /*
10302      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
10303      */
10304     monitorResize : true,
10305     /*
10306      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
10307      */
10308     toolbar : false,
10309
10310     /**
10311      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
10312      * @param {String} id The id of the div to use <b>or create</b>
10313      * @param {String} text The text for the tab
10314      * @param {String} content (optional) Content to put in the TabPanelItem body
10315      * @param {Boolean} closable (optional) True to create a close icon on the tab
10316      * @return {Roo.TabPanelItem} The created TabPanelItem
10317      */
10318     addTab : function(id, text, content, closable){
10319         var item = new Roo.TabPanelItem(this, id, text, closable);
10320         this.addTabItem(item);
10321         if(content){
10322             item.setContent(content);
10323         }
10324         return item;
10325     },
10326
10327     /**
10328      * Returns the {@link Roo.TabPanelItem} with the specified id/index
10329      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
10330      * @return {Roo.TabPanelItem}
10331      */
10332     getTab : function(id){
10333         return this.items[id];
10334     },
10335
10336     /**
10337      * Hides the {@link Roo.TabPanelItem} with the specified id/index
10338      * @param {String/Number} id The id or index of the TabPanelItem to hide.
10339      */
10340     hideTab : function(id){
10341         var t = this.items[id];
10342         if(!t.isHidden()){
10343            t.setHidden(true);
10344            this.hiddenCount++;
10345            this.autoSizeTabs();
10346         }
10347     },
10348
10349     /**
10350      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
10351      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
10352      */
10353     unhideTab : function(id){
10354         var t = this.items[id];
10355         if(t.isHidden()){
10356            t.setHidden(false);
10357            this.hiddenCount--;
10358            this.autoSizeTabs();
10359         }
10360     },
10361
10362     /**
10363      * Adds an existing {@link Roo.TabPanelItem}.
10364      * @param {Roo.TabPanelItem} item The TabPanelItem to add
10365      */
10366     addTabItem : function(item){
10367         this.items[item.id] = item;
10368         this.items.push(item);
10369         if(this.resizeTabs){
10370            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
10371            this.autoSizeTabs();
10372         }else{
10373             item.autoSize();
10374         }
10375     },
10376
10377     /**
10378      * Removes a {@link Roo.TabPanelItem}.
10379      * @param {String/Number} id The id or index of the TabPanelItem to remove.
10380      */
10381     removeTab : function(id){
10382         var items = this.items;
10383         var tab = items[id];
10384         if(!tab) { return; }
10385         var index = items.indexOf(tab);
10386         if(this.active == tab && items.length > 1){
10387             var newTab = this.getNextAvailable(index);
10388             if(newTab) {
10389                 newTab.activate();
10390             }
10391         }
10392         this.stripEl.dom.removeChild(tab.pnode.dom);
10393         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
10394             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
10395         }
10396         items.splice(index, 1);
10397         delete this.items[tab.id];
10398         tab.fireEvent("close", tab);
10399         tab.purgeListeners();
10400         this.autoSizeTabs();
10401     },
10402
10403     getNextAvailable : function(start){
10404         var items = this.items;
10405         var index = start;
10406         // look for a next tab that will slide over to
10407         // replace the one being removed
10408         while(index < items.length){
10409             var item = items[++index];
10410             if(item && !item.isHidden()){
10411                 return item;
10412             }
10413         }
10414         // if one isn't found select the previous tab (on the left)
10415         index = start;
10416         while(index >= 0){
10417             var item = items[--index];
10418             if(item && !item.isHidden()){
10419                 return item;
10420             }
10421         }
10422         return null;
10423     },
10424
10425     /**
10426      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
10427      * @param {String/Number} id The id or index of the TabPanelItem to disable.
10428      */
10429     disableTab : function(id){
10430         var tab = this.items[id];
10431         if(tab && this.active != tab){
10432             tab.disable();
10433         }
10434     },
10435
10436     /**
10437      * Enables a {@link Roo.TabPanelItem} that is disabled.
10438      * @param {String/Number} id The id or index of the TabPanelItem to enable.
10439      */
10440     enableTab : function(id){
10441         var tab = this.items[id];
10442         tab.enable();
10443     },
10444
10445     /**
10446      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
10447      * @param {String/Number} id The id or index of the TabPanelItem to activate.
10448      * @return {Roo.TabPanelItem} The TabPanelItem.
10449      */
10450     activate : function(id){
10451         var tab = this.items[id];
10452         if(!tab){
10453             return null;
10454         }
10455         if(tab == this.active || tab.disabled){
10456             return tab;
10457         }
10458         var e = {};
10459         this.fireEvent("beforetabchange", this, e, tab);
10460         if(e.cancel !== true && !tab.disabled){
10461             if(this.active){
10462                 this.active.hide();
10463             }
10464             this.active = this.items[id];
10465             this.active.show();
10466             this.fireEvent("tabchange", this, this.active);
10467         }
10468         return tab;
10469     },
10470
10471     /**
10472      * Gets the active {@link Roo.TabPanelItem}.
10473      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
10474      */
10475     getActiveTab : function(){
10476         return this.active;
10477     },
10478
10479     /**
10480      * Updates the tab body element to fit the height of the container element
10481      * for overflow scrolling
10482      * @param {Number} targetHeight (optional) Override the starting height from the elements height
10483      */
10484     syncHeight : function(targetHeight){
10485         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
10486         var bm = this.bodyEl.getMargins();
10487         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
10488         this.bodyEl.setHeight(newHeight);
10489         return newHeight;
10490     },
10491
10492     onResize : function(){
10493         if(this.monitorResize){
10494             this.autoSizeTabs();
10495         }
10496     },
10497
10498     /**
10499      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
10500      */
10501     beginUpdate : function(){
10502         this.updating = true;
10503     },
10504
10505     /**
10506      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
10507      */
10508     endUpdate : function(){
10509         this.updating = false;
10510         this.autoSizeTabs();
10511     },
10512
10513     /**
10514      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
10515      */
10516     autoSizeTabs : function(){
10517         var count = this.items.length;
10518         var vcount = count - this.hiddenCount;
10519         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
10520         var w = Math.max(this.el.getWidth() - this.cpad, 10);
10521         var availWidth = Math.floor(w / vcount);
10522         var b = this.stripBody;
10523         if(b.getWidth() > w){
10524             var tabs = this.items;
10525             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
10526             if(availWidth < this.minTabWidth){
10527                 /*if(!this.sleft){    // incomplete scrolling code
10528                     this.createScrollButtons();
10529                 }
10530                 this.showScroll();
10531                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
10532             }
10533         }else{
10534             if(this.currentTabWidth < this.preferredTabWidth){
10535                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
10536             }
10537         }
10538     },
10539
10540     /**
10541      * Returns the number of tabs in this TabPanel.
10542      * @return {Number}
10543      */
10544      getCount : function(){
10545          return this.items.length;
10546      },
10547
10548     /**
10549      * Resizes all the tabs to the passed width
10550      * @param {Number} The new width
10551      */
10552     setTabWidth : function(width){
10553         this.currentTabWidth = width;
10554         for(var i = 0, len = this.items.length; i < len; i++) {
10555                 if(!this.items[i].isHidden())this.items[i].setWidth(width);
10556         }
10557     },
10558
10559     /**
10560      * Destroys this TabPanel
10561      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
10562      */
10563     destroy : function(removeEl){
10564         Roo.EventManager.removeResizeListener(this.onResize, this);
10565         for(var i = 0, len = this.items.length; i < len; i++){
10566             this.items[i].purgeListeners();
10567         }
10568         if(removeEl === true){
10569             this.el.update("");
10570             this.el.remove();
10571         }
10572     }
10573 });
10574
10575 /**
10576  * @class Roo.TabPanelItem
10577  * @extends Roo.util.Observable
10578  * Represents an individual item (tab plus body) in a TabPanel.
10579  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
10580  * @param {String} id The id of this TabPanelItem
10581  * @param {String} text The text for the tab of this TabPanelItem
10582  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
10583  */
10584 Roo.TabPanelItem = function(tabPanel, id, text, closable){
10585     /**
10586      * The {@link Roo.TabPanel} this TabPanelItem belongs to
10587      * @type Roo.TabPanel
10588      */
10589     this.tabPanel = tabPanel;
10590     /**
10591      * The id for this TabPanelItem
10592      * @type String
10593      */
10594     this.id = id;
10595     /** @private */
10596     this.disabled = false;
10597     /** @private */
10598     this.text = text;
10599     /** @private */
10600     this.loaded = false;
10601     this.closable = closable;
10602
10603     /**
10604      * The body element for this TabPanelItem.
10605      * @type Roo.Element
10606      */
10607     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
10608     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
10609     this.bodyEl.setStyle("display", "block");
10610     this.bodyEl.setStyle("zoom", "1");
10611     this.hideAction();
10612
10613     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
10614     /** @private */
10615     this.el = Roo.get(els.el, true);
10616     this.inner = Roo.get(els.inner, true);
10617     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
10618     this.pnode = Roo.get(els.el.parentNode, true);
10619     this.el.on("mousedown", this.onTabMouseDown, this);
10620     this.el.on("click", this.onTabClick, this);
10621     /** @private */
10622     if(closable){
10623         var c = Roo.get(els.close, true);
10624         c.dom.title = this.closeText;
10625         c.addClassOnOver("close-over");
10626         c.on("click", this.closeClick, this);
10627      }
10628
10629     this.addEvents({
10630          /**
10631          * @event activate
10632          * Fires when this tab becomes the active tab.
10633          * @param {Roo.TabPanel} tabPanel The parent TabPanel
10634          * @param {Roo.TabPanelItem} this
10635          */
10636         "activate": true,
10637         /**
10638          * @event beforeclose
10639          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
10640          * @param {Roo.TabPanelItem} this
10641          * @param {Object} e Set cancel to true on this object to cancel the close.
10642          */
10643         "beforeclose": true,
10644         /**
10645          * @event close
10646          * Fires when this tab is closed.
10647          * @param {Roo.TabPanelItem} this
10648          */
10649          "close": true,
10650         /**
10651          * @event deactivate
10652          * Fires when this tab is no longer the active tab.
10653          * @param {Roo.TabPanel} tabPanel The parent TabPanel
10654          * @param {Roo.TabPanelItem} this
10655          */
10656          "deactivate" : true
10657     });
10658     this.hidden = false;
10659
10660     Roo.TabPanelItem.superclass.constructor.call(this);
10661 };
10662
10663 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
10664     purgeListeners : function(){
10665        Roo.util.Observable.prototype.purgeListeners.call(this);
10666        this.el.removeAllListeners();
10667     },
10668     /**
10669      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
10670      */
10671     show : function(){
10672         this.pnode.addClass("on");
10673         this.showAction();
10674         if(Roo.isOpera){
10675             this.tabPanel.stripWrap.repaint();
10676         }
10677         this.fireEvent("activate", this.tabPanel, this);
10678     },
10679
10680     /**
10681      * Returns true if this tab is the active tab.
10682      * @return {Boolean}
10683      */
10684     isActive : function(){
10685         return this.tabPanel.getActiveTab() == this;
10686     },
10687
10688     /**
10689      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
10690      */
10691     hide : function(){
10692         this.pnode.removeClass("on");
10693         this.hideAction();
10694         this.fireEvent("deactivate", this.tabPanel, this);
10695     },
10696
10697     hideAction : function(){
10698         this.bodyEl.hide();
10699         this.bodyEl.setStyle("position", "absolute");
10700         this.bodyEl.setLeft("-20000px");
10701         this.bodyEl.setTop("-20000px");
10702     },
10703
10704     showAction : function(){
10705         this.bodyEl.setStyle("position", "relative");
10706         this.bodyEl.setTop("");
10707         this.bodyEl.setLeft("");
10708         this.bodyEl.show();
10709     },
10710
10711     /**
10712      * Set the tooltip for the tab.
10713      * @param {String} tooltip The tab's tooltip
10714      */
10715     setTooltip : function(text){
10716         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
10717             this.textEl.dom.qtip = text;
10718             this.textEl.dom.removeAttribute('title');
10719         }else{
10720             this.textEl.dom.title = text;
10721         }
10722     },
10723
10724     onTabClick : function(e){
10725         e.preventDefault();
10726         this.tabPanel.activate(this.id);
10727     },
10728
10729     onTabMouseDown : function(e){
10730         e.preventDefault();
10731         this.tabPanel.activate(this.id);
10732     },
10733
10734     getWidth : function(){
10735         return this.inner.getWidth();
10736     },
10737
10738     setWidth : function(width){
10739         var iwidth = width - this.pnode.getPadding("lr");
10740         this.inner.setWidth(iwidth);
10741         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
10742         this.pnode.setWidth(width);
10743     },
10744
10745     /**
10746      * Show or hide the tab
10747      * @param {Boolean} hidden True to hide or false to show.
10748      */
10749     setHidden : function(hidden){
10750         this.hidden = hidden;
10751         this.pnode.setStyle("display", hidden ? "none" : "");
10752     },
10753
10754     /**
10755      * Returns true if this tab is "hidden"
10756      * @return {Boolean}
10757      */
10758     isHidden : function(){
10759         return this.hidden;
10760     },
10761
10762     /**
10763      * Returns the text for this tab
10764      * @return {String}
10765      */
10766     getText : function(){
10767         return this.text;
10768     },
10769
10770     autoSize : function(){
10771         //this.el.beginMeasure();
10772         this.textEl.setWidth(1);
10773         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
10774         //this.el.endMeasure();
10775     },
10776
10777     /**
10778      * Sets the text for the tab (Note: this also sets the tooltip text)
10779      * @param {String} text The tab's text and tooltip
10780      */
10781     setText : function(text){
10782         this.text = text;
10783         this.textEl.update(text);
10784         this.setTooltip(text);
10785         if(!this.tabPanel.resizeTabs){
10786             this.autoSize();
10787         }
10788     },
10789     /**
10790      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
10791      */
10792     activate : function(){
10793         this.tabPanel.activate(this.id);
10794     },
10795
10796     /**
10797      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
10798      */
10799     disable : function(){
10800         if(this.tabPanel.active != this){
10801             this.disabled = true;
10802             this.pnode.addClass("disabled");
10803         }
10804     },
10805
10806     /**
10807      * Enables this TabPanelItem if it was previously disabled.
10808      */
10809     enable : function(){
10810         this.disabled = false;
10811         this.pnode.removeClass("disabled");
10812     },
10813
10814     /**
10815      * Sets the content for this TabPanelItem.
10816      * @param {String} content The content
10817      * @param {Boolean} loadScripts true to look for and load scripts
10818      */
10819     setContent : function(content, loadScripts){
10820         this.bodyEl.update(content, loadScripts);
10821     },
10822
10823     /**
10824      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
10825      * @return {Roo.UpdateManager} The UpdateManager
10826      */
10827     getUpdateManager : function(){
10828         return this.bodyEl.getUpdateManager();
10829     },
10830
10831     /**
10832      * Set a URL to be used to load the content for this TabPanelItem.
10833      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
10834      * @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)
10835      * @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)
10836      * @return {Roo.UpdateManager} The UpdateManager
10837      */
10838     setUrl : function(url, params, loadOnce){
10839         if(this.refreshDelegate){
10840             this.un('activate', this.refreshDelegate);
10841         }
10842         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
10843         this.on("activate", this.refreshDelegate);
10844         return this.bodyEl.getUpdateManager();
10845     },
10846
10847     /** @private */
10848     _handleRefresh : function(url, params, loadOnce){
10849         if(!loadOnce || !this.loaded){
10850             var updater = this.bodyEl.getUpdateManager();
10851             updater.update(url, params, this._setLoaded.createDelegate(this));
10852         }
10853     },
10854
10855     /**
10856      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
10857      *   Will fail silently if the setUrl method has not been called.
10858      *   This does not activate the panel, just updates its content.
10859      */
10860     refresh : function(){
10861         if(this.refreshDelegate){
10862            this.loaded = false;
10863            this.refreshDelegate();
10864         }
10865     },
10866
10867     /** @private */
10868     _setLoaded : function(){
10869         this.loaded = true;
10870     },
10871
10872     /** @private */
10873     closeClick : function(e){
10874         var o = {};
10875         e.stopEvent();
10876         this.fireEvent("beforeclose", this, o);
10877         if(o.cancel !== true){
10878             this.tabPanel.removeTab(this.id);
10879         }
10880     },
10881     /**
10882      * The text displayed in the tooltip for the close icon.
10883      * @type String
10884      */
10885     closeText : "Close this tab"
10886 });
10887
10888 /** @private */
10889 Roo.TabPanel.prototype.createStrip = function(container){
10890     var strip = document.createElement("div");
10891     strip.className = "x-tabs-wrap";
10892     container.appendChild(strip);
10893     return strip;
10894 };
10895 /** @private */
10896 Roo.TabPanel.prototype.createStripList = function(strip){
10897     // div wrapper for retard IE
10898     // returns the "tr" element.
10899     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
10900         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
10901         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
10902     return strip.firstChild.firstChild.firstChild.firstChild;
10903 };
10904 /** @private */
10905 Roo.TabPanel.prototype.createBody = function(container){
10906     var body = document.createElement("div");
10907     Roo.id(body, "tab-body");
10908     Roo.fly(body).addClass("x-tabs-body");
10909     container.appendChild(body);
10910     return body;
10911 };
10912 /** @private */
10913 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
10914     var body = Roo.getDom(id);
10915     if(!body){
10916         body = document.createElement("div");
10917         body.id = id;
10918     }
10919     Roo.fly(body).addClass("x-tabs-item-body");
10920     bodyEl.insertBefore(body, bodyEl.firstChild);
10921     return body;
10922 };
10923 /** @private */
10924 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
10925     var td = document.createElement("td");
10926     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
10927     //stripEl.appendChild(td);
10928     if(closable){
10929         td.className = "x-tabs-closable";
10930         if(!this.closeTpl){
10931             this.closeTpl = new Roo.Template(
10932                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
10933                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
10934                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
10935             );
10936         }
10937         var el = this.closeTpl.overwrite(td, {"text": text});
10938         var close = el.getElementsByTagName("div")[0];
10939         var inner = el.getElementsByTagName("em")[0];
10940         return {"el": el, "close": close, "inner": inner};
10941     } else {
10942         if(!this.tabTpl){
10943             this.tabTpl = new Roo.Template(
10944                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
10945                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
10946             );
10947         }
10948         var el = this.tabTpl.overwrite(td, {"text": text});
10949         var inner = el.getElementsByTagName("em")[0];
10950         return {"el": el, "inner": inner};
10951     }
10952 };/*
10953  * Based on:
10954  * Ext JS Library 1.1.1
10955  * Copyright(c) 2006-2007, Ext JS, LLC.
10956  *
10957  * Originally Released Under LGPL - original licence link has changed is not relivant.
10958  *
10959  * Fork - LGPL
10960  * <script type="text/javascript">
10961  */
10962
10963 /**
10964  * @class Roo.Button
10965  * @extends Roo.util.Observable
10966  * Simple Button class
10967  * @cfg {String} text The button text
10968  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
10969  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
10970  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
10971  * @cfg {Object} scope The scope of the handler
10972  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
10973  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
10974  * @cfg {Boolean} hidden True to start hidden (defaults to false)
10975  * @cfg {Boolean} disabled True to start disabled (defaults to false)
10976  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
10977  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
10978    applies if enableToggle = true)
10979  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
10980  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
10981   an {@link Roo.util.ClickRepeater} config object (defaults to false).
10982  * @constructor
10983  * Create a new button
10984  * @param {Object} config The config object
10985  */
10986 Roo.Button = function(renderTo, config)
10987 {
10988     if (!config) {
10989         config = renderTo;
10990         renderTo = config.renderTo || false;
10991     }
10992     
10993     Roo.apply(this, config);
10994     this.addEvents({
10995         /**
10996              * @event click
10997              * Fires when this button is clicked
10998              * @param {Button} this
10999              * @param {EventObject} e The click event
11000              */
11001             "click" : true,
11002         /**
11003              * @event toggle
11004              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
11005              * @param {Button} this
11006              * @param {Boolean} pressed
11007              */
11008             "toggle" : true,
11009         /**
11010              * @event mouseover
11011              * Fires when the mouse hovers over the button
11012              * @param {Button} this
11013              * @param {Event} e The event object
11014              */
11015         'mouseover' : true,
11016         /**
11017              * @event mouseout
11018              * Fires when the mouse exits the button
11019              * @param {Button} this
11020              * @param {Event} e The event object
11021              */
11022         'mouseout': true,
11023          /**
11024              * @event render
11025              * Fires when the button is rendered
11026              * @param {Button} this
11027              */
11028         'render': true
11029     });
11030     if(this.menu){
11031         this.menu = Roo.menu.MenuMgr.get(this.menu);
11032     }
11033     // register listeners first!!  - so render can be captured..
11034     Roo.util.Observable.call(this);
11035     if(renderTo){
11036         this.render(renderTo);
11037     }
11038     
11039   
11040 };
11041
11042 Roo.extend(Roo.Button, Roo.util.Observable, {
11043     /**
11044      * 
11045      */
11046     
11047     /**
11048      * Read-only. True if this button is hidden
11049      * @type Boolean
11050      */
11051     hidden : false,
11052     /**
11053      * Read-only. True if this button is disabled
11054      * @type Boolean
11055      */
11056     disabled : false,
11057     /**
11058      * Read-only. True if this button is pressed (only if enableToggle = true)
11059      * @type Boolean
11060      */
11061     pressed : false,
11062
11063     /**
11064      * @cfg {Number} tabIndex 
11065      * The DOM tabIndex for this button (defaults to undefined)
11066      */
11067     tabIndex : undefined,
11068
11069     /**
11070      * @cfg {Boolean} enableToggle
11071      * True to enable pressed/not pressed toggling (defaults to false)
11072      */
11073     enableToggle: false,
11074     /**
11075      * @cfg {Mixed} menu
11076      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
11077      */
11078     menu : undefined,
11079     /**
11080      * @cfg {String} menuAlign
11081      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
11082      */
11083     menuAlign : "tl-bl?",
11084
11085     /**
11086      * @cfg {String} iconCls
11087      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
11088      */
11089     iconCls : undefined,
11090     /**
11091      * @cfg {String} type
11092      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
11093      */
11094     type : 'button',
11095
11096     // private
11097     menuClassTarget: 'tr',
11098
11099     /**
11100      * @cfg {String} clickEvent
11101      * The type of event to map to the button's event handler (defaults to 'click')
11102      */
11103     clickEvent : 'click',
11104
11105     /**
11106      * @cfg {Boolean} handleMouseEvents
11107      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
11108      */
11109     handleMouseEvents : true,
11110
11111     /**
11112      * @cfg {String} tooltipType
11113      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
11114      */
11115     tooltipType : 'qtip',
11116
11117     /**
11118      * @cfg {String} cls
11119      * A CSS class to apply to the button's main element.
11120      */
11121     
11122     /**
11123      * @cfg {Roo.Template} template (Optional)
11124      * An {@link Roo.Template} with which to create the Button's main element. This Template must
11125      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
11126      * require code modifications if required elements (e.g. a button) aren't present.
11127      */
11128
11129     // private
11130     render : function(renderTo){
11131         var btn;
11132         if(this.hideParent){
11133             this.parentEl = Roo.get(renderTo);
11134         }
11135         if(!this.dhconfig){
11136             if(!this.template){
11137                 if(!Roo.Button.buttonTemplate){
11138                     // hideous table template
11139                     Roo.Button.buttonTemplate = new Roo.Template(
11140                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
11141                         '<td class="x-btn-left"><i>&#160;</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>&#160;</i></td>',
11142                         "</tr></tbody></table>");
11143                 }
11144                 this.template = Roo.Button.buttonTemplate;
11145             }
11146             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
11147             var btnEl = btn.child("button:first");
11148             btnEl.on('focus', this.onFocus, this);
11149             btnEl.on('blur', this.onBlur, this);
11150             if(this.cls){
11151                 btn.addClass(this.cls);
11152             }
11153             if(this.icon){
11154                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
11155             }
11156             if(this.iconCls){
11157                 btnEl.addClass(this.iconCls);
11158                 if(!this.cls){
11159                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
11160                 }
11161             }
11162             if(this.tabIndex !== undefined){
11163                 btnEl.dom.tabIndex = this.tabIndex;
11164             }
11165             if(this.tooltip){
11166                 if(typeof this.tooltip == 'object'){
11167                     Roo.QuickTips.tips(Roo.apply({
11168                           target: btnEl.id
11169                     }, this.tooltip));
11170                 } else {
11171                     btnEl.dom[this.tooltipType] = this.tooltip;
11172                 }
11173             }
11174         }else{
11175             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
11176         }
11177         this.el = btn;
11178         if(this.id){
11179             this.el.dom.id = this.el.id = this.id;
11180         }
11181         if(this.menu){
11182             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
11183             this.menu.on("show", this.onMenuShow, this);
11184             this.menu.on("hide", this.onMenuHide, this);
11185         }
11186         btn.addClass("x-btn");
11187         if(Roo.isIE && !Roo.isIE7){
11188             this.autoWidth.defer(1, this);
11189         }else{
11190             this.autoWidth();
11191         }
11192         if(this.handleMouseEvents){
11193             btn.on("mouseover", this.onMouseOver, this);
11194             btn.on("mouseout", this.onMouseOut, this);
11195             btn.on("mousedown", this.onMouseDown, this);
11196         }
11197         btn.on(this.clickEvent, this.onClick, this);
11198         //btn.on("mouseup", this.onMouseUp, this);
11199         if(this.hidden){
11200             this.hide();
11201         }
11202         if(this.disabled){
11203             this.disable();
11204         }
11205         Roo.ButtonToggleMgr.register(this);
11206         if(this.pressed){
11207             this.el.addClass("x-btn-pressed");
11208         }
11209         if(this.repeat){
11210             var repeater = new Roo.util.ClickRepeater(btn,
11211                 typeof this.repeat == "object" ? this.repeat : {}
11212             );
11213             repeater.on("click", this.onClick,  this);
11214         }
11215         
11216         this.fireEvent('render', this);
11217         
11218     },
11219     /**
11220      * Returns the button's underlying element
11221      * @return {Roo.Element} The element
11222      */
11223     getEl : function(){
11224         return this.el;  
11225     },
11226     
11227     /**
11228      * Destroys this Button and removes any listeners.
11229      */
11230     destroy : function(){
11231         Roo.ButtonToggleMgr.unregister(this);
11232         this.el.removeAllListeners();
11233         this.purgeListeners();
11234         this.el.remove();
11235     },
11236
11237     // private
11238     autoWidth : function(){
11239         if(this.el){
11240             this.el.setWidth("auto");
11241             if(Roo.isIE7 && Roo.isStrict){
11242                 var ib = this.el.child('button');
11243                 if(ib && ib.getWidth() > 20){
11244                     ib.clip();
11245                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
11246                 }
11247             }
11248             if(this.minWidth){
11249                 if(this.hidden){
11250                     this.el.beginMeasure();
11251                 }
11252                 if(this.el.getWidth() < this.minWidth){
11253                     this.el.setWidth(this.minWidth);
11254                 }
11255                 if(this.hidden){
11256                     this.el.endMeasure();
11257                 }
11258             }
11259         }
11260     },
11261
11262     /**
11263      * Assigns this button's click handler
11264      * @param {Function} handler The function to call when the button is clicked
11265      * @param {Object} scope (optional) Scope for the function passed in
11266      */
11267     setHandler : function(handler, scope){
11268         this.handler = handler;
11269         this.scope = scope;  
11270     },
11271     
11272     /**
11273      * Sets this button's text
11274      * @param {String} text The button text
11275      */
11276     setText : function(text){
11277         this.text = text;
11278         if(this.el){
11279             this.el.child("td.x-btn-center button.x-btn-text").update(text);
11280         }
11281         this.autoWidth();
11282     },
11283     
11284     /**
11285      * Gets the text for this button
11286      * @return {String} The button text
11287      */
11288     getText : function(){
11289         return this.text;  
11290     },
11291     
11292     /**
11293      * Show this button
11294      */
11295     show: function(){
11296         this.hidden = false;
11297         if(this.el){
11298             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
11299         }
11300     },
11301     
11302     /**
11303      * Hide this button
11304      */
11305     hide: function(){
11306         this.hidden = true;
11307         if(this.el){
11308             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
11309         }
11310     },
11311     
11312     /**
11313      * Convenience function for boolean show/hide
11314      * @param {Boolean} visible True to show, false to hide
11315      */
11316     setVisible: function(visible){
11317         if(visible) {
11318             this.show();
11319         }else{
11320             this.hide();
11321         }
11322     },
11323     
11324     /**
11325      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
11326      * @param {Boolean} state (optional) Force a particular state
11327      */
11328     toggle : function(state){
11329         state = state === undefined ? !this.pressed : state;
11330         if(state != this.pressed){
11331             if(state){
11332                 this.el.addClass("x-btn-pressed");
11333                 this.pressed = true;
11334                 this.fireEvent("toggle", this, true);
11335             }else{
11336                 this.el.removeClass("x-btn-pressed");
11337                 this.pressed = false;
11338                 this.fireEvent("toggle", this, false);
11339             }
11340             if(this.toggleHandler){
11341                 this.toggleHandler.call(this.scope || this, this, state);
11342             }
11343         }
11344     },
11345     
11346     /**
11347      * Focus the button
11348      */
11349     focus : function(){
11350         this.el.child('button:first').focus();
11351     },
11352     
11353     /**
11354      * Disable this button
11355      */
11356     disable : function(){
11357         if(this.el){
11358             this.el.addClass("x-btn-disabled");
11359         }
11360         this.disabled = true;
11361     },
11362     
11363     /**
11364      * Enable this button
11365      */
11366     enable : function(){
11367         if(this.el){
11368             this.el.removeClass("x-btn-disabled");
11369         }
11370         this.disabled = false;
11371     },
11372
11373     /**
11374      * Convenience function for boolean enable/disable
11375      * @param {Boolean} enabled True to enable, false to disable
11376      */
11377     setDisabled : function(v){
11378         this[v !== true ? "enable" : "disable"]();
11379     },
11380
11381     // private
11382     onClick : function(e){
11383         if(e){
11384             e.preventDefault();
11385         }
11386         if(e.button != 0){
11387             return;
11388         }
11389         if(!this.disabled){
11390             if(this.enableToggle){
11391                 this.toggle();
11392             }
11393             if(this.menu && !this.menu.isVisible()){
11394                 this.menu.show(this.el, this.menuAlign);
11395             }
11396             this.fireEvent("click", this, e);
11397             if(this.handler){
11398                 this.el.removeClass("x-btn-over");
11399                 this.handler.call(this.scope || this, this, e);
11400             }
11401         }
11402     },
11403     // private
11404     onMouseOver : function(e){
11405         if(!this.disabled){
11406             this.el.addClass("x-btn-over");
11407             this.fireEvent('mouseover', this, e);
11408         }
11409     },
11410     // private
11411     onMouseOut : function(e){
11412         if(!e.within(this.el,  true)){
11413             this.el.removeClass("x-btn-over");
11414             this.fireEvent('mouseout', this, e);
11415         }
11416     },
11417     // private
11418     onFocus : function(e){
11419         if(!this.disabled){
11420             this.el.addClass("x-btn-focus");
11421         }
11422     },
11423     // private
11424     onBlur : function(e){
11425         this.el.removeClass("x-btn-focus");
11426     },
11427     // private
11428     onMouseDown : function(e){
11429         if(!this.disabled && e.button == 0){
11430             this.el.addClass("x-btn-click");
11431             Roo.get(document).on('mouseup', this.onMouseUp, this);
11432         }
11433     },
11434     // private
11435     onMouseUp : function(e){
11436         if(e.button == 0){
11437             this.el.removeClass("x-btn-click");
11438             Roo.get(document).un('mouseup', this.onMouseUp, this);
11439         }
11440     },
11441     // private
11442     onMenuShow : function(e){
11443         this.el.addClass("x-btn-menu-active");
11444     },
11445     // private
11446     onMenuHide : function(e){
11447         this.el.removeClass("x-btn-menu-active");
11448     }   
11449 });
11450
11451 // Private utility class used by Button
11452 Roo.ButtonToggleMgr = function(){
11453    var groups = {};
11454    
11455    function toggleGroup(btn, state){
11456        if(state){
11457            var g = groups[btn.toggleGroup];
11458            for(var i = 0, l = g.length; i < l; i++){
11459                if(g[i] != btn){
11460                    g[i].toggle(false);
11461                }
11462            }
11463        }
11464    }
11465    
11466    return {
11467        register : function(btn){
11468            if(!btn.toggleGroup){
11469                return;
11470            }
11471            var g = groups[btn.toggleGroup];
11472            if(!g){
11473                g = groups[btn.toggleGroup] = [];
11474            }
11475            g.push(btn);
11476            btn.on("toggle", toggleGroup);
11477        },
11478        
11479        unregister : function(btn){
11480            if(!btn.toggleGroup){
11481                return;
11482            }
11483            var g = groups[btn.toggleGroup];
11484            if(g){
11485                g.remove(btn);
11486                btn.un("toggle", toggleGroup);
11487            }
11488        }
11489    };
11490 }();/*
11491  * Based on:
11492  * Ext JS Library 1.1.1
11493  * Copyright(c) 2006-2007, Ext JS, LLC.
11494  *
11495  * Originally Released Under LGPL - original licence link has changed is not relivant.
11496  *
11497  * Fork - LGPL
11498  * <script type="text/javascript">
11499  */
11500  
11501 /**
11502  * @class Roo.SplitButton
11503  * @extends Roo.Button
11504  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
11505  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
11506  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
11507  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
11508  * @cfg {String} arrowTooltip The title attribute of the arrow
11509  * @constructor
11510  * Create a new menu button
11511  * @param {String/HTMLElement/Element} renderTo The element to append the button to
11512  * @param {Object} config The config object
11513  */
11514 Roo.SplitButton = function(renderTo, config){
11515     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
11516     /**
11517      * @event arrowclick
11518      * Fires when this button's arrow is clicked
11519      * @param {SplitButton} this
11520      * @param {EventObject} e The click event
11521      */
11522     this.addEvents({"arrowclick":true});
11523 };
11524
11525 Roo.extend(Roo.SplitButton, Roo.Button, {
11526     render : function(renderTo){
11527         // this is one sweet looking template!
11528         var tpl = new Roo.Template(
11529             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
11530             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
11531             '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>',
11532             "</tbody></table></td><td>",
11533             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
11534             '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>',
11535             "</tbody></table></td></tr></table>"
11536         );
11537         var btn = tpl.append(renderTo, [this.text, this.type], true);
11538         var btnEl = btn.child("button");
11539         if(this.cls){
11540             btn.addClass(this.cls);
11541         }
11542         if(this.icon){
11543             btnEl.setStyle('background-image', 'url(' +this.icon +')');
11544         }
11545         if(this.iconCls){
11546             btnEl.addClass(this.iconCls);
11547             if(!this.cls){
11548                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
11549             }
11550         }
11551         this.el = btn;
11552         if(this.handleMouseEvents){
11553             btn.on("mouseover", this.onMouseOver, this);
11554             btn.on("mouseout", this.onMouseOut, this);
11555             btn.on("mousedown", this.onMouseDown, this);
11556             btn.on("mouseup", this.onMouseUp, this);
11557         }
11558         btn.on(this.clickEvent, this.onClick, this);
11559         if(this.tooltip){
11560             if(typeof this.tooltip == 'object'){
11561                 Roo.QuickTips.tips(Roo.apply({
11562                       target: btnEl.id
11563                 }, this.tooltip));
11564             } else {
11565                 btnEl.dom[this.tooltipType] = this.tooltip;
11566             }
11567         }
11568         if(this.arrowTooltip){
11569             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
11570         }
11571         if(this.hidden){
11572             this.hide();
11573         }
11574         if(this.disabled){
11575             this.disable();
11576         }
11577         if(this.pressed){
11578             this.el.addClass("x-btn-pressed");
11579         }
11580         if(Roo.isIE && !Roo.isIE7){
11581             this.autoWidth.defer(1, this);
11582         }else{
11583             this.autoWidth();
11584         }
11585         if(this.menu){
11586             this.menu.on("show", this.onMenuShow, this);
11587             this.menu.on("hide", this.onMenuHide, this);
11588         }
11589         this.fireEvent('render', this);
11590     },
11591
11592     // private
11593     autoWidth : function(){
11594         if(this.el){
11595             var tbl = this.el.child("table:first");
11596             var tbl2 = this.el.child("table:last");
11597             this.el.setWidth("auto");
11598             tbl.setWidth("auto");
11599             if(Roo.isIE7 && Roo.isStrict){
11600                 var ib = this.el.child('button:first');
11601                 if(ib && ib.getWidth() > 20){
11602                     ib.clip();
11603                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
11604                 }
11605             }
11606             if(this.minWidth){
11607                 if(this.hidden){
11608                     this.el.beginMeasure();
11609                 }
11610                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
11611                     tbl.setWidth(this.minWidth-tbl2.getWidth());
11612                 }
11613                 if(this.hidden){
11614                     this.el.endMeasure();
11615                 }
11616             }
11617             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
11618         } 
11619     },
11620     /**
11621      * Sets this button's click handler
11622      * @param {Function} handler The function to call when the button is clicked
11623      * @param {Object} scope (optional) Scope for the function passed above
11624      */
11625     setHandler : function(handler, scope){
11626         this.handler = handler;
11627         this.scope = scope;  
11628     },
11629     
11630     /**
11631      * Sets this button's arrow click handler
11632      * @param {Function} handler The function to call when the arrow is clicked
11633      * @param {Object} scope (optional) Scope for the function passed above
11634      */
11635     setArrowHandler : function(handler, scope){
11636         this.arrowHandler = handler;
11637         this.scope = scope;  
11638     },
11639     
11640     /**
11641      * Focus the button
11642      */
11643     focus : function(){
11644         if(this.el){
11645             this.el.child("button:first").focus();
11646         }
11647     },
11648
11649     // private
11650     onClick : function(e){
11651         e.preventDefault();
11652         if(!this.disabled){
11653             if(e.getTarget(".x-btn-menu-arrow-wrap")){
11654                 if(this.menu && !this.menu.isVisible()){
11655                     this.menu.show(this.el, this.menuAlign);
11656                 }
11657                 this.fireEvent("arrowclick", this, e);
11658                 if(this.arrowHandler){
11659                     this.arrowHandler.call(this.scope || this, this, e);
11660                 }
11661             }else{
11662                 this.fireEvent("click", this, e);
11663                 if(this.handler){
11664                     this.handler.call(this.scope || this, this, e);
11665                 }
11666             }
11667         }
11668     },
11669     // private
11670     onMouseDown : function(e){
11671         if(!this.disabled){
11672             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
11673         }
11674     },
11675     // private
11676     onMouseUp : function(e){
11677         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
11678     }   
11679 });
11680
11681
11682 // backwards compat
11683 Roo.MenuButton = Roo.SplitButton;/*
11684  * Based on:
11685  * Ext JS Library 1.1.1
11686  * Copyright(c) 2006-2007, Ext JS, LLC.
11687  *
11688  * Originally Released Under LGPL - original licence link has changed is not relivant.
11689  *
11690  * Fork - LGPL
11691  * <script type="text/javascript">
11692  */
11693
11694 /**
11695  * @class Roo.Toolbar
11696  * Basic Toolbar class.
11697  * @constructor
11698  * Creates a new Toolbar
11699  * @param {Object} container The config object
11700  */ 
11701 Roo.Toolbar = function(container, buttons, config)
11702 {
11703     /// old consturctor format still supported..
11704     if(container instanceof Array){ // omit the container for later rendering
11705         buttons = container;
11706         config = buttons;
11707         container = null;
11708     }
11709     if (typeof(container) == 'object' && container.xtype) {
11710         config = container;
11711         container = config.container;
11712         buttons = config.buttons || []; // not really - use items!!
11713     }
11714     var xitems = [];
11715     if (config && config.items) {
11716         xitems = config.items;
11717         delete config.items;
11718     }
11719     Roo.apply(this, config);
11720     this.buttons = buttons;
11721     
11722     if(container){
11723         this.render(container);
11724     }
11725     this.xitems = xitems;
11726     Roo.each(xitems, function(b) {
11727         this.add(b);
11728     }, this);
11729     
11730 };
11731
11732 Roo.Toolbar.prototype = {
11733     /**
11734      * @cfg {Array} items
11735      * array of button configs or elements to add (will be converted to a MixedCollection)
11736      */
11737     
11738     /**
11739      * @cfg {String/HTMLElement/Element} container
11740      * The id or element that will contain the toolbar
11741      */
11742     // private
11743     render : function(ct){
11744         this.el = Roo.get(ct);
11745         if(this.cls){
11746             this.el.addClass(this.cls);
11747         }
11748         // using a table allows for vertical alignment
11749         // 100% width is needed by Safari...
11750         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
11751         this.tr = this.el.child("tr", true);
11752         var autoId = 0;
11753         this.items = new Roo.util.MixedCollection(false, function(o){
11754             return o.id || ("item" + (++autoId));
11755         });
11756         if(this.buttons){
11757             this.add.apply(this, this.buttons);
11758             delete this.buttons;
11759         }
11760     },
11761
11762     /**
11763      * Adds element(s) to the toolbar -- this function takes a variable number of 
11764      * arguments of mixed type and adds them to the toolbar.
11765      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
11766      * <ul>
11767      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
11768      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
11769      * <li>Field: Any form field (equivalent to {@link #addField})</li>
11770      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
11771      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
11772      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
11773      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
11774      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
11775      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
11776      * </ul>
11777      * @param {Mixed} arg2
11778      * @param {Mixed} etc.
11779      */
11780     add : function(){
11781         var a = arguments, l = a.length;
11782         for(var i = 0; i < l; i++){
11783             this._add(a[i]);
11784         }
11785     },
11786     // private..
11787     _add : function(el) {
11788         
11789         if (el.xtype) {
11790             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
11791         }
11792         
11793         if (el.applyTo){ // some kind of form field
11794             return this.addField(el);
11795         } 
11796         if (el.render){ // some kind of Toolbar.Item
11797             return this.addItem(el);
11798         }
11799         if (typeof el == "string"){ // string
11800             if(el == "separator" || el == "-"){
11801                 return this.addSeparator();
11802             }
11803             if (el == " "){
11804                 return this.addSpacer();
11805             }
11806             if(el == "->"){
11807                 return this.addFill();
11808             }
11809             return this.addText(el);
11810             
11811         }
11812         if(el.tagName){ // element
11813             return this.addElement(el);
11814         }
11815         if(typeof el == "object"){ // must be button config?
11816             return this.addButton(el);
11817         }
11818         // and now what?!?!
11819         return false;
11820         
11821     },
11822     
11823     /**
11824      * Add an Xtype element
11825      * @param {Object} xtype Xtype Object
11826      * @return {Object} created Object
11827      */
11828     addxtype : function(e){
11829         return this.add(e);  
11830     },
11831     
11832     /**
11833      * Returns the Element for this toolbar.
11834      * @return {Roo.Element}
11835      */
11836     getEl : function(){
11837         return this.el;  
11838     },
11839     
11840     /**
11841      * Adds a separator
11842      * @return {Roo.Toolbar.Item} The separator item
11843      */
11844     addSeparator : function(){
11845         return this.addItem(new Roo.Toolbar.Separator());
11846     },
11847
11848     /**
11849      * Adds a spacer element
11850      * @return {Roo.Toolbar.Spacer} The spacer item
11851      */
11852     addSpacer : function(){
11853         return this.addItem(new Roo.Toolbar.Spacer());
11854     },
11855
11856     /**
11857      * Adds a fill element that forces subsequent additions to the right side of the toolbar
11858      * @return {Roo.Toolbar.Fill} The fill item
11859      */
11860     addFill : function(){
11861         return this.addItem(new Roo.Toolbar.Fill());
11862     },
11863
11864     /**
11865      * Adds any standard HTML element to the toolbar
11866      * @param {String/HTMLElement/Element} el The element or id of the element to add
11867      * @return {Roo.Toolbar.Item} The element's item
11868      */
11869     addElement : function(el){
11870         return this.addItem(new Roo.Toolbar.Item(el));
11871     },
11872     /**
11873      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
11874      * @type Roo.util.MixedCollection  
11875      */
11876     items : false,
11877      
11878     /**
11879      * Adds any Toolbar.Item or subclass
11880      * @param {Roo.Toolbar.Item} item
11881      * @return {Roo.Toolbar.Item} The item
11882      */
11883     addItem : function(item){
11884         var td = this.nextBlock();
11885         item.render(td);
11886         this.items.add(item);
11887         return item;
11888     },
11889     
11890     /**
11891      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
11892      * @param {Object/Array} config A button config or array of configs
11893      * @return {Roo.Toolbar.Button/Array}
11894      */
11895     addButton : function(config){
11896         if(config instanceof Array){
11897             var buttons = [];
11898             for(var i = 0, len = config.length; i < len; i++) {
11899                 buttons.push(this.addButton(config[i]));
11900             }
11901             return buttons;
11902         }
11903         var b = config;
11904         if(!(config instanceof Roo.Toolbar.Button)){
11905             b = config.split ?
11906                 new Roo.Toolbar.SplitButton(config) :
11907                 new Roo.Toolbar.Button(config);
11908         }
11909         var td = this.nextBlock();
11910         b.render(td);
11911         this.items.add(b);
11912         return b;
11913     },
11914     
11915     /**
11916      * Adds text to the toolbar
11917      * @param {String} text The text to add
11918      * @return {Roo.Toolbar.Item} The element's item
11919      */
11920     addText : function(text){
11921         return this.addItem(new Roo.Toolbar.TextItem(text));
11922     },
11923     
11924     /**
11925      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
11926      * @param {Number} index The index where the item is to be inserted
11927      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
11928      * @return {Roo.Toolbar.Button/Item}
11929      */
11930     insertButton : function(index, item){
11931         if(item instanceof Array){
11932             var buttons = [];
11933             for(var i = 0, len = item.length; i < len; i++) {
11934                buttons.push(this.insertButton(index + i, item[i]));
11935             }
11936             return buttons;
11937         }
11938         if (!(item instanceof Roo.Toolbar.Button)){
11939            item = new Roo.Toolbar.Button(item);
11940         }
11941         var td = document.createElement("td");
11942         this.tr.insertBefore(td, this.tr.childNodes[index]);
11943         item.render(td);
11944         this.items.insert(index, item);
11945         return item;
11946     },
11947     
11948     /**
11949      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
11950      * @param {Object} config
11951      * @return {Roo.Toolbar.Item} The element's item
11952      */
11953     addDom : function(config, returnEl){
11954         var td = this.nextBlock();
11955         Roo.DomHelper.overwrite(td, config);
11956         var ti = new Roo.Toolbar.Item(td.firstChild);
11957         ti.render(td);
11958         this.items.add(ti);
11959         return ti;
11960     },
11961
11962     /**
11963      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
11964      * @type Roo.util.MixedCollection  
11965      */
11966     fields : false,
11967     
11968     /**
11969      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
11970      * Note: the field should not have been rendered yet. For a field that has already been
11971      * rendered, use {@link #addElement}.
11972      * @param {Roo.form.Field} field
11973      * @return {Roo.ToolbarItem}
11974      */
11975      
11976       
11977     addField : function(field) {
11978         if (!this.fields) {
11979             var autoId = 0;
11980             this.fields = new Roo.util.MixedCollection(false, function(o){
11981                 return o.id || ("item" + (++autoId));
11982             });
11983
11984         }
11985         
11986         var td = this.nextBlock();
11987         field.render(td);
11988         var ti = new Roo.Toolbar.Item(td.firstChild);
11989         ti.render(td);
11990         this.items.add(ti);
11991         this.fields.add(field);
11992         return ti;
11993     },
11994     /**
11995      * Hide the toolbar
11996      * @method hide
11997      */
11998      
11999       
12000     hide : function()
12001     {
12002         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
12003         this.el.child('div').hide();
12004     },
12005     /**
12006      * Show the toolbar
12007      * @method show
12008      */
12009     show : function()
12010     {
12011         this.el.child('div').show();
12012     },
12013       
12014     // private
12015     nextBlock : function(){
12016         var td = document.createElement("td");
12017         this.tr.appendChild(td);
12018         return td;
12019     },
12020
12021     // private
12022     destroy : function(){
12023         if(this.items){ // rendered?
12024             Roo.destroy.apply(Roo, this.items.items);
12025         }
12026         if(this.fields){ // rendered?
12027             Roo.destroy.apply(Roo, this.fields.items);
12028         }
12029         Roo.Element.uncache(this.el, this.tr);
12030     }
12031 };
12032
12033 /**
12034  * @class Roo.Toolbar.Item
12035  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
12036  * @constructor
12037  * Creates a new Item
12038  * @param {HTMLElement} el 
12039  */
12040 Roo.Toolbar.Item = function(el){
12041     this.el = Roo.getDom(el);
12042     this.id = Roo.id(this.el);
12043     this.hidden = false;
12044 };
12045
12046 Roo.Toolbar.Item.prototype = {
12047     
12048     /**
12049      * Get this item's HTML Element
12050      * @return {HTMLElement}
12051      */
12052     getEl : function(){
12053        return this.el;  
12054     },
12055
12056     // private
12057     render : function(td){
12058         this.td = td;
12059         td.appendChild(this.el);
12060     },
12061     
12062     /**
12063      * Removes and destroys this item.
12064      */
12065     destroy : function(){
12066         this.td.parentNode.removeChild(this.td);
12067     },
12068     
12069     /**
12070      * Shows this item.
12071      */
12072     show: function(){
12073         this.hidden = false;
12074         this.td.style.display = "";
12075     },
12076     
12077     /**
12078      * Hides this item.
12079      */
12080     hide: function(){
12081         this.hidden = true;
12082         this.td.style.display = "none";
12083     },
12084     
12085     /**
12086      * Convenience function for boolean show/hide.
12087      * @param {Boolean} visible true to show/false to hide
12088      */
12089     setVisible: function(visible){
12090         if(visible) {
12091             this.show();
12092         }else{
12093             this.hide();
12094         }
12095     },
12096     
12097     /**
12098      * Try to focus this item.
12099      */
12100     focus : function(){
12101         Roo.fly(this.el).focus();
12102     },
12103     
12104     /**
12105      * Disables this item.
12106      */
12107     disable : function(){
12108         Roo.fly(this.td).addClass("x-item-disabled");
12109         this.disabled = true;
12110         this.el.disabled = true;
12111     },
12112     
12113     /**
12114      * Enables this item.
12115      */
12116     enable : function(){
12117         Roo.fly(this.td).removeClass("x-item-disabled");
12118         this.disabled = false;
12119         this.el.disabled = false;
12120     }
12121 };
12122
12123
12124 /**
12125  * @class Roo.Toolbar.Separator
12126  * @extends Roo.Toolbar.Item
12127  * A simple toolbar separator class
12128  * @constructor
12129  * Creates a new Separator
12130  */
12131 Roo.Toolbar.Separator = function(){
12132     var s = document.createElement("span");
12133     s.className = "ytb-sep";
12134     Roo.Toolbar.Separator.superclass.constructor.call(this, s);
12135 };
12136 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
12137     enable:Roo.emptyFn,
12138     disable:Roo.emptyFn,
12139     focus:Roo.emptyFn
12140 });
12141
12142 /**
12143  * @class Roo.Toolbar.Spacer
12144  * @extends Roo.Toolbar.Item
12145  * A simple element that adds extra horizontal space to a toolbar.
12146  * @constructor
12147  * Creates a new Spacer
12148  */
12149 Roo.Toolbar.Spacer = function(){
12150     var s = document.createElement("div");
12151     s.className = "ytb-spacer";
12152     Roo.Toolbar.Spacer.superclass.constructor.call(this, s);
12153 };
12154 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
12155     enable:Roo.emptyFn,
12156     disable:Roo.emptyFn,
12157     focus:Roo.emptyFn
12158 });
12159
12160 /**
12161  * @class Roo.Toolbar.Fill
12162  * @extends Roo.Toolbar.Spacer
12163  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
12164  * @constructor
12165  * Creates a new Spacer
12166  */
12167 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
12168     // private
12169     render : function(td){
12170         td.style.width = '100%';
12171         Roo.Toolbar.Fill.superclass.render.call(this, td);
12172     }
12173 });
12174
12175 /**
12176  * @class Roo.Toolbar.TextItem
12177  * @extends Roo.Toolbar.Item
12178  * A simple class that renders text directly into a toolbar.
12179  * @constructor
12180  * Creates a new TextItem
12181  * @param {String} text
12182  */
12183 Roo.Toolbar.TextItem = function(text){
12184     if (typeof(text) == 'object') {
12185         text = text.text;
12186     }
12187     var s = document.createElement("span");
12188     s.className = "ytb-text";
12189     s.innerHTML = text;
12190     Roo.Toolbar.TextItem.superclass.constructor.call(this, s);
12191 };
12192 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
12193     enable:Roo.emptyFn,
12194     disable:Roo.emptyFn,
12195     focus:Roo.emptyFn
12196 });
12197
12198 /**
12199  * @class Roo.Toolbar.Button
12200  * @extends Roo.Button
12201  * A button that renders into a toolbar.
12202  * @constructor
12203  * Creates a new Button
12204  * @param {Object} config A standard {@link Roo.Button} config object
12205  */
12206 Roo.Toolbar.Button = function(config){
12207     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
12208 };
12209 Roo.extend(Roo.Toolbar.Button, Roo.Button, {
12210     render : function(td){
12211         this.td = td;
12212         Roo.Toolbar.Button.superclass.render.call(this, td);
12213     },
12214     
12215     /**
12216      * Removes and destroys this button
12217      */
12218     destroy : function(){
12219         Roo.Toolbar.Button.superclass.destroy.call(this);
12220         this.td.parentNode.removeChild(this.td);
12221     },
12222     
12223     /**
12224      * Shows this button
12225      */
12226     show: function(){
12227         this.hidden = false;
12228         this.td.style.display = "";
12229     },
12230     
12231     /**
12232      * Hides this button
12233      */
12234     hide: function(){
12235         this.hidden = true;
12236         this.td.style.display = "none";
12237     },
12238
12239     /**
12240      * Disables this item
12241      */
12242     disable : function(){
12243         Roo.fly(this.td).addClass("x-item-disabled");
12244         this.disabled = true;
12245     },
12246
12247     /**
12248      * Enables this item
12249      */
12250     enable : function(){
12251         Roo.fly(this.td).removeClass("x-item-disabled");
12252         this.disabled = false;
12253     }
12254 });
12255 // backwards compat
12256 Roo.ToolbarButton = Roo.Toolbar.Button;
12257
12258 /**
12259  * @class Roo.Toolbar.SplitButton
12260  * @extends Roo.SplitButton
12261  * A menu button that renders into a toolbar.
12262  * @constructor
12263  * Creates a new SplitButton
12264  * @param {Object} config A standard {@link Roo.SplitButton} config object
12265  */
12266 Roo.Toolbar.SplitButton = function(config){
12267     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
12268 };
12269 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
12270     render : function(td){
12271         this.td = td;
12272         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
12273     },
12274     
12275     /**
12276      * Removes and destroys this button
12277      */
12278     destroy : function(){
12279         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
12280         this.td.parentNode.removeChild(this.td);
12281     },
12282     
12283     /**
12284      * Shows this button
12285      */
12286     show: function(){
12287         this.hidden = false;
12288         this.td.style.display = "";
12289     },
12290     
12291     /**
12292      * Hides this button
12293      */
12294     hide: function(){
12295         this.hidden = true;
12296         this.td.style.display = "none";
12297     }
12298 });
12299
12300 // backwards compat
12301 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
12302  * Based on:
12303  * Ext JS Library 1.1.1
12304  * Copyright(c) 2006-2007, Ext JS, LLC.
12305  *
12306  * Originally Released Under LGPL - original licence link has changed is not relivant.
12307  *
12308  * Fork - LGPL
12309  * <script type="text/javascript">
12310  */
12311  
12312 /**
12313  * @class Roo.PagingToolbar
12314  * @extends Roo.Toolbar
12315  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
12316  * @constructor
12317  * Create a new PagingToolbar
12318  * @param {Object} config The config object
12319  */
12320 Roo.PagingToolbar = function(el, ds, config)
12321 {
12322     // old args format still supported... - xtype is prefered..
12323     if (typeof(el) == 'object' && el.xtype) {
12324         // created from xtype...
12325         config = el;
12326         ds = el.dataSource;
12327         el = config.container;
12328     }
12329     var items = [];
12330     if (config.items) {
12331         items = config.items;
12332         config.items = [];
12333     }
12334     
12335     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
12336     this.ds = ds;
12337     this.cursor = 0;
12338     this.renderButtons(this.el);
12339     this.bind(ds);
12340     
12341     // supprot items array.
12342    
12343     Roo.each(items, function(e) {
12344         this.add(Roo.factory(e));
12345     },this);
12346     
12347 };
12348
12349 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
12350     /**
12351      * @cfg {Roo.data.Store} dataSource
12352      * The underlying data store providing the paged data
12353      */
12354     /**
12355      * @cfg {String/HTMLElement/Element} container
12356      * container The id or element that will contain the toolbar
12357      */
12358     /**
12359      * @cfg {Boolean} displayInfo
12360      * True to display the displayMsg (defaults to false)
12361      */
12362     /**
12363      * @cfg {Number} pageSize
12364      * The number of records to display per page (defaults to 20)
12365      */
12366     pageSize: 20,
12367     /**
12368      * @cfg {String} displayMsg
12369      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
12370      */
12371     displayMsg : 'Displaying {0} - {1} of {2}',
12372     /**
12373      * @cfg {String} emptyMsg
12374      * The message to display when no records are found (defaults to "No data to display")
12375      */
12376     emptyMsg : 'No data to display',
12377     /**
12378      * Customizable piece of the default paging text (defaults to "Page")
12379      * @type String
12380      */
12381     beforePageText : "Page",
12382     /**
12383      * Customizable piece of the default paging text (defaults to "of %0")
12384      * @type String
12385      */
12386     afterPageText : "of {0}",
12387     /**
12388      * Customizable piece of the default paging text (defaults to "First Page")
12389      * @type String
12390      */
12391     firstText : "First Page",
12392     /**
12393      * Customizable piece of the default paging text (defaults to "Previous Page")
12394      * @type String
12395      */
12396     prevText : "Previous Page",
12397     /**
12398      * Customizable piece of the default paging text (defaults to "Next Page")
12399      * @type String
12400      */
12401     nextText : "Next Page",
12402     /**
12403      * Customizable piece of the default paging text (defaults to "Last Page")
12404      * @type String
12405      */
12406     lastText : "Last Page",
12407     /**
12408      * Customizable piece of the default paging text (defaults to "Refresh")
12409      * @type String
12410      */
12411     refreshText : "Refresh",
12412
12413     // private
12414     renderButtons : function(el){
12415         Roo.PagingToolbar.superclass.render.call(this, el);
12416         this.first = this.addButton({
12417             tooltip: this.firstText,
12418             cls: "x-btn-icon x-grid-page-first",
12419             disabled: true,
12420             handler: this.onClick.createDelegate(this, ["first"])
12421         });
12422         this.prev = this.addButton({
12423             tooltip: this.prevText,
12424             cls: "x-btn-icon x-grid-page-prev",
12425             disabled: true,
12426             handler: this.onClick.createDelegate(this, ["prev"])
12427         });
12428         //this.addSeparator();
12429         this.add(this.beforePageText);
12430         this.field = Roo.get(this.addDom({
12431            tag: "input",
12432            type: "text",
12433            size: "3",
12434            value: "1",
12435            cls: "x-grid-page-number"
12436         }).el);
12437         this.field.on("keydown", this.onPagingKeydown, this);
12438         this.field.on("focus", function(){this.dom.select();});
12439         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
12440         this.field.setHeight(18);
12441         //this.addSeparator();
12442         this.next = this.addButton({
12443             tooltip: this.nextText,
12444             cls: "x-btn-icon x-grid-page-next",
12445             disabled: true,
12446             handler: this.onClick.createDelegate(this, ["next"])
12447         });
12448         this.last = this.addButton({
12449             tooltip: this.lastText,
12450             cls: "x-btn-icon x-grid-page-last",
12451             disabled: true,
12452             handler: this.onClick.createDelegate(this, ["last"])
12453         });
12454         //this.addSeparator();
12455         this.loading = this.addButton({
12456             tooltip: this.refreshText,
12457             cls: "x-btn-icon x-grid-loading",
12458             handler: this.onClick.createDelegate(this, ["refresh"])
12459         });
12460
12461         if(this.displayInfo){
12462             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
12463         }
12464     },
12465
12466     // private
12467     updateInfo : function(){
12468         if(this.displayEl){
12469             var count = this.ds.getCount();
12470             var msg = count == 0 ?
12471                 this.emptyMsg :
12472                 String.format(
12473                     this.displayMsg,
12474                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
12475                 );
12476             this.displayEl.update(msg);
12477         }
12478     },
12479
12480     // private
12481     onLoad : function(ds, r, o){
12482        this.cursor = o.params ? o.params.start : 0;
12483        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
12484
12485        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
12486        this.field.dom.value = ap;
12487        this.first.setDisabled(ap == 1);
12488        this.prev.setDisabled(ap == 1);
12489        this.next.setDisabled(ap == ps);
12490        this.last.setDisabled(ap == ps);
12491        this.loading.enable();
12492        this.updateInfo();
12493     },
12494
12495     // private
12496     getPageData : function(){
12497         var total = this.ds.getTotalCount();
12498         return {
12499             total : total,
12500             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
12501             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
12502         };
12503     },
12504
12505     // private
12506     onLoadError : function(){
12507         this.loading.enable();
12508     },
12509
12510     // private
12511     onPagingKeydown : function(e){
12512         var k = e.getKey();
12513         var d = this.getPageData();
12514         if(k == e.RETURN){
12515             var v = this.field.dom.value, pageNum;
12516             if(!v || isNaN(pageNum = parseInt(v, 10))){
12517                 this.field.dom.value = d.activePage;
12518                 return;
12519             }
12520             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
12521             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
12522             e.stopEvent();
12523         }
12524         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))
12525         {
12526           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
12527           this.field.dom.value = pageNum;
12528           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
12529           e.stopEvent();
12530         }
12531         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
12532         {
12533           var v = this.field.dom.value, pageNum; 
12534           var increment = (e.shiftKey) ? 10 : 1;
12535           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
12536             increment *= -1;
12537           if(!v || isNaN(pageNum = parseInt(v, 10))) {
12538             this.field.dom.value = d.activePage;
12539             return;
12540           }
12541           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
12542           {
12543             this.field.dom.value = parseInt(v, 10) + increment;
12544             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
12545             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
12546           }
12547           e.stopEvent();
12548         }
12549     },
12550
12551     // private
12552     beforeLoad : function(){
12553         if(this.loading){
12554             this.loading.disable();
12555         }
12556     },
12557
12558     // private
12559     onClick : function(which){
12560         var ds = this.ds;
12561         switch(which){
12562             case "first":
12563                 ds.load({params:{start: 0, limit: this.pageSize}});
12564             break;
12565             case "prev":
12566                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
12567             break;
12568             case "next":
12569                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
12570             break;
12571             case "last":
12572                 var total = ds.getTotalCount();
12573                 var extra = total % this.pageSize;
12574                 var lastStart = extra ? (total - extra) : total-this.pageSize;
12575                 ds.load({params:{start: lastStart, limit: this.pageSize}});
12576             break;
12577             case "refresh":
12578                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
12579             break;
12580         }
12581     },
12582
12583     /**
12584      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
12585      * @param {Roo.data.Store} store The data store to unbind
12586      */
12587     unbind : function(ds){
12588         ds.un("beforeload", this.beforeLoad, this);
12589         ds.un("load", this.onLoad, this);
12590         ds.un("loadexception", this.onLoadError, this);
12591         ds.un("remove", this.updateInfo, this);
12592         ds.un("add", this.updateInfo, this);
12593         this.ds = undefined;
12594     },
12595
12596     /**
12597      * Binds the paging toolbar to the specified {@link Roo.data.Store}
12598      * @param {Roo.data.Store} store The data store to bind
12599      */
12600     bind : function(ds){
12601         ds.on("beforeload", this.beforeLoad, this);
12602         ds.on("load", this.onLoad, this);
12603         ds.on("loadexception", this.onLoadError, this);
12604         ds.on("remove", this.updateInfo, this);
12605         ds.on("add", this.updateInfo, this);
12606         this.ds = ds;
12607     }
12608 });/*
12609  * Based on:
12610  * Ext JS Library 1.1.1
12611  * Copyright(c) 2006-2007, Ext JS, LLC.
12612  *
12613  * Originally Released Under LGPL - original licence link has changed is not relivant.
12614  *
12615  * Fork - LGPL
12616  * <script type="text/javascript">
12617  */
12618
12619 /**
12620  * @class Roo.Resizable
12621  * @extends Roo.util.Observable
12622  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
12623  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
12624  * 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
12625  * the element will be wrapped for you automatically.</p>
12626  * <p>Here is the list of valid resize handles:</p>
12627  * <pre>
12628 Value   Description
12629 ------  -------------------
12630  'n'     north
12631  's'     south
12632  'e'     east
12633  'w'     west
12634  'nw'    northwest
12635  'sw'    southwest
12636  'se'    southeast
12637  'ne'    northeast
12638  'hd'    horizontal drag
12639  'all'   all
12640 </pre>
12641  * <p>Here's an example showing the creation of a typical Resizable:</p>
12642  * <pre><code>
12643 var resizer = new Roo.Resizable("element-id", {
12644     handles: 'all',
12645     minWidth: 200,
12646     minHeight: 100,
12647     maxWidth: 500,
12648     maxHeight: 400,
12649     pinned: true
12650 });
12651 resizer.on("resize", myHandler);
12652 </code></pre>
12653  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
12654  * resizer.east.setDisplayed(false);</p>
12655  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
12656  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
12657  * resize operation's new size (defaults to [0, 0])
12658  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
12659  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
12660  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
12661  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
12662  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
12663  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
12664  * @cfg {Number} width The width of the element in pixels (defaults to null)
12665  * @cfg {Number} height The height of the element in pixels (defaults to null)
12666  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
12667  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
12668  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
12669  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
12670  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
12671  * in favor of the handles config option (defaults to false)
12672  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
12673  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
12674  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
12675  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
12676  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
12677  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
12678  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
12679  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
12680  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
12681  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
12682  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
12683  * @constructor
12684  * Create a new resizable component
12685  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
12686  * @param {Object} config configuration options
12687   */
12688 Roo.Resizable = function(el, config)
12689 {
12690     this.el = Roo.get(el);
12691
12692     if(config && config.wrap){
12693         config.resizeChild = this.el;
12694         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
12695         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
12696         this.el.setStyle("overflow", "hidden");
12697         this.el.setPositioning(config.resizeChild.getPositioning());
12698         config.resizeChild.clearPositioning();
12699         if(!config.width || !config.height){
12700             var csize = config.resizeChild.getSize();
12701             this.el.setSize(csize.width, csize.height);
12702         }
12703         if(config.pinned && !config.adjustments){
12704             config.adjustments = "auto";
12705         }
12706     }
12707
12708     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
12709     this.proxy.unselectable();
12710     this.proxy.enableDisplayMode('block');
12711
12712     Roo.apply(this, config);
12713
12714     if(this.pinned){
12715         this.disableTrackOver = true;
12716         this.el.addClass("x-resizable-pinned");
12717     }
12718     // if the element isn't positioned, make it relative
12719     var position = this.el.getStyle("position");
12720     if(position != "absolute" && position != "fixed"){
12721         this.el.setStyle("position", "relative");
12722     }
12723     if(!this.handles){ // no handles passed, must be legacy style
12724         this.handles = 's,e,se';
12725         if(this.multiDirectional){
12726             this.handles += ',n,w';
12727         }
12728     }
12729     if(this.handles == "all"){
12730         this.handles = "n s e w ne nw se sw";
12731     }
12732     var hs = this.handles.split(/\s*?[,;]\s*?| /);
12733     var ps = Roo.Resizable.positions;
12734     for(var i = 0, len = hs.length; i < len; i++){
12735         if(hs[i] && ps[hs[i]]){
12736             var pos = ps[hs[i]];
12737             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
12738         }
12739     }
12740     // legacy
12741     this.corner = this.southeast;
12742     
12743     // updateBox = the box can move..
12744     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
12745         this.updateBox = true;
12746     }
12747
12748     this.activeHandle = null;
12749
12750     if(this.resizeChild){
12751         if(typeof this.resizeChild == "boolean"){
12752             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
12753         }else{
12754             this.resizeChild = Roo.get(this.resizeChild, true);
12755         }
12756     }
12757     
12758     if(this.adjustments == "auto"){
12759         var rc = this.resizeChild;
12760         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
12761         if(rc && (hw || hn)){
12762             rc.position("relative");
12763             rc.setLeft(hw ? hw.el.getWidth() : 0);
12764             rc.setTop(hn ? hn.el.getHeight() : 0);
12765         }
12766         this.adjustments = [
12767             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
12768             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
12769         ];
12770     }
12771
12772     if(this.draggable){
12773         this.dd = this.dynamic ?
12774             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
12775         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
12776     }
12777
12778     // public events
12779     this.addEvents({
12780         /**
12781          * @event beforeresize
12782          * Fired before resize is allowed. Set enabled to false to cancel resize.
12783          * @param {Roo.Resizable} this
12784          * @param {Roo.EventObject} e The mousedown event
12785          */
12786         "beforeresize" : true,
12787         /**
12788          * @event resizing
12789          * Fired a resizing.
12790          * @param {Roo.Resizable} this
12791          * @param {Number} x The new x position
12792          * @param {Number} y The new y position
12793          * @param {Number} w The new w width
12794          * @param {Number} h The new h hight
12795          * @param {Roo.EventObject} e The mouseup event
12796          */
12797         "resizing" : true,
12798         /**
12799          * @event resize
12800          * Fired after a resize.
12801          * @param {Roo.Resizable} this
12802          * @param {Number} width The new width
12803          * @param {Number} height The new height
12804          * @param {Roo.EventObject} e The mouseup event
12805          */
12806         "resize" : true
12807     });
12808
12809     if(this.width !== null && this.height !== null){
12810         this.resizeTo(this.width, this.height);
12811     }else{
12812         this.updateChildSize();
12813     }
12814     if(Roo.isIE){
12815         this.el.dom.style.zoom = 1;
12816     }
12817     Roo.Resizable.superclass.constructor.call(this);
12818 };
12819
12820 Roo.extend(Roo.Resizable, Roo.util.Observable, {
12821         resizeChild : false,
12822         adjustments : [0, 0],
12823         minWidth : 5,
12824         minHeight : 5,
12825         maxWidth : 10000,
12826         maxHeight : 10000,
12827         enabled : true,
12828         animate : false,
12829         duration : .35,
12830         dynamic : false,
12831         handles : false,
12832         multiDirectional : false,
12833         disableTrackOver : false,
12834         easing : 'easeOutStrong',
12835         widthIncrement : 0,
12836         heightIncrement : 0,
12837         pinned : false,
12838         width : null,
12839         height : null,
12840         preserveRatio : false,
12841         transparent: false,
12842         minX: 0,
12843         minY: 0,
12844         draggable: false,
12845
12846         /**
12847          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
12848          */
12849         constrainTo: undefined,
12850         /**
12851          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
12852          */
12853         resizeRegion: undefined,
12854
12855
12856     /**
12857      * Perform a manual resize
12858      * @param {Number} width
12859      * @param {Number} height
12860      */
12861     resizeTo : function(width, height){
12862         this.el.setSize(width, height);
12863         this.updateChildSize();
12864         this.fireEvent("resize", this, width, height, null);
12865     },
12866
12867     // private
12868     startSizing : function(e, handle){
12869         this.fireEvent("beforeresize", this, e);
12870         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
12871
12872             if(!this.overlay){
12873                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
12874                 this.overlay.unselectable();
12875                 this.overlay.enableDisplayMode("block");
12876                 this.overlay.on("mousemove", this.onMouseMove, this);
12877                 this.overlay.on("mouseup", this.onMouseUp, this);
12878             }
12879             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
12880
12881             this.resizing = true;
12882             this.startBox = this.el.getBox();
12883             this.startPoint = e.getXY();
12884             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
12885                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
12886
12887             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
12888             this.overlay.show();
12889
12890             if(this.constrainTo) {
12891                 var ct = Roo.get(this.constrainTo);
12892                 this.resizeRegion = ct.getRegion().adjust(
12893                     ct.getFrameWidth('t'),
12894                     ct.getFrameWidth('l'),
12895                     -ct.getFrameWidth('b'),
12896                     -ct.getFrameWidth('r')
12897                 );
12898             }
12899
12900             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
12901             this.proxy.show();
12902             this.proxy.setBox(this.startBox);
12903             if(!this.dynamic){
12904                 this.proxy.setStyle('visibility', 'visible');
12905             }
12906         }
12907     },
12908
12909     // private
12910     onMouseDown : function(handle, e){
12911         if(this.enabled){
12912             e.stopEvent();
12913             this.activeHandle = handle;
12914             this.startSizing(e, handle);
12915         }
12916     },
12917
12918     // private
12919     onMouseUp : function(e){
12920         var size = this.resizeElement();
12921         this.resizing = false;
12922         this.handleOut();
12923         this.overlay.hide();
12924         this.proxy.hide();
12925         this.fireEvent("resize", this, size.width, size.height, e);
12926     },
12927
12928     // private
12929     updateChildSize : function(){
12930         
12931         if(this.resizeChild){
12932             var el = this.el;
12933             var child = this.resizeChild;
12934             var adj = this.adjustments;
12935             if(el.dom.offsetWidth){
12936                 var b = el.getSize(true);
12937                 child.setSize(b.width+adj[0], b.height+adj[1]);
12938             }
12939             // Second call here for IE
12940             // The first call enables instant resizing and
12941             // the second call corrects scroll bars if they
12942             // exist
12943             if(Roo.isIE){
12944                 setTimeout(function(){
12945                     if(el.dom.offsetWidth){
12946                         var b = el.getSize(true);
12947                         child.setSize(b.width+adj[0], b.height+adj[1]);
12948                     }
12949                 }, 10);
12950             }
12951         }
12952     },
12953
12954     // private
12955     snap : function(value, inc, min){
12956         if(!inc || !value) return value;
12957         var newValue = value;
12958         var m = value % inc;
12959         if(m > 0){
12960             if(m > (inc/2)){
12961                 newValue = value + (inc-m);
12962             }else{
12963                 newValue = value - m;
12964             }
12965         }
12966         return Math.max(min, newValue);
12967     },
12968
12969     // private
12970     resizeElement : function(){
12971         var box = this.proxy.getBox();
12972         if(this.updateBox){
12973             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
12974         }else{
12975             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
12976         }
12977         this.updateChildSize();
12978         if(!this.dynamic){
12979             this.proxy.hide();
12980         }
12981         return box;
12982     },
12983
12984     // private
12985     constrain : function(v, diff, m, mx){
12986         if(v - diff < m){
12987             diff = v - m;
12988         }else if(v - diff > mx){
12989             diff = mx - v;
12990         }
12991         return diff;
12992     },
12993
12994     // private
12995     onMouseMove : function(e){
12996         
12997         if(this.enabled){
12998             try{// try catch so if something goes wrong the user doesn't get hung
12999
13000             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
13001                 return;
13002             }
13003
13004             //var curXY = this.startPoint;
13005             var curSize = this.curSize || this.startBox;
13006             var x = this.startBox.x, y = this.startBox.y;
13007             var ox = x, oy = y;
13008             var w = curSize.width, h = curSize.height;
13009             var ow = w, oh = h;
13010             var mw = this.minWidth, mh = this.minHeight;
13011             var mxw = this.maxWidth, mxh = this.maxHeight;
13012             var wi = this.widthIncrement;
13013             var hi = this.heightIncrement;
13014
13015             var eventXY = e.getXY();
13016             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
13017             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
13018
13019             var pos = this.activeHandle.position;
13020
13021             switch(pos){
13022                 case "east":
13023                     w += diffX;
13024                     w = Math.min(Math.max(mw, w), mxw);
13025                     break;
13026              
13027                 case "south":
13028                     h += diffY;
13029                     h = Math.min(Math.max(mh, h), mxh);
13030                     break;
13031                 case "southeast":
13032                     w += diffX;
13033                     h += diffY;
13034                     w = Math.min(Math.max(mw, w), mxw);
13035                     h = Math.min(Math.max(mh, h), mxh);
13036                     break;
13037                 case "north":
13038                     diffY = this.constrain(h, diffY, mh, mxh);
13039                     y += diffY;
13040                     h -= diffY;
13041                     break;
13042                 case "hdrag":
13043                     
13044                     if (wi) {
13045                         var adiffX = Math.abs(diffX);
13046                         var sub = (adiffX % wi); // how much 
13047                         if (sub > (wi/2)) { // far enough to snap
13048                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
13049                         } else {
13050                             // remove difference.. 
13051                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
13052                         }
13053                     }
13054                     x += diffX;
13055                     x = Math.max(this.minX, x);
13056                     break;
13057                 case "west":
13058                     diffX = this.constrain(w, diffX, mw, mxw);
13059                     x += diffX;
13060                     w -= diffX;
13061                     break;
13062                 case "northeast":
13063                     w += diffX;
13064                     w = Math.min(Math.max(mw, w), mxw);
13065                     diffY = this.constrain(h, diffY, mh, mxh);
13066                     y += diffY;
13067                     h -= diffY;
13068                     break;
13069                 case "northwest":
13070                     diffX = this.constrain(w, diffX, mw, mxw);
13071                     diffY = this.constrain(h, diffY, mh, mxh);
13072                     y += diffY;
13073                     h -= diffY;
13074                     x += diffX;
13075                     w -= diffX;
13076                     break;
13077                case "southwest":
13078                     diffX = this.constrain(w, diffX, mw, mxw);
13079                     h += diffY;
13080                     h = Math.min(Math.max(mh, h), mxh);
13081                     x += diffX;
13082                     w -= diffX;
13083                     break;
13084             }
13085
13086             var sw = this.snap(w, wi, mw);
13087             var sh = this.snap(h, hi, mh);
13088             if(sw != w || sh != h){
13089                 switch(pos){
13090                     case "northeast":
13091                         y -= sh - h;
13092                     break;
13093                     case "north":
13094                         y -= sh - h;
13095                         break;
13096                     case "southwest":
13097                         x -= sw - w;
13098                     break;
13099                     case "west":
13100                         x -= sw - w;
13101                         break;
13102                     case "northwest":
13103                         x -= sw - w;
13104                         y -= sh - h;
13105                     break;
13106                 }
13107                 w = sw;
13108                 h = sh;
13109             }
13110
13111             if(this.preserveRatio){
13112                 switch(pos){
13113                     case "southeast":
13114                     case "east":
13115                         h = oh * (w/ow);
13116                         h = Math.min(Math.max(mh, h), mxh);
13117                         w = ow * (h/oh);
13118                        break;
13119                     case "south":
13120                         w = ow * (h/oh);
13121                         w = Math.min(Math.max(mw, w), mxw);
13122                         h = oh * (w/ow);
13123                         break;
13124                     case "northeast":
13125                         w = ow * (h/oh);
13126                         w = Math.min(Math.max(mw, w), mxw);
13127                         h = oh * (w/ow);
13128                     break;
13129                     case "north":
13130                         var tw = w;
13131                         w = ow * (h/oh);
13132                         w = Math.min(Math.max(mw, w), mxw);
13133                         h = oh * (w/ow);
13134                         x += (tw - w) / 2;
13135                         break;
13136                     case "southwest":
13137                         h = oh * (w/ow);
13138                         h = Math.min(Math.max(mh, h), mxh);
13139                         var tw = w;
13140                         w = ow * (h/oh);
13141                         x += tw - w;
13142                         break;
13143                     case "west":
13144                         var th = h;
13145                         h = oh * (w/ow);
13146                         h = Math.min(Math.max(mh, h), mxh);
13147                         y += (th - h) / 2;
13148                         var tw = w;
13149                         w = ow * (h/oh);
13150                         x += tw - w;
13151                        break;
13152                     case "northwest":
13153                         var tw = w;
13154                         var th = h;
13155                         h = oh * (w/ow);
13156                         h = Math.min(Math.max(mh, h), mxh);
13157                         w = ow * (h/oh);
13158                         y += th - h;
13159                         x += tw - w;
13160                        break;
13161
13162                 }
13163             }
13164             if (pos == 'hdrag') {
13165                 w = ow;
13166             }
13167             this.proxy.setBounds(x, y, w, h);
13168             if(this.dynamic){
13169                 this.resizeElement();
13170             }
13171             }catch(e){}
13172         }
13173         this.fireEvent("resizing", this, x, y, w, h, e);
13174     },
13175
13176     // private
13177     handleOver : function(){
13178         if(this.enabled){
13179             this.el.addClass("x-resizable-over");
13180         }
13181     },
13182
13183     // private
13184     handleOut : function(){
13185         if(!this.resizing){
13186             this.el.removeClass("x-resizable-over");
13187         }
13188     },
13189
13190     /**
13191      * Returns the element this component is bound to.
13192      * @return {Roo.Element}
13193      */
13194     getEl : function(){
13195         return this.el;
13196     },
13197
13198     /**
13199      * Returns the resizeChild element (or null).
13200      * @return {Roo.Element}
13201      */
13202     getResizeChild : function(){
13203         return this.resizeChild;
13204     },
13205     groupHandler : function()
13206     {
13207         
13208     },
13209     /**
13210      * Destroys this resizable. If the element was wrapped and
13211      * removeEl is not true then the element remains.
13212      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
13213      */
13214     destroy : function(removeEl){
13215         this.proxy.remove();
13216         if(this.overlay){
13217             this.overlay.removeAllListeners();
13218             this.overlay.remove();
13219         }
13220         var ps = Roo.Resizable.positions;
13221         for(var k in ps){
13222             if(typeof ps[k] != "function" && this[ps[k]]){
13223                 var h = this[ps[k]];
13224                 h.el.removeAllListeners();
13225                 h.el.remove();
13226             }
13227         }
13228         if(removeEl){
13229             this.el.update("");
13230             this.el.remove();
13231         }
13232     }
13233 });
13234
13235 // private
13236 // hash to map config positions to true positions
13237 Roo.Resizable.positions = {
13238     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
13239     hd: "hdrag"
13240 };
13241
13242 // private
13243 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
13244     if(!this.tpl){
13245         // only initialize the template if resizable is used
13246         var tpl = Roo.DomHelper.createTemplate(
13247             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
13248         );
13249         tpl.compile();
13250         Roo.Resizable.Handle.prototype.tpl = tpl;
13251     }
13252     this.position = pos;
13253     this.rz = rz;
13254     // show north drag fro topdra
13255     var handlepos = pos == 'hdrag' ? 'north' : pos;
13256     
13257     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
13258     if (pos == 'hdrag') {
13259         this.el.setStyle('cursor', 'pointer');
13260     }
13261     this.el.unselectable();
13262     if(transparent){
13263         this.el.setOpacity(0);
13264     }
13265     this.el.on("mousedown", this.onMouseDown, this);
13266     if(!disableTrackOver){
13267         this.el.on("mouseover", this.onMouseOver, this);
13268         this.el.on("mouseout", this.onMouseOut, this);
13269     }
13270 };
13271
13272 // private
13273 Roo.Resizable.Handle.prototype = {
13274     afterResize : function(rz){
13275         // do nothing
13276     },
13277     // private
13278     onMouseDown : function(e){
13279         this.rz.onMouseDown(this, e);
13280     },
13281     // private
13282     onMouseOver : function(e){
13283         this.rz.handleOver(this, e);
13284     },
13285     // private
13286     onMouseOut : function(e){
13287         this.rz.handleOut(this, e);
13288     }
13289 };/*
13290  * Based on:
13291  * Ext JS Library 1.1.1
13292  * Copyright(c) 2006-2007, Ext JS, LLC.
13293  *
13294  * Originally Released Under LGPL - original licence link has changed is not relivant.
13295  *
13296  * Fork - LGPL
13297  * <script type="text/javascript">
13298  */
13299
13300 /**
13301  * @class Roo.Editor
13302  * @extends Roo.Component
13303  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
13304  * @constructor
13305  * Create a new Editor
13306  * @param {Roo.form.Field} field The Field object (or descendant)
13307  * @param {Object} config The config object
13308  */
13309 Roo.Editor = function(field, config){
13310     Roo.Editor.superclass.constructor.call(this, config);
13311     this.field = field;
13312     this.addEvents({
13313         /**
13314              * @event beforestartedit
13315              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
13316              * false from the handler of this event.
13317              * @param {Editor} this
13318              * @param {Roo.Element} boundEl The underlying element bound to this editor
13319              * @param {Mixed} value The field value being set
13320              */
13321         "beforestartedit" : true,
13322         /**
13323              * @event startedit
13324              * Fires when this editor is displayed
13325              * @param {Roo.Element} boundEl The underlying element bound to this editor
13326              * @param {Mixed} value The starting field value
13327              */
13328         "startedit" : true,
13329         /**
13330              * @event beforecomplete
13331              * Fires after a change has been made to the field, but before the change is reflected in the underlying
13332              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
13333              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
13334              * event will not fire since no edit actually occurred.
13335              * @param {Editor} this
13336              * @param {Mixed} value The current field value
13337              * @param {Mixed} startValue The original field value
13338              */
13339         "beforecomplete" : true,
13340         /**
13341              * @event complete
13342              * Fires after editing is complete and any changed value has been written to the underlying field.
13343              * @param {Editor} this
13344              * @param {Mixed} value The current field value
13345              * @param {Mixed} startValue The original field value
13346              */
13347         "complete" : true,
13348         /**
13349          * @event specialkey
13350          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
13351          * {@link Roo.EventObject#getKey} to determine which key was pressed.
13352          * @param {Roo.form.Field} this
13353          * @param {Roo.EventObject} e The event object
13354          */
13355         "specialkey" : true
13356     });
13357 };
13358
13359 Roo.extend(Roo.Editor, Roo.Component, {
13360     /**
13361      * @cfg {Boolean/String} autosize
13362      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
13363      * or "height" to adopt the height only (defaults to false)
13364      */
13365     /**
13366      * @cfg {Boolean} revertInvalid
13367      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
13368      * validation fails (defaults to true)
13369      */
13370     /**
13371      * @cfg {Boolean} ignoreNoChange
13372      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
13373      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
13374      * will never be ignored.
13375      */
13376     /**
13377      * @cfg {Boolean} hideEl
13378      * False to keep the bound element visible while the editor is displayed (defaults to true)
13379      */
13380     /**
13381      * @cfg {Mixed} value
13382      * The data value of the underlying field (defaults to "")
13383      */
13384     value : "",
13385     /**
13386      * @cfg {String} alignment
13387      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
13388      */
13389     alignment: "c-c?",
13390     /**
13391      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
13392      * for bottom-right shadow (defaults to "frame")
13393      */
13394     shadow : "frame",
13395     /**
13396      * @cfg {Boolean} constrain True to constrain the editor to the viewport
13397      */
13398     constrain : false,
13399     /**
13400      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
13401      */
13402     completeOnEnter : false,
13403     /**
13404      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
13405      */
13406     cancelOnEsc : false,
13407     /**
13408      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
13409      */
13410     updateEl : false,
13411
13412     // private
13413     onRender : function(ct, position){
13414         this.el = new Roo.Layer({
13415             shadow: this.shadow,
13416             cls: "x-editor",
13417             parentEl : ct,
13418             shim : this.shim,
13419             shadowOffset:4,
13420             id: this.id,
13421             constrain: this.constrain
13422         });
13423         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
13424         if(this.field.msgTarget != 'title'){
13425             this.field.msgTarget = 'qtip';
13426         }
13427         this.field.render(this.el);
13428         if(Roo.isGecko){
13429             this.field.el.dom.setAttribute('autocomplete', 'off');
13430         }
13431         this.field.on("specialkey", this.onSpecialKey, this);
13432         if(this.swallowKeys){
13433             this.field.el.swallowEvent(['keydown','keypress']);
13434         }
13435         this.field.show();
13436         this.field.on("blur", this.onBlur, this);
13437         if(this.field.grow){
13438             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
13439         }
13440     },
13441
13442     onSpecialKey : function(field, e)
13443     {
13444         //Roo.log('editor onSpecialKey');
13445         if(this.completeOnEnter && e.getKey() == e.ENTER){
13446             e.stopEvent();
13447             this.completeEdit();
13448             return;
13449         }
13450         // do not fire special key otherwise it might hide close the editor...
13451         if(e.getKey() == e.ENTER){    
13452             return;
13453         }
13454         if(this.cancelOnEsc && e.getKey() == e.ESC){
13455             this.cancelEdit();
13456             return;
13457         } 
13458         this.fireEvent('specialkey', field, e);
13459     
13460     },
13461
13462     /**
13463      * Starts the editing process and shows the editor.
13464      * @param {String/HTMLElement/Element} el The element to edit
13465      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
13466       * to the innerHTML of el.
13467      */
13468     startEdit : function(el, value){
13469         if(this.editing){
13470             this.completeEdit();
13471         }
13472         this.boundEl = Roo.get(el);
13473         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
13474         if(!this.rendered){
13475             this.render(this.parentEl || document.body);
13476         }
13477         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
13478             return;
13479         }
13480         this.startValue = v;
13481         this.field.setValue(v);
13482         if(this.autoSize){
13483             var sz = this.boundEl.getSize();
13484             switch(this.autoSize){
13485                 case "width":
13486                 this.setSize(sz.width,  "");
13487                 break;
13488                 case "height":
13489                 this.setSize("",  sz.height);
13490                 break;
13491                 default:
13492                 this.setSize(sz.width,  sz.height);
13493             }
13494         }
13495         this.el.alignTo(this.boundEl, this.alignment);
13496         this.editing = true;
13497         if(Roo.QuickTips){
13498             Roo.QuickTips.disable();
13499         }
13500         this.show();
13501     },
13502
13503     /**
13504      * Sets the height and width of this editor.
13505      * @param {Number} width The new width
13506      * @param {Number} height The new height
13507      */
13508     setSize : function(w, h){
13509         this.field.setSize(w, h);
13510         if(this.el){
13511             this.el.sync();
13512         }
13513     },
13514
13515     /**
13516      * Realigns the editor to the bound field based on the current alignment config value.
13517      */
13518     realign : function(){
13519         this.el.alignTo(this.boundEl, this.alignment);
13520     },
13521
13522     /**
13523      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
13524      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
13525      */
13526     completeEdit : function(remainVisible){
13527         if(!this.editing){
13528             return;
13529         }
13530         var v = this.getValue();
13531         if(this.revertInvalid !== false && !this.field.isValid()){
13532             v = this.startValue;
13533             this.cancelEdit(true);
13534         }
13535         if(String(v) === String(this.startValue) && this.ignoreNoChange){
13536             this.editing = false;
13537             this.hide();
13538             return;
13539         }
13540         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
13541             this.editing = false;
13542             if(this.updateEl && this.boundEl){
13543                 this.boundEl.update(v);
13544             }
13545             if(remainVisible !== true){
13546                 this.hide();
13547             }
13548             this.fireEvent("complete", this, v, this.startValue);
13549         }
13550     },
13551
13552     // private
13553     onShow : function(){
13554         this.el.show();
13555         if(this.hideEl !== false){
13556             this.boundEl.hide();
13557         }
13558         this.field.show();
13559         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
13560             this.fixIEFocus = true;
13561             this.deferredFocus.defer(50, this);
13562         }else{
13563             this.field.focus();
13564         }
13565         this.fireEvent("startedit", this.boundEl, this.startValue);
13566     },
13567
13568     deferredFocus : function(){
13569         if(this.editing){
13570             this.field.focus();
13571         }
13572     },
13573
13574     /**
13575      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
13576      * reverted to the original starting value.
13577      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
13578      * cancel (defaults to false)
13579      */
13580     cancelEdit : function(remainVisible){
13581         if(this.editing){
13582             this.setValue(this.startValue);
13583             if(remainVisible !== true){
13584                 this.hide();
13585             }
13586         }
13587     },
13588
13589     // private
13590     onBlur : function(){
13591         if(this.allowBlur !== true && this.editing){
13592             this.completeEdit();
13593         }
13594     },
13595
13596     // private
13597     onHide : function(){
13598         if(this.editing){
13599             this.completeEdit();
13600             return;
13601         }
13602         this.field.blur();
13603         if(this.field.collapse){
13604             this.field.collapse();
13605         }
13606         this.el.hide();
13607         if(this.hideEl !== false){
13608             this.boundEl.show();
13609         }
13610         if(Roo.QuickTips){
13611             Roo.QuickTips.enable();
13612         }
13613     },
13614
13615     /**
13616      * Sets the data value of the editor
13617      * @param {Mixed} value Any valid value supported by the underlying field
13618      */
13619     setValue : function(v){
13620         this.field.setValue(v);
13621     },
13622
13623     /**
13624      * Gets the data value of the editor
13625      * @return {Mixed} The data value
13626      */
13627     getValue : function(){
13628         return this.field.getValue();
13629     }
13630 });/*
13631  * Based on:
13632  * Ext JS Library 1.1.1
13633  * Copyright(c) 2006-2007, Ext JS, LLC.
13634  *
13635  * Originally Released Under LGPL - original licence link has changed is not relivant.
13636  *
13637  * Fork - LGPL
13638  * <script type="text/javascript">
13639  */
13640  
13641 /**
13642  * @class Roo.BasicDialog
13643  * @extends Roo.util.Observable
13644  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
13645  * <pre><code>
13646 var dlg = new Roo.BasicDialog("my-dlg", {
13647     height: 200,
13648     width: 300,
13649     minHeight: 100,
13650     minWidth: 150,
13651     modal: true,
13652     proxyDrag: true,
13653     shadow: true
13654 });
13655 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
13656 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
13657 dlg.addButton('Cancel', dlg.hide, dlg);
13658 dlg.show();
13659 </code></pre>
13660   <b>A Dialog should always be a direct child of the body element.</b>
13661  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
13662  * @cfg {String} title Default text to display in the title bar (defaults to null)
13663  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
13664  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
13665  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
13666  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
13667  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
13668  * (defaults to null with no animation)
13669  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
13670  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
13671  * property for valid values (defaults to 'all')
13672  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
13673  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
13674  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
13675  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
13676  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
13677  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
13678  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
13679  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
13680  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
13681  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
13682  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
13683  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
13684  * draggable = true (defaults to false)
13685  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
13686  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
13687  * shadow (defaults to false)
13688  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
13689  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
13690  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
13691  * @cfg {Array} buttons Array of buttons
13692  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
13693  * @constructor
13694  * Create a new BasicDialog.
13695  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
13696  * @param {Object} config Configuration options
13697  */
13698 Roo.BasicDialog = function(el, config){
13699     this.el = Roo.get(el);
13700     var dh = Roo.DomHelper;
13701     if(!this.el && config && config.autoCreate){
13702         if(typeof config.autoCreate == "object"){
13703             if(!config.autoCreate.id){
13704                 config.autoCreate.id = el;
13705             }
13706             this.el = dh.append(document.body,
13707                         config.autoCreate, true);
13708         }else{
13709             this.el = dh.append(document.body,
13710                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
13711         }
13712     }
13713     el = this.el;
13714     el.setDisplayed(true);
13715     el.hide = this.hideAction;
13716     this.id = el.id;
13717     el.addClass("x-dlg");
13718
13719     Roo.apply(this, config);
13720
13721     this.proxy = el.createProxy("x-dlg-proxy");
13722     this.proxy.hide = this.hideAction;
13723     this.proxy.setOpacity(.5);
13724     this.proxy.hide();
13725
13726     if(config.width){
13727         el.setWidth(config.width);
13728     }
13729     if(config.height){
13730         el.setHeight(config.height);
13731     }
13732     this.size = el.getSize();
13733     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
13734         this.xy = [config.x,config.y];
13735     }else{
13736         this.xy = el.getCenterXY(true);
13737     }
13738     /** The header element @type Roo.Element */
13739     this.header = el.child("> .x-dlg-hd");
13740     /** The body element @type Roo.Element */
13741     this.body = el.child("> .x-dlg-bd");
13742     /** The footer element @type Roo.Element */
13743     this.footer = el.child("> .x-dlg-ft");
13744
13745     if(!this.header){
13746         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
13747     }
13748     if(!this.body){
13749         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
13750     }
13751
13752     this.header.unselectable();
13753     if(this.title){
13754         this.header.update(this.title);
13755     }
13756     // this element allows the dialog to be focused for keyboard event
13757     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
13758     this.focusEl.swallowEvent("click", true);
13759
13760     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
13761
13762     // wrap the body and footer for special rendering
13763     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
13764     if(this.footer){
13765         this.bwrap.dom.appendChild(this.footer.dom);
13766     }
13767
13768     this.bg = this.el.createChild({
13769         tag: "div", cls:"x-dlg-bg",
13770         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
13771     });
13772     this.centerBg = this.bg.child("div.x-dlg-bg-center");
13773
13774
13775     if(this.autoScroll !== false && !this.autoTabs){
13776         this.body.setStyle("overflow", "auto");
13777     }
13778
13779     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
13780
13781     if(this.closable !== false){
13782         this.el.addClass("x-dlg-closable");
13783         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
13784         this.close.on("click", this.closeClick, this);
13785         this.close.addClassOnOver("x-dlg-close-over");
13786     }
13787     if(this.collapsible !== false){
13788         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
13789         this.collapseBtn.on("click", this.collapseClick, this);
13790         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
13791         this.header.on("dblclick", this.collapseClick, this);
13792     }
13793     if(this.resizable !== false){
13794         this.el.addClass("x-dlg-resizable");
13795         this.resizer = new Roo.Resizable(el, {
13796             minWidth: this.minWidth || 80,
13797             minHeight:this.minHeight || 80,
13798             handles: this.resizeHandles || "all",
13799             pinned: true
13800         });
13801         this.resizer.on("beforeresize", this.beforeResize, this);
13802         this.resizer.on("resize", this.onResize, this);
13803     }
13804     if(this.draggable !== false){
13805         el.addClass("x-dlg-draggable");
13806         if (!this.proxyDrag) {
13807             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
13808         }
13809         else {
13810             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
13811         }
13812         dd.setHandleElId(this.header.id);
13813         dd.endDrag = this.endMove.createDelegate(this);
13814         dd.startDrag = this.startMove.createDelegate(this);
13815         dd.onDrag = this.onDrag.createDelegate(this);
13816         dd.scroll = false;
13817         this.dd = dd;
13818     }
13819     if(this.modal){
13820         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
13821         this.mask.enableDisplayMode("block");
13822         this.mask.hide();
13823         this.el.addClass("x-dlg-modal");
13824     }
13825     if(this.shadow){
13826         this.shadow = new Roo.Shadow({
13827             mode : typeof this.shadow == "string" ? this.shadow : "sides",
13828             offset : this.shadowOffset
13829         });
13830     }else{
13831         this.shadowOffset = 0;
13832     }
13833     if(Roo.useShims && this.shim !== false){
13834         this.shim = this.el.createShim();
13835         this.shim.hide = this.hideAction;
13836         this.shim.hide();
13837     }else{
13838         this.shim = false;
13839     }
13840     if(this.autoTabs){
13841         this.initTabs();
13842     }
13843     if (this.buttons) { 
13844         var bts= this.buttons;
13845         this.buttons = [];
13846         Roo.each(bts, function(b) {
13847             this.addButton(b);
13848         }, this);
13849     }
13850     
13851     
13852     this.addEvents({
13853         /**
13854          * @event keydown
13855          * Fires when a key is pressed
13856          * @param {Roo.BasicDialog} this
13857          * @param {Roo.EventObject} e
13858          */
13859         "keydown" : true,
13860         /**
13861          * @event move
13862          * Fires when this dialog is moved by the user.
13863          * @param {Roo.BasicDialog} this
13864          * @param {Number} x The new page X
13865          * @param {Number} y The new page Y
13866          */
13867         "move" : true,
13868         /**
13869          * @event resize
13870          * Fires when this dialog is resized by the user.
13871          * @param {Roo.BasicDialog} this
13872          * @param {Number} width The new width
13873          * @param {Number} height The new height
13874          */
13875         "resize" : true,
13876         /**
13877          * @event beforehide
13878          * Fires before this dialog is hidden.
13879          * @param {Roo.BasicDialog} this
13880          */
13881         "beforehide" : true,
13882         /**
13883          * @event hide
13884          * Fires when this dialog is hidden.
13885          * @param {Roo.BasicDialog} this
13886          */
13887         "hide" : true,
13888         /**
13889          * @event beforeshow
13890          * Fires before this dialog is shown.
13891          * @param {Roo.BasicDialog} this
13892          */
13893         "beforeshow" : true,
13894         /**
13895          * @event show
13896          * Fires when this dialog is shown.
13897          * @param {Roo.BasicDialog} this
13898          */
13899         "show" : true
13900     });
13901     el.on("keydown", this.onKeyDown, this);
13902     el.on("mousedown", this.toFront, this);
13903     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
13904     this.el.hide();
13905     Roo.DialogManager.register(this);
13906     Roo.BasicDialog.superclass.constructor.call(this);
13907 };
13908
13909 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
13910     shadowOffset: Roo.isIE ? 6 : 5,
13911     minHeight: 80,
13912     minWidth: 200,
13913     minButtonWidth: 75,
13914     defaultButton: null,
13915     buttonAlign: "right",
13916     tabTag: 'div',
13917     firstShow: true,
13918
13919     /**
13920      * Sets the dialog title text
13921      * @param {String} text The title text to display
13922      * @return {Roo.BasicDialog} this
13923      */
13924     setTitle : function(text){
13925         this.header.update(text);
13926         return this;
13927     },
13928
13929     // private
13930     closeClick : function(){
13931         this.hide();
13932     },
13933
13934     // private
13935     collapseClick : function(){
13936         this[this.collapsed ? "expand" : "collapse"]();
13937     },
13938
13939     /**
13940      * Collapses the dialog to its minimized state (only the title bar is visible).
13941      * Equivalent to the user clicking the collapse dialog button.
13942      */
13943     collapse : function(){
13944         if(!this.collapsed){
13945             this.collapsed = true;
13946             this.el.addClass("x-dlg-collapsed");
13947             this.restoreHeight = this.el.getHeight();
13948             this.resizeTo(this.el.getWidth(), this.header.getHeight());
13949         }
13950     },
13951
13952     /**
13953      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
13954      * clicking the expand dialog button.
13955      */
13956     expand : function(){
13957         if(this.collapsed){
13958             this.collapsed = false;
13959             this.el.removeClass("x-dlg-collapsed");
13960             this.resizeTo(this.el.getWidth(), this.restoreHeight);
13961         }
13962     },
13963
13964     /**
13965      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
13966      * @return {Roo.TabPanel} The tabs component
13967      */
13968     initTabs : function(){
13969         var tabs = this.getTabs();
13970         while(tabs.getTab(0)){
13971             tabs.removeTab(0);
13972         }
13973         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
13974             var dom = el.dom;
13975             tabs.addTab(Roo.id(dom), dom.title);
13976             dom.title = "";
13977         });
13978         tabs.activate(0);
13979         return tabs;
13980     },
13981
13982     // private
13983     beforeResize : function(){
13984         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
13985     },
13986
13987     // private
13988     onResize : function(){
13989         this.refreshSize();
13990         this.syncBodyHeight();
13991         this.adjustAssets();
13992         this.focus();
13993         this.fireEvent("resize", this, this.size.width, this.size.height);
13994     },
13995
13996     // private
13997     onKeyDown : function(e){
13998         if(this.isVisible()){
13999             this.fireEvent("keydown", this, e);
14000         }
14001     },
14002
14003     /**
14004      * Resizes the dialog.
14005      * @param {Number} width
14006      * @param {Number} height
14007      * @return {Roo.BasicDialog} this
14008      */
14009     resizeTo : function(width, height){
14010         this.el.setSize(width, height);
14011         this.size = {width: width, height: height};
14012         this.syncBodyHeight();
14013         if(this.fixedcenter){
14014             this.center();
14015         }
14016         if(this.isVisible()){
14017             this.constrainXY();
14018             this.adjustAssets();
14019         }
14020         this.fireEvent("resize", this, width, height);
14021         return this;
14022     },
14023
14024
14025     /**
14026      * Resizes the dialog to fit the specified content size.
14027      * @param {Number} width
14028      * @param {Number} height
14029      * @return {Roo.BasicDialog} this
14030      */
14031     setContentSize : function(w, h){
14032         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
14033         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
14034         //if(!this.el.isBorderBox()){
14035             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
14036             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
14037         //}
14038         if(this.tabs){
14039             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
14040             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
14041         }
14042         this.resizeTo(w, h);
14043         return this;
14044     },
14045
14046     /**
14047      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
14048      * executed in response to a particular key being pressed while the dialog is active.
14049      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
14050      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14051      * @param {Function} fn The function to call
14052      * @param {Object} scope (optional) The scope of the function
14053      * @return {Roo.BasicDialog} this
14054      */
14055     addKeyListener : function(key, fn, scope){
14056         var keyCode, shift, ctrl, alt;
14057         if(typeof key == "object" && !(key instanceof Array)){
14058             keyCode = key["key"];
14059             shift = key["shift"];
14060             ctrl = key["ctrl"];
14061             alt = key["alt"];
14062         }else{
14063             keyCode = key;
14064         }
14065         var handler = function(dlg, e){
14066             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
14067                 var k = e.getKey();
14068                 if(keyCode instanceof Array){
14069                     for(var i = 0, len = keyCode.length; i < len; i++){
14070                         if(keyCode[i] == k){
14071                           fn.call(scope || window, dlg, k, e);
14072                           return;
14073                         }
14074                     }
14075                 }else{
14076                     if(k == keyCode){
14077                         fn.call(scope || window, dlg, k, e);
14078                     }
14079                 }
14080             }
14081         };
14082         this.on("keydown", handler);
14083         return this;
14084     },
14085
14086     /**
14087      * Returns the TabPanel component (creates it if it doesn't exist).
14088      * Note: If you wish to simply check for the existence of tabs without creating them,
14089      * check for a null 'tabs' property.
14090      * @return {Roo.TabPanel} The tabs component
14091      */
14092     getTabs : function(){
14093         if(!this.tabs){
14094             this.el.addClass("x-dlg-auto-tabs");
14095             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
14096             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
14097         }
14098         return this.tabs;
14099     },
14100
14101     /**
14102      * Adds a button to the footer section of the dialog.
14103      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
14104      * object or a valid Roo.DomHelper element config
14105      * @param {Function} handler The function called when the button is clicked
14106      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
14107      * @return {Roo.Button} The new button
14108      */
14109     addButton : function(config, handler, scope){
14110         var dh = Roo.DomHelper;
14111         if(!this.footer){
14112             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
14113         }
14114         if(!this.btnContainer){
14115             var tb = this.footer.createChild({
14116
14117                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
14118                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
14119             }, null, true);
14120             this.btnContainer = tb.firstChild.firstChild.firstChild;
14121         }
14122         var bconfig = {
14123             handler: handler,
14124             scope: scope,
14125             minWidth: this.minButtonWidth,
14126             hideParent:true
14127         };
14128         if(typeof config == "string"){
14129             bconfig.text = config;
14130         }else{
14131             if(config.tag){
14132                 bconfig.dhconfig = config;
14133             }else{
14134                 Roo.apply(bconfig, config);
14135             }
14136         }
14137         var fc = false;
14138         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
14139             bconfig.position = Math.max(0, bconfig.position);
14140             fc = this.btnContainer.childNodes[bconfig.position];
14141         }
14142          
14143         var btn = new Roo.Button(
14144             fc ? 
14145                 this.btnContainer.insertBefore(document.createElement("td"),fc)
14146                 : this.btnContainer.appendChild(document.createElement("td")),
14147             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
14148             bconfig
14149         );
14150         this.syncBodyHeight();
14151         if(!this.buttons){
14152             /**
14153              * Array of all the buttons that have been added to this dialog via addButton
14154              * @type Array
14155              */
14156             this.buttons = [];
14157         }
14158         this.buttons.push(btn);
14159         return btn;
14160     },
14161
14162     /**
14163      * Sets the default button to be focused when the dialog is displayed.
14164      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
14165      * @return {Roo.BasicDialog} this
14166      */
14167     setDefaultButton : function(btn){
14168         this.defaultButton = btn;
14169         return this;
14170     },
14171
14172     // private
14173     getHeaderFooterHeight : function(safe){
14174         var height = 0;
14175         if(this.header){
14176            height += this.header.getHeight();
14177         }
14178         if(this.footer){
14179            var fm = this.footer.getMargins();
14180             height += (this.footer.getHeight()+fm.top+fm.bottom);
14181         }
14182         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
14183         height += this.centerBg.getPadding("tb");
14184         return height;
14185     },
14186
14187     // private
14188     syncBodyHeight : function()
14189     {
14190         var bd = this.body, // the text
14191             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
14192             bw = this.bwrap;
14193         var height = this.size.height - this.getHeaderFooterHeight(false);
14194         bd.setHeight(height-bd.getMargins("tb"));
14195         var hh = this.header.getHeight();
14196         var h = this.size.height-hh;
14197         cb.setHeight(h);
14198         
14199         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
14200         bw.setHeight(h-cb.getPadding("tb"));
14201         
14202         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
14203         bd.setWidth(bw.getWidth(true));
14204         if(this.tabs){
14205             this.tabs.syncHeight();
14206             if(Roo.isIE){
14207                 this.tabs.el.repaint();
14208             }
14209         }
14210     },
14211
14212     /**
14213      * Restores the previous state of the dialog if Roo.state is configured.
14214      * @return {Roo.BasicDialog} this
14215      */
14216     restoreState : function(){
14217         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
14218         if(box && box.width){
14219             this.xy = [box.x, box.y];
14220             this.resizeTo(box.width, box.height);
14221         }
14222         return this;
14223     },
14224
14225     // private
14226     beforeShow : function(){
14227         this.expand();
14228         if(this.fixedcenter){
14229             this.xy = this.el.getCenterXY(true);
14230         }
14231         if(this.modal){
14232             Roo.get(document.body).addClass("x-body-masked");
14233             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
14234             this.mask.show();
14235         }
14236         this.constrainXY();
14237     },
14238
14239     // private
14240     animShow : function(){
14241         var b = Roo.get(this.animateTarget).getBox();
14242         this.proxy.setSize(b.width, b.height);
14243         this.proxy.setLocation(b.x, b.y);
14244         this.proxy.show();
14245         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
14246                     true, .35, this.showEl.createDelegate(this));
14247     },
14248
14249     /**
14250      * Shows the dialog.
14251      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
14252      * @return {Roo.BasicDialog} this
14253      */
14254     show : function(animateTarget){
14255         if (this.fireEvent("beforeshow", this) === false){
14256             return;
14257         }
14258         if(this.syncHeightBeforeShow){
14259             this.syncBodyHeight();
14260         }else if(this.firstShow){
14261             this.firstShow = false;
14262             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
14263         }
14264         this.animateTarget = animateTarget || this.animateTarget;
14265         if(!this.el.isVisible()){
14266             this.beforeShow();
14267             if(this.animateTarget && Roo.get(this.animateTarget)){
14268                 this.animShow();
14269             }else{
14270                 this.showEl();
14271             }
14272         }
14273         return this;
14274     },
14275
14276     // private
14277     showEl : function(){
14278         this.proxy.hide();
14279         this.el.setXY(this.xy);
14280         this.el.show();
14281         this.adjustAssets(true);
14282         this.toFront();
14283         this.focus();
14284         // IE peekaboo bug - fix found by Dave Fenwick
14285         if(Roo.isIE){
14286             this.el.repaint();
14287         }
14288         this.fireEvent("show", this);
14289     },
14290
14291     /**
14292      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
14293      * dialog itself will receive focus.
14294      */
14295     focus : function(){
14296         if(this.defaultButton){
14297             this.defaultButton.focus();
14298         }else{
14299             this.focusEl.focus();
14300         }
14301     },
14302
14303     // private
14304     constrainXY : function(){
14305         if(this.constraintoviewport !== false){
14306             if(!this.viewSize){
14307                 if(this.container){
14308                     var s = this.container.getSize();
14309                     this.viewSize = [s.width, s.height];
14310                 }else{
14311                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
14312                 }
14313             }
14314             var s = Roo.get(this.container||document).getScroll();
14315
14316             var x = this.xy[0], y = this.xy[1];
14317             var w = this.size.width, h = this.size.height;
14318             var vw = this.viewSize[0], vh = this.viewSize[1];
14319             // only move it if it needs it
14320             var moved = false;
14321             // first validate right/bottom
14322             if(x + w > vw+s.left){
14323                 x = vw - w;
14324                 moved = true;
14325             }
14326             if(y + h > vh+s.top){
14327                 y = vh - h;
14328                 moved = true;
14329             }
14330             // then make sure top/left isn't negative
14331             if(x < s.left){
14332                 x = s.left;
14333                 moved = true;
14334             }
14335             if(y < s.top){
14336                 y = s.top;
14337                 moved = true;
14338             }
14339             if(moved){
14340                 // cache xy
14341                 this.xy = [x, y];
14342                 if(this.isVisible()){
14343                     this.el.setLocation(x, y);
14344                     this.adjustAssets();
14345                 }
14346             }
14347         }
14348     },
14349
14350     // private
14351     onDrag : function(){
14352         if(!this.proxyDrag){
14353             this.xy = this.el.getXY();
14354             this.adjustAssets();
14355         }
14356     },
14357
14358     // private
14359     adjustAssets : function(doShow){
14360         var x = this.xy[0], y = this.xy[1];
14361         var w = this.size.width, h = this.size.height;
14362         if(doShow === true){
14363             if(this.shadow){
14364                 this.shadow.show(this.el);
14365             }
14366             if(this.shim){
14367                 this.shim.show();
14368             }
14369         }
14370         if(this.shadow && this.shadow.isVisible()){
14371             this.shadow.show(this.el);
14372         }
14373         if(this.shim && this.shim.isVisible()){
14374             this.shim.setBounds(x, y, w, h);
14375         }
14376     },
14377
14378     // private
14379     adjustViewport : function(w, h){
14380         if(!w || !h){
14381             w = Roo.lib.Dom.getViewWidth();
14382             h = Roo.lib.Dom.getViewHeight();
14383         }
14384         // cache the size
14385         this.viewSize = [w, h];
14386         if(this.modal && this.mask.isVisible()){
14387             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
14388             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
14389         }
14390         if(this.isVisible()){
14391             this.constrainXY();
14392         }
14393     },
14394
14395     /**
14396      * Destroys this dialog and all its supporting elements (including any tabs, shim,
14397      * shadow, proxy, mask, etc.)  Also removes all event listeners.
14398      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
14399      */
14400     destroy : function(removeEl){
14401         if(this.isVisible()){
14402             this.animateTarget = null;
14403             this.hide();
14404         }
14405         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
14406         if(this.tabs){
14407             this.tabs.destroy(removeEl);
14408         }
14409         Roo.destroy(
14410              this.shim,
14411              this.proxy,
14412              this.resizer,
14413              this.close,
14414              this.mask
14415         );
14416         if(this.dd){
14417             this.dd.unreg();
14418         }
14419         if(this.buttons){
14420            for(var i = 0, len = this.buttons.length; i < len; i++){
14421                this.buttons[i].destroy();
14422            }
14423         }
14424         this.el.removeAllListeners();
14425         if(removeEl === true){
14426             this.el.update("");
14427             this.el.remove();
14428         }
14429         Roo.DialogManager.unregister(this);
14430     },
14431
14432     // private
14433     startMove : function(){
14434         if(this.proxyDrag){
14435             this.proxy.show();
14436         }
14437         if(this.constraintoviewport !== false){
14438             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
14439         }
14440     },
14441
14442     // private
14443     endMove : function(){
14444         if(!this.proxyDrag){
14445             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
14446         }else{
14447             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
14448             this.proxy.hide();
14449         }
14450         this.refreshSize();
14451         this.adjustAssets();
14452         this.focus();
14453         this.fireEvent("move", this, this.xy[0], this.xy[1]);
14454     },
14455
14456     /**
14457      * Brings this dialog to the front of any other visible dialogs
14458      * @return {Roo.BasicDialog} this
14459      */
14460     toFront : function(){
14461         Roo.DialogManager.bringToFront(this);
14462         return this;
14463     },
14464
14465     /**
14466      * Sends this dialog to the back (under) of any other visible dialogs
14467      * @return {Roo.BasicDialog} this
14468      */
14469     toBack : function(){
14470         Roo.DialogManager.sendToBack(this);
14471         return this;
14472     },
14473
14474     /**
14475      * Centers this dialog in the viewport
14476      * @return {Roo.BasicDialog} this
14477      */
14478     center : function(){
14479         var xy = this.el.getCenterXY(true);
14480         this.moveTo(xy[0], xy[1]);
14481         return this;
14482     },
14483
14484     /**
14485      * Moves the dialog's top-left corner to the specified point
14486      * @param {Number} x
14487      * @param {Number} y
14488      * @return {Roo.BasicDialog} this
14489      */
14490     moveTo : function(x, y){
14491         this.xy = [x,y];
14492         if(this.isVisible()){
14493             this.el.setXY(this.xy);
14494             this.adjustAssets();
14495         }
14496         return this;
14497     },
14498
14499     /**
14500      * Aligns the dialog to the specified element
14501      * @param {String/HTMLElement/Roo.Element} element The element to align to.
14502      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
14503      * @param {Array} offsets (optional) Offset the positioning by [x, y]
14504      * @return {Roo.BasicDialog} this
14505      */
14506     alignTo : function(element, position, offsets){
14507         this.xy = this.el.getAlignToXY(element, position, offsets);
14508         if(this.isVisible()){
14509             this.el.setXY(this.xy);
14510             this.adjustAssets();
14511         }
14512         return this;
14513     },
14514
14515     /**
14516      * Anchors an element to another element and realigns it when the window is resized.
14517      * @param {String/HTMLElement/Roo.Element} element The element to align to.
14518      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
14519      * @param {Array} offsets (optional) Offset the positioning by [x, y]
14520      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
14521      * is a number, it is used as the buffer delay (defaults to 50ms).
14522      * @return {Roo.BasicDialog} this
14523      */
14524     anchorTo : function(el, alignment, offsets, monitorScroll){
14525         var action = function(){
14526             this.alignTo(el, alignment, offsets);
14527         };
14528         Roo.EventManager.onWindowResize(action, this);
14529         var tm = typeof monitorScroll;
14530         if(tm != 'undefined'){
14531             Roo.EventManager.on(window, 'scroll', action, this,
14532                 {buffer: tm == 'number' ? monitorScroll : 50});
14533         }
14534         action.call(this);
14535         return this;
14536     },
14537
14538     /**
14539      * Returns true if the dialog is visible
14540      * @return {Boolean}
14541      */
14542     isVisible : function(){
14543         return this.el.isVisible();
14544     },
14545
14546     // private
14547     animHide : function(callback){
14548         var b = Roo.get(this.animateTarget).getBox();
14549         this.proxy.show();
14550         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
14551         this.el.hide();
14552         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
14553                     this.hideEl.createDelegate(this, [callback]));
14554     },
14555
14556     /**
14557      * Hides the dialog.
14558      * @param {Function} callback (optional) Function to call when the dialog is hidden
14559      * @return {Roo.BasicDialog} this
14560      */
14561     hide : function(callback){
14562         if (this.fireEvent("beforehide", this) === false){
14563             return;
14564         }
14565         if(this.shadow){
14566             this.shadow.hide();
14567         }
14568         if(this.shim) {
14569           this.shim.hide();
14570         }
14571         // sometimes animateTarget seems to get set.. causing problems...
14572         // this just double checks..
14573         if(this.animateTarget && Roo.get(this.animateTarget)) {
14574            this.animHide(callback);
14575         }else{
14576             this.el.hide();
14577             this.hideEl(callback);
14578         }
14579         return this;
14580     },
14581
14582     // private
14583     hideEl : function(callback){
14584         this.proxy.hide();
14585         if(this.modal){
14586             this.mask.hide();
14587             Roo.get(document.body).removeClass("x-body-masked");
14588         }
14589         this.fireEvent("hide", this);
14590         if(typeof callback == "function"){
14591             callback();
14592         }
14593     },
14594
14595     // private
14596     hideAction : function(){
14597         this.setLeft("-10000px");
14598         this.setTop("-10000px");
14599         this.setStyle("visibility", "hidden");
14600     },
14601
14602     // private
14603     refreshSize : function(){
14604         this.size = this.el.getSize();
14605         this.xy = this.el.getXY();
14606         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
14607     },
14608
14609     // private
14610     // z-index is managed by the DialogManager and may be overwritten at any time
14611     setZIndex : function(index){
14612         if(this.modal){
14613             this.mask.setStyle("z-index", index);
14614         }
14615         if(this.shim){
14616             this.shim.setStyle("z-index", ++index);
14617         }
14618         if(this.shadow){
14619             this.shadow.setZIndex(++index);
14620         }
14621         this.el.setStyle("z-index", ++index);
14622         if(this.proxy){
14623             this.proxy.setStyle("z-index", ++index);
14624         }
14625         if(this.resizer){
14626             this.resizer.proxy.setStyle("z-index", ++index);
14627         }
14628
14629         this.lastZIndex = index;
14630     },
14631
14632     /**
14633      * Returns the element for this dialog
14634      * @return {Roo.Element} The underlying dialog Element
14635      */
14636     getEl : function(){
14637         return this.el;
14638     }
14639 });
14640
14641 /**
14642  * @class Roo.DialogManager
14643  * Provides global access to BasicDialogs that have been created and
14644  * support for z-indexing (layering) multiple open dialogs.
14645  */
14646 Roo.DialogManager = function(){
14647     var list = {};
14648     var accessList = [];
14649     var front = null;
14650
14651     // private
14652     var sortDialogs = function(d1, d2){
14653         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
14654     };
14655
14656     // private
14657     var orderDialogs = function(){
14658         accessList.sort(sortDialogs);
14659         var seed = Roo.DialogManager.zseed;
14660         for(var i = 0, len = accessList.length; i < len; i++){
14661             var dlg = accessList[i];
14662             if(dlg){
14663                 dlg.setZIndex(seed + (i*10));
14664             }
14665         }
14666     };
14667
14668     return {
14669         /**
14670          * The starting z-index for BasicDialogs (defaults to 9000)
14671          * @type Number The z-index value
14672          */
14673         zseed : 9000,
14674
14675         // private
14676         register : function(dlg){
14677             list[dlg.id] = dlg;
14678             accessList.push(dlg);
14679         },
14680
14681         // private
14682         unregister : function(dlg){
14683             delete list[dlg.id];
14684             var i=0;
14685             var len=0;
14686             if(!accessList.indexOf){
14687                 for(  i = 0, len = accessList.length; i < len; i++){
14688                     if(accessList[i] == dlg){
14689                         accessList.splice(i, 1);
14690                         return;
14691                     }
14692                 }
14693             }else{
14694                  i = accessList.indexOf(dlg);
14695                 if(i != -1){
14696                     accessList.splice(i, 1);
14697                 }
14698             }
14699         },
14700
14701         /**
14702          * Gets a registered dialog by id
14703          * @param {String/Object} id The id of the dialog or a dialog
14704          * @return {Roo.BasicDialog} this
14705          */
14706         get : function(id){
14707             return typeof id == "object" ? id : list[id];
14708         },
14709
14710         /**
14711          * Brings the specified dialog to the front
14712          * @param {String/Object} dlg The id of the dialog or a dialog
14713          * @return {Roo.BasicDialog} this
14714          */
14715         bringToFront : function(dlg){
14716             dlg = this.get(dlg);
14717             if(dlg != front){
14718                 front = dlg;
14719                 dlg._lastAccess = new Date().getTime();
14720                 orderDialogs();
14721             }
14722             return dlg;
14723         },
14724
14725         /**
14726          * Sends the specified dialog to the back
14727          * @param {String/Object} dlg The id of the dialog or a dialog
14728          * @return {Roo.BasicDialog} this
14729          */
14730         sendToBack : function(dlg){
14731             dlg = this.get(dlg);
14732             dlg._lastAccess = -(new Date().getTime());
14733             orderDialogs();
14734             return dlg;
14735         },
14736
14737         /**
14738          * Hides all dialogs
14739          */
14740         hideAll : function(){
14741             for(var id in list){
14742                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
14743                     list[id].hide();
14744                 }
14745             }
14746         }
14747     };
14748 }();
14749
14750 /**
14751  * @class Roo.LayoutDialog
14752  * @extends Roo.BasicDialog
14753  * Dialog which provides adjustments for working with a layout in a Dialog.
14754  * Add your necessary layout config options to the dialog's config.<br>
14755  * Example usage (including a nested layout):
14756  * <pre><code>
14757 if(!dialog){
14758     dialog = new Roo.LayoutDialog("download-dlg", {
14759         modal: true,
14760         width:600,
14761         height:450,
14762         shadow:true,
14763         minWidth:500,
14764         minHeight:350,
14765         autoTabs:true,
14766         proxyDrag:true,
14767         // layout config merges with the dialog config
14768         center:{
14769             tabPosition: "top",
14770             alwaysShowTabs: true
14771         }
14772     });
14773     dialog.addKeyListener(27, dialog.hide, dialog);
14774     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
14775     dialog.addButton("Build It!", this.getDownload, this);
14776
14777     // we can even add nested layouts
14778     var innerLayout = new Roo.BorderLayout("dl-inner", {
14779         east: {
14780             initialSize: 200,
14781             autoScroll:true,
14782             split:true
14783         },
14784         center: {
14785             autoScroll:true
14786         }
14787     });
14788     innerLayout.beginUpdate();
14789     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
14790     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
14791     innerLayout.endUpdate(true);
14792
14793     var layout = dialog.getLayout();
14794     layout.beginUpdate();
14795     layout.add("center", new Roo.ContentPanel("standard-panel",
14796                         {title: "Download the Source", fitToFrame:true}));
14797     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
14798                {title: "Build your own roo.js"}));
14799     layout.getRegion("center").showPanel(sp);
14800     layout.endUpdate();
14801 }
14802 </code></pre>
14803     * @constructor
14804     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
14805     * @param {Object} config configuration options
14806   */
14807 Roo.LayoutDialog = function(el, cfg){
14808     
14809     var config=  cfg;
14810     if (typeof(cfg) == 'undefined') {
14811         config = Roo.apply({}, el);
14812         // not sure why we use documentElement here.. - it should always be body.
14813         // IE7 borks horribly if we use documentElement.
14814         // webkit also does not like documentElement - it creates a body element...
14815         el = Roo.get( document.body || document.documentElement ).createChild();
14816         //config.autoCreate = true;
14817     }
14818     
14819     
14820     config.autoTabs = false;
14821     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
14822     this.body.setStyle({overflow:"hidden", position:"relative"});
14823     this.layout = new Roo.BorderLayout(this.body.dom, config);
14824     this.layout.monitorWindowResize = false;
14825     this.el.addClass("x-dlg-auto-layout");
14826     // fix case when center region overwrites center function
14827     this.center = Roo.BasicDialog.prototype.center;
14828     this.on("show", this.layout.layout, this.layout, true);
14829     if (config.items) {
14830         var xitems = config.items;
14831         delete config.items;
14832         Roo.each(xitems, this.addxtype, this);
14833     }
14834     
14835     
14836 };
14837 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
14838     /**
14839      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
14840      * @deprecated
14841      */
14842     endUpdate : function(){
14843         this.layout.endUpdate();
14844     },
14845
14846     /**
14847      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
14848      *  @deprecated
14849      */
14850     beginUpdate : function(){
14851         this.layout.beginUpdate();
14852     },
14853
14854     /**
14855      * Get the BorderLayout for this dialog
14856      * @return {Roo.BorderLayout}
14857      */
14858     getLayout : function(){
14859         return this.layout;
14860     },
14861
14862     showEl : function(){
14863         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
14864         if(Roo.isIE7){
14865             this.layout.layout();
14866         }
14867     },
14868
14869     // private
14870     // Use the syncHeightBeforeShow config option to control this automatically
14871     syncBodyHeight : function(){
14872         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
14873         if(this.layout){this.layout.layout();}
14874     },
14875     
14876       /**
14877      * Add an xtype element (actually adds to the layout.)
14878      * @return {Object} xdata xtype object data.
14879      */
14880     
14881     addxtype : function(c) {
14882         return this.layout.addxtype(c);
14883     }
14884 });/*
14885  * Based on:
14886  * Ext JS Library 1.1.1
14887  * Copyright(c) 2006-2007, Ext JS, LLC.
14888  *
14889  * Originally Released Under LGPL - original licence link has changed is not relivant.
14890  *
14891  * Fork - LGPL
14892  * <script type="text/javascript">
14893  */
14894  
14895 /**
14896  * @class Roo.MessageBox
14897  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
14898  * Example usage:
14899  *<pre><code>
14900 // Basic alert:
14901 Roo.Msg.alert('Status', 'Changes saved successfully.');
14902
14903 // Prompt for user data:
14904 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
14905     if (btn == 'ok'){
14906         // process text value...
14907     }
14908 });
14909
14910 // Show a dialog using config options:
14911 Roo.Msg.show({
14912    title:'Save Changes?',
14913    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
14914    buttons: Roo.Msg.YESNOCANCEL,
14915    fn: processResult,
14916    animEl: 'elId'
14917 });
14918 </code></pre>
14919  * @singleton
14920  */
14921 Roo.MessageBox = function(){
14922     var dlg, opt, mask, waitTimer;
14923     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
14924     var buttons, activeTextEl, bwidth;
14925
14926     // private
14927     var handleButton = function(button){
14928         dlg.hide();
14929         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
14930     };
14931
14932     // private
14933     var handleHide = function(){
14934         if(opt && opt.cls){
14935             dlg.el.removeClass(opt.cls);
14936         }
14937         if(waitTimer){
14938             Roo.TaskMgr.stop(waitTimer);
14939             waitTimer = null;
14940         }
14941     };
14942
14943     // private
14944     var updateButtons = function(b){
14945         var width = 0;
14946         if(!b){
14947             buttons["ok"].hide();
14948             buttons["cancel"].hide();
14949             buttons["yes"].hide();
14950             buttons["no"].hide();
14951             dlg.footer.dom.style.display = 'none';
14952             return width;
14953         }
14954         dlg.footer.dom.style.display = '';
14955         for(var k in buttons){
14956             if(typeof buttons[k] != "function"){
14957                 if(b[k]){
14958                     buttons[k].show();
14959                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
14960                     width += buttons[k].el.getWidth()+15;
14961                 }else{
14962                     buttons[k].hide();
14963                 }
14964             }
14965         }
14966         return width;
14967     };
14968
14969     // private
14970     var handleEsc = function(d, k, e){
14971         if(opt && opt.closable !== false){
14972             dlg.hide();
14973         }
14974         if(e){
14975             e.stopEvent();
14976         }
14977     };
14978
14979     return {
14980         /**
14981          * Returns a reference to the underlying {@link Roo.BasicDialog} element
14982          * @return {Roo.BasicDialog} The BasicDialog element
14983          */
14984         getDialog : function(){
14985            if(!dlg){
14986                 dlg = new Roo.BasicDialog("x-msg-box", {
14987                     autoCreate : true,
14988                     shadow: true,
14989                     draggable: true,
14990                     resizable:false,
14991                     constraintoviewport:false,
14992                     fixedcenter:true,
14993                     collapsible : false,
14994                     shim:true,
14995                     modal: true,
14996                     width:400, height:100,
14997                     buttonAlign:"center",
14998                     closeClick : function(){
14999                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
15000                             handleButton("no");
15001                         }else{
15002                             handleButton("cancel");
15003                         }
15004                     }
15005                 });
15006                 dlg.on("hide", handleHide);
15007                 mask = dlg.mask;
15008                 dlg.addKeyListener(27, handleEsc);
15009                 buttons = {};
15010                 var bt = this.buttonText;
15011                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
15012                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
15013                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
15014                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
15015                 bodyEl = dlg.body.createChild({
15016
15017                     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">&#160;</div></div></div>'
15018                 });
15019                 msgEl = bodyEl.dom.firstChild;
15020                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
15021                 textboxEl.enableDisplayMode();
15022                 textboxEl.addKeyListener([10,13], function(){
15023                     if(dlg.isVisible() && opt && opt.buttons){
15024                         if(opt.buttons.ok){
15025                             handleButton("ok");
15026                         }else if(opt.buttons.yes){
15027                             handleButton("yes");
15028                         }
15029                     }
15030                 });
15031                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
15032                 textareaEl.enableDisplayMode();
15033                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
15034                 progressEl.enableDisplayMode();
15035                 var pf = progressEl.dom.firstChild;
15036                 if (pf) {
15037                     pp = Roo.get(pf.firstChild);
15038                     pp.setHeight(pf.offsetHeight);
15039                 }
15040                 
15041             }
15042             return dlg;
15043         },
15044
15045         /**
15046          * Updates the message box body text
15047          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
15048          * the XHTML-compliant non-breaking space character '&amp;#160;')
15049          * @return {Roo.MessageBox} This message box
15050          */
15051         updateText : function(text){
15052             if(!dlg.isVisible() && !opt.width){
15053                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
15054             }
15055             msgEl.innerHTML = text || '&#160;';
15056       
15057             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
15058             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
15059             var w = Math.max(
15060                     Math.min(opt.width || cw , this.maxWidth), 
15061                     Math.max(opt.minWidth || this.minWidth, bwidth)
15062             );
15063             if(opt.prompt){
15064                 activeTextEl.setWidth(w);
15065             }
15066             if(dlg.isVisible()){
15067                 dlg.fixedcenter = false;
15068             }
15069             // to big, make it scroll. = But as usual stupid IE does not support
15070             // !important..
15071             
15072             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
15073                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
15074                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
15075             } else {
15076                 bodyEl.dom.style.height = '';
15077                 bodyEl.dom.style.overflowY = '';
15078             }
15079             if (cw > w) {
15080                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
15081             } else {
15082                 bodyEl.dom.style.overflowX = '';
15083             }
15084             
15085             dlg.setContentSize(w, bodyEl.getHeight());
15086             if(dlg.isVisible()){
15087                 dlg.fixedcenter = true;
15088             }
15089             return this;
15090         },
15091
15092         /**
15093          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
15094          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
15095          * @param {Number} value Any number between 0 and 1 (e.g., .5)
15096          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
15097          * @return {Roo.MessageBox} This message box
15098          */
15099         updateProgress : function(value, text){
15100             if(text){
15101                 this.updateText(text);
15102             }
15103             if (pp) { // weird bug on my firefox - for some reason this is not defined
15104                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
15105             }
15106             return this;
15107         },        
15108
15109         /**
15110          * Returns true if the message box is currently displayed
15111          * @return {Boolean} True if the message box is visible, else false
15112          */
15113         isVisible : function(){
15114             return dlg && dlg.isVisible();  
15115         },
15116
15117         /**
15118          * Hides the message box if it is displayed
15119          */
15120         hide : function(){
15121             if(this.isVisible()){
15122                 dlg.hide();
15123             }  
15124         },
15125
15126         /**
15127          * Displays a new message box, or reinitializes an existing message box, based on the config options
15128          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
15129          * The following config object properties are supported:
15130          * <pre>
15131 Property    Type             Description
15132 ----------  ---------------  ------------------------------------------------------------------------------------
15133 animEl            String/Element   An id or Element from which the message box should animate as it opens and
15134                                    closes (defaults to undefined)
15135 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
15136                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
15137 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
15138                                    progress and wait dialogs will ignore this property and always hide the
15139                                    close button as they can only be closed programmatically.
15140 cls               String           A custom CSS class to apply to the message box element
15141 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
15142                                    displayed (defaults to 75)
15143 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
15144                                    function will be btn (the name of the button that was clicked, if applicable,
15145                                    e.g. "ok"), and text (the value of the active text field, if applicable).
15146                                    Progress and wait dialogs will ignore this option since they do not respond to
15147                                    user actions and can only be closed programmatically, so any required function
15148                                    should be called by the same code after it closes the dialog.
15149 icon              String           A CSS class that provides a background image to be used as an icon for
15150                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
15151 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
15152 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
15153 modal             Boolean          False to allow user interaction with the page while the message box is
15154                                    displayed (defaults to true)
15155 msg               String           A string that will replace the existing message box body text (defaults
15156                                    to the XHTML-compliant non-breaking space character '&#160;')
15157 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
15158 progress          Boolean          True to display a progress bar (defaults to false)
15159 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
15160 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
15161 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
15162 title             String           The title text
15163 value             String           The string value to set into the active textbox element if displayed
15164 wait              Boolean          True to display a progress bar (defaults to false)
15165 width             Number           The width of the dialog in pixels
15166 </pre>
15167          *
15168          * Example usage:
15169          * <pre><code>
15170 Roo.Msg.show({
15171    title: 'Address',
15172    msg: 'Please enter your address:',
15173    width: 300,
15174    buttons: Roo.MessageBox.OKCANCEL,
15175    multiline: true,
15176    fn: saveAddress,
15177    animEl: 'addAddressBtn'
15178 });
15179 </code></pre>
15180          * @param {Object} config Configuration options
15181          * @return {Roo.MessageBox} This message box
15182          */
15183         show : function(options)
15184         {
15185             
15186             // this causes nightmares if you show one dialog after another
15187             // especially on callbacks..
15188              
15189             if(this.isVisible()){
15190                 
15191                 this.hide();
15192                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
15193                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
15194                 Roo.log("New Dialog Message:" +  options.msg )
15195                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
15196                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
15197                 
15198             }
15199             var d = this.getDialog();
15200             opt = options;
15201             d.setTitle(opt.title || "&#160;");
15202             d.close.setDisplayed(opt.closable !== false);
15203             activeTextEl = textboxEl;
15204             opt.prompt = opt.prompt || (opt.multiline ? true : false);
15205             if(opt.prompt){
15206                 if(opt.multiline){
15207                     textboxEl.hide();
15208                     textareaEl.show();
15209                     textareaEl.setHeight(typeof opt.multiline == "number" ?
15210                         opt.multiline : this.defaultTextHeight);
15211                     activeTextEl = textareaEl;
15212                 }else{
15213                     textboxEl.show();
15214                     textareaEl.hide();
15215                 }
15216             }else{
15217                 textboxEl.hide();
15218                 textareaEl.hide();
15219             }
15220             progressEl.setDisplayed(opt.progress === true);
15221             this.updateProgress(0);
15222             activeTextEl.dom.value = opt.value || "";
15223             if(opt.prompt){
15224                 dlg.setDefaultButton(activeTextEl);
15225             }else{
15226                 var bs = opt.buttons;
15227                 var db = null;
15228                 if(bs && bs.ok){
15229                     db = buttons["ok"];
15230                 }else if(bs && bs.yes){
15231                     db = buttons["yes"];
15232                 }
15233                 dlg.setDefaultButton(db);
15234             }
15235             bwidth = updateButtons(opt.buttons);
15236             this.updateText(opt.msg);
15237             if(opt.cls){
15238                 d.el.addClass(opt.cls);
15239             }
15240             d.proxyDrag = opt.proxyDrag === true;
15241             d.modal = opt.modal !== false;
15242             d.mask = opt.modal !== false ? mask : false;
15243             if(!d.isVisible()){
15244                 // force it to the end of the z-index stack so it gets a cursor in FF
15245                 document.body.appendChild(dlg.el.dom);
15246                 d.animateTarget = null;
15247                 d.show(options.animEl);
15248             }
15249             return this;
15250         },
15251
15252         /**
15253          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
15254          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
15255          * and closing the message box when the process is complete.
15256          * @param {String} title The title bar text
15257          * @param {String} msg The message box body text
15258          * @return {Roo.MessageBox} This message box
15259          */
15260         progress : function(title, msg){
15261             this.show({
15262                 title : title,
15263                 msg : msg,
15264                 buttons: false,
15265                 progress:true,
15266                 closable:false,
15267                 minWidth: this.minProgressWidth,
15268                 modal : true
15269             });
15270             return this;
15271         },
15272
15273         /**
15274          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
15275          * If a callback function is passed it will be called after the user clicks the button, and the
15276          * id of the button that was clicked will be passed as the only parameter to the callback
15277          * (could also be the top-right close button).
15278          * @param {String} title The title bar text
15279          * @param {String} msg The message box body text
15280          * @param {Function} fn (optional) The callback function invoked after the message box is closed
15281          * @param {Object} scope (optional) The scope of the callback function
15282          * @return {Roo.MessageBox} This message box
15283          */
15284         alert : function(title, msg, fn, scope){
15285             this.show({
15286                 title : title,
15287                 msg : msg,
15288                 buttons: this.OK,
15289                 fn: fn,
15290                 scope : scope,
15291                 modal : true
15292             });
15293             return this;
15294         },
15295
15296         /**
15297          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
15298          * interaction while waiting for a long-running process to complete that does not have defined intervals.
15299          * You are responsible for closing the message box when the process is complete.
15300          * @param {String} msg The message box body text
15301          * @param {String} title (optional) The title bar text
15302          * @return {Roo.MessageBox} This message box
15303          */
15304         wait : function(msg, title){
15305             this.show({
15306                 title : title,
15307                 msg : msg,
15308                 buttons: false,
15309                 closable:false,
15310                 progress:true,
15311                 modal:true,
15312                 width:300,
15313                 wait:true
15314             });
15315             waitTimer = Roo.TaskMgr.start({
15316                 run: function(i){
15317                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
15318                 },
15319                 interval: 1000
15320             });
15321             return this;
15322         },
15323
15324         /**
15325          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
15326          * If a callback function is passed it will be called after the user clicks either button, and the id of the
15327          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
15328          * @param {String} title The title bar text
15329          * @param {String} msg The message box body text
15330          * @param {Function} fn (optional) The callback function invoked after the message box is closed
15331          * @param {Object} scope (optional) The scope of the callback function
15332          * @return {Roo.MessageBox} This message box
15333          */
15334         confirm : function(title, msg, fn, scope){
15335             this.show({
15336                 title : title,
15337                 msg : msg,
15338                 buttons: this.YESNO,
15339                 fn: fn,
15340                 scope : scope,
15341                 modal : true
15342             });
15343             return this;
15344         },
15345
15346         /**
15347          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
15348          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
15349          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
15350          * (could also be the top-right close button) and the text that was entered will be passed as the two
15351          * parameters to the callback.
15352          * @param {String} title The title bar text
15353          * @param {String} msg The message box body text
15354          * @param {Function} fn (optional) The callback function invoked after the message box is closed
15355          * @param {Object} scope (optional) The scope of the callback function
15356          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
15357          * property, or the height in pixels to create the textbox (defaults to false / single-line)
15358          * @return {Roo.MessageBox} This message box
15359          */
15360         prompt : function(title, msg, fn, scope, multiline){
15361             this.show({
15362                 title : title,
15363                 msg : msg,
15364                 buttons: this.OKCANCEL,
15365                 fn: fn,
15366                 minWidth:250,
15367                 scope : scope,
15368                 prompt:true,
15369                 multiline: multiline,
15370                 modal : true
15371             });
15372             return this;
15373         },
15374
15375         /**
15376          * Button config that displays a single OK button
15377          * @type Object
15378          */
15379         OK : {ok:true},
15380         /**
15381          * Button config that displays Yes and No buttons
15382          * @type Object
15383          */
15384         YESNO : {yes:true, no:true},
15385         /**
15386          * Button config that displays OK and Cancel buttons
15387          * @type Object
15388          */
15389         OKCANCEL : {ok:true, cancel:true},
15390         /**
15391          * Button config that displays Yes, No and Cancel buttons
15392          * @type Object
15393          */
15394         YESNOCANCEL : {yes:true, no:true, cancel:true},
15395
15396         /**
15397          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
15398          * @type Number
15399          */
15400         defaultTextHeight : 75,
15401         /**
15402          * The maximum width in pixels of the message box (defaults to 600)
15403          * @type Number
15404          */
15405         maxWidth : 600,
15406         /**
15407          * The minimum width in pixels of the message box (defaults to 100)
15408          * @type Number
15409          */
15410         minWidth : 100,
15411         /**
15412          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
15413          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
15414          * @type Number
15415          */
15416         minProgressWidth : 250,
15417         /**
15418          * An object containing the default button text strings that can be overriden for localized language support.
15419          * Supported properties are: ok, cancel, yes and no.
15420          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
15421          * @type Object
15422          */
15423         buttonText : {
15424             ok : "OK",
15425             cancel : "Cancel",
15426             yes : "Yes",
15427             no : "No"
15428         }
15429     };
15430 }();
15431
15432 /**
15433  * Shorthand for {@link Roo.MessageBox}
15434  */
15435 Roo.Msg = Roo.MessageBox;/*
15436  * Based on:
15437  * Ext JS Library 1.1.1
15438  * Copyright(c) 2006-2007, Ext JS, LLC.
15439  *
15440  * Originally Released Under LGPL - original licence link has changed is not relivant.
15441  *
15442  * Fork - LGPL
15443  * <script type="text/javascript">
15444  */
15445 /**
15446  * @class Roo.QuickTips
15447  * Provides attractive and customizable tooltips for any element.
15448  * @singleton
15449  */
15450 Roo.QuickTips = function(){
15451     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
15452     var ce, bd, xy, dd;
15453     var visible = false, disabled = true, inited = false;
15454     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
15455     
15456     var onOver = function(e){
15457         if(disabled){
15458             return;
15459         }
15460         var t = e.getTarget();
15461         if(!t || t.nodeType !== 1 || t == document || t == document.body){
15462             return;
15463         }
15464         if(ce && t == ce.el){
15465             clearTimeout(hideProc);
15466             return;
15467         }
15468         if(t && tagEls[t.id]){
15469             tagEls[t.id].el = t;
15470             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
15471             return;
15472         }
15473         var ttp, et = Roo.fly(t);
15474         var ns = cfg.namespace;
15475         if(tm.interceptTitles && t.title){
15476             ttp = t.title;
15477             t.qtip = ttp;
15478             t.removeAttribute("title");
15479             e.preventDefault();
15480         }else{
15481             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
15482         }
15483         if(ttp){
15484             showProc = show.defer(tm.showDelay, tm, [{
15485                 el: t, 
15486                 text: ttp, 
15487                 width: et.getAttributeNS(ns, cfg.width),
15488                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
15489                 title: et.getAttributeNS(ns, cfg.title),
15490                     cls: et.getAttributeNS(ns, cfg.cls)
15491             }]);
15492         }
15493     };
15494     
15495     var onOut = function(e){
15496         clearTimeout(showProc);
15497         var t = e.getTarget();
15498         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
15499             hideProc = setTimeout(hide, tm.hideDelay);
15500         }
15501     };
15502     
15503     var onMove = function(e){
15504         if(disabled){
15505             return;
15506         }
15507         xy = e.getXY();
15508         xy[1] += 18;
15509         if(tm.trackMouse && ce){
15510             el.setXY(xy);
15511         }
15512     };
15513     
15514     var onDown = function(e){
15515         clearTimeout(showProc);
15516         clearTimeout(hideProc);
15517         if(!e.within(el)){
15518             if(tm.hideOnClick){
15519                 hide();
15520                 tm.disable();
15521                 tm.enable.defer(100, tm);
15522             }
15523         }
15524     };
15525     
15526     var getPad = function(){
15527         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
15528     };
15529
15530     var show = function(o){
15531         if(disabled){
15532             return;
15533         }
15534         clearTimeout(dismissProc);
15535         ce = o;
15536         if(removeCls){ // in case manually hidden
15537             el.removeClass(removeCls);
15538             removeCls = null;
15539         }
15540         if(ce.cls){
15541             el.addClass(ce.cls);
15542             removeCls = ce.cls;
15543         }
15544         if(ce.title){
15545             tipTitle.update(ce.title);
15546             tipTitle.show();
15547         }else{
15548             tipTitle.update('');
15549             tipTitle.hide();
15550         }
15551         el.dom.style.width  = tm.maxWidth+'px';
15552         //tipBody.dom.style.width = '';
15553         tipBodyText.update(o.text);
15554         var p = getPad(), w = ce.width;
15555         if(!w){
15556             var td = tipBodyText.dom;
15557             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
15558             if(aw > tm.maxWidth){
15559                 w = tm.maxWidth;
15560             }else if(aw < tm.minWidth){
15561                 w = tm.minWidth;
15562             }else{
15563                 w = aw;
15564             }
15565         }
15566         //tipBody.setWidth(w);
15567         el.setWidth(parseInt(w, 10) + p);
15568         if(ce.autoHide === false){
15569             close.setDisplayed(true);
15570             if(dd){
15571                 dd.unlock();
15572             }
15573         }else{
15574             close.setDisplayed(false);
15575             if(dd){
15576                 dd.lock();
15577             }
15578         }
15579         if(xy){
15580             el.avoidY = xy[1]-18;
15581             el.setXY(xy);
15582         }
15583         if(tm.animate){
15584             el.setOpacity(.1);
15585             el.setStyle("visibility", "visible");
15586             el.fadeIn({callback: afterShow});
15587         }else{
15588             afterShow();
15589         }
15590     };
15591     
15592     var afterShow = function(){
15593         if(ce){
15594             el.show();
15595             esc.enable();
15596             if(tm.autoDismiss && ce.autoHide !== false){
15597                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
15598             }
15599         }
15600     };
15601     
15602     var hide = function(noanim){
15603         clearTimeout(dismissProc);
15604         clearTimeout(hideProc);
15605         ce = null;
15606         if(el.isVisible()){
15607             esc.disable();
15608             if(noanim !== true && tm.animate){
15609                 el.fadeOut({callback: afterHide});
15610             }else{
15611                 afterHide();
15612             } 
15613         }
15614     };
15615     
15616     var afterHide = function(){
15617         el.hide();
15618         if(removeCls){
15619             el.removeClass(removeCls);
15620             removeCls = null;
15621         }
15622     };
15623     
15624     return {
15625         /**
15626         * @cfg {Number} minWidth
15627         * The minimum width of the quick tip (defaults to 40)
15628         */
15629        minWidth : 40,
15630         /**
15631         * @cfg {Number} maxWidth
15632         * The maximum width of the quick tip (defaults to 300)
15633         */
15634        maxWidth : 300,
15635         /**
15636         * @cfg {Boolean} interceptTitles
15637         * True to automatically use the element's DOM title value if available (defaults to false)
15638         */
15639        interceptTitles : false,
15640         /**
15641         * @cfg {Boolean} trackMouse
15642         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
15643         */
15644        trackMouse : false,
15645         /**
15646         * @cfg {Boolean} hideOnClick
15647         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
15648         */
15649        hideOnClick : true,
15650         /**
15651         * @cfg {Number} showDelay
15652         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
15653         */
15654        showDelay : 500,
15655         /**
15656         * @cfg {Number} hideDelay
15657         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
15658         */
15659        hideDelay : 200,
15660         /**
15661         * @cfg {Boolean} autoHide
15662         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
15663         * Used in conjunction with hideDelay.
15664         */
15665        autoHide : true,
15666         /**
15667         * @cfg {Boolean}
15668         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
15669         * (defaults to true).  Used in conjunction with autoDismissDelay.
15670         */
15671        autoDismiss : true,
15672         /**
15673         * @cfg {Number}
15674         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
15675         */
15676        autoDismissDelay : 5000,
15677        /**
15678         * @cfg {Boolean} animate
15679         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
15680         */
15681        animate : false,
15682
15683        /**
15684         * @cfg {String} title
15685         * Title text to display (defaults to '').  This can be any valid HTML markup.
15686         */
15687         title: '',
15688        /**
15689         * @cfg {String} text
15690         * Body text to display (defaults to '').  This can be any valid HTML markup.
15691         */
15692         text : '',
15693        /**
15694         * @cfg {String} cls
15695         * A CSS class to apply to the base quick tip element (defaults to '').
15696         */
15697         cls : '',
15698        /**
15699         * @cfg {Number} width
15700         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
15701         * minWidth or maxWidth.
15702         */
15703         width : null,
15704
15705     /**
15706      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
15707      * or display QuickTips in a page.
15708      */
15709        init : function(){
15710           tm = Roo.QuickTips;
15711           cfg = tm.tagConfig;
15712           if(!inited){
15713               if(!Roo.isReady){ // allow calling of init() before onReady
15714                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
15715                   return;
15716               }
15717               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
15718               el.fxDefaults = {stopFx: true};
15719               // maximum custom styling
15720               //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>');
15721               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>');              
15722               tipTitle = el.child('h3');
15723               tipTitle.enableDisplayMode("block");
15724               tipBody = el.child('div.x-tip-bd');
15725               tipBodyText = el.child('div.x-tip-bd-inner');
15726               //bdLeft = el.child('div.x-tip-bd-left');
15727               //bdRight = el.child('div.x-tip-bd-right');
15728               close = el.child('div.x-tip-close');
15729               close.enableDisplayMode("block");
15730               close.on("click", hide);
15731               var d = Roo.get(document);
15732               d.on("mousedown", onDown);
15733               d.on("mouseover", onOver);
15734               d.on("mouseout", onOut);
15735               d.on("mousemove", onMove);
15736               esc = d.addKeyListener(27, hide);
15737               esc.disable();
15738               if(Roo.dd.DD){
15739                   dd = el.initDD("default", null, {
15740                       onDrag : function(){
15741                           el.sync();  
15742                       }
15743                   });
15744                   dd.setHandleElId(tipTitle.id);
15745                   dd.lock();
15746               }
15747               inited = true;
15748           }
15749           this.enable(); 
15750        },
15751
15752     /**
15753      * Configures a new quick tip instance and assigns it to a target element.  The following config options
15754      * are supported:
15755      * <pre>
15756 Property    Type                   Description
15757 ----------  ---------------------  ------------------------------------------------------------------------
15758 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
15759      * </ul>
15760      * @param {Object} config The config object
15761      */
15762        register : function(config){
15763            var cs = config instanceof Array ? config : arguments;
15764            for(var i = 0, len = cs.length; i < len; i++) {
15765                var c = cs[i];
15766                var target = c.target;
15767                if(target){
15768                    if(target instanceof Array){
15769                        for(var j = 0, jlen = target.length; j < jlen; j++){
15770                            tagEls[target[j]] = c;
15771                        }
15772                    }else{
15773                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
15774                    }
15775                }
15776            }
15777        },
15778
15779     /**
15780      * Removes this quick tip from its element and destroys it.
15781      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
15782      */
15783        unregister : function(el){
15784            delete tagEls[Roo.id(el)];
15785        },
15786
15787     /**
15788      * Enable this quick tip.
15789      */
15790        enable : function(){
15791            if(inited && disabled){
15792                locks.pop();
15793                if(locks.length < 1){
15794                    disabled = false;
15795                }
15796            }
15797        },
15798
15799     /**
15800      * Disable this quick tip.
15801      */
15802        disable : function(){
15803           disabled = true;
15804           clearTimeout(showProc);
15805           clearTimeout(hideProc);
15806           clearTimeout(dismissProc);
15807           if(ce){
15808               hide(true);
15809           }
15810           locks.push(1);
15811        },
15812
15813     /**
15814      * Returns true if the quick tip is enabled, else false.
15815      */
15816        isEnabled : function(){
15817             return !disabled;
15818        },
15819
15820         // private
15821        tagConfig : {
15822            namespace : "ext",
15823            attribute : "qtip",
15824            width : "width",
15825            target : "target",
15826            title : "qtitle",
15827            hide : "hide",
15828            cls : "qclass"
15829        }
15830    };
15831 }();
15832
15833 // backwards compat
15834 Roo.QuickTips.tips = Roo.QuickTips.register;/*
15835  * Based on:
15836  * Ext JS Library 1.1.1
15837  * Copyright(c) 2006-2007, Ext JS, LLC.
15838  *
15839  * Originally Released Under LGPL - original licence link has changed is not relivant.
15840  *
15841  * Fork - LGPL
15842  * <script type="text/javascript">
15843  */
15844  
15845
15846 /**
15847  * @class Roo.tree.TreePanel
15848  * @extends Roo.data.Tree
15849
15850  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
15851  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
15852  * @cfg {Boolean} enableDD true to enable drag and drop
15853  * @cfg {Boolean} enableDrag true to enable just drag
15854  * @cfg {Boolean} enableDrop true to enable just drop
15855  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
15856  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
15857  * @cfg {String} ddGroup The DD group this TreePanel belongs to
15858  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
15859  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
15860  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
15861  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
15862  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
15863  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
15864  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
15865  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
15866  * @cfg {Boolean} loader A TreeLoader for use with this TreePanel
15867  * @cfg {Object|Roo.tree.TreeEditor} editor The TreeEditor or xtype data to display when clicked.
15868  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
15869  * @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>
15870  * @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>
15871  * 
15872  * @constructor
15873  * @param {String/HTMLElement/Element} el The container element
15874  * @param {Object} config
15875  */
15876 Roo.tree.TreePanel = function(el, config){
15877     var root = false;
15878     var loader = false;
15879     if (config.root) {
15880         root = config.root;
15881         delete config.root;
15882     }
15883     if (config.loader) {
15884         loader = config.loader;
15885         delete config.loader;
15886     }
15887     
15888     Roo.apply(this, config);
15889     Roo.tree.TreePanel.superclass.constructor.call(this);
15890     this.el = Roo.get(el);
15891     this.el.addClass('x-tree');
15892     //console.log(root);
15893     if (root) {
15894         this.setRootNode( Roo.factory(root, Roo.tree));
15895     }
15896     if (loader) {
15897         this.loader = Roo.factory(loader, Roo.tree);
15898     }
15899    /**
15900     * Read-only. The id of the container element becomes this TreePanel's id.
15901     */
15902     this.id = this.el.id;
15903     this.addEvents({
15904         /**
15905         * @event beforeload
15906         * Fires before a node is loaded, return false to cancel
15907         * @param {Node} node The node being loaded
15908         */
15909         "beforeload" : true,
15910         /**
15911         * @event load
15912         * Fires when a node is loaded
15913         * @param {Node} node The node that was loaded
15914         */
15915         "load" : true,
15916         /**
15917         * @event textchange
15918         * Fires when the text for a node is changed
15919         * @param {Node} node The node
15920         * @param {String} text The new text
15921         * @param {String} oldText The old text
15922         */
15923         "textchange" : true,
15924         /**
15925         * @event beforeexpand
15926         * Fires before a node is expanded, return false to cancel.
15927         * @param {Node} node The node
15928         * @param {Boolean} deep
15929         * @param {Boolean} anim
15930         */
15931         "beforeexpand" : true,
15932         /**
15933         * @event beforecollapse
15934         * Fires before a node is collapsed, return false to cancel.
15935         * @param {Node} node The node
15936         * @param {Boolean} deep
15937         * @param {Boolean} anim
15938         */
15939         "beforecollapse" : true,
15940         /**
15941         * @event expand
15942         * Fires when a node is expanded
15943         * @param {Node} node The node
15944         */
15945         "expand" : true,
15946         /**
15947         * @event disabledchange
15948         * Fires when the disabled status of a node changes
15949         * @param {Node} node The node
15950         * @param {Boolean} disabled
15951         */
15952         "disabledchange" : true,
15953         /**
15954         * @event collapse
15955         * Fires when a node is collapsed
15956         * @param {Node} node The node
15957         */
15958         "collapse" : true,
15959         /**
15960         * @event beforeclick
15961         * Fires before click processing on a node. Return false to cancel the default action.
15962         * @param {Node} node The node
15963         * @param {Roo.EventObject} e The event object
15964         */
15965         "beforeclick":true,
15966         /**
15967         * @event checkchange
15968         * Fires when a node with a checkbox's checked property changes
15969         * @param {Node} this This node
15970         * @param {Boolean} checked
15971         */
15972         "checkchange":true,
15973         /**
15974         * @event click
15975         * Fires when a node is clicked
15976         * @param {Node} node The node
15977         * @param {Roo.EventObject} e The event object
15978         */
15979         "click":true,
15980         /**
15981         * @event dblclick
15982         * Fires when a node is double clicked
15983         * @param {Node} node The node
15984         * @param {Roo.EventObject} e The event object
15985         */
15986         "dblclick":true,
15987         /**
15988         * @event contextmenu
15989         * Fires when a node is right clicked
15990         * @param {Node} node The node
15991         * @param {Roo.EventObject} e The event object
15992         */
15993         "contextmenu":true,
15994         /**
15995         * @event beforechildrenrendered
15996         * Fires right before the child nodes for a node are rendered
15997         * @param {Node} node The node
15998         */
15999         "beforechildrenrendered":true,
16000         /**
16001         * @event startdrag
16002         * Fires when a node starts being dragged
16003         * @param {Roo.tree.TreePanel} this
16004         * @param {Roo.tree.TreeNode} node
16005         * @param {event} e The raw browser event
16006         */ 
16007        "startdrag" : true,
16008        /**
16009         * @event enddrag
16010         * Fires when a drag operation is complete
16011         * @param {Roo.tree.TreePanel} this
16012         * @param {Roo.tree.TreeNode} node
16013         * @param {event} e The raw browser event
16014         */
16015        "enddrag" : true,
16016        /**
16017         * @event dragdrop
16018         * Fires when a dragged node is dropped on a valid DD target
16019         * @param {Roo.tree.TreePanel} this
16020         * @param {Roo.tree.TreeNode} node
16021         * @param {DD} dd The dd it was dropped on
16022         * @param {event} e The raw browser event
16023         */
16024        "dragdrop" : true,
16025        /**
16026         * @event beforenodedrop
16027         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
16028         * passed to handlers has the following properties:<br />
16029         * <ul style="padding:5px;padding-left:16px;">
16030         * <li>tree - The TreePanel</li>
16031         * <li>target - The node being targeted for the drop</li>
16032         * <li>data - The drag data from the drag source</li>
16033         * <li>point - The point of the drop - append, above or below</li>
16034         * <li>source - The drag source</li>
16035         * <li>rawEvent - Raw mouse event</li>
16036         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
16037         * to be inserted by setting them on this object.</li>
16038         * <li>cancel - Set this to true to cancel the drop.</li>
16039         * </ul>
16040         * @param {Object} dropEvent
16041         */
16042        "beforenodedrop" : true,
16043        /**
16044         * @event nodedrop
16045         * Fires after a DD object is dropped on a node in this tree. The dropEvent
16046         * passed to handlers has the following properties:<br />
16047         * <ul style="padding:5px;padding-left:16px;">
16048         * <li>tree - The TreePanel</li>
16049         * <li>target - The node being targeted for the drop</li>
16050         * <li>data - The drag data from the drag source</li>
16051         * <li>point - The point of the drop - append, above or below</li>
16052         * <li>source - The drag source</li>
16053         * <li>rawEvent - Raw mouse event</li>
16054         * <li>dropNode - Dropped node(s).</li>
16055         * </ul>
16056         * @param {Object} dropEvent
16057         */
16058        "nodedrop" : true,
16059         /**
16060         * @event nodedragover
16061         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
16062         * passed to handlers has the following properties:<br />
16063         * <ul style="padding:5px;padding-left:16px;">
16064         * <li>tree - The TreePanel</li>
16065         * <li>target - The node being targeted for the drop</li>
16066         * <li>data - The drag data from the drag source</li>
16067         * <li>point - The point of the drop - append, above or below</li>
16068         * <li>source - The drag source</li>
16069         * <li>rawEvent - Raw mouse event</li>
16070         * <li>dropNode - Drop node(s) provided by the source.</li>
16071         * <li>cancel - Set this to true to signal drop not allowed.</li>
16072         * </ul>
16073         * @param {Object} dragOverEvent
16074         */
16075        "nodedragover" : true
16076         
16077     });
16078     if(this.singleExpand){
16079        this.on("beforeexpand", this.restrictExpand, this);
16080     }
16081     if (this.editor) {
16082         this.editor.tree = this;
16083         this.editor = Roo.factory(this.editor, Roo.tree);
16084     }
16085     
16086     if (this.selModel) {
16087         this.selModel = Roo.factory(this.selModel, Roo.tree);
16088     }
16089    
16090 };
16091 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
16092     rootVisible : true,
16093     animate: Roo.enableFx,
16094     lines : true,
16095     enableDD : false,
16096     hlDrop : Roo.enableFx,
16097   
16098     renderer: false,
16099     
16100     rendererTip: false,
16101     // private
16102     restrictExpand : function(node){
16103         var p = node.parentNode;
16104         if(p){
16105             if(p.expandedChild && p.expandedChild.parentNode == p){
16106                 p.expandedChild.collapse();
16107             }
16108             p.expandedChild = node;
16109         }
16110     },
16111
16112     // private override
16113     setRootNode : function(node){
16114         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
16115         if(!this.rootVisible){
16116             node.ui = new Roo.tree.RootTreeNodeUI(node);
16117         }
16118         return node;
16119     },
16120
16121     /**
16122      * Returns the container element for this TreePanel
16123      */
16124     getEl : function(){
16125         return this.el;
16126     },
16127
16128     /**
16129      * Returns the default TreeLoader for this TreePanel
16130      */
16131     getLoader : function(){
16132         return this.loader;
16133     },
16134
16135     /**
16136      * Expand all nodes
16137      */
16138     expandAll : function(){
16139         this.root.expand(true);
16140     },
16141
16142     /**
16143      * Collapse all nodes
16144      */
16145     collapseAll : function(){
16146         this.root.collapse(true);
16147     },
16148
16149     /**
16150      * Returns the selection model used by this TreePanel
16151      */
16152     getSelectionModel : function(){
16153         if(!this.selModel){
16154             this.selModel = new Roo.tree.DefaultSelectionModel();
16155         }
16156         return this.selModel;
16157     },
16158
16159     /**
16160      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
16161      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
16162      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
16163      * @return {Array}
16164      */
16165     getChecked : function(a, startNode){
16166         startNode = startNode || this.root;
16167         var r = [];
16168         var f = function(){
16169             if(this.attributes.checked){
16170                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
16171             }
16172         }
16173         startNode.cascade(f);
16174         return r;
16175     },
16176
16177     /**
16178      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
16179      * @param {String} path
16180      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
16181      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
16182      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
16183      */
16184     expandPath : function(path, attr, callback){
16185         attr = attr || "id";
16186         var keys = path.split(this.pathSeparator);
16187         var curNode = this.root;
16188         if(curNode.attributes[attr] != keys[1]){ // invalid root
16189             if(callback){
16190                 callback(false, null);
16191             }
16192             return;
16193         }
16194         var index = 1;
16195         var f = function(){
16196             if(++index == keys.length){
16197                 if(callback){
16198                     callback(true, curNode);
16199                 }
16200                 return;
16201             }
16202             var c = curNode.findChild(attr, keys[index]);
16203             if(!c){
16204                 if(callback){
16205                     callback(false, curNode);
16206                 }
16207                 return;
16208             }
16209             curNode = c;
16210             c.expand(false, false, f);
16211         };
16212         curNode.expand(false, false, f);
16213     },
16214
16215     /**
16216      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
16217      * @param {String} path
16218      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
16219      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
16220      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
16221      */
16222     selectPath : function(path, attr, callback){
16223         attr = attr || "id";
16224         var keys = path.split(this.pathSeparator);
16225         var v = keys.pop();
16226         if(keys.length > 0){
16227             var f = function(success, node){
16228                 if(success && node){
16229                     var n = node.findChild(attr, v);
16230                     if(n){
16231                         n.select();
16232                         if(callback){
16233                             callback(true, n);
16234                         }
16235                     }else if(callback){
16236                         callback(false, n);
16237                     }
16238                 }else{
16239                     if(callback){
16240                         callback(false, n);
16241                     }
16242                 }
16243             };
16244             this.expandPath(keys.join(this.pathSeparator), attr, f);
16245         }else{
16246             this.root.select();
16247             if(callback){
16248                 callback(true, this.root);
16249             }
16250         }
16251     },
16252
16253     getTreeEl : function(){
16254         return this.el;
16255     },
16256
16257     /**
16258      * Trigger rendering of this TreePanel
16259      */
16260     render : function(){
16261         if (this.innerCt) {
16262             return this; // stop it rendering more than once!!
16263         }
16264         
16265         this.innerCt = this.el.createChild({tag:"ul",
16266                cls:"x-tree-root-ct " +
16267                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
16268
16269         if(this.containerScroll){
16270             Roo.dd.ScrollManager.register(this.el);
16271         }
16272         if((this.enableDD || this.enableDrop) && !this.dropZone){
16273            /**
16274             * The dropZone used by this tree if drop is enabled
16275             * @type Roo.tree.TreeDropZone
16276             */
16277              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
16278                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
16279            });
16280         }
16281         if((this.enableDD || this.enableDrag) && !this.dragZone){
16282            /**
16283             * The dragZone used by this tree if drag is enabled
16284             * @type Roo.tree.TreeDragZone
16285             */
16286             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
16287                ddGroup: this.ddGroup || "TreeDD",
16288                scroll: this.ddScroll
16289            });
16290         }
16291         this.getSelectionModel().init(this);
16292         if (!this.root) {
16293             Roo.log("ROOT not set in tree");
16294             return this;
16295         }
16296         this.root.render();
16297         if(!this.rootVisible){
16298             this.root.renderChildren();
16299         }
16300         return this;
16301     }
16302 });/*
16303  * Based on:
16304  * Ext JS Library 1.1.1
16305  * Copyright(c) 2006-2007, Ext JS, LLC.
16306  *
16307  * Originally Released Under LGPL - original licence link has changed is not relivant.
16308  *
16309  * Fork - LGPL
16310  * <script type="text/javascript">
16311  */
16312  
16313
16314 /**
16315  * @class Roo.tree.DefaultSelectionModel
16316  * @extends Roo.util.Observable
16317  * The default single selection for a TreePanel.
16318  * @param {Object} cfg Configuration
16319  */
16320 Roo.tree.DefaultSelectionModel = function(cfg){
16321    this.selNode = null;
16322    
16323    
16324    
16325    this.addEvents({
16326        /**
16327         * @event selectionchange
16328         * Fires when the selected node changes
16329         * @param {DefaultSelectionModel} this
16330         * @param {TreeNode} node the new selection
16331         */
16332        "selectionchange" : true,
16333
16334        /**
16335         * @event beforeselect
16336         * Fires before the selected node changes, return false to cancel the change
16337         * @param {DefaultSelectionModel} this
16338         * @param {TreeNode} node the new selection
16339         * @param {TreeNode} node the old selection
16340         */
16341        "beforeselect" : true
16342    });
16343    
16344     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
16345 };
16346
16347 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
16348     init : function(tree){
16349         this.tree = tree;
16350         tree.getTreeEl().on("keydown", this.onKeyDown, this);
16351         tree.on("click", this.onNodeClick, this);
16352     },
16353     
16354     onNodeClick : function(node, e){
16355         if (e.ctrlKey && this.selNode == node)  {
16356             this.unselect(node);
16357             return;
16358         }
16359         this.select(node);
16360     },
16361     
16362     /**
16363      * Select a node.
16364      * @param {TreeNode} node The node to select
16365      * @return {TreeNode} The selected node
16366      */
16367     select : function(node){
16368         var last = this.selNode;
16369         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
16370             if(last){
16371                 last.ui.onSelectedChange(false);
16372             }
16373             this.selNode = node;
16374             node.ui.onSelectedChange(true);
16375             this.fireEvent("selectionchange", this, node, last);
16376         }
16377         return node;
16378     },
16379     
16380     /**
16381      * Deselect a node.
16382      * @param {TreeNode} node The node to unselect
16383      */
16384     unselect : function(node){
16385         if(this.selNode == node){
16386             this.clearSelections();
16387         }    
16388     },
16389     
16390     /**
16391      * Clear all selections
16392      */
16393     clearSelections : function(){
16394         var n = this.selNode;
16395         if(n){
16396             n.ui.onSelectedChange(false);
16397             this.selNode = null;
16398             this.fireEvent("selectionchange", this, null);
16399         }
16400         return n;
16401     },
16402     
16403     /**
16404      * Get the selected node
16405      * @return {TreeNode} The selected node
16406      */
16407     getSelectedNode : function(){
16408         return this.selNode;    
16409     },
16410     
16411     /**
16412      * Returns true if the node is selected
16413      * @param {TreeNode} node The node to check
16414      * @return {Boolean}
16415      */
16416     isSelected : function(node){
16417         return this.selNode == node;  
16418     },
16419
16420     /**
16421      * Selects the node above the selected node in the tree, intelligently walking the nodes
16422      * @return TreeNode The new selection
16423      */
16424     selectPrevious : function(){
16425         var s = this.selNode || this.lastSelNode;
16426         if(!s){
16427             return null;
16428         }
16429         var ps = s.previousSibling;
16430         if(ps){
16431             if(!ps.isExpanded() || ps.childNodes.length < 1){
16432                 return this.select(ps);
16433             } else{
16434                 var lc = ps.lastChild;
16435                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
16436                     lc = lc.lastChild;
16437                 }
16438                 return this.select(lc);
16439             }
16440         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
16441             return this.select(s.parentNode);
16442         }
16443         return null;
16444     },
16445
16446     /**
16447      * Selects the node above the selected node in the tree, intelligently walking the nodes
16448      * @return TreeNode The new selection
16449      */
16450     selectNext : function(){
16451         var s = this.selNode || this.lastSelNode;
16452         if(!s){
16453             return null;
16454         }
16455         if(s.firstChild && s.isExpanded()){
16456              return this.select(s.firstChild);
16457          }else if(s.nextSibling){
16458              return this.select(s.nextSibling);
16459          }else if(s.parentNode){
16460             var newS = null;
16461             s.parentNode.bubble(function(){
16462                 if(this.nextSibling){
16463                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
16464                     return false;
16465                 }
16466             });
16467             return newS;
16468          }
16469         return null;
16470     },
16471
16472     onKeyDown : function(e){
16473         var s = this.selNode || this.lastSelNode;
16474         // undesirable, but required
16475         var sm = this;
16476         if(!s){
16477             return;
16478         }
16479         var k = e.getKey();
16480         switch(k){
16481              case e.DOWN:
16482                  e.stopEvent();
16483                  this.selectNext();
16484              break;
16485              case e.UP:
16486                  e.stopEvent();
16487                  this.selectPrevious();
16488              break;
16489              case e.RIGHT:
16490                  e.preventDefault();
16491                  if(s.hasChildNodes()){
16492                      if(!s.isExpanded()){
16493                          s.expand();
16494                      }else if(s.firstChild){
16495                          this.select(s.firstChild, e);
16496                      }
16497                  }
16498              break;
16499              case e.LEFT:
16500                  e.preventDefault();
16501                  if(s.hasChildNodes() && s.isExpanded()){
16502                      s.collapse();
16503                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
16504                      this.select(s.parentNode, e);
16505                  }
16506              break;
16507         };
16508     }
16509 });
16510
16511 /**
16512  * @class Roo.tree.MultiSelectionModel
16513  * @extends Roo.util.Observable
16514  * Multi selection for a TreePanel.
16515  * @param {Object} cfg Configuration
16516  */
16517 Roo.tree.MultiSelectionModel = function(){
16518    this.selNodes = [];
16519    this.selMap = {};
16520    this.addEvents({
16521        /**
16522         * @event selectionchange
16523         * Fires when the selected nodes change
16524         * @param {MultiSelectionModel} this
16525         * @param {Array} nodes Array of the selected nodes
16526         */
16527        "selectionchange" : true
16528    });
16529    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
16530    
16531 };
16532
16533 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
16534     init : function(tree){
16535         this.tree = tree;
16536         tree.getTreeEl().on("keydown", this.onKeyDown, this);
16537         tree.on("click", this.onNodeClick, this);
16538     },
16539     
16540     onNodeClick : function(node, e){
16541         this.select(node, e, e.ctrlKey);
16542     },
16543     
16544     /**
16545      * Select a node.
16546      * @param {TreeNode} node The node to select
16547      * @param {EventObject} e (optional) An event associated with the selection
16548      * @param {Boolean} keepExisting True to retain existing selections
16549      * @return {TreeNode} The selected node
16550      */
16551     select : function(node, e, keepExisting){
16552         if(keepExisting !== true){
16553             this.clearSelections(true);
16554         }
16555         if(this.isSelected(node)){
16556             this.lastSelNode = node;
16557             return node;
16558         }
16559         this.selNodes.push(node);
16560         this.selMap[node.id] = node;
16561         this.lastSelNode = node;
16562         node.ui.onSelectedChange(true);
16563         this.fireEvent("selectionchange", this, this.selNodes);
16564         return node;
16565     },
16566     
16567     /**
16568      * Deselect a node.
16569      * @param {TreeNode} node The node to unselect
16570      */
16571     unselect : function(node){
16572         if(this.selMap[node.id]){
16573             node.ui.onSelectedChange(false);
16574             var sn = this.selNodes;
16575             var index = -1;
16576             if(sn.indexOf){
16577                 index = sn.indexOf(node);
16578             }else{
16579                 for(var i = 0, len = sn.length; i < len; i++){
16580                     if(sn[i] == node){
16581                         index = i;
16582                         break;
16583                     }
16584                 }
16585             }
16586             if(index != -1){
16587                 this.selNodes.splice(index, 1);
16588             }
16589             delete this.selMap[node.id];
16590             this.fireEvent("selectionchange", this, this.selNodes);
16591         }
16592     },
16593     
16594     /**
16595      * Clear all selections
16596      */
16597     clearSelections : function(suppressEvent){
16598         var sn = this.selNodes;
16599         if(sn.length > 0){
16600             for(var i = 0, len = sn.length; i < len; i++){
16601                 sn[i].ui.onSelectedChange(false);
16602             }
16603             this.selNodes = [];
16604             this.selMap = {};
16605             if(suppressEvent !== true){
16606                 this.fireEvent("selectionchange", this, this.selNodes);
16607             }
16608         }
16609     },
16610     
16611     /**
16612      * Returns true if the node is selected
16613      * @param {TreeNode} node The node to check
16614      * @return {Boolean}
16615      */
16616     isSelected : function(node){
16617         return this.selMap[node.id] ? true : false;  
16618     },
16619     
16620     /**
16621      * Returns an array of the selected nodes
16622      * @return {Array}
16623      */
16624     getSelectedNodes : function(){
16625         return this.selNodes;    
16626     },
16627
16628     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
16629
16630     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
16631
16632     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
16633 });/*
16634  * Based on:
16635  * Ext JS Library 1.1.1
16636  * Copyright(c) 2006-2007, Ext JS, LLC.
16637  *
16638  * Originally Released Under LGPL - original licence link has changed is not relivant.
16639  *
16640  * Fork - LGPL
16641  * <script type="text/javascript">
16642  */
16643  
16644 /**
16645  * @class Roo.tree.TreeNode
16646  * @extends Roo.data.Node
16647  * @cfg {String} text The text for this node
16648  * @cfg {Boolean} expanded true to start the node expanded
16649  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
16650  * @cfg {Boolean} allowDrop false if this node cannot be drop on
16651  * @cfg {Boolean} disabled true to start the node disabled
16652  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
16653  * is to use the cls or iconCls attributes and add the icon via a CSS background image.
16654  * @cfg {String} cls A css class to be added to the node
16655  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
16656  * @cfg {String} href URL of the link used for the node (defaults to #)
16657  * @cfg {String} hrefTarget target frame for the link
16658  * @cfg {String} qtip An Ext QuickTip for the node
16659  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
16660  * @cfg {Boolean} singleClickExpand True for single click expand on this node
16661  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
16662  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
16663  * (defaults to undefined with no checkbox rendered)
16664  * @constructor
16665  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
16666  */
16667 Roo.tree.TreeNode = function(attributes){
16668     attributes = attributes || {};
16669     if(typeof attributes == "string"){
16670         attributes = {text: attributes};
16671     }
16672     this.childrenRendered = false;
16673     this.rendered = false;
16674     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
16675     this.expanded = attributes.expanded === true;
16676     this.isTarget = attributes.isTarget !== false;
16677     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
16678     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
16679
16680     /**
16681      * Read-only. The text for this node. To change it use setText().
16682      * @type String
16683      */
16684     this.text = attributes.text;
16685     /**
16686      * True if this node is disabled.
16687      * @type Boolean
16688      */
16689     this.disabled = attributes.disabled === true;
16690
16691     this.addEvents({
16692         /**
16693         * @event textchange
16694         * Fires when the text for this node is changed
16695         * @param {Node} this This node
16696         * @param {String} text The new text
16697         * @param {String} oldText The old text
16698         */
16699         "textchange" : true,
16700         /**
16701         * @event beforeexpand
16702         * Fires before this node is expanded, return false to cancel.
16703         * @param {Node} this This node
16704         * @param {Boolean} deep
16705         * @param {Boolean} anim
16706         */
16707         "beforeexpand" : true,
16708         /**
16709         * @event beforecollapse
16710         * Fires before this node is collapsed, return false to cancel.
16711         * @param {Node} this This node
16712         * @param {Boolean} deep
16713         * @param {Boolean} anim
16714         */
16715         "beforecollapse" : true,
16716         /**
16717         * @event expand
16718         * Fires when this node is expanded
16719         * @param {Node} this This node
16720         */
16721         "expand" : true,
16722         /**
16723         * @event disabledchange
16724         * Fires when the disabled status of this node changes
16725         * @param {Node} this This node
16726         * @param {Boolean} disabled
16727         */
16728         "disabledchange" : true,
16729         /**
16730         * @event collapse
16731         * Fires when this node is collapsed
16732         * @param {Node} this This node
16733         */
16734         "collapse" : true,
16735         /**
16736         * @event beforeclick
16737         * Fires before click processing. Return false to cancel the default action.
16738         * @param {Node} this This node
16739         * @param {Roo.EventObject} e The event object
16740         */
16741         "beforeclick":true,
16742         /**
16743         * @event checkchange
16744         * Fires when a node with a checkbox's checked property changes
16745         * @param {Node} this This node
16746         * @param {Boolean} checked
16747         */
16748         "checkchange":true,
16749         /**
16750         * @event click
16751         * Fires when this node is clicked
16752         * @param {Node} this This node
16753         * @param {Roo.EventObject} e The event object
16754         */
16755         "click":true,
16756         /**
16757         * @event dblclick
16758         * Fires when this node is double clicked
16759         * @param {Node} this This node
16760         * @param {Roo.EventObject} e The event object
16761         */
16762         "dblclick":true,
16763         /**
16764         * @event contextmenu
16765         * Fires when this node is right clicked
16766         * @param {Node} this This node
16767         * @param {Roo.EventObject} e The event object
16768         */
16769         "contextmenu":true,
16770         /**
16771         * @event beforechildrenrendered
16772         * Fires right before the child nodes for this node are rendered
16773         * @param {Node} this This node
16774         */
16775         "beforechildrenrendered":true
16776     });
16777
16778     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
16779
16780     /**
16781      * Read-only. The UI for this node
16782      * @type TreeNodeUI
16783      */
16784     this.ui = new uiClass(this);
16785     
16786     // finally support items[]
16787     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
16788         return;
16789     }
16790     
16791     
16792     Roo.each(this.attributes.items, function(c) {
16793         this.appendChild(Roo.factory(c,Roo.Tree));
16794     }, this);
16795     delete this.attributes.items;
16796     
16797     
16798     
16799 };
16800 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
16801     preventHScroll: true,
16802     /**
16803      * Returns true if this node is expanded
16804      * @return {Boolean}
16805      */
16806     isExpanded : function(){
16807         return this.expanded;
16808     },
16809
16810     /**
16811      * Returns the UI object for this node
16812      * @return {TreeNodeUI}
16813      */
16814     getUI : function(){
16815         return this.ui;
16816     },
16817
16818     // private override
16819     setFirstChild : function(node){
16820         var of = this.firstChild;
16821         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
16822         if(this.childrenRendered && of && node != of){
16823             of.renderIndent(true, true);
16824         }
16825         if(this.rendered){
16826             this.renderIndent(true, true);
16827         }
16828     },
16829
16830     // private override
16831     setLastChild : function(node){
16832         var ol = this.lastChild;
16833         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
16834         if(this.childrenRendered && ol && node != ol){
16835             ol.renderIndent(true, true);
16836         }
16837         if(this.rendered){
16838             this.renderIndent(true, true);
16839         }
16840     },
16841
16842     // these methods are overridden to provide lazy rendering support
16843     // private override
16844     appendChild : function()
16845     {
16846         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
16847         if(node && this.childrenRendered){
16848             node.render();
16849         }
16850         this.ui.updateExpandIcon();
16851         return node;
16852     },
16853
16854     // private override
16855     removeChild : function(node){
16856         this.ownerTree.getSelectionModel().unselect(node);
16857         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
16858         // if it's been rendered remove dom node
16859         if(this.childrenRendered){
16860             node.ui.remove();
16861         }
16862         if(this.childNodes.length < 1){
16863             this.collapse(false, false);
16864         }else{
16865             this.ui.updateExpandIcon();
16866         }
16867         if(!this.firstChild) {
16868             this.childrenRendered = false;
16869         }
16870         return node;
16871     },
16872
16873     // private override
16874     insertBefore : function(node, refNode){
16875         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
16876         if(newNode && refNode && this.childrenRendered){
16877             node.render();
16878         }
16879         this.ui.updateExpandIcon();
16880         return newNode;
16881     },
16882
16883     /**
16884      * Sets the text for this node
16885      * @param {String} text
16886      */
16887     setText : function(text){
16888         var oldText = this.text;
16889         this.text = text;
16890         this.attributes.text = text;
16891         if(this.rendered){ // event without subscribing
16892             this.ui.onTextChange(this, text, oldText);
16893         }
16894         this.fireEvent("textchange", this, text, oldText);
16895     },
16896
16897     /**
16898      * Triggers selection of this node
16899      */
16900     select : function(){
16901         this.getOwnerTree().getSelectionModel().select(this);
16902     },
16903
16904     /**
16905      * Triggers deselection of this node
16906      */
16907     unselect : function(){
16908         this.getOwnerTree().getSelectionModel().unselect(this);
16909     },
16910
16911     /**
16912      * Returns true if this node is selected
16913      * @return {Boolean}
16914      */
16915     isSelected : function(){
16916         return this.getOwnerTree().getSelectionModel().isSelected(this);
16917     },
16918
16919     /**
16920      * Expand this node.
16921      * @param {Boolean} deep (optional) True to expand all children as well
16922      * @param {Boolean} anim (optional) false to cancel the default animation
16923      * @param {Function} callback (optional) A callback to be called when
16924      * expanding this node completes (does not wait for deep expand to complete).
16925      * Called with 1 parameter, this node.
16926      */
16927     expand : function(deep, anim, callback){
16928         if(!this.expanded){
16929             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
16930                 return;
16931             }
16932             if(!this.childrenRendered){
16933                 this.renderChildren();
16934             }
16935             this.expanded = true;
16936             if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
16937                 this.ui.animExpand(function(){
16938                     this.fireEvent("expand", this);
16939                     if(typeof callback == "function"){
16940                         callback(this);
16941                     }
16942                     if(deep === true){
16943                         this.expandChildNodes(true);
16944                     }
16945                 }.createDelegate(this));
16946                 return;
16947             }else{
16948                 this.ui.expand();
16949                 this.fireEvent("expand", this);
16950                 if(typeof callback == "function"){
16951                     callback(this);
16952                 }
16953             }
16954         }else{
16955            if(typeof callback == "function"){
16956                callback(this);
16957            }
16958         }
16959         if(deep === true){
16960             this.expandChildNodes(true);
16961         }
16962     },
16963
16964     isHiddenRoot : function(){
16965         return this.isRoot && !this.getOwnerTree().rootVisible;
16966     },
16967
16968     /**
16969      * Collapse this node.
16970      * @param {Boolean} deep (optional) True to collapse all children as well
16971      * @param {Boolean} anim (optional) false to cancel the default animation
16972      */
16973     collapse : function(deep, anim){
16974         if(this.expanded && !this.isHiddenRoot()){
16975             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
16976                 return;
16977             }
16978             this.expanded = false;
16979             if((this.getOwnerTree().animate && anim !== false) || anim){
16980                 this.ui.animCollapse(function(){
16981                     this.fireEvent("collapse", this);
16982                     if(deep === true){
16983                         this.collapseChildNodes(true);
16984                     }
16985                 }.createDelegate(this));
16986                 return;
16987             }else{
16988                 this.ui.collapse();
16989                 this.fireEvent("collapse", this);
16990             }
16991         }
16992         if(deep === true){
16993             var cs = this.childNodes;
16994             for(var i = 0, len = cs.length; i < len; i++) {
16995                 cs[i].collapse(true, false);
16996             }
16997         }
16998     },
16999
17000     // private
17001     delayedExpand : function(delay){
17002         if(!this.expandProcId){
17003             this.expandProcId = this.expand.defer(delay, this);
17004         }
17005     },
17006
17007     // private
17008     cancelExpand : function(){
17009         if(this.expandProcId){
17010             clearTimeout(this.expandProcId);
17011         }
17012         this.expandProcId = false;
17013     },
17014
17015     /**
17016      * Toggles expanded/collapsed state of the node
17017      */
17018     toggle : function(){
17019         if(this.expanded){
17020             this.collapse();
17021         }else{
17022             this.expand();
17023         }
17024     },
17025
17026     /**
17027      * Ensures all parent nodes are expanded
17028      */
17029     ensureVisible : function(callback){
17030         var tree = this.getOwnerTree();
17031         tree.expandPath(this.parentNode.getPath(), false, function(){
17032             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
17033             Roo.callback(callback);
17034         }.createDelegate(this));
17035     },
17036
17037     /**
17038      * Expand all child nodes
17039      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
17040      */
17041     expandChildNodes : function(deep){
17042         var cs = this.childNodes;
17043         for(var i = 0, len = cs.length; i < len; i++) {
17044                 cs[i].expand(deep);
17045         }
17046     },
17047
17048     /**
17049      * Collapse all child nodes
17050      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
17051      */
17052     collapseChildNodes : function(deep){
17053         var cs = this.childNodes;
17054         for(var i = 0, len = cs.length; i < len; i++) {
17055                 cs[i].collapse(deep);
17056         }
17057     },
17058
17059     /**
17060      * Disables this node
17061      */
17062     disable : function(){
17063         this.disabled = true;
17064         this.unselect();
17065         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
17066             this.ui.onDisableChange(this, true);
17067         }
17068         this.fireEvent("disabledchange", this, true);
17069     },
17070
17071     /**
17072      * Enables this node
17073      */
17074     enable : function(){
17075         this.disabled = false;
17076         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
17077             this.ui.onDisableChange(this, false);
17078         }
17079         this.fireEvent("disabledchange", this, false);
17080     },
17081
17082     // private
17083     renderChildren : function(suppressEvent){
17084         if(suppressEvent !== false){
17085             this.fireEvent("beforechildrenrendered", this);
17086         }
17087         var cs = this.childNodes;
17088         for(var i = 0, len = cs.length; i < len; i++){
17089             cs[i].render(true);
17090         }
17091         this.childrenRendered = true;
17092     },
17093
17094     // private
17095     sort : function(fn, scope){
17096         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
17097         if(this.childrenRendered){
17098             var cs = this.childNodes;
17099             for(var i = 0, len = cs.length; i < len; i++){
17100                 cs[i].render(true);
17101             }
17102         }
17103     },
17104
17105     // private
17106     render : function(bulkRender){
17107         this.ui.render(bulkRender);
17108         if(!this.rendered){
17109             this.rendered = true;
17110             if(this.expanded){
17111                 this.expanded = false;
17112                 this.expand(false, false);
17113             }
17114         }
17115     },
17116
17117     // private
17118     renderIndent : function(deep, refresh){
17119         if(refresh){
17120             this.ui.childIndent = null;
17121         }
17122         this.ui.renderIndent();
17123         if(deep === true && this.childrenRendered){
17124             var cs = this.childNodes;
17125             for(var i = 0, len = cs.length; i < len; i++){
17126                 cs[i].renderIndent(true, refresh);
17127             }
17128         }
17129     }
17130 });/*
17131  * Based on:
17132  * Ext JS Library 1.1.1
17133  * Copyright(c) 2006-2007, Ext JS, LLC.
17134  *
17135  * Originally Released Under LGPL - original licence link has changed is not relivant.
17136  *
17137  * Fork - LGPL
17138  * <script type="text/javascript">
17139  */
17140  
17141 /**
17142  * @class Roo.tree.AsyncTreeNode
17143  * @extends Roo.tree.TreeNode
17144  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
17145  * @constructor
17146  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
17147  */
17148  Roo.tree.AsyncTreeNode = function(config){
17149     this.loaded = false;
17150     this.loading = false;
17151     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
17152     /**
17153     * @event beforeload
17154     * Fires before this node is loaded, return false to cancel
17155     * @param {Node} this This node
17156     */
17157     this.addEvents({'beforeload':true, 'load': true});
17158     /**
17159     * @event load
17160     * Fires when this node is loaded
17161     * @param {Node} this This node
17162     */
17163     /**
17164      * The loader used by this node (defaults to using the tree's defined loader)
17165      * @type TreeLoader
17166      * @property loader
17167      */
17168 };
17169 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
17170     expand : function(deep, anim, callback){
17171         if(this.loading){ // if an async load is already running, waiting til it's done
17172             var timer;
17173             var f = function(){
17174                 if(!this.loading){ // done loading
17175                     clearInterval(timer);
17176                     this.expand(deep, anim, callback);
17177                 }
17178             }.createDelegate(this);
17179             timer = setInterval(f, 200);
17180             return;
17181         }
17182         if(!this.loaded){
17183             if(this.fireEvent("beforeload", this) === false){
17184                 return;
17185             }
17186             this.loading = true;
17187             this.ui.beforeLoad(this);
17188             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
17189             if(loader){
17190                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
17191                 return;
17192             }
17193         }
17194         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
17195     },
17196     
17197     /**
17198      * Returns true if this node is currently loading
17199      * @return {Boolean}
17200      */
17201     isLoading : function(){
17202         return this.loading;  
17203     },
17204     
17205     loadComplete : function(deep, anim, callback){
17206         this.loading = false;
17207         this.loaded = true;
17208         this.ui.afterLoad(this);
17209         this.fireEvent("load", this);
17210         this.expand(deep, anim, callback);
17211     },
17212     
17213     /**
17214      * Returns true if this node has been loaded
17215      * @return {Boolean}
17216      */
17217     isLoaded : function(){
17218         return this.loaded;
17219     },
17220     
17221     hasChildNodes : function(){
17222         if(!this.isLeaf() && !this.loaded){
17223             return true;
17224         }else{
17225             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
17226         }
17227     },
17228
17229     /**
17230      * Trigger a reload for this node
17231      * @param {Function} callback
17232      */
17233     reload : function(callback){
17234         this.collapse(false, false);
17235         while(this.firstChild){
17236             this.removeChild(this.firstChild);
17237         }
17238         this.childrenRendered = false;
17239         this.loaded = false;
17240         if(this.isHiddenRoot()){
17241             this.expanded = false;
17242         }
17243         this.expand(false, false, callback);
17244     }
17245 });/*
17246  * Based on:
17247  * Ext JS Library 1.1.1
17248  * Copyright(c) 2006-2007, Ext JS, LLC.
17249  *
17250  * Originally Released Under LGPL - original licence link has changed is not relivant.
17251  *
17252  * Fork - LGPL
17253  * <script type="text/javascript">
17254  */
17255  
17256 /**
17257  * @class Roo.tree.TreeNodeUI
17258  * @constructor
17259  * @param {Object} node The node to render
17260  * The TreeNode UI implementation is separate from the
17261  * tree implementation. Unless you are customizing the tree UI,
17262  * you should never have to use this directly.
17263  */
17264 Roo.tree.TreeNodeUI = function(node){
17265     this.node = node;
17266     this.rendered = false;
17267     this.animating = false;
17268     this.emptyIcon = Roo.BLANK_IMAGE_URL;
17269 };
17270
17271 Roo.tree.TreeNodeUI.prototype = {
17272     removeChild : function(node){
17273         if(this.rendered){
17274             this.ctNode.removeChild(node.ui.getEl());
17275         }
17276     },
17277
17278     beforeLoad : function(){
17279          this.addClass("x-tree-node-loading");
17280     },
17281
17282     afterLoad : function(){
17283          this.removeClass("x-tree-node-loading");
17284     },
17285
17286     onTextChange : function(node, text, oldText){
17287         if(this.rendered){
17288             this.textNode.innerHTML = text;
17289         }
17290     },
17291
17292     onDisableChange : function(node, state){
17293         this.disabled = state;
17294         if(state){
17295             this.addClass("x-tree-node-disabled");
17296         }else{
17297             this.removeClass("x-tree-node-disabled");
17298         }
17299     },
17300
17301     onSelectedChange : function(state){
17302         if(state){
17303             this.focus();
17304             this.addClass("x-tree-selected");
17305         }else{
17306             //this.blur();
17307             this.removeClass("x-tree-selected");
17308         }
17309     },
17310
17311     onMove : function(tree, node, oldParent, newParent, index, refNode){
17312         this.childIndent = null;
17313         if(this.rendered){
17314             var targetNode = newParent.ui.getContainer();
17315             if(!targetNode){//target not rendered
17316                 this.holder = document.createElement("div");
17317                 this.holder.appendChild(this.wrap);
17318                 return;
17319             }
17320             var insertBefore = refNode ? refNode.ui.getEl() : null;
17321             if(insertBefore){
17322                 targetNode.insertBefore(this.wrap, insertBefore);
17323             }else{
17324                 targetNode.appendChild(this.wrap);
17325             }
17326             this.node.renderIndent(true);
17327         }
17328     },
17329
17330     addClass : function(cls){
17331         if(this.elNode){
17332             Roo.fly(this.elNode).addClass(cls);
17333         }
17334     },
17335
17336     removeClass : function(cls){
17337         if(this.elNode){
17338             Roo.fly(this.elNode).removeClass(cls);
17339         }
17340     },
17341
17342     remove : function(){
17343         if(this.rendered){
17344             this.holder = document.createElement("div");
17345             this.holder.appendChild(this.wrap);
17346         }
17347     },
17348
17349     fireEvent : function(){
17350         return this.node.fireEvent.apply(this.node, arguments);
17351     },
17352
17353     initEvents : function(){
17354         this.node.on("move", this.onMove, this);
17355         var E = Roo.EventManager;
17356         var a = this.anchor;
17357
17358         var el = Roo.fly(a, '_treeui');
17359
17360         if(Roo.isOpera){ // opera render bug ignores the CSS
17361             el.setStyle("text-decoration", "none");
17362         }
17363
17364         el.on("click", this.onClick, this);
17365         el.on("dblclick", this.onDblClick, this);
17366
17367         if(this.checkbox){
17368             Roo.EventManager.on(this.checkbox,
17369                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
17370         }
17371
17372         el.on("contextmenu", this.onContextMenu, this);
17373
17374         var icon = Roo.fly(this.iconNode);
17375         icon.on("click", this.onClick, this);
17376         icon.on("dblclick", this.onDblClick, this);
17377         icon.on("contextmenu", this.onContextMenu, this);
17378         E.on(this.ecNode, "click", this.ecClick, this, true);
17379
17380         if(this.node.disabled){
17381             this.addClass("x-tree-node-disabled");
17382         }
17383         if(this.node.hidden){
17384             this.addClass("x-tree-node-disabled");
17385         }
17386         var ot = this.node.getOwnerTree();
17387         var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
17388         if(dd && (!this.node.isRoot || ot.rootVisible)){
17389             Roo.dd.Registry.register(this.elNode, {
17390                 node: this.node,
17391                 handles: this.getDDHandles(),
17392                 isHandle: false
17393             });
17394         }
17395     },
17396
17397     getDDHandles : function(){
17398         return [this.iconNode, this.textNode];
17399     },
17400
17401     hide : function(){
17402         if(this.rendered){
17403             this.wrap.style.display = "none";
17404         }
17405     },
17406
17407     show : function(){
17408         if(this.rendered){
17409             this.wrap.style.display = "";
17410         }
17411     },
17412
17413     onContextMenu : function(e){
17414         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
17415             e.preventDefault();
17416             this.focus();
17417             this.fireEvent("contextmenu", this.node, e);
17418         }
17419     },
17420
17421     onClick : function(e){
17422         if(this.dropping){
17423             e.stopEvent();
17424             return;
17425         }
17426         if(this.fireEvent("beforeclick", this.node, e) !== false){
17427             if(!this.disabled && this.node.attributes.href){
17428                 this.fireEvent("click", this.node, e);
17429                 return;
17430             }
17431             e.preventDefault();
17432             if(this.disabled){
17433                 return;
17434             }
17435
17436             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
17437                 this.node.toggle();
17438             }
17439
17440             this.fireEvent("click", this.node, e);
17441         }else{
17442             e.stopEvent();
17443         }
17444     },
17445
17446     onDblClick : function(e){
17447         e.preventDefault();
17448         if(this.disabled){
17449             return;
17450         }
17451         if(this.checkbox){
17452             this.toggleCheck();
17453         }
17454         if(!this.animating && this.node.hasChildNodes()){
17455             this.node.toggle();
17456         }
17457         this.fireEvent("dblclick", this.node, e);
17458     },
17459
17460     onCheckChange : function(){
17461         var checked = this.checkbox.checked;
17462         this.node.attributes.checked = checked;
17463         this.fireEvent('checkchange', this.node, checked);
17464     },
17465
17466     ecClick : function(e){
17467         if(!this.animating && this.node.hasChildNodes()){
17468             this.node.toggle();
17469         }
17470     },
17471
17472     startDrop : function(){
17473         this.dropping = true;
17474     },
17475
17476     // delayed drop so the click event doesn't get fired on a drop
17477     endDrop : function(){
17478        setTimeout(function(){
17479            this.dropping = false;
17480        }.createDelegate(this), 50);
17481     },
17482
17483     expand : function(){
17484         this.updateExpandIcon();
17485         this.ctNode.style.display = "";
17486     },
17487
17488     focus : function(){
17489         if(!this.node.preventHScroll){
17490             try{this.anchor.focus();
17491             }catch(e){}
17492         }else if(!Roo.isIE){
17493             try{
17494                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
17495                 var l = noscroll.scrollLeft;
17496                 this.anchor.focus();
17497                 noscroll.scrollLeft = l;
17498             }catch(e){}
17499         }
17500     },
17501
17502     toggleCheck : function(value){
17503         var cb = this.checkbox;
17504         if(cb){
17505             cb.checked = (value === undefined ? !cb.checked : value);
17506         }
17507     },
17508
17509     blur : function(){
17510         try{
17511             this.anchor.blur();
17512         }catch(e){}
17513     },
17514
17515     animExpand : function(callback){
17516         var ct = Roo.get(this.ctNode);
17517         ct.stopFx();
17518         if(!this.node.hasChildNodes()){
17519             this.updateExpandIcon();
17520             this.ctNode.style.display = "";
17521             Roo.callback(callback);
17522             return;
17523         }
17524         this.animating = true;
17525         this.updateExpandIcon();
17526
17527         ct.slideIn('t', {
17528            callback : function(){
17529                this.animating = false;
17530                Roo.callback(callback);
17531             },
17532             scope: this,
17533             duration: this.node.ownerTree.duration || .25
17534         });
17535     },
17536
17537     highlight : function(){
17538         var tree = this.node.getOwnerTree();
17539         Roo.fly(this.wrap).highlight(
17540             tree.hlColor || "C3DAF9",
17541             {endColor: tree.hlBaseColor}
17542         );
17543     },
17544
17545     collapse : function(){
17546         this.updateExpandIcon();
17547         this.ctNode.style.display = "none";
17548     },
17549
17550     animCollapse : function(callback){
17551         var ct = Roo.get(this.ctNode);
17552         ct.enableDisplayMode('block');
17553         ct.stopFx();
17554
17555         this.animating = true;
17556         this.updateExpandIcon();
17557
17558         ct.slideOut('t', {
17559             callback : function(){
17560                this.animating = false;
17561                Roo.callback(callback);
17562             },
17563             scope: this,
17564             duration: this.node.ownerTree.duration || .25
17565         });
17566     },
17567
17568     getContainer : function(){
17569         return this.ctNode;
17570     },
17571
17572     getEl : function(){
17573         return this.wrap;
17574     },
17575
17576     appendDDGhost : function(ghostNode){
17577         ghostNode.appendChild(this.elNode.cloneNode(true));
17578     },
17579
17580     getDDRepairXY : function(){
17581         return Roo.lib.Dom.getXY(this.iconNode);
17582     },
17583
17584     onRender : function(){
17585         this.render();
17586     },
17587
17588     render : function(bulkRender){
17589         var n = this.node, a = n.attributes;
17590         var targetNode = n.parentNode ?
17591               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
17592
17593         if(!this.rendered){
17594             this.rendered = true;
17595
17596             this.renderElements(n, a, targetNode, bulkRender);
17597
17598             if(a.qtip){
17599                if(this.textNode.setAttributeNS){
17600                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
17601                    if(a.qtipTitle){
17602                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
17603                    }
17604                }else{
17605                    this.textNode.setAttribute("ext:qtip", a.qtip);
17606                    if(a.qtipTitle){
17607                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
17608                    }
17609                }
17610             }else if(a.qtipCfg){
17611                 a.qtipCfg.target = Roo.id(this.textNode);
17612                 Roo.QuickTips.register(a.qtipCfg);
17613             }
17614             this.initEvents();
17615             if(!this.node.expanded){
17616                 this.updateExpandIcon();
17617             }
17618         }else{
17619             if(bulkRender === true) {
17620                 targetNode.appendChild(this.wrap);
17621             }
17622         }
17623     },
17624
17625     renderElements : function(n, a, targetNode, bulkRender)
17626     {
17627         // add some indent caching, this helps performance when rendering a large tree
17628         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
17629         var t = n.getOwnerTree();
17630         var txt = t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
17631         if (typeof(n.attributes.html) != 'undefined') {
17632             txt = n.attributes.html;
17633         }
17634         var tip = t.rendererTip ? t.rendererTip(n.attributes) : txt;
17635         var cb = typeof a.checked == 'boolean';
17636         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
17637         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
17638             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
17639             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
17640             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
17641             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
17642             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
17643              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
17644                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
17645             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
17646             "</li>"];
17647
17648         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
17649             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
17650                                 n.nextSibling.ui.getEl(), buf.join(""));
17651         }else{
17652             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
17653         }
17654
17655         this.elNode = this.wrap.childNodes[0];
17656         this.ctNode = this.wrap.childNodes[1];
17657         var cs = this.elNode.childNodes;
17658         this.indentNode = cs[0];
17659         this.ecNode = cs[1];
17660         this.iconNode = cs[2];
17661         var index = 3;
17662         if(cb){
17663             this.checkbox = cs[3];
17664             index++;
17665         }
17666         this.anchor = cs[index];
17667         this.textNode = cs[index].firstChild;
17668     },
17669
17670     getAnchor : function(){
17671         return this.anchor;
17672     },
17673
17674     getTextEl : function(){
17675         return this.textNode;
17676     },
17677
17678     getIconEl : function(){
17679         return this.iconNode;
17680     },
17681
17682     isChecked : function(){
17683         return this.checkbox ? this.checkbox.checked : false;
17684     },
17685
17686     updateExpandIcon : function(){
17687         if(this.rendered){
17688             var n = this.node, c1, c2;
17689             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
17690             var hasChild = n.hasChildNodes();
17691             if(hasChild){
17692                 if(n.expanded){
17693                     cls += "-minus";
17694                     c1 = "x-tree-node-collapsed";
17695                     c2 = "x-tree-node-expanded";
17696                 }else{
17697                     cls += "-plus";
17698                     c1 = "x-tree-node-expanded";
17699                     c2 = "x-tree-node-collapsed";
17700                 }
17701                 if(this.wasLeaf){
17702                     this.removeClass("x-tree-node-leaf");
17703                     this.wasLeaf = false;
17704                 }
17705                 if(this.c1 != c1 || this.c2 != c2){
17706                     Roo.fly(this.elNode).replaceClass(c1, c2);
17707                     this.c1 = c1; this.c2 = c2;
17708                 }
17709             }else{
17710                 // this changes non-leafs into leafs if they have no children.
17711                 // it's not very rational behaviour..
17712                 
17713                 if(!this.wasLeaf && this.node.leaf){
17714                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
17715                     delete this.c1;
17716                     delete this.c2;
17717                     this.wasLeaf = true;
17718                 }
17719             }
17720             var ecc = "x-tree-ec-icon "+cls;
17721             if(this.ecc != ecc){
17722                 this.ecNode.className = ecc;
17723                 this.ecc = ecc;
17724             }
17725         }
17726     },
17727
17728     getChildIndent : function(){
17729         if(!this.childIndent){
17730             var buf = [];
17731             var p = this.node;
17732             while(p){
17733                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
17734                     if(!p.isLast()) {
17735                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
17736                     } else {
17737                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
17738                     }
17739                 }
17740                 p = p.parentNode;
17741             }
17742             this.childIndent = buf.join("");
17743         }
17744         return this.childIndent;
17745     },
17746
17747     renderIndent : function(){
17748         if(this.rendered){
17749             var indent = "";
17750             var p = this.node.parentNode;
17751             if(p){
17752                 indent = p.ui.getChildIndent();
17753             }
17754             if(this.indentMarkup != indent){ // don't rerender if not required
17755                 this.indentNode.innerHTML = indent;
17756                 this.indentMarkup = indent;
17757             }
17758             this.updateExpandIcon();
17759         }
17760     }
17761 };
17762
17763 Roo.tree.RootTreeNodeUI = function(){
17764     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
17765 };
17766 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
17767     render : function(){
17768         if(!this.rendered){
17769             var targetNode = this.node.ownerTree.innerCt.dom;
17770             this.node.expanded = true;
17771             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
17772             this.wrap = this.ctNode = targetNode.firstChild;
17773         }
17774     },
17775     collapse : function(){
17776     },
17777     expand : function(){
17778     }
17779 });/*
17780  * Based on:
17781  * Ext JS Library 1.1.1
17782  * Copyright(c) 2006-2007, Ext JS, LLC.
17783  *
17784  * Originally Released Under LGPL - original licence link has changed is not relivant.
17785  *
17786  * Fork - LGPL
17787  * <script type="text/javascript">
17788  */
17789 /**
17790  * @class Roo.tree.TreeLoader
17791  * @extends Roo.util.Observable
17792  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
17793  * nodes from a specified URL. The response must be a javascript Array definition
17794  * who's elements are node definition objects. eg:
17795  * <pre><code>
17796 {  success : true,
17797    data :      [
17798    
17799     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
17800     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
17801     ]
17802 }
17803
17804
17805 </code></pre>
17806  * <br><br>
17807  * The old style respose with just an array is still supported, but not recommended.
17808  * <br><br>
17809  *
17810  * A server request is sent, and child nodes are loaded only when a node is expanded.
17811  * The loading node's id is passed to the server under the parameter name "node" to
17812  * enable the server to produce the correct child nodes.
17813  * <br><br>
17814  * To pass extra parameters, an event handler may be attached to the "beforeload"
17815  * event, and the parameters specified in the TreeLoader's baseParams property:
17816  * <pre><code>
17817     myTreeLoader.on("beforeload", function(treeLoader, node) {
17818         this.baseParams.category = node.attributes.category;
17819     }, this);
17820 </code></pre><
17821  * This would pass an HTTP parameter called "category" to the server containing
17822  * the value of the Node's "category" attribute.
17823  * @constructor
17824  * Creates a new Treeloader.
17825  * @param {Object} config A config object containing config properties.
17826  */
17827 Roo.tree.TreeLoader = function(config){
17828     this.baseParams = {};
17829     this.requestMethod = "POST";
17830     Roo.apply(this, config);
17831
17832     this.addEvents({
17833     
17834         /**
17835          * @event beforeload
17836          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
17837          * @param {Object} This TreeLoader object.
17838          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
17839          * @param {Object} callback The callback function specified in the {@link #load} call.
17840          */
17841         beforeload : true,
17842         /**
17843          * @event load
17844          * Fires when the node has been successfuly loaded.
17845          * @param {Object} This TreeLoader object.
17846          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
17847          * @param {Object} response The response object containing the data from the server.
17848          */
17849         load : true,
17850         /**
17851          * @event loadexception
17852          * Fires if the network request failed.
17853          * @param {Object} This TreeLoader object.
17854          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
17855          * @param {Object} response The response object containing the data from the server.
17856          */
17857         loadexception : true,
17858         /**
17859          * @event create
17860          * Fires before a node is created, enabling you to return custom Node types 
17861          * @param {Object} This TreeLoader object.
17862          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
17863          */
17864         create : true
17865     });
17866
17867     Roo.tree.TreeLoader.superclass.constructor.call(this);
17868 };
17869
17870 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
17871     /**
17872     * @cfg {String} dataUrl The URL from which to request a Json string which
17873     * specifies an array of node definition object representing the child nodes
17874     * to be loaded.
17875     */
17876     /**
17877     * @cfg {String} requestMethod either GET or POST
17878     * defaults to POST (due to BC)
17879     * to be loaded.
17880     */
17881     /**
17882     * @cfg {Object} baseParams (optional) An object containing properties which
17883     * specify HTTP parameters to be passed to each request for child nodes.
17884     */
17885     /**
17886     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
17887     * created by this loader. If the attributes sent by the server have an attribute in this object,
17888     * they take priority.
17889     */
17890     /**
17891     * @cfg {Object} uiProviders (optional) An object containing properties which
17892     * 
17893     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
17894     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
17895     * <i>uiProvider</i> attribute of a returned child node is a string rather
17896     * than a reference to a TreeNodeUI implementation, this that string value
17897     * is used as a property name in the uiProviders object. You can define the provider named
17898     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
17899     */
17900     uiProviders : {},
17901
17902     /**
17903     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
17904     * child nodes before loading.
17905     */
17906     clearOnLoad : true,
17907
17908     /**
17909     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
17910     * property on loading, rather than expecting an array. (eg. more compatible to a standard
17911     * Grid query { data : [ .....] }
17912     */
17913     
17914     root : false,
17915      /**
17916     * @cfg {String} queryParam (optional) 
17917     * Name of the query as it will be passed on the querystring (defaults to 'node')
17918     * eg. the request will be ?node=[id]
17919     */
17920     
17921     
17922     queryParam: false,
17923     
17924     /**
17925      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
17926      * This is called automatically when a node is expanded, but may be used to reload
17927      * a node (or append new children if the {@link #clearOnLoad} option is false.)
17928      * @param {Roo.tree.TreeNode} node
17929      * @param {Function} callback
17930      */
17931     load : function(node, callback){
17932         if(this.clearOnLoad){
17933             while(node.firstChild){
17934                 node.removeChild(node.firstChild);
17935             }
17936         }
17937         if(node.attributes.children){ // preloaded json children
17938             var cs = node.attributes.children;
17939             for(var i = 0, len = cs.length; i < len; i++){
17940                 node.appendChild(this.createNode(cs[i]));
17941             }
17942             if(typeof callback == "function"){
17943                 callback();
17944             }
17945         }else if(this.dataUrl){
17946             this.requestData(node, callback);
17947         }
17948     },
17949
17950     getParams: function(node){
17951         var buf = [], bp = this.baseParams;
17952         for(var key in bp){
17953             if(typeof bp[key] != "function"){
17954                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
17955             }
17956         }
17957         var n = this.queryParam === false ? 'node' : this.queryParam;
17958         buf.push(n + "=", encodeURIComponent(node.id));
17959         return buf.join("");
17960     },
17961
17962     requestData : function(node, callback){
17963         if(this.fireEvent("beforeload", this, node, callback) !== false){
17964             this.transId = Roo.Ajax.request({
17965                 method:this.requestMethod,
17966                 url: this.dataUrl||this.url,
17967                 success: this.handleResponse,
17968                 failure: this.handleFailure,
17969                 scope: this,
17970                 argument: {callback: callback, node: node},
17971                 params: this.getParams(node)
17972             });
17973         }else{
17974             // if the load is cancelled, make sure we notify
17975             // the node that we are done
17976             if(typeof callback == "function"){
17977                 callback();
17978             }
17979         }
17980     },
17981
17982     isLoading : function(){
17983         return this.transId ? true : false;
17984     },
17985
17986     abort : function(){
17987         if(this.isLoading()){
17988             Roo.Ajax.abort(this.transId);
17989         }
17990     },
17991
17992     // private
17993     createNode : function(attr)
17994     {
17995         // apply baseAttrs, nice idea Corey!
17996         if(this.baseAttrs){
17997             Roo.applyIf(attr, this.baseAttrs);
17998         }
17999         if(this.applyLoader !== false){
18000             attr.loader = this;
18001         }
18002         // uiProvider = depreciated..
18003         
18004         if(typeof(attr.uiProvider) == 'string'){
18005            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
18006                 /**  eval:var:attr */ eval(attr.uiProvider);
18007         }
18008         if(typeof(this.uiProviders['default']) != 'undefined') {
18009             attr.uiProvider = this.uiProviders['default'];
18010         }
18011         
18012         this.fireEvent('create', this, attr);
18013         
18014         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
18015         return(attr.leaf ?
18016                         new Roo.tree.TreeNode(attr) :
18017                         new Roo.tree.AsyncTreeNode(attr));
18018     },
18019
18020     processResponse : function(response, node, callback)
18021     {
18022         var json = response.responseText;
18023         try {
18024             
18025             var o = Roo.decode(json);
18026             
18027             if (this.root === false && typeof(o.success) != undefined) {
18028                 this.root = 'data'; // the default behaviour for list like data..
18029                 }
18030                 
18031             if (this.root !== false &&  !o.success) {
18032                 // it's a failure condition.
18033                 var a = response.argument;
18034                 this.fireEvent("loadexception", this, a.node, response);
18035                 Roo.log("Load failed - should have a handler really");
18036                 return;
18037             }
18038             
18039             
18040             
18041             if (this.root !== false) {
18042                  o = o[this.root];
18043             }
18044             
18045             for(var i = 0, len = o.length; i < len; i++){
18046                 var n = this.createNode(o[i]);
18047                 if(n){
18048                     node.appendChild(n);
18049                 }
18050             }
18051             if(typeof callback == "function"){
18052                 callback(this, node);
18053             }
18054         }catch(e){
18055             this.handleFailure(response);
18056         }
18057     },
18058
18059     handleResponse : function(response){
18060         this.transId = false;
18061         var a = response.argument;
18062         this.processResponse(response, a.node, a.callback);
18063         this.fireEvent("load", this, a.node, response);
18064     },
18065
18066     handleFailure : function(response)
18067     {
18068         // should handle failure better..
18069         this.transId = false;
18070         var a = response.argument;
18071         this.fireEvent("loadexception", this, a.node, response);
18072         if(typeof a.callback == "function"){
18073             a.callback(this, a.node);
18074         }
18075     }
18076 });/*
18077  * Based on:
18078  * Ext JS Library 1.1.1
18079  * Copyright(c) 2006-2007, Ext JS, LLC.
18080  *
18081  * Originally Released Under LGPL - original licence link has changed is not relivant.
18082  *
18083  * Fork - LGPL
18084  * <script type="text/javascript">
18085  */
18086
18087 /**
18088 * @class Roo.tree.TreeFilter
18089 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
18090 * @param {TreePanel} tree
18091 * @param {Object} config (optional)
18092  */
18093 Roo.tree.TreeFilter = function(tree, config){
18094     this.tree = tree;
18095     this.filtered = {};
18096     Roo.apply(this, config);
18097 };
18098
18099 Roo.tree.TreeFilter.prototype = {
18100     clearBlank:false,
18101     reverse:false,
18102     autoClear:false,
18103     remove:false,
18104
18105      /**
18106      * Filter the data by a specific attribute.
18107      * @param {String/RegExp} value Either string that the attribute value
18108      * should start with or a RegExp to test against the attribute
18109      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
18110      * @param {TreeNode} startNode (optional) The node to start the filter at.
18111      */
18112     filter : function(value, attr, startNode){
18113         attr = attr || "text";
18114         var f;
18115         if(typeof value == "string"){
18116             var vlen = value.length;
18117             // auto clear empty filter
18118             if(vlen == 0 && this.clearBlank){
18119                 this.clear();
18120                 return;
18121             }
18122             value = value.toLowerCase();
18123             f = function(n){
18124                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
18125             };
18126         }else if(value.exec){ // regex?
18127             f = function(n){
18128                 return value.test(n.attributes[attr]);
18129             };
18130         }else{
18131             throw 'Illegal filter type, must be string or regex';
18132         }
18133         this.filterBy(f, null, startNode);
18134         },
18135
18136     /**
18137      * Filter by a function. The passed function will be called with each
18138      * node in the tree (or from the startNode). If the function returns true, the node is kept
18139      * otherwise it is filtered. If a node is filtered, its children are also filtered.
18140      * @param {Function} fn The filter function
18141      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
18142      */
18143     filterBy : function(fn, scope, startNode){
18144         startNode = startNode || this.tree.root;
18145         if(this.autoClear){
18146             this.clear();
18147         }
18148         var af = this.filtered, rv = this.reverse;
18149         var f = function(n){
18150             if(n == startNode){
18151                 return true;
18152             }
18153             if(af[n.id]){
18154                 return false;
18155             }
18156             var m = fn.call(scope || n, n);
18157             if(!m || rv){
18158                 af[n.id] = n;
18159                 n.ui.hide();
18160                 return false;
18161             }
18162             return true;
18163         };
18164         startNode.cascade(f);
18165         if(this.remove){
18166            for(var id in af){
18167                if(typeof id != "function"){
18168                    var n = af[id];
18169                    if(n && n.parentNode){
18170                        n.parentNode.removeChild(n);
18171                    }
18172                }
18173            }
18174         }
18175     },
18176
18177     /**
18178      * Clears the current filter. Note: with the "remove" option
18179      * set a filter cannot be cleared.
18180      */
18181     clear : function(){
18182         var t = this.tree;
18183         var af = this.filtered;
18184         for(var id in af){
18185             if(typeof id != "function"){
18186                 var n = af[id];
18187                 if(n){
18188                     n.ui.show();
18189                 }
18190             }
18191         }
18192         this.filtered = {};
18193     }
18194 };
18195 /*
18196  * Based on:
18197  * Ext JS Library 1.1.1
18198  * Copyright(c) 2006-2007, Ext JS, LLC.
18199  *
18200  * Originally Released Under LGPL - original licence link has changed is not relivant.
18201  *
18202  * Fork - LGPL
18203  * <script type="text/javascript">
18204  */
18205  
18206
18207 /**
18208  * @class Roo.tree.TreeSorter
18209  * Provides sorting of nodes in a TreePanel
18210  * 
18211  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
18212  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
18213  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
18214  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
18215  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
18216  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
18217  * @constructor
18218  * @param {TreePanel} tree
18219  * @param {Object} config
18220  */
18221 Roo.tree.TreeSorter = function(tree, config){
18222     Roo.apply(this, config);
18223     tree.on("beforechildrenrendered", this.doSort, this);
18224     tree.on("append", this.updateSort, this);
18225     tree.on("insert", this.updateSort, this);
18226     
18227     var dsc = this.dir && this.dir.toLowerCase() == "desc";
18228     var p = this.property || "text";
18229     var sortType = this.sortType;
18230     var fs = this.folderSort;
18231     var cs = this.caseSensitive === true;
18232     var leafAttr = this.leafAttr || 'leaf';
18233
18234     this.sortFn = function(n1, n2){
18235         if(fs){
18236             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
18237                 return 1;
18238             }
18239             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
18240                 return -1;
18241             }
18242         }
18243         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
18244         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
18245         if(v1 < v2){
18246                         return dsc ? +1 : -1;
18247                 }else if(v1 > v2){
18248                         return dsc ? -1 : +1;
18249         }else{
18250                 return 0;
18251         }
18252     };
18253 };
18254
18255 Roo.tree.TreeSorter.prototype = {
18256     doSort : function(node){
18257         node.sort(this.sortFn);
18258     },
18259     
18260     compareNodes : function(n1, n2){
18261         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
18262     },
18263     
18264     updateSort : function(tree, node){
18265         if(node.childrenRendered){
18266             this.doSort.defer(1, this, [node]);
18267         }
18268     }
18269 };/*
18270  * Based on:
18271  * Ext JS Library 1.1.1
18272  * Copyright(c) 2006-2007, Ext JS, LLC.
18273  *
18274  * Originally Released Under LGPL - original licence link has changed is not relivant.
18275  *
18276  * Fork - LGPL
18277  * <script type="text/javascript">
18278  */
18279
18280 if(Roo.dd.DropZone){
18281     
18282 Roo.tree.TreeDropZone = function(tree, config){
18283     this.allowParentInsert = false;
18284     this.allowContainerDrop = false;
18285     this.appendOnly = false;
18286     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
18287     this.tree = tree;
18288     this.lastInsertClass = "x-tree-no-status";
18289     this.dragOverData = {};
18290 };
18291
18292 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
18293     ddGroup : "TreeDD",
18294     scroll:  true,
18295     
18296     expandDelay : 1000,
18297     
18298     expandNode : function(node){
18299         if(node.hasChildNodes() && !node.isExpanded()){
18300             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
18301         }
18302     },
18303     
18304     queueExpand : function(node){
18305         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
18306     },
18307     
18308     cancelExpand : function(){
18309         if(this.expandProcId){
18310             clearTimeout(this.expandProcId);
18311             this.expandProcId = false;
18312         }
18313     },
18314     
18315     isValidDropPoint : function(n, pt, dd, e, data){
18316         if(!n || !data){ return false; }
18317         var targetNode = n.node;
18318         var dropNode = data.node;
18319         // default drop rules
18320         if(!(targetNode && targetNode.isTarget && pt)){
18321             return false;
18322         }
18323         if(pt == "append" && targetNode.allowChildren === false){
18324             return false;
18325         }
18326         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
18327             return false;
18328         }
18329         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
18330             return false;
18331         }
18332         // reuse the object
18333         var overEvent = this.dragOverData;
18334         overEvent.tree = this.tree;
18335         overEvent.target = targetNode;
18336         overEvent.data = data;
18337         overEvent.point = pt;
18338         overEvent.source = dd;
18339         overEvent.rawEvent = e;
18340         overEvent.dropNode = dropNode;
18341         overEvent.cancel = false;  
18342         var result = this.tree.fireEvent("nodedragover", overEvent);
18343         return overEvent.cancel === false && result !== false;
18344     },
18345     
18346     getDropPoint : function(e, n, dd)
18347     {
18348         var tn = n.node;
18349         if(tn.isRoot){
18350             return tn.allowChildren !== false ? "append" : false; // always append for root
18351         }
18352         var dragEl = n.ddel;
18353         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
18354         var y = Roo.lib.Event.getPageY(e);
18355         //var noAppend = tn.allowChildren === false || tn.isLeaf();
18356         
18357         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
18358         var noAppend = tn.allowChildren === false;
18359         if(this.appendOnly || tn.parentNode.allowChildren === false){
18360             return noAppend ? false : "append";
18361         }
18362         var noBelow = false;
18363         if(!this.allowParentInsert){
18364             noBelow = tn.hasChildNodes() && tn.isExpanded();
18365         }
18366         var q = (b - t) / (noAppend ? 2 : 3);
18367         if(y >= t && y < (t + q)){
18368             return "above";
18369         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
18370             return "below";
18371         }else{
18372             return "append";
18373         }
18374     },
18375     
18376     onNodeEnter : function(n, dd, e, data)
18377     {
18378         this.cancelExpand();
18379     },
18380     
18381     onNodeOver : function(n, dd, e, data)
18382     {
18383        
18384         var pt = this.getDropPoint(e, n, dd);
18385         var node = n.node;
18386         
18387         // auto node expand check
18388         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
18389             this.queueExpand(node);
18390         }else if(pt != "append"){
18391             this.cancelExpand();
18392         }
18393         
18394         // set the insert point style on the target node
18395         var returnCls = this.dropNotAllowed;
18396         if(this.isValidDropPoint(n, pt, dd, e, data)){
18397            if(pt){
18398                var el = n.ddel;
18399                var cls;
18400                if(pt == "above"){
18401                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
18402                    cls = "x-tree-drag-insert-above";
18403                }else if(pt == "below"){
18404                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
18405                    cls = "x-tree-drag-insert-below";
18406                }else{
18407                    returnCls = "x-tree-drop-ok-append";
18408                    cls = "x-tree-drag-append";
18409                }
18410                if(this.lastInsertClass != cls){
18411                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
18412                    this.lastInsertClass = cls;
18413                }
18414            }
18415        }
18416        return returnCls;
18417     },
18418     
18419     onNodeOut : function(n, dd, e, data){
18420         
18421         this.cancelExpand();
18422         this.removeDropIndicators(n);
18423     },
18424     
18425     onNodeDrop : function(n, dd, e, data){
18426         var point = this.getDropPoint(e, n, dd);
18427         var targetNode = n.node;
18428         targetNode.ui.startDrop();
18429         if(!this.isValidDropPoint(n, point, dd, e, data)){
18430             targetNode.ui.endDrop();
18431             return false;
18432         }
18433         // first try to find the drop node
18434         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
18435         var dropEvent = {
18436             tree : this.tree,
18437             target: targetNode,
18438             data: data,
18439             point: point,
18440             source: dd,
18441             rawEvent: e,
18442             dropNode: dropNode,
18443             cancel: !dropNode   
18444         };
18445         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
18446         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
18447             targetNode.ui.endDrop();
18448             return false;
18449         }
18450         // allow target changing
18451         targetNode = dropEvent.target;
18452         if(point == "append" && !targetNode.isExpanded()){
18453             targetNode.expand(false, null, function(){
18454                 this.completeDrop(dropEvent);
18455             }.createDelegate(this));
18456         }else{
18457             this.completeDrop(dropEvent);
18458         }
18459         return true;
18460     },
18461     
18462     completeDrop : function(de){
18463         var ns = de.dropNode, p = de.point, t = de.target;
18464         if(!(ns instanceof Array)){
18465             ns = [ns];
18466         }
18467         var n;
18468         for(var i = 0, len = ns.length; i < len; i++){
18469             n = ns[i];
18470             if(p == "above"){
18471                 t.parentNode.insertBefore(n, t);
18472             }else if(p == "below"){
18473                 t.parentNode.insertBefore(n, t.nextSibling);
18474             }else{
18475                 t.appendChild(n);
18476             }
18477         }
18478         n.ui.focus();
18479         if(this.tree.hlDrop){
18480             n.ui.highlight();
18481         }
18482         t.ui.endDrop();
18483         this.tree.fireEvent("nodedrop", de);
18484     },
18485     
18486     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
18487         if(this.tree.hlDrop){
18488             dropNode.ui.focus();
18489             dropNode.ui.highlight();
18490         }
18491         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
18492     },
18493     
18494     getTree : function(){
18495         return this.tree;
18496     },
18497     
18498     removeDropIndicators : function(n){
18499         if(n && n.ddel){
18500             var el = n.ddel;
18501             Roo.fly(el).removeClass([
18502                     "x-tree-drag-insert-above",
18503                     "x-tree-drag-insert-below",
18504                     "x-tree-drag-append"]);
18505             this.lastInsertClass = "_noclass";
18506         }
18507     },
18508     
18509     beforeDragDrop : function(target, e, id){
18510         this.cancelExpand();
18511         return true;
18512     },
18513     
18514     afterRepair : function(data){
18515         if(data && Roo.enableFx){
18516             data.node.ui.highlight();
18517         }
18518         this.hideProxy();
18519     } 
18520     
18521 });
18522
18523 }
18524 /*
18525  * Based on:
18526  * Ext JS Library 1.1.1
18527  * Copyright(c) 2006-2007, Ext JS, LLC.
18528  *
18529  * Originally Released Under LGPL - original licence link has changed is not relivant.
18530  *
18531  * Fork - LGPL
18532  * <script type="text/javascript">
18533  */
18534  
18535
18536 if(Roo.dd.DragZone){
18537 Roo.tree.TreeDragZone = function(tree, config){
18538     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
18539     this.tree = tree;
18540 };
18541
18542 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
18543     ddGroup : "TreeDD",
18544    
18545     onBeforeDrag : function(data, e){
18546         var n = data.node;
18547         return n && n.draggable && !n.disabled;
18548     },
18549      
18550     
18551     onInitDrag : function(e){
18552         var data = this.dragData;
18553         this.tree.getSelectionModel().select(data.node);
18554         this.proxy.update("");
18555         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
18556         this.tree.fireEvent("startdrag", this.tree, data.node, e);
18557     },
18558     
18559     getRepairXY : function(e, data){
18560         return data.node.ui.getDDRepairXY();
18561     },
18562     
18563     onEndDrag : function(data, e){
18564         this.tree.fireEvent("enddrag", this.tree, data.node, e);
18565         
18566         
18567     },
18568     
18569     onValidDrop : function(dd, e, id){
18570         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
18571         this.hideProxy();
18572     },
18573     
18574     beforeInvalidDrop : function(e, id){
18575         // this scrolls the original position back into view
18576         var sm = this.tree.getSelectionModel();
18577         sm.clearSelections();
18578         sm.select(this.dragData.node);
18579     }
18580 });
18581 }/*
18582  * Based on:
18583  * Ext JS Library 1.1.1
18584  * Copyright(c) 2006-2007, Ext JS, LLC.
18585  *
18586  * Originally Released Under LGPL - original licence link has changed is not relivant.
18587  *
18588  * Fork - LGPL
18589  * <script type="text/javascript">
18590  */
18591 /**
18592  * @class Roo.tree.TreeEditor
18593  * @extends Roo.Editor
18594  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
18595  * as the editor field.
18596  * @constructor
18597  * @param {Object} config (used to be the tree panel.)
18598  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
18599  * 
18600  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
18601  * @cfg {Roo.form.TextField|Object} field The field configuration
18602  *
18603  * 
18604  */
18605 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
18606     var tree = config;
18607     var field;
18608     if (oldconfig) { // old style..
18609         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
18610     } else {
18611         // new style..
18612         tree = config.tree;
18613         config.field = config.field  || {};
18614         config.field.xtype = 'TextField';
18615         field = Roo.factory(config.field, Roo.form);
18616     }
18617     config = config || {};
18618     
18619     
18620     this.addEvents({
18621         /**
18622          * @event beforenodeedit
18623          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
18624          * false from the handler of this event.
18625          * @param {Editor} this
18626          * @param {Roo.tree.Node} node 
18627          */
18628         "beforenodeedit" : true
18629     });
18630     
18631     //Roo.log(config);
18632     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
18633
18634     this.tree = tree;
18635
18636     tree.on('beforeclick', this.beforeNodeClick, this);
18637     tree.getTreeEl().on('mousedown', this.hide, this);
18638     this.on('complete', this.updateNode, this);
18639     this.on('beforestartedit', this.fitToTree, this);
18640     this.on('startedit', this.bindScroll, this, {delay:10});
18641     this.on('specialkey', this.onSpecialKey, this);
18642 };
18643
18644 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
18645     /**
18646      * @cfg {String} alignment
18647      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
18648      */
18649     alignment: "l-l",
18650     // inherit
18651     autoSize: false,
18652     /**
18653      * @cfg {Boolean} hideEl
18654      * True to hide the bound element while the editor is displayed (defaults to false)
18655      */
18656     hideEl : false,
18657     /**
18658      * @cfg {String} cls
18659      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
18660      */
18661     cls: "x-small-editor x-tree-editor",
18662     /**
18663      * @cfg {Boolean} shim
18664      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
18665      */
18666     shim:false,
18667     // inherit
18668     shadow:"frame",
18669     /**
18670      * @cfg {Number} maxWidth
18671      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
18672      * the containing tree element's size, it will be automatically limited for you to the container width, taking
18673      * scroll and client offsets into account prior to each edit.
18674      */
18675     maxWidth: 250,
18676
18677     editDelay : 350,
18678
18679     // private
18680     fitToTree : function(ed, el){
18681         var td = this.tree.getTreeEl().dom, nd = el.dom;
18682         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
18683             td.scrollLeft = nd.offsetLeft;
18684         }
18685         var w = Math.min(
18686                 this.maxWidth,
18687                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
18688         this.setSize(w, '');
18689         
18690         return this.fireEvent('beforenodeedit', this, this.editNode);
18691         
18692     },
18693
18694     // private
18695     triggerEdit : function(node){
18696         this.completeEdit();
18697         this.editNode = node;
18698         this.startEdit(node.ui.textNode, node.text);
18699     },
18700
18701     // private
18702     bindScroll : function(){
18703         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
18704     },
18705
18706     // private
18707     beforeNodeClick : function(node, e){
18708         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
18709         this.lastClick = new Date();
18710         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
18711             e.stopEvent();
18712             this.triggerEdit(node);
18713             return false;
18714         }
18715         return true;
18716     },
18717
18718     // private
18719     updateNode : function(ed, value){
18720         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
18721         this.editNode.setText(value);
18722     },
18723
18724     // private
18725     onHide : function(){
18726         Roo.tree.TreeEditor.superclass.onHide.call(this);
18727         if(this.editNode){
18728             this.editNode.ui.focus();
18729         }
18730     },
18731
18732     // private
18733     onSpecialKey : function(field, e){
18734         var k = e.getKey();
18735         if(k == e.ESC){
18736             e.stopEvent();
18737             this.cancelEdit();
18738         }else if(k == e.ENTER && !e.hasModifier()){
18739             e.stopEvent();
18740             this.completeEdit();
18741         }
18742     }
18743 });//<Script type="text/javascript">
18744 /*
18745  * Based on:
18746  * Ext JS Library 1.1.1
18747  * Copyright(c) 2006-2007, Ext JS, LLC.
18748  *
18749  * Originally Released Under LGPL - original licence link has changed is not relivant.
18750  *
18751  * Fork - LGPL
18752  * <script type="text/javascript">
18753  */
18754  
18755 /**
18756  * Not documented??? - probably should be...
18757  */
18758
18759 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
18760     //focus: Roo.emptyFn, // prevent odd scrolling behavior
18761     
18762     renderElements : function(n, a, targetNode, bulkRender){
18763         //consel.log("renderElements?");
18764         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
18765
18766         var t = n.getOwnerTree();
18767         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
18768         
18769         var cols = t.columns;
18770         var bw = t.borderWidth;
18771         var c = cols[0];
18772         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
18773          var cb = typeof a.checked == "boolean";
18774         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
18775         var colcls = 'x-t-' + tid + '-c0';
18776         var buf = [
18777             '<li class="x-tree-node">',
18778             
18779                 
18780                 '<div class="x-tree-node-el ', a.cls,'">',
18781                     // extran...
18782                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
18783                 
18784                 
18785                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
18786                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
18787                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
18788                            (a.icon ? ' x-tree-node-inline-icon' : ''),
18789                            (a.iconCls ? ' '+a.iconCls : ''),
18790                            '" unselectable="on" />',
18791                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
18792                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
18793                              
18794                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
18795                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
18796                             '<span unselectable="on" qtip="' + tx + '">',
18797                              tx,
18798                              '</span></a>' ,
18799                     '</div>',
18800                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
18801                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
18802                  ];
18803         for(var i = 1, len = cols.length; i < len; i++){
18804             c = cols[i];
18805             colcls = 'x-t-' + tid + '-c' +i;
18806             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
18807             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
18808                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
18809                       "</div>");
18810          }
18811          
18812          buf.push(
18813             '</a>',
18814             '<div class="x-clear"></div></div>',
18815             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
18816             "</li>");
18817         
18818         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
18819             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
18820                                 n.nextSibling.ui.getEl(), buf.join(""));
18821         }else{
18822             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
18823         }
18824         var el = this.wrap.firstChild;
18825         this.elRow = el;
18826         this.elNode = el.firstChild;
18827         this.ranchor = el.childNodes[1];
18828         this.ctNode = this.wrap.childNodes[1];
18829         var cs = el.firstChild.childNodes;
18830         this.indentNode = cs[0];
18831         this.ecNode = cs[1];
18832         this.iconNode = cs[2];
18833         var index = 3;
18834         if(cb){
18835             this.checkbox = cs[3];
18836             index++;
18837         }
18838         this.anchor = cs[index];
18839         
18840         this.textNode = cs[index].firstChild;
18841         
18842         //el.on("click", this.onClick, this);
18843         //el.on("dblclick", this.onDblClick, this);
18844         
18845         
18846        // console.log(this);
18847     },
18848     initEvents : function(){
18849         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
18850         
18851             
18852         var a = this.ranchor;
18853
18854         var el = Roo.get(a);
18855
18856         if(Roo.isOpera){ // opera render bug ignores the CSS
18857             el.setStyle("text-decoration", "none");
18858         }
18859
18860         el.on("click", this.onClick, this);
18861         el.on("dblclick", this.onDblClick, this);
18862         el.on("contextmenu", this.onContextMenu, this);
18863         
18864     },
18865     
18866     /*onSelectedChange : function(state){
18867         if(state){
18868             this.focus();
18869             this.addClass("x-tree-selected");
18870         }else{
18871             //this.blur();
18872             this.removeClass("x-tree-selected");
18873         }
18874     },*/
18875     addClass : function(cls){
18876         if(this.elRow){
18877             Roo.fly(this.elRow).addClass(cls);
18878         }
18879         
18880     },
18881     
18882     
18883     removeClass : function(cls){
18884         if(this.elRow){
18885             Roo.fly(this.elRow).removeClass(cls);
18886         }
18887     }
18888
18889     
18890     
18891 });//<Script type="text/javascript">
18892
18893 /*
18894  * Based on:
18895  * Ext JS Library 1.1.1
18896  * Copyright(c) 2006-2007, Ext JS, LLC.
18897  *
18898  * Originally Released Under LGPL - original licence link has changed is not relivant.
18899  *
18900  * Fork - LGPL
18901  * <script type="text/javascript">
18902  */
18903  
18904
18905 /**
18906  * @class Roo.tree.ColumnTree
18907  * @extends Roo.data.TreePanel
18908  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
18909  * @cfg {int} borderWidth  compined right/left border allowance
18910  * @constructor
18911  * @param {String/HTMLElement/Element} el The container element
18912  * @param {Object} config
18913  */
18914 Roo.tree.ColumnTree =  function(el, config)
18915 {
18916    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
18917    this.addEvents({
18918         /**
18919         * @event resize
18920         * Fire this event on a container when it resizes
18921         * @param {int} w Width
18922         * @param {int} h Height
18923         */
18924        "resize" : true
18925     });
18926     this.on('resize', this.onResize, this);
18927 };
18928
18929 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
18930     //lines:false,
18931     
18932     
18933     borderWidth: Roo.isBorderBox ? 0 : 2, 
18934     headEls : false,
18935     
18936     render : function(){
18937         // add the header.....
18938        
18939         Roo.tree.ColumnTree.superclass.render.apply(this);
18940         
18941         this.el.addClass('x-column-tree');
18942         
18943         this.headers = this.el.createChild(
18944             {cls:'x-tree-headers'},this.innerCt.dom);
18945    
18946         var cols = this.columns, c;
18947         var totalWidth = 0;
18948         this.headEls = [];
18949         var  len = cols.length;
18950         for(var i = 0; i < len; i++){
18951              c = cols[i];
18952              totalWidth += c.width;
18953             this.headEls.push(this.headers.createChild({
18954                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
18955                  cn: {
18956                      cls:'x-tree-hd-text',
18957                      html: c.header
18958                  },
18959                  style:'width:'+(c.width-this.borderWidth)+'px;'
18960              }));
18961         }
18962         this.headers.createChild({cls:'x-clear'});
18963         // prevent floats from wrapping when clipped
18964         this.headers.setWidth(totalWidth);
18965         //this.innerCt.setWidth(totalWidth);
18966         this.innerCt.setStyle({ overflow: 'auto' });
18967         this.onResize(this.width, this.height);
18968              
18969         
18970     },
18971     onResize : function(w,h)
18972     {
18973         this.height = h;
18974         this.width = w;
18975         // resize cols..
18976         this.innerCt.setWidth(this.width);
18977         this.innerCt.setHeight(this.height-20);
18978         
18979         // headers...
18980         var cols = this.columns, c;
18981         var totalWidth = 0;
18982         var expEl = false;
18983         var len = cols.length;
18984         for(var i = 0; i < len; i++){
18985             c = cols[i];
18986             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
18987                 // it's the expander..
18988                 expEl  = this.headEls[i];
18989                 continue;
18990             }
18991             totalWidth += c.width;
18992             
18993         }
18994         if (expEl) {
18995             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
18996         }
18997         this.headers.setWidth(w-20);
18998
18999         
19000         
19001         
19002     }
19003 });
19004 /*
19005  * Based on:
19006  * Ext JS Library 1.1.1
19007  * Copyright(c) 2006-2007, Ext JS, LLC.
19008  *
19009  * Originally Released Under LGPL - original licence link has changed is not relivant.
19010  *
19011  * Fork - LGPL
19012  * <script type="text/javascript">
19013  */
19014  
19015 /**
19016  * @class Roo.menu.Menu
19017  * @extends Roo.util.Observable
19018  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
19019  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
19020  * @constructor
19021  * Creates a new Menu
19022  * @param {Object} config Configuration options
19023  */
19024 Roo.menu.Menu = function(config){
19025     Roo.apply(this, config);
19026     this.id = this.id || Roo.id();
19027     this.addEvents({
19028         /**
19029          * @event beforeshow
19030          * Fires before this menu is displayed
19031          * @param {Roo.menu.Menu} this
19032          */
19033         beforeshow : true,
19034         /**
19035          * @event beforehide
19036          * Fires before this menu is hidden
19037          * @param {Roo.menu.Menu} this
19038          */
19039         beforehide : true,
19040         /**
19041          * @event show
19042          * Fires after this menu is displayed
19043          * @param {Roo.menu.Menu} this
19044          */
19045         show : true,
19046         /**
19047          * @event hide
19048          * Fires after this menu is hidden
19049          * @param {Roo.menu.Menu} this
19050          */
19051         hide : true,
19052         /**
19053          * @event click
19054          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
19055          * @param {Roo.menu.Menu} this
19056          * @param {Roo.menu.Item} menuItem The menu item that was clicked
19057          * @param {Roo.EventObject} e
19058          */
19059         click : true,
19060         /**
19061          * @event mouseover
19062          * Fires when the mouse is hovering over this menu
19063          * @param {Roo.menu.Menu} this
19064          * @param {Roo.EventObject} e
19065          * @param {Roo.menu.Item} menuItem The menu item that was clicked
19066          */
19067         mouseover : true,
19068         /**
19069          * @event mouseout
19070          * Fires when the mouse exits this menu
19071          * @param {Roo.menu.Menu} this
19072          * @param {Roo.EventObject} e
19073          * @param {Roo.menu.Item} menuItem The menu item that was clicked
19074          */
19075         mouseout : true,
19076         /**
19077          * @event itemclick
19078          * Fires when a menu item contained in this menu is clicked
19079          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
19080          * @param {Roo.EventObject} e
19081          */
19082         itemclick: true
19083     });
19084     if (this.registerMenu) {
19085         Roo.menu.MenuMgr.register(this);
19086     }
19087     
19088     var mis = this.items;
19089     this.items = new Roo.util.MixedCollection();
19090     if(mis){
19091         this.add.apply(this, mis);
19092     }
19093 };
19094
19095 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
19096     /**
19097      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
19098      */
19099     minWidth : 120,
19100     /**
19101      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
19102      * for bottom-right shadow (defaults to "sides")
19103      */
19104     shadow : "sides",
19105     /**
19106      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
19107      * this menu (defaults to "tl-tr?")
19108      */
19109     subMenuAlign : "tl-tr?",
19110     /**
19111      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
19112      * relative to its element of origin (defaults to "tl-bl?")
19113      */
19114     defaultAlign : "tl-bl?",
19115     /**
19116      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
19117      */
19118     allowOtherMenus : false,
19119     /**
19120      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
19121      */
19122     registerMenu : true,
19123
19124     hidden:true,
19125
19126     // private
19127     render : function(){
19128         if(this.el){
19129             return;
19130         }
19131         var el = this.el = new Roo.Layer({
19132             cls: "x-menu",
19133             shadow:this.shadow,
19134             constrain: false,
19135             parentEl: this.parentEl || document.body,
19136             zindex:15000
19137         });
19138
19139         this.keyNav = new Roo.menu.MenuNav(this);
19140
19141         if(this.plain){
19142             el.addClass("x-menu-plain");
19143         }
19144         if(this.cls){
19145             el.addClass(this.cls);
19146         }
19147         // generic focus element
19148         this.focusEl = el.createChild({
19149             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
19150         });
19151         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
19152         ul.on("click", this.onClick, this);
19153         ul.on("mouseover", this.onMouseOver, this);
19154         ul.on("mouseout", this.onMouseOut, this);
19155         this.items.each(function(item){
19156             if (item.hidden) {
19157                 return;
19158             }
19159             
19160             var li = document.createElement("li");
19161             li.className = "x-menu-list-item";
19162             ul.dom.appendChild(li);
19163             item.render(li, this);
19164         }, this);
19165         this.ul = ul;
19166         this.autoWidth();
19167     },
19168
19169     // private
19170     autoWidth : function(){
19171         var el = this.el, ul = this.ul;
19172         if(!el){
19173             return;
19174         }
19175         var w = this.width;
19176         if(w){
19177             el.setWidth(w);
19178         }else if(Roo.isIE){
19179             el.setWidth(this.minWidth);
19180             var t = el.dom.offsetWidth; // force recalc
19181             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
19182         }
19183     },
19184
19185     // private
19186     delayAutoWidth : function(){
19187         if(this.rendered){
19188             if(!this.awTask){
19189                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
19190             }
19191             this.awTask.delay(20);
19192         }
19193     },
19194
19195     // private
19196     findTargetItem : function(e){
19197         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
19198         if(t && t.menuItemId){
19199             return this.items.get(t.menuItemId);
19200         }
19201     },
19202
19203     // private
19204     onClick : function(e){
19205         var t;
19206         if(t = this.findTargetItem(e)){
19207             t.onClick(e);
19208             this.fireEvent("click", this, t, e);
19209         }
19210     },
19211
19212     // private
19213     setActiveItem : function(item, autoExpand){
19214         if(item != this.activeItem){
19215             if(this.activeItem){
19216                 this.activeItem.deactivate();
19217             }
19218             this.activeItem = item;
19219             item.activate(autoExpand);
19220         }else if(autoExpand){
19221             item.expandMenu();
19222         }
19223     },
19224
19225     // private
19226     tryActivate : function(start, step){
19227         var items = this.items;
19228         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
19229             var item = items.get(i);
19230             if(!item.disabled && item.canActivate){
19231                 this.setActiveItem(item, false);
19232                 return item;
19233             }
19234         }
19235         return false;
19236     },
19237
19238     // private
19239     onMouseOver : function(e){
19240         var t;
19241         if(t = this.findTargetItem(e)){
19242             if(t.canActivate && !t.disabled){
19243                 this.setActiveItem(t, true);
19244             }
19245         }
19246         this.fireEvent("mouseover", this, e, t);
19247     },
19248
19249     // private
19250     onMouseOut : function(e){
19251         var t;
19252         if(t = this.findTargetItem(e)){
19253             if(t == this.activeItem && t.shouldDeactivate(e)){
19254                 this.activeItem.deactivate();
19255                 delete this.activeItem;
19256             }
19257         }
19258         this.fireEvent("mouseout", this, e, t);
19259     },
19260
19261     /**
19262      * Read-only.  Returns true if the menu is currently displayed, else false.
19263      * @type Boolean
19264      */
19265     isVisible : function(){
19266         return this.el && !this.hidden;
19267     },
19268
19269     /**
19270      * Displays this menu relative to another element
19271      * @param {String/HTMLElement/Roo.Element} element The element to align to
19272      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
19273      * the element (defaults to this.defaultAlign)
19274      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
19275      */
19276     show : function(el, pos, parentMenu){
19277         this.parentMenu = parentMenu;
19278         if(!this.el){
19279             this.render();
19280         }
19281         this.fireEvent("beforeshow", this);
19282         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
19283     },
19284
19285     /**
19286      * Displays this menu at a specific xy position
19287      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
19288      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
19289      */
19290     showAt : function(xy, parentMenu, /* private: */_e){
19291         this.parentMenu = parentMenu;
19292         if(!this.el){
19293             this.render();
19294         }
19295         if(_e !== false){
19296             this.fireEvent("beforeshow", this);
19297             xy = this.el.adjustForConstraints(xy);
19298         }
19299         this.el.setXY(xy);
19300         this.el.show();
19301         this.hidden = false;
19302         this.focus();
19303         this.fireEvent("show", this);
19304     },
19305
19306     focus : function(){
19307         if(!this.hidden){
19308             this.doFocus.defer(50, this);
19309         }
19310     },
19311
19312     doFocus : function(){
19313         if(!this.hidden){
19314             this.focusEl.focus();
19315         }
19316     },
19317
19318     /**
19319      * Hides this menu and optionally all parent menus
19320      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
19321      */
19322     hide : function(deep){
19323         if(this.el && this.isVisible()){
19324             this.fireEvent("beforehide", this);
19325             if(this.activeItem){
19326                 this.activeItem.deactivate();
19327                 this.activeItem = null;
19328             }
19329             this.el.hide();
19330             this.hidden = true;
19331             this.fireEvent("hide", this);
19332         }
19333         if(deep === true && this.parentMenu){
19334             this.parentMenu.hide(true);
19335         }
19336     },
19337
19338     /**
19339      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
19340      * Any of the following are valid:
19341      * <ul>
19342      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
19343      * <li>An HTMLElement object which will be converted to a menu item</li>
19344      * <li>A menu item config object that will be created as a new menu item</li>
19345      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
19346      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
19347      * </ul>
19348      * Usage:
19349      * <pre><code>
19350 // Create the menu
19351 var menu = new Roo.menu.Menu();
19352
19353 // Create a menu item to add by reference
19354 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
19355
19356 // Add a bunch of items at once using different methods.
19357 // Only the last item added will be returned.
19358 var item = menu.add(
19359     menuItem,                // add existing item by ref
19360     'Dynamic Item',          // new TextItem
19361     '-',                     // new separator
19362     { text: 'Config Item' }  // new item by config
19363 );
19364 </code></pre>
19365      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
19366      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
19367      */
19368     add : function(){
19369         var a = arguments, l = a.length, item;
19370         for(var i = 0; i < l; i++){
19371             var el = a[i];
19372             if ((typeof(el) == "object") && el.xtype && el.xns) {
19373                 el = Roo.factory(el, Roo.menu);
19374             }
19375             
19376             if(el.render){ // some kind of Item
19377                 item = this.addItem(el);
19378             }else if(typeof el == "string"){ // string
19379                 if(el == "separator" || el == "-"){
19380                     item = this.addSeparator();
19381                 }else{
19382                     item = this.addText(el);
19383                 }
19384             }else if(el.tagName || el.el){ // element
19385                 item = this.addElement(el);
19386             }else if(typeof el == "object"){ // must be menu item config?
19387                 item = this.addMenuItem(el);
19388             }
19389         }
19390         return item;
19391     },
19392
19393     /**
19394      * Returns this menu's underlying {@link Roo.Element} object
19395      * @return {Roo.Element} The element
19396      */
19397     getEl : function(){
19398         if(!this.el){
19399             this.render();
19400         }
19401         return this.el;
19402     },
19403
19404     /**
19405      * Adds a separator bar to the menu
19406      * @return {Roo.menu.Item} The menu item that was added
19407      */
19408     addSeparator : function(){
19409         return this.addItem(new Roo.menu.Separator());
19410     },
19411
19412     /**
19413      * Adds an {@link Roo.Element} object to the menu
19414      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
19415      * @return {Roo.menu.Item} The menu item that was added
19416      */
19417     addElement : function(el){
19418         return this.addItem(new Roo.menu.BaseItem(el));
19419     },
19420
19421     /**
19422      * Adds an existing object based on {@link Roo.menu.Item} to the menu
19423      * @param {Roo.menu.Item} item The menu item to add
19424      * @return {Roo.menu.Item} The menu item that was added
19425      */
19426     addItem : function(item){
19427         this.items.add(item);
19428         if(this.ul){
19429             var li = document.createElement("li");
19430             li.className = "x-menu-list-item";
19431             this.ul.dom.appendChild(li);
19432             item.render(li, this);
19433             this.delayAutoWidth();
19434         }
19435         return item;
19436     },
19437
19438     /**
19439      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
19440      * @param {Object} config A MenuItem config object
19441      * @return {Roo.menu.Item} The menu item that was added
19442      */
19443     addMenuItem : function(config){
19444         if(!(config instanceof Roo.menu.Item)){
19445             if(typeof config.checked == "boolean"){ // must be check menu item config?
19446                 config = new Roo.menu.CheckItem(config);
19447             }else{
19448                 config = new Roo.menu.Item(config);
19449             }
19450         }
19451         return this.addItem(config);
19452     },
19453
19454     /**
19455      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
19456      * @param {String} text The text to display in the menu item
19457      * @return {Roo.menu.Item} The menu item that was added
19458      */
19459     addText : function(text){
19460         return this.addItem(new Roo.menu.TextItem({ text : text }));
19461     },
19462
19463     /**
19464      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
19465      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
19466      * @param {Roo.menu.Item} item The menu item to add
19467      * @return {Roo.menu.Item} The menu item that was added
19468      */
19469     insert : function(index, item){
19470         this.items.insert(index, item);
19471         if(this.ul){
19472             var li = document.createElement("li");
19473             li.className = "x-menu-list-item";
19474             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
19475             item.render(li, this);
19476             this.delayAutoWidth();
19477         }
19478         return item;
19479     },
19480
19481     /**
19482      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
19483      * @param {Roo.menu.Item} item The menu item to remove
19484      */
19485     remove : function(item){
19486         this.items.removeKey(item.id);
19487         item.destroy();
19488     },
19489
19490     /**
19491      * Removes and destroys all items in the menu
19492      */
19493     removeAll : function(){
19494         var f;
19495         while(f = this.items.first()){
19496             this.remove(f);
19497         }
19498     }
19499 });
19500
19501 // MenuNav is a private utility class used internally by the Menu
19502 Roo.menu.MenuNav = function(menu){
19503     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
19504     this.scope = this.menu = menu;
19505 };
19506
19507 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
19508     doRelay : function(e, h){
19509         var k = e.getKey();
19510         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
19511             this.menu.tryActivate(0, 1);
19512             return false;
19513         }
19514         return h.call(this.scope || this, e, this.menu);
19515     },
19516
19517     up : function(e, m){
19518         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
19519             m.tryActivate(m.items.length-1, -1);
19520         }
19521     },
19522
19523     down : function(e, m){
19524         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
19525             m.tryActivate(0, 1);
19526         }
19527     },
19528
19529     right : function(e, m){
19530         if(m.activeItem){
19531             m.activeItem.expandMenu(true);
19532         }
19533     },
19534
19535     left : function(e, m){
19536         m.hide();
19537         if(m.parentMenu && m.parentMenu.activeItem){
19538             m.parentMenu.activeItem.activate();
19539         }
19540     },
19541
19542     enter : function(e, m){
19543         if(m.activeItem){
19544             e.stopPropagation();
19545             m.activeItem.onClick(e);
19546             m.fireEvent("click", this, m.activeItem);
19547             return true;
19548         }
19549     }
19550 });/*
19551  * Based on:
19552  * Ext JS Library 1.1.1
19553  * Copyright(c) 2006-2007, Ext JS, LLC.
19554  *
19555  * Originally Released Under LGPL - original licence link has changed is not relivant.
19556  *
19557  * Fork - LGPL
19558  * <script type="text/javascript">
19559  */
19560  
19561 /**
19562  * @class Roo.menu.MenuMgr
19563  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
19564  * @singleton
19565  */
19566 Roo.menu.MenuMgr = function(){
19567    var menus, active, groups = {}, attached = false, lastShow = new Date();
19568
19569    // private - called when first menu is created
19570    function init(){
19571        menus = {};
19572        active = new Roo.util.MixedCollection();
19573        Roo.get(document).addKeyListener(27, function(){
19574            if(active.length > 0){
19575                hideAll();
19576            }
19577        });
19578    }
19579
19580    // private
19581    function hideAll(){
19582        if(active && active.length > 0){
19583            var c = active.clone();
19584            c.each(function(m){
19585                m.hide();
19586            });
19587        }
19588    }
19589
19590    // private
19591    function onHide(m){
19592        active.remove(m);
19593        if(active.length < 1){
19594            Roo.get(document).un("mousedown", onMouseDown);
19595            attached = false;
19596        }
19597    }
19598
19599    // private
19600    function onShow(m){
19601        var last = active.last();
19602        lastShow = new Date();
19603        active.add(m);
19604        if(!attached){
19605            Roo.get(document).on("mousedown", onMouseDown);
19606            attached = true;
19607        }
19608        if(m.parentMenu){
19609           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
19610           m.parentMenu.activeChild = m;
19611        }else if(last && last.isVisible()){
19612           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
19613        }
19614    }
19615
19616    // private
19617    function onBeforeHide(m){
19618        if(m.activeChild){
19619            m.activeChild.hide();
19620        }
19621        if(m.autoHideTimer){
19622            clearTimeout(m.autoHideTimer);
19623            delete m.autoHideTimer;
19624        }
19625    }
19626
19627    // private
19628    function onBeforeShow(m){
19629        var pm = m.parentMenu;
19630        if(!pm && !m.allowOtherMenus){
19631            hideAll();
19632        }else if(pm && pm.activeChild && active != m){
19633            pm.activeChild.hide();
19634        }
19635    }
19636
19637    // private
19638    function onMouseDown(e){
19639        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
19640            hideAll();
19641        }
19642    }
19643
19644    // private
19645    function onBeforeCheck(mi, state){
19646        if(state){
19647            var g = groups[mi.group];
19648            for(var i = 0, l = g.length; i < l; i++){
19649                if(g[i] != mi){
19650                    g[i].setChecked(false);
19651                }
19652            }
19653        }
19654    }
19655
19656    return {
19657
19658        /**
19659         * Hides all menus that are currently visible
19660         */
19661        hideAll : function(){
19662             hideAll();  
19663        },
19664
19665        // private
19666        register : function(menu){
19667            if(!menus){
19668                init();
19669            }
19670            menus[menu.id] = menu;
19671            menu.on("beforehide", onBeforeHide);
19672            menu.on("hide", onHide);
19673            menu.on("beforeshow", onBeforeShow);
19674            menu.on("show", onShow);
19675            var g = menu.group;
19676            if(g && menu.events["checkchange"]){
19677                if(!groups[g]){
19678                    groups[g] = [];
19679                }
19680                groups[g].push(menu);
19681                menu.on("checkchange", onCheck);
19682            }
19683        },
19684
19685         /**
19686          * Returns a {@link Roo.menu.Menu} object
19687          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
19688          * be used to generate and return a new Menu instance.
19689          */
19690        get : function(menu){
19691            if(typeof menu == "string"){ // menu id
19692                return menus[menu];
19693            }else if(menu.events){  // menu instance
19694                return menu;
19695            }else if(typeof menu.length == 'number'){ // array of menu items?
19696                return new Roo.menu.Menu({items:menu});
19697            }else{ // otherwise, must be a config
19698                return new Roo.menu.Menu(menu);
19699            }
19700        },
19701
19702        // private
19703        unregister : function(menu){
19704            delete menus[menu.id];
19705            menu.un("beforehide", onBeforeHide);
19706            menu.un("hide", onHide);
19707            menu.un("beforeshow", onBeforeShow);
19708            menu.un("show", onShow);
19709            var g = menu.group;
19710            if(g && menu.events["checkchange"]){
19711                groups[g].remove(menu);
19712                menu.un("checkchange", onCheck);
19713            }
19714        },
19715
19716        // private
19717        registerCheckable : function(menuItem){
19718            var g = menuItem.group;
19719            if(g){
19720                if(!groups[g]){
19721                    groups[g] = [];
19722                }
19723                groups[g].push(menuItem);
19724                menuItem.on("beforecheckchange", onBeforeCheck);
19725            }
19726        },
19727
19728        // private
19729        unregisterCheckable : function(menuItem){
19730            var g = menuItem.group;
19731            if(g){
19732                groups[g].remove(menuItem);
19733                menuItem.un("beforecheckchange", onBeforeCheck);
19734            }
19735        }
19736    };
19737 }();/*
19738  * Based on:
19739  * Ext JS Library 1.1.1
19740  * Copyright(c) 2006-2007, Ext JS, LLC.
19741  *
19742  * Originally Released Under LGPL - original licence link has changed is not relivant.
19743  *
19744  * Fork - LGPL
19745  * <script type="text/javascript">
19746  */
19747  
19748
19749 /**
19750  * @class Roo.menu.BaseItem
19751  * @extends Roo.Component
19752  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
19753  * management and base configuration options shared by all menu components.
19754  * @constructor
19755  * Creates a new BaseItem
19756  * @param {Object} config Configuration options
19757  */
19758 Roo.menu.BaseItem = function(config){
19759     Roo.menu.BaseItem.superclass.constructor.call(this, config);
19760
19761     this.addEvents({
19762         /**
19763          * @event click
19764          * Fires when this item is clicked
19765          * @param {Roo.menu.BaseItem} this
19766          * @param {Roo.EventObject} e
19767          */
19768         click: true,
19769         /**
19770          * @event activate
19771          * Fires when this item is activated
19772          * @param {Roo.menu.BaseItem} this
19773          */
19774         activate : true,
19775         /**
19776          * @event deactivate
19777          * Fires when this item is deactivated
19778          * @param {Roo.menu.BaseItem} this
19779          */
19780         deactivate : true
19781     });
19782
19783     if(this.handler){
19784         this.on("click", this.handler, this.scope, true);
19785     }
19786 };
19787
19788 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
19789     /**
19790      * @cfg {Function} handler
19791      * A function that will handle the click event of this menu item (defaults to undefined)
19792      */
19793     /**
19794      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
19795      */
19796     canActivate : false,
19797     
19798      /**
19799      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
19800      */
19801     hidden: false,
19802     
19803     /**
19804      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
19805      */
19806     activeClass : "x-menu-item-active",
19807     /**
19808      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
19809      */
19810     hideOnClick : true,
19811     /**
19812      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
19813      */
19814     hideDelay : 100,
19815
19816     // private
19817     ctype: "Roo.menu.BaseItem",
19818
19819     // private
19820     actionMode : "container",
19821
19822     // private
19823     render : function(container, parentMenu){
19824         this.parentMenu = parentMenu;
19825         Roo.menu.BaseItem.superclass.render.call(this, container);
19826         this.container.menuItemId = this.id;
19827     },
19828
19829     // private
19830     onRender : function(container, position){
19831         this.el = Roo.get(this.el);
19832         container.dom.appendChild(this.el.dom);
19833     },
19834
19835     // private
19836     onClick : function(e){
19837         if(!this.disabled && this.fireEvent("click", this, e) !== false
19838                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
19839             this.handleClick(e);
19840         }else{
19841             e.stopEvent();
19842         }
19843     },
19844
19845     // private
19846     activate : function(){
19847         if(this.disabled){
19848             return false;
19849         }
19850         var li = this.container;
19851         li.addClass(this.activeClass);
19852         this.region = li.getRegion().adjust(2, 2, -2, -2);
19853         this.fireEvent("activate", this);
19854         return true;
19855     },
19856
19857     // private
19858     deactivate : function(){
19859         this.container.removeClass(this.activeClass);
19860         this.fireEvent("deactivate", this);
19861     },
19862
19863     // private
19864     shouldDeactivate : function(e){
19865         return !this.region || !this.region.contains(e.getPoint());
19866     },
19867
19868     // private
19869     handleClick : function(e){
19870         if(this.hideOnClick){
19871             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
19872         }
19873     },
19874
19875     // private
19876     expandMenu : function(autoActivate){
19877         // do nothing
19878     },
19879
19880     // private
19881     hideMenu : function(){
19882         // do nothing
19883     }
19884 });/*
19885  * Based on:
19886  * Ext JS Library 1.1.1
19887  * Copyright(c) 2006-2007, Ext JS, LLC.
19888  *
19889  * Originally Released Under LGPL - original licence link has changed is not relivant.
19890  *
19891  * Fork - LGPL
19892  * <script type="text/javascript">
19893  */
19894  
19895 /**
19896  * @class Roo.menu.Adapter
19897  * @extends Roo.menu.BaseItem
19898  * 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.
19899  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
19900  * @constructor
19901  * Creates a new Adapter
19902  * @param {Object} config Configuration options
19903  */
19904 Roo.menu.Adapter = function(component, config){
19905     Roo.menu.Adapter.superclass.constructor.call(this, config);
19906     this.component = component;
19907 };
19908 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
19909     // private
19910     canActivate : true,
19911
19912     // private
19913     onRender : function(container, position){
19914         this.component.render(container);
19915         this.el = this.component.getEl();
19916     },
19917
19918     // private
19919     activate : function(){
19920         if(this.disabled){
19921             return false;
19922         }
19923         this.component.focus();
19924         this.fireEvent("activate", this);
19925         return true;
19926     },
19927
19928     // private
19929     deactivate : function(){
19930         this.fireEvent("deactivate", this);
19931     },
19932
19933     // private
19934     disable : function(){
19935         this.component.disable();
19936         Roo.menu.Adapter.superclass.disable.call(this);
19937     },
19938
19939     // private
19940     enable : function(){
19941         this.component.enable();
19942         Roo.menu.Adapter.superclass.enable.call(this);
19943     }
19944 });/*
19945  * Based on:
19946  * Ext JS Library 1.1.1
19947  * Copyright(c) 2006-2007, Ext JS, LLC.
19948  *
19949  * Originally Released Under LGPL - original licence link has changed is not relivant.
19950  *
19951  * Fork - LGPL
19952  * <script type="text/javascript">
19953  */
19954
19955 /**
19956  * @class Roo.menu.TextItem
19957  * @extends Roo.menu.BaseItem
19958  * Adds a static text string to a menu, usually used as either a heading or group separator.
19959  * Note: old style constructor with text is still supported.
19960  * 
19961  * @constructor
19962  * Creates a new TextItem
19963  * @param {Object} cfg Configuration
19964  */
19965 Roo.menu.TextItem = function(cfg){
19966     if (typeof(cfg) == 'string') {
19967         this.text = cfg;
19968     } else {
19969         Roo.apply(this,cfg);
19970     }
19971     
19972     Roo.menu.TextItem.superclass.constructor.call(this);
19973 };
19974
19975 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
19976     /**
19977      * @cfg {Boolean} text Text to show on item.
19978      */
19979     text : '',
19980     
19981     /**
19982      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
19983      */
19984     hideOnClick : false,
19985     /**
19986      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
19987      */
19988     itemCls : "x-menu-text",
19989
19990     // private
19991     onRender : function(){
19992         var s = document.createElement("span");
19993         s.className = this.itemCls;
19994         s.innerHTML = this.text;
19995         this.el = s;
19996         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
19997     }
19998 });/*
19999  * Based on:
20000  * Ext JS Library 1.1.1
20001  * Copyright(c) 2006-2007, Ext JS, LLC.
20002  *
20003  * Originally Released Under LGPL - original licence link has changed is not relivant.
20004  *
20005  * Fork - LGPL
20006  * <script type="text/javascript">
20007  */
20008
20009 /**
20010  * @class Roo.menu.Separator
20011  * @extends Roo.menu.BaseItem
20012  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
20013  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
20014  * @constructor
20015  * @param {Object} config Configuration options
20016  */
20017 Roo.menu.Separator = function(config){
20018     Roo.menu.Separator.superclass.constructor.call(this, config);
20019 };
20020
20021 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
20022     /**
20023      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
20024      */
20025     itemCls : "x-menu-sep",
20026     /**
20027      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
20028      */
20029     hideOnClick : false,
20030
20031     // private
20032     onRender : function(li){
20033         var s = document.createElement("span");
20034         s.className = this.itemCls;
20035         s.innerHTML = "&#160;";
20036         this.el = s;
20037         li.addClass("x-menu-sep-li");
20038         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
20039     }
20040 });/*
20041  * Based on:
20042  * Ext JS Library 1.1.1
20043  * Copyright(c) 2006-2007, Ext JS, LLC.
20044  *
20045  * Originally Released Under LGPL - original licence link has changed is not relivant.
20046  *
20047  * Fork - LGPL
20048  * <script type="text/javascript">
20049  */
20050 /**
20051  * @class Roo.menu.Item
20052  * @extends Roo.menu.BaseItem
20053  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
20054  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
20055  * activation and click handling.
20056  * @constructor
20057  * Creates a new Item
20058  * @param {Object} config Configuration options
20059  */
20060 Roo.menu.Item = function(config){
20061     Roo.menu.Item.superclass.constructor.call(this, config);
20062     if(this.menu){
20063         this.menu = Roo.menu.MenuMgr.get(this.menu);
20064     }
20065 };
20066 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
20067     
20068     /**
20069      * @cfg {String} text
20070      * The text to show on the menu item.
20071      */
20072     text: '',
20073      /**
20074      * @cfg {String} HTML to render in menu
20075      * The text to show on the menu item (HTML version).
20076      */
20077     html: '',
20078     /**
20079      * @cfg {String} icon
20080      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
20081      */
20082     icon: undefined,
20083     /**
20084      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
20085      */
20086     itemCls : "x-menu-item",
20087     /**
20088      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
20089      */
20090     canActivate : true,
20091     /**
20092      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
20093      */
20094     showDelay: 200,
20095     // doc'd in BaseItem
20096     hideDelay: 200,
20097
20098     // private
20099     ctype: "Roo.menu.Item",
20100     
20101     // private
20102     onRender : function(container, position){
20103         var el = document.createElement("a");
20104         el.hideFocus = true;
20105         el.unselectable = "on";
20106         el.href = this.href || "#";
20107         if(this.hrefTarget){
20108             el.target = this.hrefTarget;
20109         }
20110         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
20111         
20112         var html = this.html.length ? this.html  : String.format('{0}',this.text);
20113         
20114         el.innerHTML = String.format(
20115                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
20116                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
20117         this.el = el;
20118         Roo.menu.Item.superclass.onRender.call(this, container, position);
20119     },
20120
20121     /**
20122      * Sets the text to display in this menu item
20123      * @param {String} text The text to display
20124      * @param {Boolean} isHTML true to indicate text is pure html.
20125      */
20126     setText : function(text, isHTML){
20127         if (isHTML) {
20128             this.html = text;
20129         } else {
20130             this.text = text;
20131             this.html = '';
20132         }
20133         if(this.rendered){
20134             var html = this.html.length ? this.html  : String.format('{0}',this.text);
20135      
20136             this.el.update(String.format(
20137                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
20138                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
20139             this.parentMenu.autoWidth();
20140         }
20141     },
20142
20143     // private
20144     handleClick : function(e){
20145         if(!this.href){ // if no link defined, stop the event automatically
20146             e.stopEvent();
20147         }
20148         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
20149     },
20150
20151     // private
20152     activate : function(autoExpand){
20153         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
20154             this.focus();
20155             if(autoExpand){
20156                 this.expandMenu();
20157             }
20158         }
20159         return true;
20160     },
20161
20162     // private
20163     shouldDeactivate : function(e){
20164         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
20165             if(this.menu && this.menu.isVisible()){
20166                 return !this.menu.getEl().getRegion().contains(e.getPoint());
20167             }
20168             return true;
20169         }
20170         return false;
20171     },
20172
20173     // private
20174     deactivate : function(){
20175         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
20176         this.hideMenu();
20177     },
20178
20179     // private
20180     expandMenu : function(autoActivate){
20181         if(!this.disabled && this.menu){
20182             clearTimeout(this.hideTimer);
20183             delete this.hideTimer;
20184             if(!this.menu.isVisible() && !this.showTimer){
20185                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
20186             }else if (this.menu.isVisible() && autoActivate){
20187                 this.menu.tryActivate(0, 1);
20188             }
20189         }
20190     },
20191
20192     // private
20193     deferExpand : function(autoActivate){
20194         delete this.showTimer;
20195         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
20196         if(autoActivate){
20197             this.menu.tryActivate(0, 1);
20198         }
20199     },
20200
20201     // private
20202     hideMenu : function(){
20203         clearTimeout(this.showTimer);
20204         delete this.showTimer;
20205         if(!this.hideTimer && this.menu && this.menu.isVisible()){
20206             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
20207         }
20208     },
20209
20210     // private
20211     deferHide : function(){
20212         delete this.hideTimer;
20213         this.menu.hide();
20214     }
20215 });/*
20216  * Based on:
20217  * Ext JS Library 1.1.1
20218  * Copyright(c) 2006-2007, Ext JS, LLC.
20219  *
20220  * Originally Released Under LGPL - original licence link has changed is not relivant.
20221  *
20222  * Fork - LGPL
20223  * <script type="text/javascript">
20224  */
20225  
20226 /**
20227  * @class Roo.menu.CheckItem
20228  * @extends Roo.menu.Item
20229  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
20230  * @constructor
20231  * Creates a new CheckItem
20232  * @param {Object} config Configuration options
20233  */
20234 Roo.menu.CheckItem = function(config){
20235     Roo.menu.CheckItem.superclass.constructor.call(this, config);
20236     this.addEvents({
20237         /**
20238          * @event beforecheckchange
20239          * Fires before the checked value is set, providing an opportunity to cancel if needed
20240          * @param {Roo.menu.CheckItem} this
20241          * @param {Boolean} checked The new checked value that will be set
20242          */
20243         "beforecheckchange" : true,
20244         /**
20245          * @event checkchange
20246          * Fires after the checked value has been set
20247          * @param {Roo.menu.CheckItem} this
20248          * @param {Boolean} checked The checked value that was set
20249          */
20250         "checkchange" : true
20251     });
20252     if(this.checkHandler){
20253         this.on('checkchange', this.checkHandler, this.scope);
20254     }
20255 };
20256 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
20257     /**
20258      * @cfg {String} group
20259      * All check items with the same group name will automatically be grouped into a single-select
20260      * radio button group (defaults to '')
20261      */
20262     /**
20263      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
20264      */
20265     itemCls : "x-menu-item x-menu-check-item",
20266     /**
20267      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
20268      */
20269     groupClass : "x-menu-group-item",
20270
20271     /**
20272      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
20273      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
20274      * initialized with checked = true will be rendered as checked.
20275      */
20276     checked: false,
20277
20278     // private
20279     ctype: "Roo.menu.CheckItem",
20280
20281     // private
20282     onRender : function(c){
20283         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
20284         if(this.group){
20285             this.el.addClass(this.groupClass);
20286         }
20287         Roo.menu.MenuMgr.registerCheckable(this);
20288         if(this.checked){
20289             this.checked = false;
20290             this.setChecked(true, true);
20291         }
20292     },
20293
20294     // private
20295     destroy : function(){
20296         if(this.rendered){
20297             Roo.menu.MenuMgr.unregisterCheckable(this);
20298         }
20299         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
20300     },
20301
20302     /**
20303      * Set the checked state of this item
20304      * @param {Boolean} checked The new checked value
20305      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
20306      */
20307     setChecked : function(state, suppressEvent){
20308         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
20309             if(this.container){
20310                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
20311             }
20312             this.checked = state;
20313             if(suppressEvent !== true){
20314                 this.fireEvent("checkchange", this, state);
20315             }
20316         }
20317     },
20318
20319     // private
20320     handleClick : function(e){
20321        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
20322            this.setChecked(!this.checked);
20323        }
20324        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
20325     }
20326 });/*
20327  * Based on:
20328  * Ext JS Library 1.1.1
20329  * Copyright(c) 2006-2007, Ext JS, LLC.
20330  *
20331  * Originally Released Under LGPL - original licence link has changed is not relivant.
20332  *
20333  * Fork - LGPL
20334  * <script type="text/javascript">
20335  */
20336  
20337 /**
20338  * @class Roo.menu.DateItem
20339  * @extends Roo.menu.Adapter
20340  * A menu item that wraps the {@link Roo.DatPicker} component.
20341  * @constructor
20342  * Creates a new DateItem
20343  * @param {Object} config Configuration options
20344  */
20345 Roo.menu.DateItem = function(config){
20346     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
20347     /** The Roo.DatePicker object @type Roo.DatePicker */
20348     this.picker = this.component;
20349     this.addEvents({select: true});
20350     
20351     this.picker.on("render", function(picker){
20352         picker.getEl().swallowEvent("click");
20353         picker.container.addClass("x-menu-date-item");
20354     });
20355
20356     this.picker.on("select", this.onSelect, this);
20357 };
20358
20359 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
20360     // private
20361     onSelect : function(picker, date){
20362         this.fireEvent("select", this, date, picker);
20363         Roo.menu.DateItem.superclass.handleClick.call(this);
20364     }
20365 });/*
20366  * Based on:
20367  * Ext JS Library 1.1.1
20368  * Copyright(c) 2006-2007, Ext JS, LLC.
20369  *
20370  * Originally Released Under LGPL - original licence link has changed is not relivant.
20371  *
20372  * Fork - LGPL
20373  * <script type="text/javascript">
20374  */
20375  
20376 /**
20377  * @class Roo.menu.ColorItem
20378  * @extends Roo.menu.Adapter
20379  * A menu item that wraps the {@link Roo.ColorPalette} component.
20380  * @constructor
20381  * Creates a new ColorItem
20382  * @param {Object} config Configuration options
20383  */
20384 Roo.menu.ColorItem = function(config){
20385     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
20386     /** The Roo.ColorPalette object @type Roo.ColorPalette */
20387     this.palette = this.component;
20388     this.relayEvents(this.palette, ["select"]);
20389     if(this.selectHandler){
20390         this.on('select', this.selectHandler, this.scope);
20391     }
20392 };
20393 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
20394  * Based on:
20395  * Ext JS Library 1.1.1
20396  * Copyright(c) 2006-2007, Ext JS, LLC.
20397  *
20398  * Originally Released Under LGPL - original licence link has changed is not relivant.
20399  *
20400  * Fork - LGPL
20401  * <script type="text/javascript">
20402  */
20403  
20404
20405 /**
20406  * @class Roo.menu.DateMenu
20407  * @extends Roo.menu.Menu
20408  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
20409  * @constructor
20410  * Creates a new DateMenu
20411  * @param {Object} config Configuration options
20412  */
20413 Roo.menu.DateMenu = function(config){
20414     Roo.menu.DateMenu.superclass.constructor.call(this, config);
20415     this.plain = true;
20416     var di = new Roo.menu.DateItem(config);
20417     this.add(di);
20418     /**
20419      * The {@link Roo.DatePicker} instance for this DateMenu
20420      * @type DatePicker
20421      */
20422     this.picker = di.picker;
20423     /**
20424      * @event select
20425      * @param {DatePicker} picker
20426      * @param {Date} date
20427      */
20428     this.relayEvents(di, ["select"]);
20429     this.on('beforeshow', function(){
20430         if(this.picker){
20431             this.picker.hideMonthPicker(false);
20432         }
20433     }, this);
20434 };
20435 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
20436     cls:'x-date-menu'
20437 });/*
20438  * Based on:
20439  * Ext JS Library 1.1.1
20440  * Copyright(c) 2006-2007, Ext JS, LLC.
20441  *
20442  * Originally Released Under LGPL - original licence link has changed is not relivant.
20443  *
20444  * Fork - LGPL
20445  * <script type="text/javascript">
20446  */
20447  
20448
20449 /**
20450  * @class Roo.menu.ColorMenu
20451  * @extends Roo.menu.Menu
20452  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
20453  * @constructor
20454  * Creates a new ColorMenu
20455  * @param {Object} config Configuration options
20456  */
20457 Roo.menu.ColorMenu = function(config){
20458     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
20459     this.plain = true;
20460     var ci = new Roo.menu.ColorItem(config);
20461     this.add(ci);
20462     /**
20463      * The {@link Roo.ColorPalette} instance for this ColorMenu
20464      * @type ColorPalette
20465      */
20466     this.palette = ci.palette;
20467     /**
20468      * @event select
20469      * @param {ColorPalette} palette
20470      * @param {String} color
20471      */
20472     this.relayEvents(ci, ["select"]);
20473 };
20474 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
20475  * Based on:
20476  * Ext JS Library 1.1.1
20477  * Copyright(c) 2006-2007, Ext JS, LLC.
20478  *
20479  * Originally Released Under LGPL - original licence link has changed is not relivant.
20480  *
20481  * Fork - LGPL
20482  * <script type="text/javascript">
20483  */
20484  
20485 /**
20486  * @class Roo.form.Field
20487  * @extends Roo.BoxComponent
20488  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
20489  * @constructor
20490  * Creates a new Field
20491  * @param {Object} config Configuration options
20492  */
20493 Roo.form.Field = function(config){
20494     Roo.form.Field.superclass.constructor.call(this, config);
20495 };
20496
20497 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
20498     /**
20499      * @cfg {String} fieldLabel Label to use when rendering a form.
20500      */
20501        /**
20502      * @cfg {String} qtip Mouse over tip
20503      */
20504      
20505     /**
20506      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
20507      */
20508     invalidClass : "x-form-invalid",
20509     /**
20510      * @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")
20511      */
20512     invalidText : "The value in this field is invalid",
20513     /**
20514      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
20515      */
20516     focusClass : "x-form-focus",
20517     /**
20518      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
20519       automatic validation (defaults to "keyup").
20520      */
20521     validationEvent : "keyup",
20522     /**
20523      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
20524      */
20525     validateOnBlur : true,
20526     /**
20527      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
20528      */
20529     validationDelay : 250,
20530     /**
20531      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20532      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
20533      */
20534     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
20535     /**
20536      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
20537      */
20538     fieldClass : "x-form-field",
20539     /**
20540      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
20541      *<pre>
20542 Value         Description
20543 -----------   ----------------------------------------------------------------------
20544 qtip          Display a quick tip when the user hovers over the field
20545 title         Display a default browser title attribute popup
20546 under         Add a block div beneath the field containing the error text
20547 side          Add an error icon to the right of the field with a popup on hover
20548 [element id]  Add the error text directly to the innerHTML of the specified element
20549 </pre>
20550      */
20551     msgTarget : 'qtip',
20552     /**
20553      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
20554      */
20555     msgFx : 'normal',
20556
20557     /**
20558      * @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.
20559      */
20560     readOnly : false,
20561
20562     /**
20563      * @cfg {Boolean} disabled True to disable the field (defaults to false).
20564      */
20565     disabled : false,
20566
20567     /**
20568      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
20569      */
20570     inputType : undefined,
20571     
20572     /**
20573      * @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).
20574          */
20575         tabIndex : undefined,
20576         
20577     // private
20578     isFormField : true,
20579
20580     // private
20581     hasFocus : false,
20582     /**
20583      * @property {Roo.Element} fieldEl
20584      * Element Containing the rendered Field (with label etc.)
20585      */
20586     /**
20587      * @cfg {Mixed} value A value to initialize this field with.
20588      */
20589     value : undefined,
20590
20591     /**
20592      * @cfg {String} name The field's HTML name attribute.
20593      */
20594     /**
20595      * @cfg {String} cls A CSS class to apply to the field's underlying element.
20596      */
20597
20598         // private ??
20599         initComponent : function(){
20600         Roo.form.Field.superclass.initComponent.call(this);
20601         this.addEvents({
20602             /**
20603              * @event focus
20604              * Fires when this field receives input focus.
20605              * @param {Roo.form.Field} this
20606              */
20607             focus : true,
20608             /**
20609              * @event blur
20610              * Fires when this field loses input focus.
20611              * @param {Roo.form.Field} this
20612              */
20613             blur : true,
20614             /**
20615              * @event specialkey
20616              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
20617              * {@link Roo.EventObject#getKey} to determine which key was pressed.
20618              * @param {Roo.form.Field} this
20619              * @param {Roo.EventObject} e The event object
20620              */
20621             specialkey : true,
20622             /**
20623              * @event change
20624              * Fires just before the field blurs if the field value has changed.
20625              * @param {Roo.form.Field} this
20626              * @param {Mixed} newValue The new value
20627              * @param {Mixed} oldValue The original value
20628              */
20629             change : true,
20630             /**
20631              * @event invalid
20632              * Fires after the field has been marked as invalid.
20633              * @param {Roo.form.Field} this
20634              * @param {String} msg The validation message
20635              */
20636             invalid : true,
20637             /**
20638              * @event valid
20639              * Fires after the field has been validated with no errors.
20640              * @param {Roo.form.Field} this
20641              */
20642             valid : true,
20643              /**
20644              * @event keyup
20645              * Fires after the key up
20646              * @param {Roo.form.Field} this
20647              * @param {Roo.EventObject}  e The event Object
20648              */
20649             keyup : true
20650         });
20651     },
20652
20653     /**
20654      * Returns the name attribute of the field if available
20655      * @return {String} name The field name
20656      */
20657     getName: function(){
20658          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
20659     },
20660
20661     // private
20662     onRender : function(ct, position){
20663         Roo.form.Field.superclass.onRender.call(this, ct, position);
20664         if(!this.el){
20665             var cfg = this.getAutoCreate();
20666             if(!cfg.name){
20667                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
20668             }
20669             if (!cfg.name.length) {
20670                 delete cfg.name;
20671             }
20672             if(this.inputType){
20673                 cfg.type = this.inputType;
20674             }
20675             this.el = ct.createChild(cfg, position);
20676         }
20677         var type = this.el.dom.type;
20678         if(type){
20679             if(type == 'password'){
20680                 type = 'text';
20681             }
20682             this.el.addClass('x-form-'+type);
20683         }
20684         if(this.readOnly){
20685             this.el.dom.readOnly = true;
20686         }
20687         if(this.tabIndex !== undefined){
20688             this.el.dom.setAttribute('tabIndex', this.tabIndex);
20689         }
20690
20691         this.el.addClass([this.fieldClass, this.cls]);
20692         this.initValue();
20693     },
20694
20695     /**
20696      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
20697      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
20698      * @return {Roo.form.Field} this
20699      */
20700     applyTo : function(target){
20701         this.allowDomMove = false;
20702         this.el = Roo.get(target);
20703         this.render(this.el.dom.parentNode);
20704         return this;
20705     },
20706
20707     // private
20708     initValue : function(){
20709         if(this.value !== undefined){
20710             this.setValue(this.value);
20711         }else if(this.el.dom.value.length > 0){
20712             this.setValue(this.el.dom.value);
20713         }
20714     },
20715
20716     /**
20717      * Returns true if this field has been changed since it was originally loaded and is not disabled.
20718      */
20719     isDirty : function() {
20720         if(this.disabled) {
20721             return false;
20722         }
20723         return String(this.getValue()) !== String(this.originalValue);
20724     },
20725
20726     // private
20727     afterRender : function(){
20728         Roo.form.Field.superclass.afterRender.call(this);
20729         this.initEvents();
20730     },
20731
20732     // private
20733     fireKey : function(e){
20734         //Roo.log('field ' + e.getKey());
20735         if(e.isNavKeyPress()){
20736             this.fireEvent("specialkey", this, e);
20737         }
20738     },
20739
20740     /**
20741      * Resets the current field value to the originally loaded value and clears any validation messages
20742      */
20743     reset : function(){
20744         this.setValue(this.originalValue);
20745         this.clearInvalid();
20746     },
20747
20748     // private
20749     initEvents : function(){
20750         // safari killled keypress - so keydown is now used..
20751         this.el.on("keydown" , this.fireKey,  this);
20752         this.el.on("focus", this.onFocus,  this);
20753         this.el.on("blur", this.onBlur,  this);
20754         this.el.relayEvent('keyup', this);
20755
20756         // reference to original value for reset
20757         this.originalValue = this.getValue();
20758     },
20759
20760     // private
20761     onFocus : function(){
20762         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
20763             this.el.addClass(this.focusClass);
20764         }
20765         if(!this.hasFocus){
20766             this.hasFocus = true;
20767             this.startValue = this.getValue();
20768             this.fireEvent("focus", this);
20769         }
20770     },
20771
20772     beforeBlur : Roo.emptyFn,
20773
20774     // private
20775     onBlur : function(){
20776         this.beforeBlur();
20777         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
20778             this.el.removeClass(this.focusClass);
20779         }
20780         this.hasFocus = false;
20781         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
20782             this.validate();
20783         }
20784         var v = this.getValue();
20785         if(String(v) !== String(this.startValue)){
20786             this.fireEvent('change', this, v, this.startValue);
20787         }
20788         this.fireEvent("blur", this);
20789     },
20790
20791     /**
20792      * Returns whether or not the field value is currently valid
20793      * @param {Boolean} preventMark True to disable marking the field invalid
20794      * @return {Boolean} True if the value is valid, else false
20795      */
20796     isValid : function(preventMark){
20797         if(this.disabled){
20798             return true;
20799         }
20800         var restore = this.preventMark;
20801         this.preventMark = preventMark === true;
20802         var v = this.validateValue(this.processValue(this.getRawValue()));
20803         this.preventMark = restore;
20804         return v;
20805     },
20806
20807     /**
20808      * Validates the field value
20809      * @return {Boolean} True if the value is valid, else false
20810      */
20811     validate : function(){
20812         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
20813             this.clearInvalid();
20814             return true;
20815         }
20816         return false;
20817     },
20818
20819     processValue : function(value){
20820         return value;
20821     },
20822
20823     // private
20824     // Subclasses should provide the validation implementation by overriding this
20825     validateValue : function(value){
20826         return true;
20827     },
20828
20829     /**
20830      * Mark this field as invalid
20831      * @param {String} msg The validation message
20832      */
20833     markInvalid : function(msg){
20834         if(!this.rendered || this.preventMark){ // not rendered
20835             return;
20836         }
20837         this.el.addClass(this.invalidClass);
20838         msg = msg || this.invalidText;
20839         switch(this.msgTarget){
20840             case 'qtip':
20841                 this.el.dom.qtip = msg;
20842                 this.el.dom.qclass = 'x-form-invalid-tip';
20843                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
20844                     Roo.QuickTips.enable();
20845                 }
20846                 break;
20847             case 'title':
20848                 this.el.dom.title = msg;
20849                 break;
20850             case 'under':
20851                 if(!this.errorEl){
20852                     var elp = this.el.findParent('.x-form-element', 5, true);
20853                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
20854                     this.errorEl.setWidth(elp.getWidth(true)-20);
20855                 }
20856                 this.errorEl.update(msg);
20857                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
20858                 break;
20859             case 'side':
20860                 if(!this.errorIcon){
20861                     var elp = this.el.findParent('.x-form-element', 5, true);
20862                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
20863                 }
20864                 this.alignErrorIcon();
20865                 this.errorIcon.dom.qtip = msg;
20866                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
20867                 this.errorIcon.show();
20868                 this.on('resize', this.alignErrorIcon, this);
20869                 break;
20870             default:
20871                 var t = Roo.getDom(this.msgTarget);
20872                 t.innerHTML = msg;
20873                 t.style.display = this.msgDisplay;
20874                 break;
20875         }
20876         this.fireEvent('invalid', this, msg);
20877     },
20878
20879     // private
20880     alignErrorIcon : function(){
20881         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
20882     },
20883
20884     /**
20885      * Clear any invalid styles/messages for this field
20886      */
20887     clearInvalid : function(){
20888         if(!this.rendered || this.preventMark){ // not rendered
20889             return;
20890         }
20891         this.el.removeClass(this.invalidClass);
20892         switch(this.msgTarget){
20893             case 'qtip':
20894                 this.el.dom.qtip = '';
20895                 break;
20896             case 'title':
20897                 this.el.dom.title = '';
20898                 break;
20899             case 'under':
20900                 if(this.errorEl){
20901                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
20902                 }
20903                 break;
20904             case 'side':
20905                 if(this.errorIcon){
20906                     this.errorIcon.dom.qtip = '';
20907                     this.errorIcon.hide();
20908                     this.un('resize', this.alignErrorIcon, this);
20909                 }
20910                 break;
20911             default:
20912                 var t = Roo.getDom(this.msgTarget);
20913                 t.innerHTML = '';
20914                 t.style.display = 'none';
20915                 break;
20916         }
20917         this.fireEvent('valid', this);
20918     },
20919
20920     /**
20921      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
20922      * @return {Mixed} value The field value
20923      */
20924     getRawValue : function(){
20925         var v = this.el.getValue();
20926         
20927         return v;
20928     },
20929
20930     /**
20931      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
20932      * @return {Mixed} value The field value
20933      */
20934     getValue : function(){
20935         var v = this.el.getValue();
20936          
20937         return v;
20938     },
20939
20940     /**
20941      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
20942      * @param {Mixed} value The value to set
20943      */
20944     setRawValue : function(v){
20945         return this.el.dom.value = (v === null || v === undefined ? '' : v);
20946     },
20947
20948     /**
20949      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
20950      * @param {Mixed} value The value to set
20951      */
20952     setValue : function(v){
20953         this.value = v;
20954         if(this.rendered){
20955             this.el.dom.value = (v === null || v === undefined ? '' : v);
20956              this.validate();
20957         }
20958     },
20959
20960     adjustSize : function(w, h){
20961         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
20962         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
20963         return s;
20964     },
20965
20966     adjustWidth : function(tag, w){
20967         tag = tag.toLowerCase();
20968         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
20969             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
20970                 if(tag == 'input'){
20971                     return w + 2;
20972                 }
20973                 if(tag == 'textarea'){
20974                     return w-2;
20975                 }
20976             }else if(Roo.isOpera){
20977                 if(tag == 'input'){
20978                     return w + 2;
20979                 }
20980                 if(tag == 'textarea'){
20981                     return w-2;
20982                 }
20983             }
20984         }
20985         return w;
20986     }
20987 });
20988
20989
20990 // anything other than normal should be considered experimental
20991 Roo.form.Field.msgFx = {
20992     normal : {
20993         show: function(msgEl, f){
20994             msgEl.setDisplayed('block');
20995         },
20996
20997         hide : function(msgEl, f){
20998             msgEl.setDisplayed(false).update('');
20999         }
21000     },
21001
21002     slide : {
21003         show: function(msgEl, f){
21004             msgEl.slideIn('t', {stopFx:true});
21005         },
21006
21007         hide : function(msgEl, f){
21008             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
21009         }
21010     },
21011
21012     slideRight : {
21013         show: function(msgEl, f){
21014             msgEl.fixDisplay();
21015             msgEl.alignTo(f.el, 'tl-tr');
21016             msgEl.slideIn('l', {stopFx:true});
21017         },
21018
21019         hide : function(msgEl, f){
21020             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
21021         }
21022     }
21023 };/*
21024  * Based on:
21025  * Ext JS Library 1.1.1
21026  * Copyright(c) 2006-2007, Ext JS, LLC.
21027  *
21028  * Originally Released Under LGPL - original licence link has changed is not relivant.
21029  *
21030  * Fork - LGPL
21031  * <script type="text/javascript">
21032  */
21033  
21034
21035 /**
21036  * @class Roo.form.TextField
21037  * @extends Roo.form.Field
21038  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
21039  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
21040  * @constructor
21041  * Creates a new TextField
21042  * @param {Object} config Configuration options
21043  */
21044 Roo.form.TextField = function(config){
21045     Roo.form.TextField.superclass.constructor.call(this, config);
21046     this.addEvents({
21047         /**
21048          * @event autosize
21049          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
21050          * according to the default logic, but this event provides a hook for the developer to apply additional
21051          * logic at runtime to resize the field if needed.
21052              * @param {Roo.form.Field} this This text field
21053              * @param {Number} width The new field width
21054              */
21055         autosize : true
21056     });
21057 };
21058
21059 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
21060     /**
21061      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
21062      */
21063     grow : false,
21064     /**
21065      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
21066      */
21067     growMin : 30,
21068     /**
21069      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
21070      */
21071     growMax : 800,
21072     /**
21073      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
21074      */
21075     vtype : null,
21076     /**
21077      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
21078      */
21079     maskRe : null,
21080     /**
21081      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
21082      */
21083     disableKeyFilter : false,
21084     /**
21085      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
21086      */
21087     allowBlank : true,
21088     /**
21089      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
21090      */
21091     minLength : 0,
21092     /**
21093      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
21094      */
21095     maxLength : Number.MAX_VALUE,
21096     /**
21097      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
21098      */
21099     minLengthText : "The minimum length for this field is {0}",
21100     /**
21101      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
21102      */
21103     maxLengthText : "The maximum length for this field is {0}",
21104     /**
21105      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
21106      */
21107     selectOnFocus : false,
21108     /**
21109      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
21110      */
21111     blankText : "This field is required",
21112     /**
21113      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
21114      * If available, this function will be called only after the basic validators all return true, and will be passed the
21115      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
21116      */
21117     validator : null,
21118     /**
21119      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
21120      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
21121      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
21122      */
21123     regex : null,
21124     /**
21125      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
21126      */
21127     regexText : "",
21128     /**
21129      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
21130      */
21131     emptyText : null,
21132    
21133
21134     // private
21135     initEvents : function()
21136     {
21137         if (this.emptyText) {
21138             this.el.attr('placeholder', this.emptyText);
21139         }
21140         
21141         Roo.form.TextField.superclass.initEvents.call(this);
21142         if(this.validationEvent == 'keyup'){
21143             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
21144             this.el.on('keyup', this.filterValidation, this);
21145         }
21146         else if(this.validationEvent !== false){
21147             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
21148         }
21149         
21150         if(this.selectOnFocus){
21151             this.on("focus", this.preFocus, this);
21152             
21153         }
21154         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
21155             this.el.on("keypress", this.filterKeys, this);
21156         }
21157         if(this.grow){
21158             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
21159             this.el.on("click", this.autoSize,  this);
21160         }
21161         if(this.el.is('input[type=password]') && Roo.isSafari){
21162             this.el.on('keydown', this.SafariOnKeyDown, this);
21163         }
21164     },
21165
21166     processValue : function(value){
21167         if(this.stripCharsRe){
21168             var newValue = value.replace(this.stripCharsRe, '');
21169             if(newValue !== value){
21170                 this.setRawValue(newValue);
21171                 return newValue;
21172             }
21173         }
21174         return value;
21175     },
21176
21177     filterValidation : function(e){
21178         if(!e.isNavKeyPress()){
21179             this.validationTask.delay(this.validationDelay);
21180         }
21181     },
21182
21183     // private
21184     onKeyUp : function(e){
21185         if(!e.isNavKeyPress()){
21186             this.autoSize();
21187         }
21188     },
21189
21190     /**
21191      * Resets the current field value to the originally-loaded value and clears any validation messages.
21192      *  
21193      */
21194     reset : function(){
21195         Roo.form.TextField.superclass.reset.call(this);
21196        
21197     },
21198
21199     
21200     // private
21201     preFocus : function(){
21202         
21203         if(this.selectOnFocus){
21204             this.el.dom.select();
21205         }
21206     },
21207
21208     
21209     // private
21210     filterKeys : function(e){
21211         var k = e.getKey();
21212         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
21213             return;
21214         }
21215         var c = e.getCharCode(), cc = String.fromCharCode(c);
21216         if(Roo.isIE && (e.isSpecialKey() || !cc)){
21217             return;
21218         }
21219         if(!this.maskRe.test(cc)){
21220             e.stopEvent();
21221         }
21222     },
21223
21224     setValue : function(v){
21225         
21226         Roo.form.TextField.superclass.setValue.apply(this, arguments);
21227         
21228         this.autoSize();
21229     },
21230
21231     /**
21232      * Validates a value according to the field's validation rules and marks the field as invalid
21233      * if the validation fails
21234      * @param {Mixed} value The value to validate
21235      * @return {Boolean} True if the value is valid, else false
21236      */
21237     validateValue : function(value){
21238         if(value.length < 1)  { // if it's blank
21239              if(this.allowBlank){
21240                 this.clearInvalid();
21241                 return true;
21242              }else{
21243                 this.markInvalid(this.blankText);
21244                 return false;
21245              }
21246         }
21247         if(value.length < this.minLength){
21248             this.markInvalid(String.format(this.minLengthText, this.minLength));
21249             return false;
21250         }
21251         if(value.length > this.maxLength){
21252             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
21253             return false;
21254         }
21255         if(this.vtype){
21256             var vt = Roo.form.VTypes;
21257             if(!vt[this.vtype](value, this)){
21258                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
21259                 return false;
21260             }
21261         }
21262         if(typeof this.validator == "function"){
21263             var msg = this.validator(value);
21264             if(msg !== true){
21265                 this.markInvalid(msg);
21266                 return false;
21267             }
21268         }
21269         if(this.regex && !this.regex.test(value)){
21270             this.markInvalid(this.regexText);
21271             return false;
21272         }
21273         return true;
21274     },
21275
21276     /**
21277      * Selects text in this field
21278      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
21279      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
21280      */
21281     selectText : function(start, end){
21282         var v = this.getRawValue();
21283         if(v.length > 0){
21284             start = start === undefined ? 0 : start;
21285             end = end === undefined ? v.length : end;
21286             var d = this.el.dom;
21287             if(d.setSelectionRange){
21288                 d.setSelectionRange(start, end);
21289             }else if(d.createTextRange){
21290                 var range = d.createTextRange();
21291                 range.moveStart("character", start);
21292                 range.moveEnd("character", v.length-end);
21293                 range.select();
21294             }
21295         }
21296     },
21297
21298     /**
21299      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
21300      * This only takes effect if grow = true, and fires the autosize event.
21301      */
21302     autoSize : function(){
21303         if(!this.grow || !this.rendered){
21304             return;
21305         }
21306         if(!this.metrics){
21307             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
21308         }
21309         var el = this.el;
21310         var v = el.dom.value;
21311         var d = document.createElement('div');
21312         d.appendChild(document.createTextNode(v));
21313         v = d.innerHTML;
21314         d = null;
21315         v += "&#160;";
21316         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
21317         this.el.setWidth(w);
21318         this.fireEvent("autosize", this, w);
21319     },
21320     
21321     // private
21322     SafariOnKeyDown : function(event)
21323     {
21324         // this is a workaround for a password hang bug on chrome/ webkit.
21325         
21326         var isSelectAll = false;
21327         
21328         if(this.el.dom.selectionEnd > 0){
21329             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
21330         }
21331         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
21332             event.preventDefault();
21333             this.setValue('');
21334             return;
21335         }
21336         
21337         if(isSelectAll){ // backspace and delete key
21338             
21339             event.preventDefault();
21340             // this is very hacky as keydown always get's upper case.
21341             //
21342             var cc = String.fromCharCode(event.getCharCode());
21343             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
21344             
21345         }
21346         
21347         
21348     }
21349 });/*
21350  * Based on:
21351  * Ext JS Library 1.1.1
21352  * Copyright(c) 2006-2007, Ext JS, LLC.
21353  *
21354  * Originally Released Under LGPL - original licence link has changed is not relivant.
21355  *
21356  * Fork - LGPL
21357  * <script type="text/javascript">
21358  */
21359  
21360 /**
21361  * @class Roo.form.Hidden
21362  * @extends Roo.form.TextField
21363  * Simple Hidden element used on forms 
21364  * 
21365  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
21366  * 
21367  * @constructor
21368  * Creates a new Hidden form element.
21369  * @param {Object} config Configuration options
21370  */
21371
21372
21373
21374 // easy hidden field...
21375 Roo.form.Hidden = function(config){
21376     Roo.form.Hidden.superclass.constructor.call(this, config);
21377 };
21378   
21379 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
21380     fieldLabel:      '',
21381     inputType:      'hidden',
21382     width:          50,
21383     allowBlank:     true,
21384     labelSeparator: '',
21385     hidden:         true,
21386     itemCls :       'x-form-item-display-none'
21387
21388
21389 });
21390
21391
21392 /*
21393  * Based on:
21394  * Ext JS Library 1.1.1
21395  * Copyright(c) 2006-2007, Ext JS, LLC.
21396  *
21397  * Originally Released Under LGPL - original licence link has changed is not relivant.
21398  *
21399  * Fork - LGPL
21400  * <script type="text/javascript">
21401  */
21402  
21403 /**
21404  * @class Roo.form.TriggerField
21405  * @extends Roo.form.TextField
21406  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
21407  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
21408  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
21409  * for which you can provide a custom implementation.  For example:
21410  * <pre><code>
21411 var trigger = new Roo.form.TriggerField();
21412 trigger.onTriggerClick = myTriggerFn;
21413 trigger.applyTo('my-field');
21414 </code></pre>
21415  *
21416  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
21417  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
21418  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
21419  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
21420  * @constructor
21421  * Create a new TriggerField.
21422  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
21423  * to the base TextField)
21424  */
21425 Roo.form.TriggerField = function(config){
21426     this.mimicing = false;
21427     Roo.form.TriggerField.superclass.constructor.call(this, config);
21428 };
21429
21430 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
21431     /**
21432      * @cfg {String} triggerClass A CSS class to apply to the trigger
21433      */
21434     /**
21435      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
21436      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
21437      */
21438     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
21439     /**
21440      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
21441      */
21442     hideTrigger:false,
21443
21444     /** @cfg {Boolean} grow @hide */
21445     /** @cfg {Number} growMin @hide */
21446     /** @cfg {Number} growMax @hide */
21447
21448     /**
21449      * @hide 
21450      * @method
21451      */
21452     autoSize: Roo.emptyFn,
21453     // private
21454     monitorTab : true,
21455     // private
21456     deferHeight : true,
21457
21458     
21459     actionMode : 'wrap',
21460     // private
21461     onResize : function(w, h){
21462         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
21463         if(typeof w == 'number'){
21464             var x = w - this.trigger.getWidth();
21465             this.el.setWidth(this.adjustWidth('input', x));
21466             this.trigger.setStyle('left', x+'px');
21467         }
21468     },
21469
21470     // private
21471     adjustSize : Roo.BoxComponent.prototype.adjustSize,
21472
21473     // private
21474     getResizeEl : function(){
21475         return this.wrap;
21476     },
21477
21478     // private
21479     getPositionEl : function(){
21480         return this.wrap;
21481     },
21482
21483     // private
21484     alignErrorIcon : function(){
21485         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
21486     },
21487
21488     // private
21489     onRender : function(ct, position){
21490         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
21491         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
21492         this.trigger = this.wrap.createChild(this.triggerConfig ||
21493                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
21494         if(this.hideTrigger){
21495             this.trigger.setDisplayed(false);
21496         }
21497         this.initTrigger();
21498         if(!this.width){
21499             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
21500         }
21501     },
21502
21503     // private
21504     initTrigger : function(){
21505         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
21506         this.trigger.addClassOnOver('x-form-trigger-over');
21507         this.trigger.addClassOnClick('x-form-trigger-click');
21508     },
21509
21510     // private
21511     onDestroy : function(){
21512         if(this.trigger){
21513             this.trigger.removeAllListeners();
21514             this.trigger.remove();
21515         }
21516         if(this.wrap){
21517             this.wrap.remove();
21518         }
21519         Roo.form.TriggerField.superclass.onDestroy.call(this);
21520     },
21521
21522     // private
21523     onFocus : function(){
21524         Roo.form.TriggerField.superclass.onFocus.call(this);
21525         if(!this.mimicing){
21526             this.wrap.addClass('x-trigger-wrap-focus');
21527             this.mimicing = true;
21528             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
21529             if(this.monitorTab){
21530                 this.el.on("keydown", this.checkTab, this);
21531             }
21532         }
21533     },
21534
21535     // private
21536     checkTab : function(e){
21537         if(e.getKey() == e.TAB){
21538             this.triggerBlur();
21539         }
21540     },
21541
21542     // private
21543     onBlur : function(){
21544         // do nothing
21545     },
21546
21547     // private
21548     mimicBlur : function(e, t){
21549         if(!this.wrap.contains(t) && this.validateBlur()){
21550             this.triggerBlur();
21551         }
21552     },
21553
21554     // private
21555     triggerBlur : function(){
21556         this.mimicing = false;
21557         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
21558         if(this.monitorTab){
21559             this.el.un("keydown", this.checkTab, this);
21560         }
21561         this.wrap.removeClass('x-trigger-wrap-focus');
21562         Roo.form.TriggerField.superclass.onBlur.call(this);
21563     },
21564
21565     // private
21566     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
21567     validateBlur : function(e, t){
21568         return true;
21569     },
21570
21571     // private
21572     onDisable : function(){
21573         Roo.form.TriggerField.superclass.onDisable.call(this);
21574         if(this.wrap){
21575             this.wrap.addClass('x-item-disabled');
21576         }
21577     },
21578
21579     // private
21580     onEnable : function(){
21581         Roo.form.TriggerField.superclass.onEnable.call(this);
21582         if(this.wrap){
21583             this.wrap.removeClass('x-item-disabled');
21584         }
21585     },
21586
21587     // private
21588     onShow : function(){
21589         var ae = this.getActionEl();
21590         
21591         if(ae){
21592             ae.dom.style.display = '';
21593             ae.dom.style.visibility = 'visible';
21594         }
21595     },
21596
21597     // private
21598     
21599     onHide : function(){
21600         var ae = this.getActionEl();
21601         ae.dom.style.display = 'none';
21602     },
21603
21604     /**
21605      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
21606      * by an implementing function.
21607      * @method
21608      * @param {EventObject} e
21609      */
21610     onTriggerClick : Roo.emptyFn
21611 });
21612
21613 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
21614 // to be extended by an implementing class.  For an example of implementing this class, see the custom
21615 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
21616 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
21617     initComponent : function(){
21618         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
21619
21620         this.triggerConfig = {
21621             tag:'span', cls:'x-form-twin-triggers', cn:[
21622             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
21623             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
21624         ]};
21625     },
21626
21627     getTrigger : function(index){
21628         return this.triggers[index];
21629     },
21630
21631     initTrigger : function(){
21632         var ts = this.trigger.select('.x-form-trigger', true);
21633         this.wrap.setStyle('overflow', 'hidden');
21634         var triggerField = this;
21635         ts.each(function(t, all, index){
21636             t.hide = function(){
21637                 var w = triggerField.wrap.getWidth();
21638                 this.dom.style.display = 'none';
21639                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
21640             };
21641             t.show = function(){
21642                 var w = triggerField.wrap.getWidth();
21643                 this.dom.style.display = '';
21644                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
21645             };
21646             var triggerIndex = 'Trigger'+(index+1);
21647
21648             if(this['hide'+triggerIndex]){
21649                 t.dom.style.display = 'none';
21650             }
21651             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
21652             t.addClassOnOver('x-form-trigger-over');
21653             t.addClassOnClick('x-form-trigger-click');
21654         }, this);
21655         this.triggers = ts.elements;
21656     },
21657
21658     onTrigger1Click : Roo.emptyFn,
21659     onTrigger2Click : Roo.emptyFn
21660 });/*
21661  * Based on:
21662  * Ext JS Library 1.1.1
21663  * Copyright(c) 2006-2007, Ext JS, LLC.
21664  *
21665  * Originally Released Under LGPL - original licence link has changed is not relivant.
21666  *
21667  * Fork - LGPL
21668  * <script type="text/javascript">
21669  */
21670  
21671 /**
21672  * @class Roo.form.TextArea
21673  * @extends Roo.form.TextField
21674  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
21675  * support for auto-sizing.
21676  * @constructor
21677  * Creates a new TextArea
21678  * @param {Object} config Configuration options
21679  */
21680 Roo.form.TextArea = function(config){
21681     Roo.form.TextArea.superclass.constructor.call(this, config);
21682     // these are provided exchanges for backwards compat
21683     // minHeight/maxHeight were replaced by growMin/growMax to be
21684     // compatible with TextField growing config values
21685     if(this.minHeight !== undefined){
21686         this.growMin = this.minHeight;
21687     }
21688     if(this.maxHeight !== undefined){
21689         this.growMax = this.maxHeight;
21690     }
21691 };
21692
21693 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
21694     /**
21695      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
21696      */
21697     growMin : 60,
21698     /**
21699      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
21700      */
21701     growMax: 1000,
21702     /**
21703      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
21704      * in the field (equivalent to setting overflow: hidden, defaults to false)
21705      */
21706     preventScrollbars: false,
21707     /**
21708      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
21709      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
21710      */
21711
21712     // private
21713     onRender : function(ct, position){
21714         if(!this.el){
21715             this.defaultAutoCreate = {
21716                 tag: "textarea",
21717                 style:"width:300px;height:60px;",
21718                 autocomplete: "off"
21719             };
21720         }
21721         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
21722         if(this.grow){
21723             this.textSizeEl = Roo.DomHelper.append(document.body, {
21724                 tag: "pre", cls: "x-form-grow-sizer"
21725             });
21726             if(this.preventScrollbars){
21727                 this.el.setStyle("overflow", "hidden");
21728             }
21729             this.el.setHeight(this.growMin);
21730         }
21731     },
21732
21733     onDestroy : function(){
21734         if(this.textSizeEl){
21735             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
21736         }
21737         Roo.form.TextArea.superclass.onDestroy.call(this);
21738     },
21739
21740     // private
21741     onKeyUp : function(e){
21742         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
21743             this.autoSize();
21744         }
21745     },
21746
21747     /**
21748      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
21749      * This only takes effect if grow = true, and fires the autosize event if the height changes.
21750      */
21751     autoSize : function(){
21752         if(!this.grow || !this.textSizeEl){
21753             return;
21754         }
21755         var el = this.el;
21756         var v = el.dom.value;
21757         var ts = this.textSizeEl;
21758
21759         ts.innerHTML = '';
21760         ts.appendChild(document.createTextNode(v));
21761         v = ts.innerHTML;
21762
21763         Roo.fly(ts).setWidth(this.el.getWidth());
21764         if(v.length < 1){
21765             v = "&#160;&#160;";
21766         }else{
21767             if(Roo.isIE){
21768                 v = v.replace(/\n/g, '<p>&#160;</p>');
21769             }
21770             v += "&#160;\n&#160;";
21771         }
21772         ts.innerHTML = v;
21773         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
21774         if(h != this.lastHeight){
21775             this.lastHeight = h;
21776             this.el.setHeight(h);
21777             this.fireEvent("autosize", this, h);
21778         }
21779     }
21780 });/*
21781  * Based on:
21782  * Ext JS Library 1.1.1
21783  * Copyright(c) 2006-2007, Ext JS, LLC.
21784  *
21785  * Originally Released Under LGPL - original licence link has changed is not relivant.
21786  *
21787  * Fork - LGPL
21788  * <script type="text/javascript">
21789  */
21790  
21791
21792 /**
21793  * @class Roo.form.NumberField
21794  * @extends Roo.form.TextField
21795  * Numeric text field that provides automatic keystroke filtering and numeric validation.
21796  * @constructor
21797  * Creates a new NumberField
21798  * @param {Object} config Configuration options
21799  */
21800 Roo.form.NumberField = function(config){
21801     Roo.form.NumberField.superclass.constructor.call(this, config);
21802 };
21803
21804 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
21805     /**
21806      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
21807      */
21808     fieldClass: "x-form-field x-form-num-field",
21809     /**
21810      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
21811      */
21812     allowDecimals : true,
21813     /**
21814      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
21815      */
21816     decimalSeparator : ".",
21817     /**
21818      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
21819      */
21820     decimalPrecision : 2,
21821     /**
21822      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
21823      */
21824     allowNegative : true,
21825     /**
21826      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
21827      */
21828     minValue : Number.NEGATIVE_INFINITY,
21829     /**
21830      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
21831      */
21832     maxValue : Number.MAX_VALUE,
21833     /**
21834      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
21835      */
21836     minText : "The minimum value for this field is {0}",
21837     /**
21838      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
21839      */
21840     maxText : "The maximum value for this field is {0}",
21841     /**
21842      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
21843      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
21844      */
21845     nanText : "{0} is not a valid number",
21846
21847     // private
21848     initEvents : function(){
21849         Roo.form.NumberField.superclass.initEvents.call(this);
21850         var allowed = "0123456789";
21851         if(this.allowDecimals){
21852             allowed += this.decimalSeparator;
21853         }
21854         if(this.allowNegative){
21855             allowed += "-";
21856         }
21857         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
21858         var keyPress = function(e){
21859             var k = e.getKey();
21860             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
21861                 return;
21862             }
21863             var c = e.getCharCode();
21864             if(allowed.indexOf(String.fromCharCode(c)) === -1){
21865                 e.stopEvent();
21866             }
21867         };
21868         this.el.on("keypress", keyPress, this);
21869     },
21870
21871     // private
21872     validateValue : function(value){
21873         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
21874             return false;
21875         }
21876         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
21877              return true;
21878         }
21879         var num = this.parseValue(value);
21880         if(isNaN(num)){
21881             this.markInvalid(String.format(this.nanText, value));
21882             return false;
21883         }
21884         if(num < this.minValue){
21885             this.markInvalid(String.format(this.minText, this.minValue));
21886             return false;
21887         }
21888         if(num > this.maxValue){
21889             this.markInvalid(String.format(this.maxText, this.maxValue));
21890             return false;
21891         }
21892         return true;
21893     },
21894
21895     getValue : function(){
21896         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
21897     },
21898
21899     // private
21900     parseValue : function(value){
21901         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
21902         return isNaN(value) ? '' : value;
21903     },
21904
21905     // private
21906     fixPrecision : function(value){
21907         var nan = isNaN(value);
21908         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
21909             return nan ? '' : value;
21910         }
21911         return parseFloat(value).toFixed(this.decimalPrecision);
21912     },
21913
21914     setValue : function(v){
21915         v = this.fixPrecision(v);
21916         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
21917     },
21918
21919     // private
21920     decimalPrecisionFcn : function(v){
21921         return Math.floor(v);
21922     },
21923
21924     beforeBlur : function(){
21925         var v = this.parseValue(this.getRawValue());
21926         if(v){
21927             this.setValue(v);
21928         }
21929     }
21930 });/*
21931  * Based on:
21932  * Ext JS Library 1.1.1
21933  * Copyright(c) 2006-2007, Ext JS, LLC.
21934  *
21935  * Originally Released Under LGPL - original licence link has changed is not relivant.
21936  *
21937  * Fork - LGPL
21938  * <script type="text/javascript">
21939  */
21940  
21941 /**
21942  * @class Roo.form.DateField
21943  * @extends Roo.form.TriggerField
21944  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
21945 * @constructor
21946 * Create a new DateField
21947 * @param {Object} config
21948  */
21949 Roo.form.DateField = function(config){
21950     Roo.form.DateField.superclass.constructor.call(this, config);
21951     
21952       this.addEvents({
21953          
21954         /**
21955          * @event select
21956          * Fires when a date is selected
21957              * @param {Roo.form.DateField} combo This combo box
21958              * @param {Date} date The date selected
21959              */
21960         'select' : true
21961          
21962     });
21963     
21964     
21965     if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
21966     if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
21967     this.ddMatch = null;
21968     if(this.disabledDates){
21969         var dd = this.disabledDates;
21970         var re = "(?:";
21971         for(var i = 0; i < dd.length; i++){
21972             re += dd[i];
21973             if(i != dd.length-1) re += "|";
21974         }
21975         this.ddMatch = new RegExp(re + ")");
21976     }
21977 };
21978
21979 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
21980     /**
21981      * @cfg {String} format
21982      * The default date format string which can be overriden for localization support.  The format must be
21983      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
21984      */
21985     format : "m/d/y",
21986     /**
21987      * @cfg {String} altFormats
21988      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
21989      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
21990      */
21991     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
21992     /**
21993      * @cfg {Array} disabledDays
21994      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
21995      */
21996     disabledDays : null,
21997     /**
21998      * @cfg {String} disabledDaysText
21999      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
22000      */
22001     disabledDaysText : "Disabled",
22002     /**
22003      * @cfg {Array} disabledDates
22004      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
22005      * expression so they are very powerful. Some examples:
22006      * <ul>
22007      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
22008      * <li>["03/08", "09/16"] would disable those days for every year</li>
22009      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
22010      * <li>["03/../2006"] would disable every day in March 2006</li>
22011      * <li>["^03"] would disable every day in every March</li>
22012      * </ul>
22013      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
22014      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
22015      */
22016     disabledDates : null,
22017     /**
22018      * @cfg {String} disabledDatesText
22019      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
22020      */
22021     disabledDatesText : "Disabled",
22022     /**
22023      * @cfg {Date/String} minValue
22024      * The minimum allowed date. Can be either a Javascript date object or a string date in a
22025      * valid format (defaults to null).
22026      */
22027     minValue : null,
22028     /**
22029      * @cfg {Date/String} maxValue
22030      * The maximum allowed date. Can be either a Javascript date object or a string date in a
22031      * valid format (defaults to null).
22032      */
22033     maxValue : null,
22034     /**
22035      * @cfg {String} minText
22036      * The error text to display when the date in the cell is before minValue (defaults to
22037      * 'The date in this field must be after {minValue}').
22038      */
22039     minText : "The date in this field must be equal to or after {0}",
22040     /**
22041      * @cfg {String} maxText
22042      * The error text to display when the date in the cell is after maxValue (defaults to
22043      * 'The date in this field must be before {maxValue}').
22044      */
22045     maxText : "The date in this field must be equal to or before {0}",
22046     /**
22047      * @cfg {String} invalidText
22048      * The error text to display when the date in the field is invalid (defaults to
22049      * '{value} is not a valid date - it must be in the format {format}').
22050      */
22051     invalidText : "{0} is not a valid date - it must be in the format {1}",
22052     /**
22053      * @cfg {String} triggerClass
22054      * An additional CSS class used to style the trigger button.  The trigger will always get the
22055      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
22056      * which displays a calendar icon).
22057      */
22058     triggerClass : 'x-form-date-trigger',
22059     
22060
22061     /**
22062      * @cfg {Boolean} useIso
22063      * if enabled, then the date field will use a hidden field to store the 
22064      * real value as iso formated date. default (false)
22065      */ 
22066     useIso : false,
22067     /**
22068      * @cfg {String/Object} autoCreate
22069      * A DomHelper element spec, or true for a default element spec (defaults to
22070      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
22071      */ 
22072     // private
22073     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
22074     
22075     // private
22076     hiddenField: false,
22077     
22078     onRender : function(ct, position)
22079     {
22080         Roo.form.DateField.superclass.onRender.call(this, ct, position);
22081         if (this.useIso) {
22082             //this.el.dom.removeAttribute('name'); 
22083             Roo.log("Changing name?");
22084             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
22085             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
22086                     'before', true);
22087             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
22088             // prevent input submission
22089             this.hiddenName = this.name;
22090         }
22091             
22092             
22093     },
22094     
22095     // private
22096     validateValue : function(value)
22097     {
22098         value = this.formatDate(value);
22099         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
22100             Roo.log('super failed');
22101             return false;
22102         }
22103         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
22104              return true;
22105         }
22106         var svalue = value;
22107         value = this.parseDate(value);
22108         if(!value){
22109             Roo.log('parse date failed' + svalue);
22110             this.markInvalid(String.format(this.invalidText, svalue, this.format));
22111             return false;
22112         }
22113         var time = value.getTime();
22114         if(this.minValue && time < this.minValue.getTime()){
22115             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
22116             return false;
22117         }
22118         if(this.maxValue && time > this.maxValue.getTime()){
22119             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
22120             return false;
22121         }
22122         if(this.disabledDays){
22123             var day = value.getDay();
22124             for(var i = 0; i < this.disabledDays.length; i++) {
22125                 if(day === this.disabledDays[i]){
22126                     this.markInvalid(this.disabledDaysText);
22127                     return false;
22128                 }
22129             }
22130         }
22131         var fvalue = this.formatDate(value);
22132         if(this.ddMatch && this.ddMatch.test(fvalue)){
22133             this.markInvalid(String.format(this.disabledDatesText, fvalue));
22134             return false;
22135         }
22136         return true;
22137     },
22138
22139     // private
22140     // Provides logic to override the default TriggerField.validateBlur which just returns true
22141     validateBlur : function(){
22142         return !this.menu || !this.menu.isVisible();
22143     },
22144     
22145     getName: function()
22146     {
22147         // returns hidden if it's set..
22148         if (!this.rendered) {return ''};
22149         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
22150         
22151     },
22152
22153     /**
22154      * Returns the current date value of the date field.
22155      * @return {Date} The date value
22156      */
22157     getValue : function(){
22158         
22159         return  this.hiddenField ?
22160                 this.hiddenField.value :
22161                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
22162     },
22163
22164     /**
22165      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
22166      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
22167      * (the default format used is "m/d/y").
22168      * <br />Usage:
22169      * <pre><code>
22170 //All of these calls set the same date value (May 4, 2006)
22171
22172 //Pass a date object:
22173 var dt = new Date('5/4/06');
22174 dateField.setValue(dt);
22175
22176 //Pass a date string (default format):
22177 dateField.setValue('5/4/06');
22178
22179 //Pass a date string (custom format):
22180 dateField.format = 'Y-m-d';
22181 dateField.setValue('2006-5-4');
22182 </code></pre>
22183      * @param {String/Date} date The date or valid date string
22184      */
22185     setValue : function(date){
22186         if (this.hiddenField) {
22187             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
22188         }
22189         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
22190         // make sure the value field is always stored as a date..
22191         this.value = this.parseDate(date);
22192         
22193         
22194     },
22195
22196     // private
22197     parseDate : function(value){
22198         if(!value || value instanceof Date){
22199             return value;
22200         }
22201         var v = Date.parseDate(value, this.format);
22202          if (!v && this.useIso) {
22203             v = Date.parseDate(value, 'Y-m-d');
22204         }
22205         if(!v && this.altFormats){
22206             if(!this.altFormatsArray){
22207                 this.altFormatsArray = this.altFormats.split("|");
22208             }
22209             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
22210                 v = Date.parseDate(value, this.altFormatsArray[i]);
22211             }
22212         }
22213         return v;
22214     },
22215
22216     // private
22217     formatDate : function(date, fmt){
22218         return (!date || !(date instanceof Date)) ?
22219                date : date.dateFormat(fmt || this.format);
22220     },
22221
22222     // private
22223     menuListeners : {
22224         select: function(m, d){
22225             
22226             this.setValue(d);
22227             this.fireEvent('select', this, d);
22228         },
22229         show : function(){ // retain focus styling
22230             this.onFocus();
22231         },
22232         hide : function(){
22233             this.focus.defer(10, this);
22234             var ml = this.menuListeners;
22235             this.menu.un("select", ml.select,  this);
22236             this.menu.un("show", ml.show,  this);
22237             this.menu.un("hide", ml.hide,  this);
22238         }
22239     },
22240
22241     // private
22242     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
22243     onTriggerClick : function(){
22244         if(this.disabled){
22245             return;
22246         }
22247         if(this.menu == null){
22248             this.menu = new Roo.menu.DateMenu();
22249         }
22250         Roo.apply(this.menu.picker,  {
22251             showClear: this.allowBlank,
22252             minDate : this.minValue,
22253             maxDate : this.maxValue,
22254             disabledDatesRE : this.ddMatch,
22255             disabledDatesText : this.disabledDatesText,
22256             disabledDays : this.disabledDays,
22257             disabledDaysText : this.disabledDaysText,
22258             format : this.useIso ? 'Y-m-d' : this.format,
22259             minText : String.format(this.minText, this.formatDate(this.minValue)),
22260             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
22261         });
22262         this.menu.on(Roo.apply({}, this.menuListeners, {
22263             scope:this
22264         }));
22265         this.menu.picker.setValue(this.getValue() || new Date());
22266         this.menu.show(this.el, "tl-bl?");
22267     },
22268
22269     beforeBlur : function(){
22270         var v = this.parseDate(this.getRawValue());
22271         if(v){
22272             this.setValue(v);
22273         }
22274     }
22275
22276     /** @cfg {Boolean} grow @hide */
22277     /** @cfg {Number} growMin @hide */
22278     /** @cfg {Number} growMax @hide */
22279     /**
22280      * @hide
22281      * @method autoSize
22282      */
22283 });/*
22284  * Based on:
22285  * Ext JS Library 1.1.1
22286  * Copyright(c) 2006-2007, Ext JS, LLC.
22287  *
22288  * Originally Released Under LGPL - original licence link has changed is not relivant.
22289  *
22290  * Fork - LGPL
22291  * <script type="text/javascript">
22292  */
22293  
22294 /**
22295  * @class Roo.form.MonthField
22296  * @extends Roo.form.TriggerField
22297  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
22298 * @constructor
22299 * Create a new MonthField
22300 * @param {Object} config
22301  */
22302 Roo.form.MonthField = function(config){
22303     
22304     Roo.form.MonthField.superclass.constructor.call(this, config);
22305     
22306       this.addEvents({
22307          
22308         /**
22309          * @event select
22310          * Fires when a date is selected
22311              * @param {Roo.form.MonthFieeld} combo This combo box
22312              * @param {Date} date The date selected
22313              */
22314         'select' : true
22315          
22316     });
22317     
22318     
22319     if(typeof this.minValue == "string") this.minValue = this.parseDate(this.minValue);
22320     if(typeof this.maxValue == "string") this.maxValue = this.parseDate(this.maxValue);
22321     this.ddMatch = null;
22322     if(this.disabledDates){
22323         var dd = this.disabledDates;
22324         var re = "(?:";
22325         for(var i = 0; i < dd.length; i++){
22326             re += dd[i];
22327             if(i != dd.length-1) re += "|";
22328         }
22329         this.ddMatch = new RegExp(re + ")");
22330     }
22331 };
22332
22333 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
22334     /**
22335      * @cfg {String} format
22336      * The default date format string which can be overriden for localization support.  The format must be
22337      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
22338      */
22339     format : "M Y",
22340     /**
22341      * @cfg {String} altFormats
22342      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
22343      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
22344      */
22345     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
22346     /**
22347      * @cfg {Array} disabledDays
22348      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
22349      */
22350     disabledDays : [0,1,2,3,4,5,6],
22351     /**
22352      * @cfg {String} disabledDaysText
22353      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
22354      */
22355     disabledDaysText : "Disabled",
22356     /**
22357      * @cfg {Array} disabledDates
22358      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
22359      * expression so they are very powerful. Some examples:
22360      * <ul>
22361      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
22362      * <li>["03/08", "09/16"] would disable those days for every year</li>
22363      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
22364      * <li>["03/../2006"] would disable every day in March 2006</li>
22365      * <li>["^03"] would disable every day in every March</li>
22366      * </ul>
22367      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
22368      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
22369      */
22370     disabledDates : null,
22371     /**
22372      * @cfg {String} disabledDatesText
22373      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
22374      */
22375     disabledDatesText : "Disabled",
22376     /**
22377      * @cfg {Date/String} minValue
22378      * The minimum allowed date. Can be either a Javascript date object or a string date in a
22379      * valid format (defaults to null).
22380      */
22381     minValue : null,
22382     /**
22383      * @cfg {Date/String} maxValue
22384      * The maximum allowed date. Can be either a Javascript date object or a string date in a
22385      * valid format (defaults to null).
22386      */
22387     maxValue : null,
22388     /**
22389      * @cfg {String} minText
22390      * The error text to display when the date in the cell is before minValue (defaults to
22391      * 'The date in this field must be after {minValue}').
22392      */
22393     minText : "The date in this field must be equal to or after {0}",
22394     /**
22395      * @cfg {String} maxTextf
22396      * The error text to display when the date in the cell is after maxValue (defaults to
22397      * 'The date in this field must be before {maxValue}').
22398      */
22399     maxText : "The date in this field must be equal to or before {0}",
22400     /**
22401      * @cfg {String} invalidText
22402      * The error text to display when the date in the field is invalid (defaults to
22403      * '{value} is not a valid date - it must be in the format {format}').
22404      */
22405     invalidText : "{0} is not a valid date - it must be in the format {1}",
22406     /**
22407      * @cfg {String} triggerClass
22408      * An additional CSS class used to style the trigger button.  The trigger will always get the
22409      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
22410      * which displays a calendar icon).
22411      */
22412     triggerClass : 'x-form-date-trigger',
22413     
22414
22415     /**
22416      * @cfg {Boolean} useIso
22417      * if enabled, then the date field will use a hidden field to store the 
22418      * real value as iso formated date. default (true)
22419      */ 
22420     useIso : true,
22421     /**
22422      * @cfg {String/Object} autoCreate
22423      * A DomHelper element spec, or true for a default element spec (defaults to
22424      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
22425      */ 
22426     // private
22427     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
22428     
22429     // private
22430     hiddenField: false,
22431     
22432     hideMonthPicker : false,
22433     
22434     onRender : function(ct, position)
22435     {
22436         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
22437         if (this.useIso) {
22438             this.el.dom.removeAttribute('name'); 
22439             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
22440                     'before', true);
22441             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
22442             // prevent input submission
22443             this.hiddenName = this.name;
22444         }
22445             
22446             
22447     },
22448     
22449     // private
22450     validateValue : function(value)
22451     {
22452         value = this.formatDate(value);
22453         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
22454             return false;
22455         }
22456         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
22457              return true;
22458         }
22459         var svalue = value;
22460         value = this.parseDate(value);
22461         if(!value){
22462             this.markInvalid(String.format(this.invalidText, svalue, this.format));
22463             return false;
22464         }
22465         var time = value.getTime();
22466         if(this.minValue && time < this.minValue.getTime()){
22467             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
22468             return false;
22469         }
22470         if(this.maxValue && time > this.maxValue.getTime()){
22471             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
22472             return false;
22473         }
22474         /*if(this.disabledDays){
22475             var day = value.getDay();
22476             for(var i = 0; i < this.disabledDays.length; i++) {
22477                 if(day === this.disabledDays[i]){
22478                     this.markInvalid(this.disabledDaysText);
22479                     return false;
22480                 }
22481             }
22482         }
22483         */
22484         var fvalue = this.formatDate(value);
22485         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
22486             this.markInvalid(String.format(this.disabledDatesText, fvalue));
22487             return false;
22488         }
22489         */
22490         return true;
22491     },
22492
22493     // private
22494     // Provides logic to override the default TriggerField.validateBlur which just returns true
22495     validateBlur : function(){
22496         return !this.menu || !this.menu.isVisible();
22497     },
22498
22499     /**
22500      * Returns the current date value of the date field.
22501      * @return {Date} The date value
22502      */
22503     getValue : function(){
22504         
22505         
22506         
22507         return  this.hiddenField ?
22508                 this.hiddenField.value :
22509                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
22510     },
22511
22512     /**
22513      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
22514      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
22515      * (the default format used is "m/d/y").
22516      * <br />Usage:
22517      * <pre><code>
22518 //All of these calls set the same date value (May 4, 2006)
22519
22520 //Pass a date object:
22521 var dt = new Date('5/4/06');
22522 monthField.setValue(dt);
22523
22524 //Pass a date string (default format):
22525 monthField.setValue('5/4/06');
22526
22527 //Pass a date string (custom format):
22528 monthField.format = 'Y-m-d';
22529 monthField.setValue('2006-5-4');
22530 </code></pre>
22531      * @param {String/Date} date The date or valid date string
22532      */
22533     setValue : function(date){
22534         Roo.log('month setValue' + date);
22535         // can only be first of month..
22536         
22537         var val = this.parseDate(date);
22538         
22539         if (this.hiddenField) {
22540             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
22541         }
22542         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
22543         this.value = this.parseDate(date);
22544     },
22545
22546     // private
22547     parseDate : function(value){
22548         if(!value || value instanceof Date){
22549             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
22550             return value;
22551         }
22552         var v = Date.parseDate(value, this.format);
22553         if (!v && this.useIso) {
22554             v = Date.parseDate(value, 'Y-m-d');
22555         }
22556         if (v) {
22557             // 
22558             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
22559         }
22560         
22561         
22562         if(!v && this.altFormats){
22563             if(!this.altFormatsArray){
22564                 this.altFormatsArray = this.altFormats.split("|");
22565             }
22566             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
22567                 v = Date.parseDate(value, this.altFormatsArray[i]);
22568             }
22569         }
22570         return v;
22571     },
22572
22573     // private
22574     formatDate : function(date, fmt){
22575         return (!date || !(date instanceof Date)) ?
22576                date : date.dateFormat(fmt || this.format);
22577     },
22578
22579     // private
22580     menuListeners : {
22581         select: function(m, d){
22582             this.setValue(d);
22583             this.fireEvent('select', this, d);
22584         },
22585         show : function(){ // retain focus styling
22586             this.onFocus();
22587         },
22588         hide : function(){
22589             this.focus.defer(10, this);
22590             var ml = this.menuListeners;
22591             this.menu.un("select", ml.select,  this);
22592             this.menu.un("show", ml.show,  this);
22593             this.menu.un("hide", ml.hide,  this);
22594         }
22595     },
22596     // private
22597     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
22598     onTriggerClick : function(){
22599         if(this.disabled){
22600             return;
22601         }
22602         if(this.menu == null){
22603             this.menu = new Roo.menu.DateMenu();
22604            
22605         }
22606         
22607         Roo.apply(this.menu.picker,  {
22608             
22609             showClear: this.allowBlank,
22610             minDate : this.minValue,
22611             maxDate : this.maxValue,
22612             disabledDatesRE : this.ddMatch,
22613             disabledDatesText : this.disabledDatesText,
22614             
22615             format : this.useIso ? 'Y-m-d' : this.format,
22616             minText : String.format(this.minText, this.formatDate(this.minValue)),
22617             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
22618             
22619         });
22620          this.menu.on(Roo.apply({}, this.menuListeners, {
22621             scope:this
22622         }));
22623        
22624         
22625         var m = this.menu;
22626         var p = m.picker;
22627         
22628         // hide month picker get's called when we called by 'before hide';
22629         
22630         var ignorehide = true;
22631         p.hideMonthPicker  = function(disableAnim){
22632             if (ignorehide) {
22633                 return;
22634             }
22635              if(this.monthPicker){
22636                 Roo.log("hideMonthPicker called");
22637                 if(disableAnim === true){
22638                     this.monthPicker.hide();
22639                 }else{
22640                     this.monthPicker.slideOut('t', {duration:.2});
22641                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
22642                     p.fireEvent("select", this, this.value);
22643                     m.hide();
22644                 }
22645             }
22646         }
22647         
22648         Roo.log('picker set value');
22649         Roo.log(this.getValue());
22650         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
22651         m.show(this.el, 'tl-bl?');
22652         ignorehide  = false;
22653         // this will trigger hideMonthPicker..
22654         
22655         
22656         // hidden the day picker
22657         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
22658         
22659         
22660         
22661       
22662         
22663         p.showMonthPicker.defer(100, p);
22664     
22665         
22666        
22667     },
22668
22669     beforeBlur : function(){
22670         var v = this.parseDate(this.getRawValue());
22671         if(v){
22672             this.setValue(v);
22673         }
22674     }
22675
22676     /** @cfg {Boolean} grow @hide */
22677     /** @cfg {Number} growMin @hide */
22678     /** @cfg {Number} growMax @hide */
22679     /**
22680      * @hide
22681      * @method autoSize
22682      */
22683 });/*
22684  * Based on:
22685  * Ext JS Library 1.1.1
22686  * Copyright(c) 2006-2007, Ext JS, LLC.
22687  *
22688  * Originally Released Under LGPL - original licence link has changed is not relivant.
22689  *
22690  * Fork - LGPL
22691  * <script type="text/javascript">
22692  */
22693  
22694
22695 /**
22696  * @class Roo.form.ComboBox
22697  * @extends Roo.form.TriggerField
22698  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
22699  * @constructor
22700  * Create a new ComboBox.
22701  * @param {Object} config Configuration options
22702  */
22703 Roo.form.ComboBox = function(config){
22704     Roo.form.ComboBox.superclass.constructor.call(this, config);
22705     this.addEvents({
22706         /**
22707          * @event expand
22708          * Fires when the dropdown list is expanded
22709              * @param {Roo.form.ComboBox} combo This combo box
22710              */
22711         'expand' : true,
22712         /**
22713          * @event collapse
22714          * Fires when the dropdown list is collapsed
22715              * @param {Roo.form.ComboBox} combo This combo box
22716              */
22717         'collapse' : true,
22718         /**
22719          * @event beforeselect
22720          * Fires before a list item is selected. Return false to cancel the selection.
22721              * @param {Roo.form.ComboBox} combo This combo box
22722              * @param {Roo.data.Record} record The data record returned from the underlying store
22723              * @param {Number} index The index of the selected item in the dropdown list
22724              */
22725         'beforeselect' : true,
22726         /**
22727          * @event select
22728          * Fires when a list item is selected
22729              * @param {Roo.form.ComboBox} combo This combo box
22730              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
22731              * @param {Number} index The index of the selected item in the dropdown list
22732              */
22733         'select' : true,
22734         /**
22735          * @event beforequery
22736          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
22737          * The event object passed has these properties:
22738              * @param {Roo.form.ComboBox} combo This combo box
22739              * @param {String} query The query
22740              * @param {Boolean} forceAll true to force "all" query
22741              * @param {Boolean} cancel true to cancel the query
22742              * @param {Object} e The query event object
22743              */
22744         'beforequery': true,
22745          /**
22746          * @event add
22747          * Fires when the 'add' icon is pressed (add a listener to enable add button)
22748              * @param {Roo.form.ComboBox} combo This combo box
22749              */
22750         'add' : true,
22751         /**
22752          * @event edit
22753          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
22754              * @param {Roo.form.ComboBox} combo This combo box
22755              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
22756              */
22757         'edit' : true
22758         
22759         
22760     });
22761     if(this.transform){
22762         this.allowDomMove = false;
22763         var s = Roo.getDom(this.transform);
22764         if(!this.hiddenName){
22765             this.hiddenName = s.name;
22766         }
22767         if(!this.store){
22768             this.mode = 'local';
22769             var d = [], opts = s.options;
22770             for(var i = 0, len = opts.length;i < len; i++){
22771                 var o = opts[i];
22772                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
22773                 if(o.selected) {
22774                     this.value = value;
22775                 }
22776                 d.push([value, o.text]);
22777             }
22778             this.store = new Roo.data.SimpleStore({
22779                 'id': 0,
22780                 fields: ['value', 'text'],
22781                 data : d
22782             });
22783             this.valueField = 'value';
22784             this.displayField = 'text';
22785         }
22786         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
22787         if(!this.lazyRender){
22788             this.target = true;
22789             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
22790             s.parentNode.removeChild(s); // remove it
22791             this.render(this.el.parentNode);
22792         }else{
22793             s.parentNode.removeChild(s); // remove it
22794         }
22795
22796     }
22797     if (this.store) {
22798         this.store = Roo.factory(this.store, Roo.data);
22799     }
22800     
22801     this.selectedIndex = -1;
22802     if(this.mode == 'local'){
22803         if(config.queryDelay === undefined){
22804             this.queryDelay = 10;
22805         }
22806         if(config.minChars === undefined){
22807             this.minChars = 0;
22808         }
22809     }
22810 };
22811
22812 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
22813     /**
22814      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
22815      */
22816     /**
22817      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
22818      * rendering into an Roo.Editor, defaults to false)
22819      */
22820     /**
22821      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
22822      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
22823      */
22824     /**
22825      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
22826      */
22827     /**
22828      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
22829      * the dropdown list (defaults to undefined, with no header element)
22830      */
22831
22832      /**
22833      * @cfg {String/Roo.Template} tpl The template to use to render the output
22834      */
22835      
22836     // private
22837     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
22838     /**
22839      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
22840      */
22841     listWidth: undefined,
22842     /**
22843      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
22844      * mode = 'remote' or 'text' if mode = 'local')
22845      */
22846     displayField: undefined,
22847     /**
22848      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
22849      * mode = 'remote' or 'value' if mode = 'local'). 
22850      * Note: use of a valueField requires the user make a selection
22851      * in order for a value to be mapped.
22852      */
22853     valueField: undefined,
22854     
22855     
22856     /**
22857      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
22858      * field's data value (defaults to the underlying DOM element's name)
22859      */
22860     hiddenName: undefined,
22861     /**
22862      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
22863      */
22864     listClass: '',
22865     /**
22866      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
22867      */
22868     selectedClass: 'x-combo-selected',
22869     /**
22870      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
22871      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
22872      * which displays a downward arrow icon).
22873      */
22874     triggerClass : 'x-form-arrow-trigger',
22875     /**
22876      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
22877      */
22878     shadow:'sides',
22879     /**
22880      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
22881      * anchor positions (defaults to 'tl-bl')
22882      */
22883     listAlign: 'tl-bl?',
22884     /**
22885      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
22886      */
22887     maxHeight: 300,
22888     /**
22889      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
22890      * query specified by the allQuery config option (defaults to 'query')
22891      */
22892     triggerAction: 'query',
22893     /**
22894      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
22895      * (defaults to 4, does not apply if editable = false)
22896      */
22897     minChars : 4,
22898     /**
22899      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
22900      * delay (typeAheadDelay) if it matches a known value (defaults to false)
22901      */
22902     typeAhead: false,
22903     /**
22904      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
22905      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
22906      */
22907     queryDelay: 500,
22908     /**
22909      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
22910      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
22911      */
22912     pageSize: 0,
22913     /**
22914      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
22915      * when editable = true (defaults to false)
22916      */
22917     selectOnFocus:false,
22918     /**
22919      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
22920      */
22921     queryParam: 'query',
22922     /**
22923      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
22924      * when mode = 'remote' (defaults to 'Loading...')
22925      */
22926     loadingText: 'Loading...',
22927     /**
22928      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
22929      */
22930     resizable: false,
22931     /**
22932      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
22933      */
22934     handleHeight : 8,
22935     /**
22936      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
22937      * traditional select (defaults to true)
22938      */
22939     editable: true,
22940     /**
22941      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
22942      */
22943     allQuery: '',
22944     /**
22945      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
22946      */
22947     mode: 'remote',
22948     /**
22949      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
22950      * listWidth has a higher value)
22951      */
22952     minListWidth : 70,
22953     /**
22954      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
22955      * allow the user to set arbitrary text into the field (defaults to false)
22956      */
22957     forceSelection:false,
22958     /**
22959      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
22960      * if typeAhead = true (defaults to 250)
22961      */
22962     typeAheadDelay : 250,
22963     /**
22964      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
22965      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
22966      */
22967     valueNotFoundText : undefined,
22968     /**
22969      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
22970      */
22971     blockFocus : false,
22972     
22973     /**
22974      * @cfg {Boolean} disableClear Disable showing of clear button.
22975      */
22976     disableClear : false,
22977     /**
22978      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
22979      */
22980     alwaysQuery : false,
22981     
22982     //private
22983     addicon : false,
22984     editicon: false,
22985     
22986     // element that contains real text value.. (when hidden is used..)
22987      
22988     // private
22989     onRender : function(ct, position){
22990         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
22991         if(this.hiddenName){
22992             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
22993                     'before', true);
22994             this.hiddenField.value =
22995                 this.hiddenValue !== undefined ? this.hiddenValue :
22996                 this.value !== undefined ? this.value : '';
22997
22998             // prevent input submission
22999             this.el.dom.removeAttribute('name');
23000              
23001              
23002         }
23003         if(Roo.isGecko){
23004             this.el.dom.setAttribute('autocomplete', 'off');
23005         }
23006
23007         var cls = 'x-combo-list';
23008
23009         this.list = new Roo.Layer({
23010             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
23011         });
23012
23013         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
23014         this.list.setWidth(lw);
23015         this.list.swallowEvent('mousewheel');
23016         this.assetHeight = 0;
23017
23018         if(this.title){
23019             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
23020             this.assetHeight += this.header.getHeight();
23021         }
23022
23023         this.innerList = this.list.createChild({cls:cls+'-inner'});
23024         this.innerList.on('mouseover', this.onViewOver, this);
23025         this.innerList.on('mousemove', this.onViewMove, this);
23026         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
23027         
23028         if(this.allowBlank && !this.pageSize && !this.disableClear){
23029             this.footer = this.list.createChild({cls:cls+'-ft'});
23030             this.pageTb = new Roo.Toolbar(this.footer);
23031            
23032         }
23033         if(this.pageSize){
23034             this.footer = this.list.createChild({cls:cls+'-ft'});
23035             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
23036                     {pageSize: this.pageSize});
23037             
23038         }
23039         
23040         if (this.pageTb && this.allowBlank && !this.disableClear) {
23041             var _this = this;
23042             this.pageTb.add(new Roo.Toolbar.Fill(), {
23043                 cls: 'x-btn-icon x-btn-clear',
23044                 text: '&#160;',
23045                 handler: function()
23046                 {
23047                     _this.collapse();
23048                     _this.clearValue();
23049                     _this.onSelect(false, -1);
23050                 }
23051             });
23052         }
23053         if (this.footer) {
23054             this.assetHeight += this.footer.getHeight();
23055         }
23056         
23057
23058         if(!this.tpl){
23059             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
23060         }
23061
23062         this.view = new Roo.View(this.innerList, this.tpl, {
23063             singleSelect:true, store: this.store, selectedClass: this.selectedClass
23064         });
23065
23066         this.view.on('click', this.onViewClick, this);
23067
23068         this.store.on('beforeload', this.onBeforeLoad, this);
23069         this.store.on('load', this.onLoad, this);
23070         this.store.on('loadexception', this.onLoadException, this);
23071
23072         if(this.resizable){
23073             this.resizer = new Roo.Resizable(this.list,  {
23074                pinned:true, handles:'se'
23075             });
23076             this.resizer.on('resize', function(r, w, h){
23077                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
23078                 this.listWidth = w;
23079                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
23080                 this.restrictHeight();
23081             }, this);
23082             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
23083         }
23084         if(!this.editable){
23085             this.editable = true;
23086             this.setEditable(false);
23087         }  
23088         
23089         
23090         if (typeof(this.events.add.listeners) != 'undefined') {
23091             
23092             this.addicon = this.wrap.createChild(
23093                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
23094        
23095             this.addicon.on('click', function(e) {
23096                 this.fireEvent('add', this);
23097             }, this);
23098         }
23099         if (typeof(this.events.edit.listeners) != 'undefined') {
23100             
23101             this.editicon = this.wrap.createChild(
23102                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
23103             if (this.addicon) {
23104                 this.editicon.setStyle('margin-left', '40px');
23105             }
23106             this.editicon.on('click', function(e) {
23107                 
23108                 // we fire even  if inothing is selected..
23109                 this.fireEvent('edit', this, this.lastData );
23110                 
23111             }, this);
23112         }
23113         
23114         
23115         
23116     },
23117
23118     // private
23119     initEvents : function(){
23120         Roo.form.ComboBox.superclass.initEvents.call(this);
23121
23122         this.keyNav = new Roo.KeyNav(this.el, {
23123             "up" : function(e){
23124                 this.inKeyMode = true;
23125                 this.selectPrev();
23126             },
23127
23128             "down" : function(e){
23129                 if(!this.isExpanded()){
23130                     this.onTriggerClick();
23131                 }else{
23132                     this.inKeyMode = true;
23133                     this.selectNext();
23134                 }
23135             },
23136
23137             "enter" : function(e){
23138                 this.onViewClick();
23139                 //return true;
23140             },
23141
23142             "esc" : function(e){
23143                 this.collapse();
23144             },
23145
23146             "tab" : function(e){
23147                 this.onViewClick(false);
23148                 this.fireEvent("specialkey", this, e);
23149                 return true;
23150             },
23151
23152             scope : this,
23153
23154             doRelay : function(foo, bar, hname){
23155                 if(hname == 'down' || this.scope.isExpanded()){
23156                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
23157                 }
23158                 return true;
23159             },
23160
23161             forceKeyDown: true
23162         });
23163         this.queryDelay = Math.max(this.queryDelay || 10,
23164                 this.mode == 'local' ? 10 : 250);
23165         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
23166         if(this.typeAhead){
23167             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
23168         }
23169         if(this.editable !== false){
23170             this.el.on("keyup", this.onKeyUp, this);
23171         }
23172         if(this.forceSelection){
23173             this.on('blur', this.doForce, this);
23174         }
23175     },
23176
23177     onDestroy : function(){
23178         if(this.view){
23179             this.view.setStore(null);
23180             this.view.el.removeAllListeners();
23181             this.view.el.remove();
23182             this.view.purgeListeners();
23183         }
23184         if(this.list){
23185             this.list.destroy();
23186         }
23187         if(this.store){
23188             this.store.un('beforeload', this.onBeforeLoad, this);
23189             this.store.un('load', this.onLoad, this);
23190             this.store.un('loadexception', this.onLoadException, this);
23191         }
23192         Roo.form.ComboBox.superclass.onDestroy.call(this);
23193     },
23194
23195     // private
23196     fireKey : function(e){
23197         if(e.isNavKeyPress() && !this.list.isVisible()){
23198             this.fireEvent("specialkey", this, e);
23199         }
23200     },
23201
23202     // private
23203     onResize: function(w, h){
23204         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
23205         
23206         if(typeof w != 'number'){
23207             // we do not handle it!?!?
23208             return;
23209         }
23210         var tw = this.trigger.getWidth();
23211         tw += this.addicon ? this.addicon.getWidth() : 0;
23212         tw += this.editicon ? this.editicon.getWidth() : 0;
23213         var x = w - tw;
23214         this.el.setWidth( this.adjustWidth('input', x));
23215             
23216         this.trigger.setStyle('left', x+'px');
23217         
23218         if(this.list && this.listWidth === undefined){
23219             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
23220             this.list.setWidth(lw);
23221             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
23222         }
23223         
23224     
23225         
23226     },
23227
23228     /**
23229      * Allow or prevent the user from directly editing the field text.  If false is passed,
23230      * the user will only be able to select from the items defined in the dropdown list.  This method
23231      * is the runtime equivalent of setting the 'editable' config option at config time.
23232      * @param {Boolean} value True to allow the user to directly edit the field text
23233      */
23234     setEditable : function(value){
23235         if(value == this.editable){
23236             return;
23237         }
23238         this.editable = value;
23239         if(!value){
23240             this.el.dom.setAttribute('readOnly', true);
23241             this.el.on('mousedown', this.onTriggerClick,  this);
23242             this.el.addClass('x-combo-noedit');
23243         }else{
23244             this.el.dom.setAttribute('readOnly', false);
23245             this.el.un('mousedown', this.onTriggerClick,  this);
23246             this.el.removeClass('x-combo-noedit');
23247         }
23248     },
23249
23250     // private
23251     onBeforeLoad : function(){
23252         if(!this.hasFocus){
23253             return;
23254         }
23255         this.innerList.update(this.loadingText ?
23256                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
23257         this.restrictHeight();
23258         this.selectedIndex = -1;
23259     },
23260
23261     // private
23262     onLoad : function(){
23263         if(!this.hasFocus){
23264             return;
23265         }
23266         if(this.store.getCount() > 0){
23267             this.expand();
23268             this.restrictHeight();
23269             if(this.lastQuery == this.allQuery){
23270                 if(this.editable){
23271                     this.el.dom.select();
23272                 }
23273                 if(!this.selectByValue(this.value, true)){
23274                     this.select(0, true);
23275                 }
23276             }else{
23277                 this.selectNext();
23278                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
23279                     this.taTask.delay(this.typeAheadDelay);
23280                 }
23281             }
23282         }else{
23283             this.onEmptyResults();
23284         }
23285         //this.el.focus();
23286     },
23287     // private
23288     onLoadException : function()
23289     {
23290         this.collapse();
23291         Roo.log(this.store.reader.jsonData);
23292         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
23293             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
23294         }
23295         
23296         
23297     },
23298     // private
23299     onTypeAhead : function(){
23300         if(this.store.getCount() > 0){
23301             var r = this.store.getAt(0);
23302             var newValue = r.data[this.displayField];
23303             var len = newValue.length;
23304             var selStart = this.getRawValue().length;
23305             if(selStart != len){
23306                 this.setRawValue(newValue);
23307                 this.selectText(selStart, newValue.length);
23308             }
23309         }
23310     },
23311
23312     // private
23313     onSelect : function(record, index){
23314         if(this.fireEvent('beforeselect', this, record, index) !== false){
23315             this.setFromData(index > -1 ? record.data : false);
23316             this.collapse();
23317             this.fireEvent('select', this, record, index);
23318         }
23319     },
23320
23321     /**
23322      * Returns the currently selected field value or empty string if no value is set.
23323      * @return {String} value The selected value
23324      */
23325     getValue : function(){
23326         if(this.valueField){
23327             return typeof this.value != 'undefined' ? this.value : '';
23328         }else{
23329             return Roo.form.ComboBox.superclass.getValue.call(this);
23330         }
23331     },
23332
23333     /**
23334      * Clears any text/value currently set in the field
23335      */
23336     clearValue : function(){
23337         if(this.hiddenField){
23338             this.hiddenField.value = '';
23339         }
23340         this.value = '';
23341         this.setRawValue('');
23342         this.lastSelectionText = '';
23343         
23344     },
23345
23346     /**
23347      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
23348      * will be displayed in the field.  If the value does not match the data value of an existing item,
23349      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
23350      * Otherwise the field will be blank (although the value will still be set).
23351      * @param {String} value The value to match
23352      */
23353     setValue : function(v){
23354         var text = v;
23355         if(this.valueField){
23356             var r = this.findRecord(this.valueField, v);
23357             if(r){
23358                 text = r.data[this.displayField];
23359             }else if(this.valueNotFoundText !== undefined){
23360                 text = this.valueNotFoundText;
23361             }
23362         }
23363         this.lastSelectionText = text;
23364         if(this.hiddenField){
23365             this.hiddenField.value = v;
23366         }
23367         Roo.form.ComboBox.superclass.setValue.call(this, text);
23368         this.value = v;
23369     },
23370     /**
23371      * @property {Object} the last set data for the element
23372      */
23373     
23374     lastData : false,
23375     /**
23376      * Sets the value of the field based on a object which is related to the record format for the store.
23377      * @param {Object} value the value to set as. or false on reset?
23378      */
23379     setFromData : function(o){
23380         var dv = ''; // display value
23381         var vv = ''; // value value..
23382         this.lastData = o;
23383         if (this.displayField) {
23384             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
23385         } else {
23386             // this is an error condition!!!
23387             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
23388         }
23389         
23390         if(this.valueField){
23391             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
23392         }
23393         if(this.hiddenField){
23394             this.hiddenField.value = vv;
23395             
23396             this.lastSelectionText = dv;
23397             Roo.form.ComboBox.superclass.setValue.call(this, dv);
23398             this.value = vv;
23399             return;
23400         }
23401         // no hidden field.. - we store the value in 'value', but still display
23402         // display field!!!!
23403         this.lastSelectionText = dv;
23404         Roo.form.ComboBox.superclass.setValue.call(this, dv);
23405         this.value = vv;
23406         
23407         
23408     },
23409     // private
23410     reset : function(){
23411         // overridden so that last data is reset..
23412         this.setValue(this.originalValue);
23413         this.clearInvalid();
23414         this.lastData = false;
23415         if (this.view) {
23416             this.view.clearSelections();
23417         }
23418     },
23419     // private
23420     findRecord : function(prop, value){
23421         var record;
23422         if(this.store.getCount() > 0){
23423             this.store.each(function(r){
23424                 if(r.data[prop] == value){
23425                     record = r;
23426                     return false;
23427                 }
23428                 return true;
23429             });
23430         }
23431         return record;
23432     },
23433     
23434     getName: function()
23435     {
23436         // returns hidden if it's set..
23437         if (!this.rendered) {return ''};
23438         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
23439         
23440     },
23441     // private
23442     onViewMove : function(e, t){
23443         this.inKeyMode = false;
23444     },
23445
23446     // private
23447     onViewOver : function(e, t){
23448         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
23449             return;
23450         }
23451         var item = this.view.findItemFromChild(t);
23452         if(item){
23453             var index = this.view.indexOf(item);
23454             this.select(index, false);
23455         }
23456     },
23457
23458     // private
23459     onViewClick : function(doFocus)
23460     {
23461         var index = this.view.getSelectedIndexes()[0];
23462         var r = this.store.getAt(index);
23463         if(r){
23464             this.onSelect(r, index);
23465         }
23466         if(doFocus !== false && !this.blockFocus){
23467             this.el.focus();
23468         }
23469     },
23470
23471     // private
23472     restrictHeight : function(){
23473         this.innerList.dom.style.height = '';
23474         var inner = this.innerList.dom;
23475         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
23476         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
23477         this.list.beginUpdate();
23478         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
23479         this.list.alignTo(this.el, this.listAlign);
23480         this.list.endUpdate();
23481     },
23482
23483     // private
23484     onEmptyResults : function(){
23485         this.collapse();
23486     },
23487
23488     /**
23489      * Returns true if the dropdown list is expanded, else false.
23490      */
23491     isExpanded : function(){
23492         return this.list.isVisible();
23493     },
23494
23495     /**
23496      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
23497      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
23498      * @param {String} value The data value of the item to select
23499      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
23500      * selected item if it is not currently in view (defaults to true)
23501      * @return {Boolean} True if the value matched an item in the list, else false
23502      */
23503     selectByValue : function(v, scrollIntoView){
23504         if(v !== undefined && v !== null){
23505             var r = this.findRecord(this.valueField || this.displayField, v);
23506             if(r){
23507                 this.select(this.store.indexOf(r), scrollIntoView);
23508                 return true;
23509             }
23510         }
23511         return false;
23512     },
23513
23514     /**
23515      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
23516      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
23517      * @param {Number} index The zero-based index of the list item to select
23518      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
23519      * selected item if it is not currently in view (defaults to true)
23520      */
23521     select : function(index, scrollIntoView){
23522         this.selectedIndex = index;
23523         this.view.select(index);
23524         if(scrollIntoView !== false){
23525             var el = this.view.getNode(index);
23526             if(el){
23527                 this.innerList.scrollChildIntoView(el, false);
23528             }
23529         }
23530     },
23531
23532     // private
23533     selectNext : function(){
23534         var ct = this.store.getCount();
23535         if(ct > 0){
23536             if(this.selectedIndex == -1){
23537                 this.select(0);
23538             }else if(this.selectedIndex < ct-1){
23539                 this.select(this.selectedIndex+1);
23540             }
23541         }
23542     },
23543
23544     // private
23545     selectPrev : function(){
23546         var ct = this.store.getCount();
23547         if(ct > 0){
23548             if(this.selectedIndex == -1){
23549                 this.select(0);
23550             }else if(this.selectedIndex != 0){
23551                 this.select(this.selectedIndex-1);
23552             }
23553         }
23554     },
23555
23556     // private
23557     onKeyUp : function(e){
23558         if(this.editable !== false && !e.isSpecialKey()){
23559             this.lastKey = e.getKey();
23560             this.dqTask.delay(this.queryDelay);
23561         }
23562     },
23563
23564     // private
23565     validateBlur : function(){
23566         return !this.list || !this.list.isVisible();   
23567     },
23568
23569     // private
23570     initQuery : function(){
23571         this.doQuery(this.getRawValue());
23572     },
23573
23574     // private
23575     doForce : function(){
23576         if(this.el.dom.value.length > 0){
23577             this.el.dom.value =
23578                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
23579              
23580         }
23581     },
23582
23583     /**
23584      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
23585      * query allowing the query action to be canceled if needed.
23586      * @param {String} query The SQL query to execute
23587      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
23588      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
23589      * saved in the current store (defaults to false)
23590      */
23591     doQuery : function(q, forceAll){
23592         if(q === undefined || q === null){
23593             q = '';
23594         }
23595         var qe = {
23596             query: q,
23597             forceAll: forceAll,
23598             combo: this,
23599             cancel:false
23600         };
23601         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
23602             return false;
23603         }
23604         q = qe.query;
23605         forceAll = qe.forceAll;
23606         if(forceAll === true || (q.length >= this.minChars)){
23607             if(this.lastQuery != q || this.alwaysQuery){
23608                 this.lastQuery = q;
23609                 if(this.mode == 'local'){
23610                     this.selectedIndex = -1;
23611                     if(forceAll){
23612                         this.store.clearFilter();
23613                     }else{
23614                         this.store.filter(this.displayField, q);
23615                     }
23616                     this.onLoad();
23617                 }else{
23618                     this.store.baseParams[this.queryParam] = q;
23619                     this.store.load({
23620                         params: this.getParams(q)
23621                     });
23622                     this.expand();
23623                 }
23624             }else{
23625                 this.selectedIndex = -1;
23626                 this.onLoad();   
23627             }
23628         }
23629     },
23630
23631     // private
23632     getParams : function(q){
23633         var p = {};
23634         //p[this.queryParam] = q;
23635         if(this.pageSize){
23636             p.start = 0;
23637             p.limit = this.pageSize;
23638         }
23639         return p;
23640     },
23641
23642     /**
23643      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
23644      */
23645     collapse : function(){
23646         if(!this.isExpanded()){
23647             return;
23648         }
23649         this.list.hide();
23650         Roo.get(document).un('mousedown', this.collapseIf, this);
23651         Roo.get(document).un('mousewheel', this.collapseIf, this);
23652         if (!this.editable) {
23653             Roo.get(document).un('keydown', this.listKeyPress, this);
23654         }
23655         this.fireEvent('collapse', this);
23656     },
23657
23658     // private
23659     collapseIf : function(e){
23660         if(!e.within(this.wrap) && !e.within(this.list)){
23661             this.collapse();
23662         }
23663     },
23664
23665     /**
23666      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
23667      */
23668     expand : function(){
23669         if(this.isExpanded() || !this.hasFocus){
23670             return;
23671         }
23672         this.list.alignTo(this.el, this.listAlign);
23673         this.list.show();
23674         Roo.get(document).on('mousedown', this.collapseIf, this);
23675         Roo.get(document).on('mousewheel', this.collapseIf, this);
23676         if (!this.editable) {
23677             Roo.get(document).on('keydown', this.listKeyPress, this);
23678         }
23679         
23680         this.fireEvent('expand', this);
23681     },
23682
23683     // private
23684     // Implements the default empty TriggerField.onTriggerClick function
23685     onTriggerClick : function(){
23686         if(this.disabled){
23687             return;
23688         }
23689         if(this.isExpanded()){
23690             this.collapse();
23691             if (!this.blockFocus) {
23692                 this.el.focus();
23693             }
23694             
23695         }else {
23696             this.hasFocus = true;
23697             if(this.triggerAction == 'all') {
23698                 this.doQuery(this.allQuery, true);
23699             } else {
23700                 this.doQuery(this.getRawValue());
23701             }
23702             if (!this.blockFocus) {
23703                 this.el.focus();
23704             }
23705         }
23706     },
23707     listKeyPress : function(e)
23708     {
23709         //Roo.log('listkeypress');
23710         // scroll to first matching element based on key pres..
23711         if (e.isSpecialKey()) {
23712             return false;
23713         }
23714         var k = String.fromCharCode(e.getKey()).toUpperCase();
23715         //Roo.log(k);
23716         var match  = false;
23717         var csel = this.view.getSelectedNodes();
23718         var cselitem = false;
23719         if (csel.length) {
23720             var ix = this.view.indexOf(csel[0]);
23721             cselitem  = this.store.getAt(ix);
23722             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
23723                 cselitem = false;
23724             }
23725             
23726         }
23727         
23728         this.store.each(function(v) { 
23729             if (cselitem) {
23730                 // start at existing selection.
23731                 if (cselitem.id == v.id) {
23732                     cselitem = false;
23733                 }
23734                 return;
23735             }
23736                 
23737             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
23738                 match = this.store.indexOf(v);
23739                 return false;
23740             }
23741         }, this);
23742         
23743         if (match === false) {
23744             return true; // no more action?
23745         }
23746         // scroll to?
23747         this.view.select(match);
23748         var sn = Roo.get(this.view.getSelectedNodes()[0])
23749         sn.scrollIntoView(sn.dom.parentNode, false);
23750     }
23751
23752     /** 
23753     * @cfg {Boolean} grow 
23754     * @hide 
23755     */
23756     /** 
23757     * @cfg {Number} growMin 
23758     * @hide 
23759     */
23760     /** 
23761     * @cfg {Number} growMax 
23762     * @hide 
23763     */
23764     /**
23765      * @hide
23766      * @method autoSize
23767      */
23768 });/*
23769  * Copyright(c) 2010-2012, Roo J Solutions Limited
23770  *
23771  * Licence LGPL
23772  *
23773  */
23774
23775 /**
23776  * @class Roo.form.ComboBoxArray
23777  * @extends Roo.form.TextField
23778  * A facebook style adder... for lists of email / people / countries  etc...
23779  * pick multiple items from a combo box, and shows each one.
23780  *
23781  *  Fred [x]  Brian [x]  [Pick another |v]
23782  *
23783  *
23784  *  For this to work: it needs various extra information
23785  *    - normal combo problay has
23786  *      name, hiddenName
23787  *    + displayField, valueField
23788  *
23789  *    For our purpose...
23790  *
23791  *
23792  *   If we change from 'extends' to wrapping...
23793  *   
23794  *  
23795  *
23796  
23797  
23798  * @constructor
23799  * Create a new ComboBoxArray.
23800  * @param {Object} config Configuration options
23801  */
23802  
23803
23804 Roo.form.ComboBoxArray = function(config)
23805 {
23806     
23807     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
23808     
23809     this.items = new Roo.util.MixedCollection(false);
23810     
23811     // construct the child combo...
23812     
23813     
23814     
23815     
23816    
23817     
23818 }
23819
23820  
23821 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
23822
23823     /**
23824      * @cfg {Roo.form.Combo} combo The combo box that is wrapped
23825      */
23826     
23827     lastData : false,
23828     
23829     // behavies liek a hiddne field
23830     inputType:      'hidden',
23831     /**
23832      * @cfg {Number} width The width of the box that displays the selected element
23833      */ 
23834     width:          300,
23835
23836     
23837     
23838     /**
23839      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
23840      */
23841     name : false,
23842     /**
23843      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
23844      */
23845     hiddenName : false,
23846     
23847     
23848     // private the array of items that are displayed..
23849     items  : false,
23850     // private - the hidden field el.
23851     hiddenEl : false,
23852     // private - the filed el..
23853     el : false,
23854     
23855     //validateValue : function() { return true; }, // all values are ok!
23856     //onAddClick: function() { },
23857     
23858     onRender : function(ct, position) 
23859     {
23860         
23861         // create the standard hidden element
23862         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
23863         
23864         
23865         // give fake names to child combo;
23866         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
23867         this.combo.name = this.name? (this.name+'-subcombo') : this.name;
23868         
23869         this.combo = Roo.factory(this.combo, Roo.form);
23870         this.combo.onRender(ct, position);
23871         if (typeof(this.combo.width) != 'undefined') {
23872             this.combo.onResize(this.combo.width,0);
23873         }
23874         
23875         this.combo.initEvents();
23876         
23877         // assigned so form know we need to do this..
23878         this.store          = this.combo.store;
23879         this.valueField     = this.combo.valueField;
23880         this.displayField   = this.combo.displayField ;
23881         
23882         
23883         this.combo.wrap.addClass('x-cbarray-grp');
23884         
23885         var cbwrap = this.combo.wrap.createChild(
23886             {tag: 'div', cls: 'x-cbarray-cb'},
23887             this.combo.el.dom
23888         );
23889         
23890              
23891         this.hiddenEl = this.combo.wrap.createChild({
23892             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
23893         });
23894         this.el = this.combo.wrap.createChild({
23895             tag: 'input',  type:'hidden' , name: this.name, value : ''
23896         });
23897          //   this.el.dom.removeAttribute("name");
23898         
23899         
23900         this.outerWrap = this.combo.wrap;
23901         this.wrap = cbwrap;
23902         
23903         this.outerWrap.setWidth(this.width);
23904         this.outerWrap.dom.removeChild(this.el.dom);
23905         
23906         this.wrap.dom.appendChild(this.el.dom);
23907         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
23908         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
23909         
23910         this.combo.trigger.setStyle('position','relative');
23911         this.combo.trigger.setStyle('left', '0px');
23912         this.combo.trigger.setStyle('top', '2px');
23913         
23914         this.combo.el.setStyle('vertical-align', 'text-bottom');
23915         
23916         //this.trigger.setStyle('vertical-align', 'top');
23917         
23918         // this should use the code from combo really... on('add' ....)
23919         if (this.adder) {
23920             
23921         
23922             this.adder = this.outerWrap.createChild(
23923                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
23924             var _t = this;
23925             this.adder.on('click', function(e) {
23926                 _t.fireEvent('adderclick', this, e);
23927             }, _t);
23928         }
23929         //var _t = this;
23930         //this.adder.on('click', this.onAddClick, _t);
23931         
23932         
23933         this.combo.on('select', function(cb, rec, ix) {
23934             this.addItem(rec.data);
23935             
23936             cb.setValue('');
23937             cb.el.dom.value = '';
23938             //cb.lastData = rec.data;
23939             // add to list
23940             
23941         }, this);
23942         
23943         
23944     },
23945     
23946     
23947     getName: function()
23948     {
23949         // returns hidden if it's set..
23950         if (!this.rendered) {return ''};
23951         return  this.hiddenName ? this.hiddenName : this.name;
23952         
23953     },
23954     
23955     
23956     onResize: function(w, h){
23957         
23958         return;
23959         // not sure if this is needed..
23960         //this.combo.onResize(w,h);
23961         
23962         if(typeof w != 'number'){
23963             // we do not handle it!?!?
23964             return;
23965         }
23966         var tw = this.combo.trigger.getWidth();
23967         tw += this.addicon ? this.addicon.getWidth() : 0;
23968         tw += this.editicon ? this.editicon.getWidth() : 0;
23969         var x = w - tw;
23970         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
23971             
23972         this.combo.trigger.setStyle('left', '0px');
23973         
23974         if(this.list && this.listWidth === undefined){
23975             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
23976             this.list.setWidth(lw);
23977             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
23978         }
23979         
23980     
23981         
23982     },
23983     
23984     addItem: function(rec)
23985     {
23986         var valueField = this.combo.valueField;
23987         var displayField = this.combo.displayField;
23988         if (this.items.indexOfKey(rec[valueField]) > -1) {
23989             //console.log("GOT " + rec.data.id);
23990             return;
23991         }
23992         
23993         var x = new Roo.form.ComboBoxArray.Item({
23994             //id : rec[this.idField],
23995             data : rec,
23996             displayField : displayField ,
23997             tipField : displayField ,
23998             cb : this
23999         });
24000         // use the 
24001         this.items.add(rec[valueField],x);
24002         // add it before the element..
24003         this.updateHiddenEl();
24004         x.render(this.outerWrap, this.wrap.dom);
24005         // add the image handler..
24006     },
24007     
24008     updateHiddenEl : function()
24009     {
24010         this.validate();
24011         if (!this.hiddenEl) {
24012             return;
24013         }
24014         var ar = [];
24015         var idField = this.combo.valueField;
24016         
24017         this.items.each(function(f) {
24018             ar.push(f.data[idField]);
24019            
24020         });
24021         this.hiddenEl.dom.value = ar.join(',');
24022         this.validate();
24023     },
24024     
24025     reset : function()
24026     {
24027         //Roo.form.ComboBoxArray.superclass.reset.call(this); 
24028         this.items.each(function(f) {
24029            f.remove(); 
24030         });
24031         this.el.dom.value = '';
24032         if (this.hiddenEl) {
24033             this.hiddenEl.dom.value = '';
24034         }
24035         
24036     },
24037     getValue: function()
24038     {
24039         return this.hiddenEl ? this.hiddenEl.dom.value : '';
24040     },
24041     setValue: function(v) // not a valid action - must use addItems..
24042     {
24043          
24044         this.reset();
24045         
24046         
24047         
24048         if (this.store.isLocal && (typeof(v) == 'string')) {
24049             // then we can use the store to find the values..
24050             // comma seperated at present.. this needs to allow JSON based encoding..
24051             this.hiddenEl.value  = v;
24052             var v_ar = [];
24053             Roo.each(v.split(','), function(k) {
24054                 Roo.log("CHECK " + this.valueField + ',' + k);
24055                 var li = this.store.query(this.valueField, k);
24056                 if (!li.length) {
24057                     return;
24058                 }
24059                 var add = {};
24060                 add[this.valueField] = k;
24061                 add[this.displayField] = li.item(0).data[this.displayField];
24062                 
24063                 this.addItem(add);
24064             }, this) 
24065              
24066         }
24067         if (typeof(v) == 'object') {
24068             // then let's assume it's an array of objects..
24069             Roo.each(v, function(l) {
24070                 this.addItem(l);
24071             }, this);
24072              
24073         }
24074         
24075         
24076     },
24077     setFromData: function(v)
24078     {
24079         // this recieves an object, if setValues is called.
24080         this.reset();
24081         this.el.dom.value = v[this.displayField];
24082         this.hiddenEl.dom.value = v[this.valueField];
24083         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
24084             return;
24085         }
24086         var kv = v[this.valueField];
24087         var dv = v[this.displayField];
24088         kv = typeof(kv) != 'string' ? '' : kv;
24089         dv = typeof(dv) != 'string' ? '' : dv;
24090         
24091         
24092         var keys = kv.split(',');
24093         var display = dv.split(',');
24094         for (var i = 0 ; i < keys.length; i++) {
24095             
24096             add = {};
24097             add[this.valueField] = keys[i];
24098             add[this.displayField] = display[i];
24099             this.addItem(add);
24100         }
24101       
24102         
24103     },
24104     
24105     /**
24106      * Validates the combox array value
24107      * @return {Boolean} True if the value is valid, else false
24108      */
24109     validate : function(){
24110         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
24111             this.clearInvalid();
24112             return true;
24113         }
24114         return false;
24115     },
24116     
24117     validateValue : function(value){
24118         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
24119         
24120     },
24121     
24122     /**
24123      * Mark this combo array as invalid
24124      * @param {String} msg The validation message
24125      */
24126     markInvalid : function(msg){
24127         if(!this.rendered || this.preventMark){ // not rendered
24128             return;
24129         }
24130         this.combo.el.addClass(this.invalidClass);
24131         msg = msg || this.invalidText;
24132         switch(this.msgTarget){
24133             case 'qtip':
24134                 this.el.dom.qtip = msg;
24135                 this.el.dom.qclass = 'x-form-invalid-tip';
24136                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
24137                     Roo.QuickTips.enable();
24138                 }
24139                 break;
24140             case 'title':
24141                 this.el.dom.title = msg;
24142                 break;
24143             case 'under':
24144                 if(!this.errorEl){
24145                     var elp = this.el.findParent('.x-form-element', 5, true);
24146                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
24147                     this.errorEl.setWidth(elp.getWidth(true)-20);
24148                 }
24149                 this.errorEl.update(msg);
24150                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
24151                 break;
24152             case 'side':
24153                 if(!this.errorIcon){
24154                     var elp = this.el.findParent('.x-form-element', 5, true);
24155                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
24156                 }
24157                 this.alignErrorIcon();
24158                 this.errorIcon.dom.qtip = msg;
24159                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
24160                 this.errorIcon.show();
24161                 this.on('resize', this.alignErrorIcon, this);
24162                 break;
24163             default:
24164                 var t = Roo.getDom(this.msgTarget);
24165                 t.innerHTML = msg;
24166                 t.style.display = this.msgDisplay;
24167                 break;
24168         }
24169         this.fireEvent('invalid', this, msg);
24170     }
24171     
24172 });
24173
24174
24175
24176 /**
24177  * @class Roo.form.ComboBoxArray.Item
24178  * @extends Roo.BoxComponent
24179  * A selected item in the list
24180  *  Fred [x]  Brian [x]  [Pick another |v]
24181  * 
24182  * @constructor
24183  * Create a new item.
24184  * @param {Object} config Configuration options
24185  */
24186  
24187 Roo.form.ComboBoxArray.Item = function(config) {
24188     config.id = Roo.id();
24189     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
24190 }
24191
24192 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
24193     data : {},
24194     cb: false,
24195     displayField : false,
24196     tipField : false,
24197     
24198     
24199     defaultAutoCreate : {
24200         tag: 'div',
24201         cls: 'x-cbarray-item',
24202         cn : [ 
24203             { tag: 'div' },
24204             {
24205                 tag: 'img',
24206                 width:16,
24207                 height : 16,
24208                 src : Roo.BLANK_IMAGE_URL ,
24209                 align: 'center'
24210             }
24211         ]
24212         
24213     },
24214     
24215  
24216     onRender : function(ct, position)
24217     {
24218         Roo.form.Field.superclass.onRender.call(this, ct, position);
24219         
24220         if(!this.el){
24221             var cfg = this.getAutoCreate();
24222             this.el = ct.createChild(cfg, position);
24223         }
24224         
24225         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
24226         
24227         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
24228             this.cb.renderer(this.data) :
24229             String.format('{0}',this.data[this.displayField]);
24230         
24231             
24232         this.el.child('div').dom.setAttribute('qtip',
24233                         String.format('{0}',this.data[this.tipField])
24234         );
24235         
24236         this.el.child('img').on('click', this.remove, this);
24237         
24238     },
24239    
24240     remove : function()
24241     {
24242         
24243         this.cb.items.remove(this);
24244         this.el.child('img').un('click', this.remove, this);
24245         this.el.remove();
24246         this.cb.updateHiddenEl();
24247     }
24248     
24249 });/*
24250  * Based on:
24251  * Ext JS Library 1.1.1
24252  * Copyright(c) 2006-2007, Ext JS, LLC.
24253  *
24254  * Originally Released Under LGPL - original licence link has changed is not relivant.
24255  *
24256  * Fork - LGPL
24257  * <script type="text/javascript">
24258  */
24259 /**
24260  * @class Roo.form.Checkbox
24261  * @extends Roo.form.Field
24262  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
24263  * @constructor
24264  * Creates a new Checkbox
24265  * @param {Object} config Configuration options
24266  */
24267 Roo.form.Checkbox = function(config){
24268     Roo.form.Checkbox.superclass.constructor.call(this, config);
24269     this.addEvents({
24270         /**
24271          * @event check
24272          * Fires when the checkbox is checked or unchecked.
24273              * @param {Roo.form.Checkbox} this This checkbox
24274              * @param {Boolean} checked The new checked value
24275              */
24276         check : true
24277     });
24278 };
24279
24280 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
24281     /**
24282      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
24283      */
24284     focusClass : undefined,
24285     /**
24286      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
24287      */
24288     fieldClass: "x-form-field",
24289     /**
24290      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
24291      */
24292     checked: false,
24293     /**
24294      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
24295      * {tag: "input", type: "checkbox", autocomplete: "off"})
24296      */
24297     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
24298     /**
24299      * @cfg {String} boxLabel The text that appears beside the checkbox
24300      */
24301     boxLabel : "",
24302     /**
24303      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
24304      */  
24305     inputValue : '1',
24306     /**
24307      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
24308      */
24309      valueOff: '0', // value when not checked..
24310
24311     actionMode : 'viewEl', 
24312     //
24313     // private
24314     itemCls : 'x-menu-check-item x-form-item',
24315     groupClass : 'x-menu-group-item',
24316     inputType : 'hidden',
24317     
24318     
24319     inSetChecked: false, // check that we are not calling self...
24320     
24321     inputElement: false, // real input element?
24322     basedOn: false, // ????
24323     
24324     isFormField: true, // not sure where this is needed!!!!
24325
24326     onResize : function(){
24327         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
24328         if(!this.boxLabel){
24329             this.el.alignTo(this.wrap, 'c-c');
24330         }
24331     },
24332
24333     initEvents : function(){
24334         Roo.form.Checkbox.superclass.initEvents.call(this);
24335         this.el.on("click", this.onClick,  this);
24336         this.el.on("change", this.onClick,  this);
24337     },
24338
24339
24340     getResizeEl : function(){
24341         return this.wrap;
24342     },
24343
24344     getPositionEl : function(){
24345         return this.wrap;
24346     },
24347
24348     // private
24349     onRender : function(ct, position){
24350         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
24351         /*
24352         if(this.inputValue !== undefined){
24353             this.el.dom.value = this.inputValue;
24354         }
24355         */
24356         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
24357         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
24358         var viewEl = this.wrap.createChild({ 
24359             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
24360         this.viewEl = viewEl;   
24361         this.wrap.on('click', this.onClick,  this); 
24362         
24363         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
24364         this.el.on('propertychange', this.setFromHidden,  this);  //ie
24365         
24366         
24367         
24368         if(this.boxLabel){
24369             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
24370         //    viewEl.on('click', this.onClick,  this); 
24371         }
24372         //if(this.checked){
24373             this.setChecked(this.checked);
24374         //}else{
24375             //this.checked = this.el.dom;
24376         //}
24377
24378     },
24379
24380     // private
24381     initValue : Roo.emptyFn,
24382
24383     /**
24384      * Returns the checked state of the checkbox.
24385      * @return {Boolean} True if checked, else false
24386      */
24387     getValue : function(){
24388         if(this.el){
24389             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
24390         }
24391         return this.valueOff;
24392         
24393     },
24394
24395         // private
24396     onClick : function(){ 
24397         this.setChecked(!this.checked);
24398
24399         //if(this.el.dom.checked != this.checked){
24400         //    this.setValue(this.el.dom.checked);
24401        // }
24402     },
24403
24404     /**
24405      * Sets the checked state of the checkbox.
24406      * On is always based on a string comparison between inputValue and the param.
24407      * @param {Boolean/String} value - the value to set 
24408      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
24409      */
24410     setValue : function(v,suppressEvent){
24411         
24412         
24413         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
24414         //if(this.el && this.el.dom){
24415         //    this.el.dom.checked = this.checked;
24416         //    this.el.dom.defaultChecked = this.checked;
24417         //}
24418         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
24419         //this.fireEvent("check", this, this.checked);
24420     },
24421     // private..
24422     setChecked : function(state,suppressEvent)
24423     {
24424         if (this.inSetChecked) {
24425             this.checked = state;
24426             return;
24427         }
24428         
24429     
24430         if(this.wrap){
24431             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
24432         }
24433         this.checked = state;
24434         if(suppressEvent !== true){
24435             this.fireEvent('check', this, state);
24436         }
24437         this.inSetChecked = true;
24438         this.el.dom.value = state ? this.inputValue : this.valueOff;
24439         this.inSetChecked = false;
24440         
24441     },
24442     // handle setting of hidden value by some other method!!?!?
24443     setFromHidden: function()
24444     {
24445         if(!this.el){
24446             return;
24447         }
24448         //console.log("SET FROM HIDDEN");
24449         //alert('setFrom hidden');
24450         this.setValue(this.el.dom.value);
24451     },
24452     
24453     onDestroy : function()
24454     {
24455         if(this.viewEl){
24456             Roo.get(this.viewEl).remove();
24457         }
24458          
24459         Roo.form.Checkbox.superclass.onDestroy.call(this);
24460     }
24461
24462 });/*
24463  * Based on:
24464  * Ext JS Library 1.1.1
24465  * Copyright(c) 2006-2007, Ext JS, LLC.
24466  *
24467  * Originally Released Under LGPL - original licence link has changed is not relivant.
24468  *
24469  * Fork - LGPL
24470  * <script type="text/javascript">
24471  */
24472  
24473 /**
24474  * @class Roo.form.Radio
24475  * @extends Roo.form.Checkbox
24476  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
24477  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
24478  * @constructor
24479  * Creates a new Radio
24480  * @param {Object} config Configuration options
24481  */
24482 Roo.form.Radio = function(){
24483     Roo.form.Radio.superclass.constructor.apply(this, arguments);
24484 };
24485 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
24486     inputType: 'radio',
24487
24488     /**
24489      * If this radio is part of a group, it will return the selected value
24490      * @return {String}
24491      */
24492     getGroupValue : function(){
24493         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
24494     },
24495     
24496     
24497     onRender : function(ct, position){
24498         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
24499         
24500         if(this.inputValue !== undefined){
24501             this.el.dom.value = this.inputValue;
24502         }
24503          
24504         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
24505         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
24506         //var viewEl = this.wrap.createChild({ 
24507         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
24508         //this.viewEl = viewEl;   
24509         //this.wrap.on('click', this.onClick,  this); 
24510         
24511         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
24512         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
24513         
24514         
24515         
24516         if(this.boxLabel){
24517             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
24518         //    viewEl.on('click', this.onClick,  this); 
24519         }
24520          if(this.checked){
24521             this.el.dom.checked =   'checked' ;
24522         }
24523          
24524     } 
24525     
24526     
24527 });//<script type="text/javascript">
24528
24529 /*
24530  * Ext JS Library 1.1.1
24531  * Copyright(c) 2006-2007, Ext JS, LLC.
24532  * licensing@extjs.com
24533  * 
24534  * http://www.extjs.com/license
24535  */
24536  
24537  /*
24538   * 
24539   * Known bugs:
24540   * Default CSS appears to render it as fixed text by default (should really be Sans-Serif)
24541   * - IE ? - no idea how much works there.
24542   * 
24543   * 
24544   * 
24545   */
24546  
24547
24548 /**
24549  * @class Ext.form.HtmlEditor
24550  * @extends Ext.form.Field
24551  * Provides a lightweight HTML Editor component.
24552  *
24553  * This has been tested on Fireforx / Chrome.. IE may not be so great..
24554  * 
24555  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
24556  * supported by this editor.</b><br/><br/>
24557  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
24558  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
24559  */
24560 Roo.form.HtmlEditor = Roo.extend(Roo.form.Field, {
24561       /**
24562      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
24563      */
24564     toolbars : false,
24565     /**
24566      * @cfg {String} createLinkText The default text for the create link prompt
24567      */
24568     createLinkText : 'Please enter the URL for the link:',
24569     /**
24570      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
24571      */
24572     defaultLinkValue : 'http:/'+'/',
24573    
24574      /**
24575      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
24576      *                        Roo.resizable.
24577      */
24578     resizable : false,
24579      /**
24580      * @cfg {Number} height (in pixels)
24581      */   
24582     height: 300,
24583    /**
24584      * @cfg {Number} width (in pixels)
24585      */   
24586     width: 500,
24587     
24588     /**
24589      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
24590      * 
24591      */
24592     stylesheets: false,
24593     
24594     // id of frame..
24595     frameId: false,
24596     
24597     // private properties
24598     validationEvent : false,
24599     deferHeight: true,
24600     initialized : false,
24601     activated : false,
24602     sourceEditMode : false,
24603     onFocus : Roo.emptyFn,
24604     iframePad:3,
24605     hideMode:'offsets',
24606     
24607     defaultAutoCreate : { // modified by initCompnoent..
24608         tag: "textarea",
24609         style:"width:500px;height:300px;",
24610         autocomplete: "off"
24611     },
24612
24613     // private
24614     initComponent : function(){
24615         this.addEvents({
24616             /**
24617              * @event initialize
24618              * Fires when the editor is fully initialized (including the iframe)
24619              * @param {HtmlEditor} this
24620              */
24621             initialize: true,
24622             /**
24623              * @event activate
24624              * Fires when the editor is first receives the focus. Any insertion must wait
24625              * until after this event.
24626              * @param {HtmlEditor} this
24627              */
24628             activate: true,
24629              /**
24630              * @event beforesync
24631              * Fires before the textarea is updated with content from the editor iframe. Return false
24632              * to cancel the sync.
24633              * @param {HtmlEditor} this
24634              * @param {String} html
24635              */
24636             beforesync: true,
24637              /**
24638              * @event beforepush
24639              * Fires before the iframe editor is updated with content from the textarea. Return false
24640              * to cancel the push.
24641              * @param {HtmlEditor} this
24642              * @param {String} html
24643              */
24644             beforepush: true,
24645              /**
24646              * @event sync
24647              * Fires when the textarea is updated with content from the editor iframe.
24648              * @param {HtmlEditor} this
24649              * @param {String} html
24650              */
24651             sync: true,
24652              /**
24653              * @event push
24654              * Fires when the iframe editor is updated with content from the textarea.
24655              * @param {HtmlEditor} this
24656              * @param {String} html
24657              */
24658             push: true,
24659              /**
24660              * @event editmodechange
24661              * Fires when the editor switches edit modes
24662              * @param {HtmlEditor} this
24663              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
24664              */
24665             editmodechange: true,
24666             /**
24667              * @event editorevent
24668              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
24669              * @param {HtmlEditor} this
24670              */
24671             editorevent: true
24672         });
24673         this.defaultAutoCreate =  {
24674             tag: "textarea",
24675             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
24676             autocomplete: "off"
24677         };
24678     },
24679
24680     /**
24681      * Protected method that will not generally be called directly. It
24682      * is called when the editor creates its toolbar. Override this method if you need to
24683      * add custom toolbar buttons.
24684      * @param {HtmlEditor} editor
24685      */
24686     createToolbar : function(editor){
24687         if (!editor.toolbars || !editor.toolbars.length) {
24688             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
24689         }
24690         
24691         for (var i =0 ; i < editor.toolbars.length;i++) {
24692             editor.toolbars[i] = Roo.factory(
24693                     typeof(editor.toolbars[i]) == 'string' ?
24694                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
24695                 Roo.form.HtmlEditor);
24696             editor.toolbars[i].init(editor);
24697         }
24698          
24699         
24700     },
24701
24702     /**
24703      * Protected method that will not generally be called directly. It
24704      * is called when the editor initializes the iframe with HTML contents. Override this method if you
24705      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
24706      */
24707     getDocMarkup : function(){
24708         // body styles..
24709         var st = '';
24710         if (this.stylesheets === false) {
24711             
24712             Roo.get(document.head).select('style').each(function(node) {
24713                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
24714             });
24715             
24716             Roo.get(document.head).select('link').each(function(node) { 
24717                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
24718             });
24719             
24720         } else if (!this.stylesheets.length) {
24721                 // simple..
24722                 st = '<style type="text/css">' +
24723                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
24724                    '</style>';
24725         } else {
24726             Roo.each(this.stylesheets, function(s) {
24727                 st += '<link rel="stylesheet" type="text/css" href="' + s +'" />'
24728             });
24729             
24730         }
24731         
24732         st +=  '<style type="text/css">' +
24733             'IMG { cursor: pointer } ' +
24734         '</style>';
24735
24736         
24737         return '<html><head>' + st  +
24738             //<style type="text/css">' +
24739             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
24740             //'</style>' +
24741             ' </head><body class="roo-htmleditor-body"></body></html>';
24742     },
24743
24744     // private
24745     onRender : function(ct, position)
24746     {
24747         var _t = this;
24748         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
24749         this.el.dom.style.border = '0 none';
24750         this.el.dom.setAttribute('tabIndex', -1);
24751         this.el.addClass('x-hidden');
24752         if(Roo.isIE){ // fix IE 1px bogus margin
24753             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
24754         }
24755         this.wrap = this.el.wrap({
24756             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
24757         });
24758         
24759         if (this.resizable) {
24760             this.resizeEl = new Roo.Resizable(this.wrap, {
24761                 pinned : true,
24762                 wrap: true,
24763                 dynamic : true,
24764                 minHeight : this.height,
24765                 height: this.height,
24766                 handles : this.resizable,
24767                 width: this.width,
24768                 listeners : {
24769                     resize : function(r, w, h) {
24770                         _t.onResize(w,h); // -something
24771                     }
24772                 }
24773             });
24774             
24775         }
24776
24777         this.frameId = Roo.id();
24778         
24779         this.createToolbar(this);
24780         
24781       
24782         
24783         var iframe = this.wrap.createChild({
24784             tag: 'iframe',
24785             id: this.frameId,
24786             name: this.frameId,
24787             frameBorder : 'no',
24788             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
24789         }, this.el
24790         );
24791         
24792        // console.log(iframe);
24793         //this.wrap.dom.appendChild(iframe);
24794
24795         this.iframe = iframe.dom;
24796
24797          this.assignDocWin();
24798         
24799         this.doc.designMode = 'on';
24800        
24801         this.doc.open();
24802         this.doc.write(this.getDocMarkup());
24803         this.doc.close();
24804
24805         
24806         var task = { // must defer to wait for browser to be ready
24807             run : function(){
24808                 //console.log("run task?" + this.doc.readyState);
24809                 this.assignDocWin();
24810                 if(this.doc.body || this.doc.readyState == 'complete'){
24811                     try {
24812                         this.doc.designMode="on";
24813                     } catch (e) {
24814                         return;
24815                     }
24816                     Roo.TaskMgr.stop(task);
24817                     this.initEditor.defer(10, this);
24818                 }
24819             },
24820             interval : 10,
24821             duration:10000,
24822             scope: this
24823         };
24824         Roo.TaskMgr.start(task);
24825
24826         if(!this.width){
24827             this.setSize(this.wrap.getSize());
24828         }
24829         if (this.resizeEl) {
24830             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
24831             // should trigger onReize..
24832         }
24833     },
24834
24835     // private
24836     onResize : function(w, h)
24837     {
24838         //Roo.log('resize: ' +w + ',' + h );
24839         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
24840         if(this.el && this.iframe){
24841             if(typeof w == 'number'){
24842                 var aw = w - this.wrap.getFrameWidth('lr');
24843                 this.el.setWidth(this.adjustWidth('textarea', aw));
24844                 this.iframe.style.width = aw + 'px';
24845             }
24846             if(typeof h == 'number'){
24847                 var tbh = 0;
24848                 for (var i =0; i < this.toolbars.length;i++) {
24849                     // fixme - ask toolbars for heights?
24850                     tbh += this.toolbars[i].tb.el.getHeight();
24851                     if (this.toolbars[i].footer) {
24852                         tbh += this.toolbars[i].footer.el.getHeight();
24853                     }
24854                 }
24855                 
24856                 
24857                 
24858                 
24859                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
24860                 ah -= 5; // knock a few pixes off for look..
24861                 this.el.setHeight(this.adjustWidth('textarea', ah));
24862                 this.iframe.style.height = ah + 'px';
24863                 if(this.doc){
24864                     (this.doc.body || this.doc.documentElement).style.height = (ah - (this.iframePad*2)) + 'px';
24865                 }
24866             }
24867         }
24868     },
24869
24870     /**
24871      * Toggles the editor between standard and source edit mode.
24872      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
24873      */
24874     toggleSourceEdit : function(sourceEditMode){
24875         
24876         this.sourceEditMode = sourceEditMode === true;
24877         
24878         if(this.sourceEditMode){
24879 //            Roo.log('in');
24880 //            Roo.log(this.syncValue());
24881             this.syncValue();
24882             this.iframe.className = 'x-hidden';
24883             this.el.removeClass('x-hidden');
24884             this.el.dom.removeAttribute('tabIndex');
24885             this.el.focus();
24886         }else{
24887 //            Roo.log('out')
24888 //            Roo.log(this.pushValue()); 
24889             this.pushValue();
24890             this.iframe.className = '';
24891             this.el.addClass('x-hidden');
24892             this.el.dom.setAttribute('tabIndex', -1);
24893             this.deferFocus();
24894         }
24895         this.setSize(this.wrap.getSize());
24896         this.fireEvent('editmodechange', this, this.sourceEditMode);
24897     },
24898
24899     // private used internally
24900     createLink : function(){
24901         var url = prompt(this.createLinkText, this.defaultLinkValue);
24902         if(url && url != 'http:/'+'/'){
24903             this.relayCmd('createlink', url);
24904         }
24905     },
24906
24907     // private (for BoxComponent)
24908     adjustSize : Roo.BoxComponent.prototype.adjustSize,
24909
24910     // private (for BoxComponent)
24911     getResizeEl : function(){
24912         return this.wrap;
24913     },
24914
24915     // private (for BoxComponent)
24916     getPositionEl : function(){
24917         return this.wrap;
24918     },
24919
24920     // private
24921     initEvents : function(){
24922         this.originalValue = this.getValue();
24923     },
24924
24925     /**
24926      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
24927      * @method
24928      */
24929     markInvalid : Roo.emptyFn,
24930     /**
24931      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
24932      * @method
24933      */
24934     clearInvalid : Roo.emptyFn,
24935
24936     setValue : function(v){
24937         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
24938         this.pushValue();
24939     },
24940
24941     /**
24942      * Protected method that will not generally be called directly. If you need/want
24943      * custom HTML cleanup, this is the method you should override.
24944      * @param {String} html The HTML to be cleaned
24945      * return {String} The cleaned HTML
24946      */
24947     cleanHtml : function(html){
24948         html = String(html);
24949         if(html.length > 5){
24950             if(Roo.isSafari){ // strip safari nonsense
24951                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
24952             }
24953         }
24954         if(html == '&nbsp;'){
24955             html = '';
24956         }
24957         return html;
24958     },
24959
24960     /**
24961      * Protected method that will not generally be called directly. Syncs the contents
24962      * of the editor iframe with the textarea.
24963      */
24964     syncValue : function(){
24965         if(this.initialized){
24966             var bd = (this.doc.body || this.doc.documentElement);
24967             //this.cleanUpPaste(); -- this is done else where and causes havoc..
24968             var html = bd.innerHTML;
24969             if(Roo.isSafari){
24970                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
24971                 var m = bs.match(/text-align:(.*?);/i);
24972                 if(m && m[1]){
24973                     html = '<div style="'+m[0]+'">' + html + '</div>';
24974                 }
24975             }
24976             html = this.cleanHtml(html);
24977             // fix up the special chars.. normaly like back quotes in word...
24978             // however we do not want to do this with chinese..
24979             html = html.replace(/([\x80-\uffff])/g, function (a, b) {
24980                 var cc = b.charCodeAt();
24981                 if (
24982                     (cc >= 0x4E00 && cc < 0xA000 ) ||
24983                     (cc >= 0x3400 && cc < 0x4E00 ) ||
24984                     (cc >= 0xf900 && cc < 0xfb00 )
24985                 ) {
24986                         return b;
24987                 }
24988                 return "&#"+cc+";" 
24989             });
24990             if(this.fireEvent('beforesync', this, html) !== false){
24991                 this.el.dom.value = html;
24992                 this.fireEvent('sync', this, html);
24993             }
24994         }
24995     },
24996
24997     /**
24998      * Protected method that will not generally be called directly. Pushes the value of the textarea
24999      * into the iframe editor.
25000      */
25001     pushValue : function(){
25002         if(this.initialized){
25003             var v = this.el.dom.value;
25004             
25005             if(v.length < 1){
25006                 v = '&#160;';
25007             }
25008             
25009             if(this.fireEvent('beforepush', this, v) !== false){
25010                 var d = (this.doc.body || this.doc.documentElement);
25011                 d.innerHTML = v;
25012                 this.cleanUpPaste();
25013                 this.el.dom.value = d.innerHTML;
25014                 this.fireEvent('push', this, v);
25015             }
25016         }
25017     },
25018
25019     // private
25020     deferFocus : function(){
25021         this.focus.defer(10, this);
25022     },
25023
25024     // doc'ed in Field
25025     focus : function(){
25026         if(this.win && !this.sourceEditMode){
25027             this.win.focus();
25028         }else{
25029             this.el.focus();
25030         }
25031     },
25032     
25033     assignDocWin: function()
25034     {
25035         var iframe = this.iframe;
25036         
25037          if(Roo.isIE){
25038             this.doc = iframe.contentWindow.document;
25039             this.win = iframe.contentWindow;
25040         } else {
25041             if (!Roo.get(this.frameId)) {
25042                 return;
25043             }
25044             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
25045             this.win = Roo.get(this.frameId).dom.contentWindow;
25046         }
25047     },
25048     
25049     // private
25050     initEditor : function(){
25051         //console.log("INIT EDITOR");
25052         this.assignDocWin();
25053         
25054         
25055         
25056         this.doc.designMode="on";
25057         this.doc.open();
25058         this.doc.write(this.getDocMarkup());
25059         this.doc.close();
25060         
25061         var dbody = (this.doc.body || this.doc.documentElement);
25062         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
25063         // this copies styles from the containing element into thsi one..
25064         // not sure why we need all of this..
25065         var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
25066         ss['background-attachment'] = 'fixed'; // w3c
25067         dbody.bgProperties = 'fixed'; // ie
25068         Roo.DomHelper.applyStyles(dbody, ss);
25069         Roo.EventManager.on(this.doc, {
25070             //'mousedown': this.onEditorEvent,
25071             'mouseup': this.onEditorEvent,
25072             'dblclick': this.onEditorEvent,
25073             'click': this.onEditorEvent,
25074             'keyup': this.onEditorEvent,
25075             buffer:100,
25076             scope: this
25077         });
25078         if(Roo.isGecko){
25079             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
25080         }
25081         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
25082             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
25083         }
25084         this.initialized = true;
25085
25086         this.fireEvent('initialize', this);
25087         this.pushValue();
25088     },
25089
25090     // private
25091     onDestroy : function(){
25092         
25093         
25094         
25095         if(this.rendered){
25096             
25097             for (var i =0; i < this.toolbars.length;i++) {
25098                 // fixme - ask toolbars for heights?
25099                 this.toolbars[i].onDestroy();
25100             }
25101             
25102             this.wrap.dom.innerHTML = '';
25103             this.wrap.remove();
25104         }
25105     },
25106
25107     // private
25108     onFirstFocus : function(){
25109         
25110         this.assignDocWin();
25111         
25112         
25113         this.activated = true;
25114         for (var i =0; i < this.toolbars.length;i++) {
25115             this.toolbars[i].onFirstFocus();
25116         }
25117        
25118         if(Roo.isGecko){ // prevent silly gecko errors
25119             this.win.focus();
25120             var s = this.win.getSelection();
25121             if(!s.focusNode || s.focusNode.nodeType != 3){
25122                 var r = s.getRangeAt(0);
25123                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
25124                 r.collapse(true);
25125                 this.deferFocus();
25126             }
25127             try{
25128                 this.execCmd('useCSS', true);
25129                 this.execCmd('styleWithCSS', false);
25130             }catch(e){}
25131         }
25132         this.fireEvent('activate', this);
25133     },
25134
25135     // private
25136     adjustFont: function(btn){
25137         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
25138         //if(Roo.isSafari){ // safari
25139         //    adjust *= 2;
25140        // }
25141         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
25142         if(Roo.isSafari){ // safari
25143             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
25144             v =  (v < 10) ? 10 : v;
25145             v =  (v > 48) ? 48 : v;
25146             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
25147             
25148         }
25149         
25150         
25151         v = Math.max(1, v+adjust);
25152         
25153         this.execCmd('FontSize', v  );
25154     },
25155
25156     onEditorEvent : function(e){
25157         this.fireEvent('editorevent', this, e);
25158       //  this.updateToolbar();
25159         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
25160     },
25161
25162     insertTag : function(tg)
25163     {
25164         // could be a bit smarter... -> wrap the current selected tRoo..
25165         if (tg.toLowerCase() == 'span' || tg.toLowerCase() == 'code') {
25166             
25167             range = this.createRange(this.getSelection());
25168             var wrappingNode = this.doc.createElement(tg.toLowerCase());
25169             wrappingNode.appendChild(range.extractContents());
25170             range.insertNode(wrappingNode);
25171
25172             return;
25173             
25174             
25175             
25176         }
25177         this.execCmd("formatblock",   tg);
25178         
25179     },
25180     
25181     insertText : function(txt)
25182     {
25183         
25184         
25185         var range = this.createRange();
25186         range.deleteContents();
25187                //alert(Sender.getAttribute('label'));
25188                
25189         range.insertNode(this.doc.createTextNode(txt));
25190     } ,
25191     
25192     // private
25193     relayBtnCmd : function(btn){
25194         this.relayCmd(btn.cmd);
25195     },
25196
25197     /**
25198      * Executes a Midas editor command on the editor document and performs necessary focus and
25199      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
25200      * @param {String} cmd The Midas command
25201      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25202      */
25203     relayCmd : function(cmd, value){
25204         this.win.focus();
25205         this.execCmd(cmd, value);
25206         this.fireEvent('editorevent', this);
25207         //this.updateToolbar();
25208         this.deferFocus();
25209     },
25210
25211     /**
25212      * Executes a Midas editor command directly on the editor document.
25213      * For visual commands, you should use {@link #relayCmd} instead.
25214      * <b>This should only be called after the editor is initialized.</b>
25215      * @param {String} cmd The Midas command
25216      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
25217      */
25218     execCmd : function(cmd, value){
25219         this.doc.execCommand(cmd, false, value === undefined ? null : value);
25220         this.syncValue();
25221     },
25222  
25223  
25224    
25225     /**
25226      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
25227      * to insert tRoo.
25228      * @param {String} text | dom node.. 
25229      */
25230     insertAtCursor : function(text)
25231     {
25232         
25233         
25234         
25235         if(!this.activated){
25236             return;
25237         }
25238         /*
25239         if(Roo.isIE){
25240             this.win.focus();
25241             var r = this.doc.selection.createRange();
25242             if(r){
25243                 r.collapse(true);
25244                 r.pasteHTML(text);
25245                 this.syncValue();
25246                 this.deferFocus();
25247             
25248             }
25249             return;
25250         }
25251         */
25252         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
25253             this.win.focus();
25254             
25255             
25256             // from jquery ui (MIT licenced)
25257             var range, node;
25258             var win = this.win;
25259             
25260             if (win.getSelection && win.getSelection().getRangeAt) {
25261                 range = win.getSelection().getRangeAt(0);
25262                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
25263                 range.insertNode(node);
25264             } else if (win.document.selection && win.document.selection.createRange) {
25265                 // no firefox support
25266                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25267                 win.document.selection.createRange().pasteHTML(txt);
25268             } else {
25269                 // no firefox support
25270                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
25271                 this.execCmd('InsertHTML', txt);
25272             } 
25273             
25274             this.syncValue();
25275             
25276             this.deferFocus();
25277         }
25278     },
25279  // private
25280     mozKeyPress : function(e){
25281         if(e.ctrlKey){
25282             var c = e.getCharCode(), cmd;
25283           
25284             if(c > 0){
25285                 c = String.fromCharCode(c).toLowerCase();
25286                 switch(c){
25287                     case 'b':
25288                         cmd = 'bold';
25289                         break;
25290                     case 'i':
25291                         cmd = 'italic';
25292                         break;
25293                     
25294                     case 'u':
25295                         cmd = 'underline';
25296                         break;
25297                     
25298                     case 'v':
25299                         this.cleanUpPaste.defer(100, this);
25300                         return;
25301                         
25302                 }
25303                 if(cmd){
25304                     this.win.focus();
25305                     this.execCmd(cmd);
25306                     this.deferFocus();
25307                     e.preventDefault();
25308                 }
25309                 
25310             }
25311         }
25312     },
25313
25314     // private
25315     fixKeys : function(){ // load time branching for fastest keydown performance
25316         if(Roo.isIE){
25317             return function(e){
25318                 var k = e.getKey(), r;
25319                 if(k == e.TAB){
25320                     e.stopEvent();
25321                     r = this.doc.selection.createRange();
25322                     if(r){
25323                         r.collapse(true);
25324                         r.pasteHTML('&#160;&#160;&#160;&#160;');
25325                         this.deferFocus();
25326                     }
25327                     return;
25328                 }
25329                 
25330                 if(k == e.ENTER){
25331                     r = this.doc.selection.createRange();
25332                     if(r){
25333                         var target = r.parentElement();
25334                         if(!target || target.tagName.toLowerCase() != 'li'){
25335                             e.stopEvent();
25336                             r.pasteHTML('<br />');
25337                             r.collapse(false);
25338                             r.select();
25339                         }
25340                     }
25341                 }
25342                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25343                     this.cleanUpPaste.defer(100, this);
25344                     return;
25345                 }
25346                 
25347                 
25348             };
25349         }else if(Roo.isOpera){
25350             return function(e){
25351                 var k = e.getKey();
25352                 if(k == e.TAB){
25353                     e.stopEvent();
25354                     this.win.focus();
25355                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
25356                     this.deferFocus();
25357                 }
25358                 if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25359                     this.cleanUpPaste.defer(100, this);
25360                     return;
25361                 }
25362                 
25363             };
25364         }else if(Roo.isSafari){
25365             return function(e){
25366                 var k = e.getKey();
25367                 
25368                 if(k == e.TAB){
25369                     e.stopEvent();
25370                     this.execCmd('InsertText','\t');
25371                     this.deferFocus();
25372                     return;
25373                 }
25374                if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
25375                     this.cleanUpPaste.defer(100, this);
25376                     return;
25377                 }
25378                 
25379              };
25380         }
25381     }(),
25382     
25383     getAllAncestors: function()
25384     {
25385         var p = this.getSelectedNode();
25386         var a = [];
25387         if (!p) {
25388             a.push(p); // push blank onto stack..
25389             p = this.getParentElement();
25390         }
25391         
25392         
25393         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
25394             a.push(p);
25395             p = p.parentNode;
25396         }
25397         a.push(this.doc.body);
25398         return a;
25399     },
25400     lastSel : false,
25401     lastSelNode : false,
25402     
25403     
25404     getSelection : function() 
25405     {
25406         this.assignDocWin();
25407         return Roo.isIE ? this.doc.selection : this.win.getSelection();
25408     },
25409     
25410     getSelectedNode: function() 
25411     {
25412         // this may only work on Gecko!!!
25413         
25414         // should we cache this!!!!
25415         
25416         
25417         
25418          
25419         var range = this.createRange(this.getSelection()).cloneRange();
25420         
25421         if (Roo.isIE) {
25422             var parent = range.parentElement();
25423             while (true) {
25424                 var testRange = range.duplicate();
25425                 testRange.moveToElementText(parent);
25426                 if (testRange.inRange(range)) {
25427                     break;
25428                 }
25429                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
25430                     break;
25431                 }
25432                 parent = parent.parentElement;
25433             }
25434             return parent;
25435         }
25436         
25437         // is ancestor a text element.
25438         var ac =  range.commonAncestorContainer;
25439         if (ac.nodeType == 3) {
25440             ac = ac.parentNode;
25441         }
25442         
25443         var ar = ac.childNodes;
25444          
25445         var nodes = [];
25446         var other_nodes = [];
25447         var has_other_nodes = false;
25448         for (var i=0;i<ar.length;i++) {
25449             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
25450                 continue;
25451             }
25452             // fullly contained node.
25453             
25454             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
25455                 nodes.push(ar[i]);
25456                 continue;
25457             }
25458             
25459             // probably selected..
25460             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
25461                 other_nodes.push(ar[i]);
25462                 continue;
25463             }
25464             // outer..
25465             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
25466                 continue;
25467             }
25468             
25469             
25470             has_other_nodes = true;
25471         }
25472         if (!nodes.length && other_nodes.length) {
25473             nodes= other_nodes;
25474         }
25475         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
25476             return false;
25477         }
25478         
25479         return nodes[0];
25480     },
25481     createRange: function(sel)
25482     {
25483         // this has strange effects when using with 
25484         // top toolbar - not sure if it's a great idea.
25485         //this.editor.contentWindow.focus();
25486         if (typeof sel != "undefined") {
25487             try {
25488                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
25489             } catch(e) {
25490                 return this.doc.createRange();
25491             }
25492         } else {
25493             return this.doc.createRange();
25494         }
25495     },
25496     getParentElement: function()
25497     {
25498         
25499         this.assignDocWin();
25500         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
25501         
25502         var range = this.createRange(sel);
25503          
25504         try {
25505             var p = range.commonAncestorContainer;
25506             while (p.nodeType == 3) { // text node
25507                 p = p.parentNode;
25508             }
25509             return p;
25510         } catch (e) {
25511             return null;
25512         }
25513     
25514     },
25515     /***
25516      *
25517      * Range intersection.. the hard stuff...
25518      *  '-1' = before
25519      *  '0' = hits..
25520      *  '1' = after.
25521      *         [ -- selected range --- ]
25522      *   [fail]                        [fail]
25523      *
25524      *    basically..
25525      *      if end is before start or  hits it. fail.
25526      *      if start is after end or hits it fail.
25527      *
25528      *   if either hits (but other is outside. - then it's not 
25529      *   
25530      *    
25531      **/
25532     
25533     
25534     // @see http://www.thismuchiknow.co.uk/?p=64.
25535     rangeIntersectsNode : function(range, node)
25536     {
25537         var nodeRange = node.ownerDocument.createRange();
25538         try {
25539             nodeRange.selectNode(node);
25540         } catch (e) {
25541             nodeRange.selectNodeContents(node);
25542         }
25543     
25544         var rangeStartRange = range.cloneRange();
25545         rangeStartRange.collapse(true);
25546     
25547         var rangeEndRange = range.cloneRange();
25548         rangeEndRange.collapse(false);
25549     
25550         var nodeStartRange = nodeRange.cloneRange();
25551         nodeStartRange.collapse(true);
25552     
25553         var nodeEndRange = nodeRange.cloneRange();
25554         nodeEndRange.collapse(false);
25555     
25556         return rangeStartRange.compareBoundaryPoints(
25557                  Range.START_TO_START, nodeEndRange) == -1 &&
25558                rangeEndRange.compareBoundaryPoints(
25559                  Range.START_TO_START, nodeStartRange) == 1;
25560         
25561          
25562     },
25563     rangeCompareNode : function(range, node)
25564     {
25565         var nodeRange = node.ownerDocument.createRange();
25566         try {
25567             nodeRange.selectNode(node);
25568         } catch (e) {
25569             nodeRange.selectNodeContents(node);
25570         }
25571         
25572         
25573         range.collapse(true);
25574     
25575         nodeRange.collapse(true);
25576      
25577         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
25578         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
25579          
25580         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
25581         
25582         var nodeIsBefore   =  ss == 1;
25583         var nodeIsAfter    = ee == -1;
25584         
25585         if (nodeIsBefore && nodeIsAfter)
25586             return 0; // outer
25587         if (!nodeIsBefore && nodeIsAfter)
25588             return 1; //right trailed.
25589         
25590         if (nodeIsBefore && !nodeIsAfter)
25591             return 2;  // left trailed.
25592         // fully contined.
25593         return 3;
25594     },
25595
25596     // private? - in a new class?
25597     cleanUpPaste :  function()
25598     {
25599         // cleans up the whole document..
25600          Roo.log('cleanuppaste');
25601         this.cleanUpChildren(this.doc.body);
25602         var clean = this.cleanWordChars(this.doc.body.innerHTML);
25603         if (clean != this.doc.body.innerHTML) {
25604             this.doc.body.innerHTML = clean;
25605         }
25606         
25607     },
25608     
25609     cleanWordChars : function(input) {// change the chars to hex code
25610         var he = Roo.form.HtmlEditor;
25611         
25612         var output = input;
25613         Roo.each(he.swapCodes, function(sw) { 
25614             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
25615             
25616             output = output.replace(swapper, sw[1]);
25617         });
25618         
25619         return output;
25620     },
25621     
25622     
25623     cleanUpChildren : function (n)
25624     {
25625         if (!n.childNodes.length) {
25626             return;
25627         }
25628         for (var i = n.childNodes.length-1; i > -1 ; i--) {
25629            this.cleanUpChild(n.childNodes[i]);
25630         }
25631     },
25632     
25633     
25634         
25635     
25636     cleanUpChild : function (node)
25637     {
25638         var ed = this;
25639         //console.log(node);
25640         if (node.nodeName == "#text") {
25641             // clean up silly Windows -- stuff?
25642             return; 
25643         }
25644         if (node.nodeName == "#comment") {
25645             node.parentNode.removeChild(node);
25646             // clean up silly Windows -- stuff?
25647             return; 
25648         }
25649         
25650         if (Roo.form.HtmlEditor.black.indexOf(node.tagName.toLowerCase()) > -1) {
25651             // remove node.
25652             node.parentNode.removeChild(node);
25653             return;
25654             
25655         }
25656         
25657         var remove_keep_children= Roo.form.HtmlEditor.remove.indexOf(node.tagName.toLowerCase()) > -1;
25658         
25659         // remove <a name=....> as rendering on yahoo mailer is borked with this.
25660         // this will have to be flaged elsewhere - perhaps ablack=name... on the mailer..
25661         
25662         //if (node.tagName.toLowerCase() == 'a' && !node.hasAttribute('href')) {
25663         //    remove_keep_children = true;
25664         //}
25665         
25666         if (remove_keep_children) {
25667             this.cleanUpChildren(node);
25668             // inserts everything just before this node...
25669             while (node.childNodes.length) {
25670                 var cn = node.childNodes[0];
25671                 node.removeChild(cn);
25672                 node.parentNode.insertBefore(cn, node);
25673             }
25674             node.parentNode.removeChild(node);
25675             return;
25676         }
25677         
25678         if (!node.attributes || !node.attributes.length) {
25679             this.cleanUpChildren(node);
25680             return;
25681         }
25682         
25683         function cleanAttr(n,v)
25684         {
25685             
25686             if (v.match(/^\./) || v.match(/^\//)) {
25687                 return;
25688             }
25689             if (v.match(/^(http|https):\/\//) || v.match(/^mailto:/)) {
25690                 return;
25691             }
25692             if (v.match(/^#/)) {
25693                 return;
25694             }
25695 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
25696             node.removeAttribute(n);
25697             
25698         }
25699         
25700         function cleanStyle(n,v)
25701         {
25702             if (v.match(/expression/)) { //XSS?? should we even bother..
25703                 node.removeAttribute(n);
25704                 return;
25705             }
25706             var cwhite = typeof(ed.cwhite) == 'undefined' ? Roo.form.HtmlEditor.cwhite : ed.cwhite;
25707             var cblack = typeof(ed.cblack) == 'undefined' ? Roo.form.HtmlEditor.cblack : ed.cblack;
25708             
25709             
25710             var parts = v.split(/;/);
25711             var clean = [];
25712             
25713             Roo.each(parts, function(p) {
25714                 p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
25715                 if (!p.length) {
25716                     return true;
25717                 }
25718                 var l = p.split(':').shift().replace(/\s+/g,'');
25719                 l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
25720                 
25721                 
25722                 if ( cblack.indexOf(l) > -1) {
25723 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
25724                     //node.removeAttribute(n);
25725                     return true;
25726                 }
25727                 //Roo.log()
25728                 // only allow 'c whitelisted system attributes'
25729                 if ( cwhite.length &&  cwhite.indexOf(l) < 0) {
25730 //                    Roo.log('(REMOVE CSS)' + node.tagName +'.' + n + ':'+l + '=' + v);
25731                     //node.removeAttribute(n);
25732                     return true;
25733                 }
25734                 
25735                 
25736                  
25737                 
25738                 clean.push(p);
25739                 return true;
25740             });
25741             if (clean.length) { 
25742                 node.setAttribute(n, clean.join(';'));
25743             } else {
25744                 node.removeAttribute(n);
25745             }
25746             
25747         }
25748         
25749         
25750         for (var i = node.attributes.length-1; i > -1 ; i--) {
25751             var a = node.attributes[i];
25752             //console.log(a);
25753             
25754             if (a.name.toLowerCase().substr(0,2)=='on')  {
25755                 node.removeAttribute(a.name);
25756                 continue;
25757             }
25758             if (Roo.form.HtmlEditor.ablack.indexOf(a.name.toLowerCase()) > -1) {
25759                 node.removeAttribute(a.name);
25760                 continue;
25761             }
25762             if (Roo.form.HtmlEditor.aclean.indexOf(a.name.toLowerCase()) > -1) {
25763                 cleanAttr(a.name,a.value); // fixme..
25764                 continue;
25765             }
25766             if (a.name == 'style') {
25767                 cleanStyle(a.name,a.value);
25768                 continue;
25769             }
25770             /// clean up MS crap..
25771             // tecnically this should be a list of valid class'es..
25772             
25773             
25774             if (a.name == 'class') {
25775                 if (a.value.match(/^Mso/)) {
25776                     node.className = '';
25777                 }
25778                 
25779                 if (a.value.match(/body/)) {
25780                     node.className = '';
25781                 }
25782                 continue;
25783             }
25784             
25785             // style cleanup!?
25786             // class cleanup?
25787             
25788         }
25789         
25790         
25791         this.cleanUpChildren(node);
25792         
25793         
25794     }
25795     
25796     
25797     // hide stuff that is not compatible
25798     /**
25799      * @event blur
25800      * @hide
25801      */
25802     /**
25803      * @event change
25804      * @hide
25805      */
25806     /**
25807      * @event focus
25808      * @hide
25809      */
25810     /**
25811      * @event specialkey
25812      * @hide
25813      */
25814     /**
25815      * @cfg {String} fieldClass @hide
25816      */
25817     /**
25818      * @cfg {String} focusClass @hide
25819      */
25820     /**
25821      * @cfg {String} autoCreate @hide
25822      */
25823     /**
25824      * @cfg {String} inputType @hide
25825      */
25826     /**
25827      * @cfg {String} invalidClass @hide
25828      */
25829     /**
25830      * @cfg {String} invalidText @hide
25831      */
25832     /**
25833      * @cfg {String} msgFx @hide
25834      */
25835     /**
25836      * @cfg {String} validateOnBlur @hide
25837      */
25838 });
25839
25840 Roo.form.HtmlEditor.white = [
25841         'area', 'br', 'img', 'input', 'hr', 'wbr',
25842         
25843        'address', 'blockquote', 'center', 'dd',      'dir',       'div', 
25844        'dl',      'dt',         'h1',     'h2',      'h3',        'h4', 
25845        'h5',      'h6',         'hr',     'isindex', 'listing',   'marquee', 
25846        'menu',    'multicol',   'ol',     'p',       'plaintext', 'pre', 
25847        'table',   'ul',         'xmp', 
25848        
25849        'caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 
25850       'thead',   'tr', 
25851      
25852       'dir', 'menu', 'ol', 'ul', 'dl',
25853        
25854       'embed',  'object'
25855 ];
25856
25857
25858 Roo.form.HtmlEditor.black = [
25859     //    'embed',  'object', // enable - backend responsiblity to clean thiese
25860         'applet', // 
25861         'base',   'basefont', 'bgsound', 'blink',  'body', 
25862         'frame',  'frameset', 'head',    'html',   'ilayer', 
25863         'iframe', 'layer',  'link',     'meta',    'object',   
25864         'script', 'style' ,'title',  'xml' // clean later..
25865 ];
25866 Roo.form.HtmlEditor.clean = [
25867     'script', 'style', 'title', 'xml'
25868 ];
25869 Roo.form.HtmlEditor.remove = [
25870     'font'
25871 ];
25872 // attributes..
25873
25874 Roo.form.HtmlEditor.ablack = [
25875     'on'
25876 ];
25877     
25878 Roo.form.HtmlEditor.aclean = [ 
25879     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
25880 ];
25881
25882 // protocols..
25883 Roo.form.HtmlEditor.pwhite= [
25884         'http',  'https',  'mailto'
25885 ];
25886
25887 // white listed style attributes.
25888 Roo.form.HtmlEditor.cwhite= [
25889       //  'text-align', /// default is to allow most things..
25890       
25891          
25892 //        'font-size'//??
25893 ];
25894
25895 // black listed style attributes.
25896 Roo.form.HtmlEditor.cblack= [
25897       //  'font-size' -- this can be set by the project 
25898 ];
25899
25900
25901 Roo.form.HtmlEditor.swapCodes   =[ 
25902     [    8211, "--" ], 
25903     [    8212, "--" ], 
25904     [    8216,  "'" ],  
25905     [    8217, "'" ],  
25906     [    8220, '"' ],  
25907     [    8221, '"' ],  
25908     [    8226, "*" ],  
25909     [    8230, "..." ]
25910 ]; 
25911
25912     // <script type="text/javascript">
25913 /*
25914  * Based on
25915  * Ext JS Library 1.1.1
25916  * Copyright(c) 2006-2007, Ext JS, LLC.
25917  *  
25918  
25919  */
25920
25921 /**
25922  * @class Roo.form.HtmlEditorToolbar1
25923  * Basic Toolbar
25924  * 
25925  * Usage:
25926  *
25927  new Roo.form.HtmlEditor({
25928     ....
25929     toolbars : [
25930         new Roo.form.HtmlEditorToolbar1({
25931             disable : { fonts: 1 , format: 1, ..., ... , ...],
25932             btns : [ .... ]
25933         })
25934     }
25935      
25936  * 
25937  * @cfg {Object} disable List of elements to disable..
25938  * @cfg {Array} btns List of additional buttons.
25939  * 
25940  * 
25941  * NEEDS Extra CSS? 
25942  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
25943  */
25944  
25945 Roo.form.HtmlEditor.ToolbarStandard = function(config)
25946 {
25947     
25948     Roo.apply(this, config);
25949     
25950     // default disabled, based on 'good practice'..
25951     this.disable = this.disable || {};
25952     Roo.applyIf(this.disable, {
25953         fontSize : true,
25954         colors : true,
25955         specialElements : true
25956     });
25957     
25958     
25959     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
25960     // dont call parent... till later.
25961 }
25962
25963 Roo.apply(Roo.form.HtmlEditor.ToolbarStandard.prototype,  {
25964     
25965     tb: false,
25966     
25967     rendered: false,
25968     
25969     editor : false,
25970     /**
25971      * @cfg {Object} disable  List of toolbar elements to disable
25972          
25973      */
25974     disable : false,
25975       /**
25976      * @cfg {Array} fontFamilies An array of available font families
25977      */
25978     fontFamilies : [
25979         'Arial',
25980         'Courier New',
25981         'Tahoma',
25982         'Times New Roman',
25983         'Verdana'
25984     ],
25985     
25986     specialChars : [
25987            "&#169;",
25988           "&#174;",     
25989           "&#8482;",    
25990           "&#163;" ,    
25991          // "&#8212;",    
25992           "&#8230;",    
25993           "&#247;" ,    
25994         //  "&#225;" ,     ?? a acute?
25995            "&#8364;"    , //Euro
25996        //   "&#8220;"    ,
25997         //  "&#8221;"    ,
25998         //  "&#8226;"    ,
25999           "&#176;"  //   , // degrees
26000
26001          // "&#233;"     , // e ecute
26002          // "&#250;"     , // u ecute?
26003     ],
26004     
26005     specialElements : [
26006         {
26007             text: "Insert Table",
26008             xtype: 'MenuItem',
26009             xns : Roo.Menu,
26010             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
26011                 
26012         },
26013         {    
26014             text: "Insert Image",
26015             xtype: 'MenuItem',
26016             xns : Roo.Menu,
26017             ihtml : '<img src="about:blank"/>'
26018             
26019         }
26020         
26021          
26022     ],
26023     
26024     
26025     inputElements : [ 
26026             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
26027             "input:submit", "input:button", "select", "textarea", "label" ],
26028     formats : [
26029         ["p"] ,  
26030         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
26031         ["pre"],[ "code"], 
26032         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
26033         ['div'],['span']
26034     ],
26035     
26036     cleanStyles : [
26037         "font-size"
26038     ],
26039      /**
26040      * @cfg {String} defaultFont default font to use.
26041      */
26042     defaultFont: 'tahoma',
26043    
26044     fontSelect : false,
26045     
26046     
26047     formatCombo : false,
26048     
26049     init : function(editor)
26050     {
26051         this.editor = editor;
26052         
26053         
26054         var fid = editor.frameId;
26055         var etb = this;
26056         function btn(id, toggle, handler){
26057             var xid = fid + '-'+ id ;
26058             return {
26059                 id : xid,
26060                 cmd : id,
26061                 cls : 'x-btn-icon x-edit-'+id,
26062                 enableToggle:toggle !== false,
26063                 scope: editor, // was editor...
26064                 handler:handler||editor.relayBtnCmd,
26065                 clickEvent:'mousedown',
26066                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
26067                 tabIndex:-1
26068             };
26069         }
26070         
26071         
26072         
26073         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
26074         this.tb = tb;
26075          // stop form submits
26076         tb.el.on('click', function(e){
26077             e.preventDefault(); // what does this do?
26078         });
26079
26080         if(!this.disable.font) { // && !Roo.isSafari){
26081             /* why no safari for fonts 
26082             editor.fontSelect = tb.el.createChild({
26083                 tag:'select',
26084                 tabIndex: -1,
26085                 cls:'x-font-select',
26086                 html: this.createFontOptions()
26087             });
26088             
26089             editor.fontSelect.on('change', function(){
26090                 var font = editor.fontSelect.dom.value;
26091                 editor.relayCmd('fontname', font);
26092                 editor.deferFocus();
26093             }, editor);
26094             
26095             tb.add(
26096                 editor.fontSelect.dom,
26097                 '-'
26098             );
26099             */
26100             
26101         };
26102         if(!this.disable.formats){
26103             this.formatCombo = new Roo.form.ComboBox({
26104                 store: new Roo.data.SimpleStore({
26105                     id : 'tag',
26106                     fields: ['tag'],
26107                     data : this.formats // from states.js
26108                 }),
26109                 blockFocus : true,
26110                 name : '',
26111                 //autoCreate : {tag: "div",  size: "20"},
26112                 displayField:'tag',
26113                 typeAhead: false,
26114                 mode: 'local',
26115                 editable : false,
26116                 triggerAction: 'all',
26117                 emptyText:'Add tag',
26118                 selectOnFocus:true,
26119                 width:135,
26120                 listeners : {
26121                     'select': function(c, r, i) {
26122                         editor.insertTag(r.get('tag'));
26123                         editor.focus();
26124                     }
26125                 }
26126
26127             });
26128             tb.addField(this.formatCombo);
26129             
26130         }
26131         
26132         if(!this.disable.format){
26133             tb.add(
26134                 btn('bold'),
26135                 btn('italic'),
26136                 btn('underline')
26137             );
26138         };
26139         if(!this.disable.fontSize){
26140             tb.add(
26141                 '-',
26142                 
26143                 
26144                 btn('increasefontsize', false, editor.adjustFont),
26145                 btn('decreasefontsize', false, editor.adjustFont)
26146             );
26147         };
26148         
26149         
26150         if(!this.disable.colors){
26151             tb.add(
26152                 '-', {
26153                     id:editor.frameId +'-forecolor',
26154                     cls:'x-btn-icon x-edit-forecolor',
26155                     clickEvent:'mousedown',
26156                     tooltip: this.buttonTips['forecolor'] || undefined,
26157                     tabIndex:-1,
26158                     menu : new Roo.menu.ColorMenu({
26159                         allowReselect: true,
26160                         focus: Roo.emptyFn,
26161                         value:'000000',
26162                         plain:true,
26163                         selectHandler: function(cp, color){
26164                             editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
26165                             editor.deferFocus();
26166                         },
26167                         scope: editor,
26168                         clickEvent:'mousedown'
26169                     })
26170                 }, {
26171                     id:editor.frameId +'backcolor',
26172                     cls:'x-btn-icon x-edit-backcolor',
26173                     clickEvent:'mousedown',
26174                     tooltip: this.buttonTips['backcolor'] || undefined,
26175                     tabIndex:-1,
26176                     menu : new Roo.menu.ColorMenu({
26177                         focus: Roo.emptyFn,
26178                         value:'FFFFFF',
26179                         plain:true,
26180                         allowReselect: true,
26181                         selectHandler: function(cp, color){
26182                             if(Roo.isGecko){
26183                                 editor.execCmd('useCSS', false);
26184                                 editor.execCmd('hilitecolor', color);
26185                                 editor.execCmd('useCSS', true);
26186                                 editor.deferFocus();
26187                             }else{
26188                                 editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
26189                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
26190                                 editor.deferFocus();
26191                             }
26192                         },
26193                         scope:editor,
26194                         clickEvent:'mousedown'
26195                     })
26196                 }
26197             );
26198         };
26199         // now add all the items...
26200         
26201
26202         if(!this.disable.alignments){
26203             tb.add(
26204                 '-',
26205                 btn('justifyleft'),
26206                 btn('justifycenter'),
26207                 btn('justifyright')
26208             );
26209         };
26210
26211         //if(!Roo.isSafari){
26212             if(!this.disable.links){
26213                 tb.add(
26214                     '-',
26215                     btn('createlink', false, editor.createLink)    /// MOVE TO HERE?!!?!?!?!
26216                 );
26217             };
26218
26219             if(!this.disable.lists){
26220                 tb.add(
26221                     '-',
26222                     btn('insertorderedlist'),
26223                     btn('insertunorderedlist')
26224                 );
26225             }
26226             if(!this.disable.sourceEdit){
26227                 tb.add(
26228                     '-',
26229                     btn('sourceedit', true, function(btn){
26230                         this.toggleSourceEdit(btn.pressed);
26231                     })
26232                 );
26233             }
26234         //}
26235         
26236         var smenu = { };
26237         // special menu.. - needs to be tidied up..
26238         if (!this.disable.special) {
26239             smenu = {
26240                 text: "&#169;",
26241                 cls: 'x-edit-none',
26242                 
26243                 menu : {
26244                     items : []
26245                 }
26246             };
26247             for (var i =0; i < this.specialChars.length; i++) {
26248                 smenu.menu.items.push({
26249                     
26250                     html: this.specialChars[i],
26251                     handler: function(a,b) {
26252                         editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
26253                         //editor.insertAtCursor(a.html);
26254                         
26255                     },
26256                     tabIndex:-1
26257                 });
26258             }
26259             
26260             
26261             tb.add(smenu);
26262             
26263             
26264         }
26265         
26266         var cmenu = { };
26267         if (!this.disable.cleanStyles) {
26268             cmenu = {
26269                 cls: 'x-btn-icon x-btn-clear',
26270                 
26271                 menu : {
26272                     items : []
26273                 }
26274             };
26275             for (var i =0; i < this.cleanStyles.length; i++) {
26276                 cmenu.menu.items.push({
26277                     actiontype : this.cleanStyles[i],
26278                     html: 'Remove ' + this.cleanStyles[i],
26279                     handler: function(a,b) {
26280                         Roo.log(a);
26281                         Roo.log(b);
26282                         var c = Roo.get(editor.doc.body);
26283                         c.select('[style]').each(function(s) {
26284                             s.dom.style.removeProperty(a.actiontype);
26285                         });
26286                         
26287                     },
26288                     tabIndex:-1
26289                 });
26290             }
26291             
26292             tb.add(cmenu);
26293         }
26294          
26295         if (!this.disable.specialElements) {
26296             var semenu = {
26297                 text: "Other;",
26298                 cls: 'x-edit-none',
26299                 menu : {
26300                     items : []
26301                 }
26302             };
26303             for (var i =0; i < this.specialElements.length; i++) {
26304                 semenu.menu.items.push(
26305                     Roo.apply({ 
26306                         handler: function(a,b) {
26307                             editor.insertAtCursor(this.ihtml);
26308                         }
26309                     }, this.specialElements[i])
26310                 );
26311                     
26312             }
26313             
26314             tb.add(semenu);
26315             
26316             
26317         }
26318          
26319         
26320         if (this.btns) {
26321             for(var i =0; i< this.btns.length;i++) {
26322                 var b = Roo.factory(this.btns[i],Roo.form);
26323                 b.cls =  'x-edit-none';
26324                 b.scope = editor;
26325                 tb.add(b);
26326             }
26327         
26328         }
26329         
26330         
26331         
26332         // disable everything...
26333         
26334         this.tb.items.each(function(item){
26335            if(item.id != editor.frameId+ '-sourceedit'){
26336                 item.disable();
26337             }
26338         });
26339         this.rendered = true;
26340         
26341         // the all the btns;
26342         editor.on('editorevent', this.updateToolbar, this);
26343         // other toolbars need to implement this..
26344         //editor.on('editmodechange', this.updateToolbar, this);
26345     },
26346     
26347     
26348     
26349     /**
26350      * Protected method that will not generally be called directly. It triggers
26351      * a toolbar update by reading the markup state of the current selection in the editor.
26352      */
26353     updateToolbar: function(){
26354
26355         if(!this.editor.activated){
26356             this.editor.onFirstFocus();
26357             return;
26358         }
26359
26360         var btns = this.tb.items.map, 
26361             doc = this.editor.doc,
26362             frameId = this.editor.frameId;
26363
26364         if(!this.disable.font && !Roo.isSafari){
26365             /*
26366             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
26367             if(name != this.fontSelect.dom.value){
26368                 this.fontSelect.dom.value = name;
26369             }
26370             */
26371         }
26372         if(!this.disable.format){
26373             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
26374             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
26375             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
26376         }
26377         if(!this.disable.alignments){
26378             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
26379             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
26380             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
26381         }
26382         if(!Roo.isSafari && !this.disable.lists){
26383             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
26384             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
26385         }
26386         
26387         var ans = this.editor.getAllAncestors();
26388         if (this.formatCombo) {
26389             
26390             
26391             var store = this.formatCombo.store;
26392             this.formatCombo.setValue("");
26393             for (var i =0; i < ans.length;i++) {
26394                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
26395                     // select it..
26396                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
26397                     break;
26398                 }
26399             }
26400         }
26401         
26402         
26403         
26404         // hides menus... - so this cant be on a menu...
26405         Roo.menu.MenuMgr.hideAll();
26406
26407         //this.editorsyncValue();
26408     },
26409    
26410     
26411     createFontOptions : function(){
26412         var buf = [], fs = this.fontFamilies, ff, lc;
26413         
26414         
26415         
26416         for(var i = 0, len = fs.length; i< len; i++){
26417             ff = fs[i];
26418             lc = ff.toLowerCase();
26419             buf.push(
26420                 '<option value="',lc,'" style="font-family:',ff,';"',
26421                     (this.defaultFont == lc ? ' selected="true">' : '>'),
26422                     ff,
26423                 '</option>'
26424             );
26425         }
26426         return buf.join('');
26427     },
26428     
26429     toggleSourceEdit : function(sourceEditMode){
26430         if(sourceEditMode === undefined){
26431             sourceEditMode = !this.sourceEditMode;
26432         }
26433         this.sourceEditMode = sourceEditMode === true;
26434         var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
26435         // just toggle the button?
26436         if(btn.pressed !== this.editor.sourceEditMode){
26437             btn.toggle(this.editor.sourceEditMode);
26438             return;
26439         }
26440         
26441         if(this.sourceEditMode){
26442             this.tb.items.each(function(item){
26443                 if(item.cmd != 'sourceedit'){
26444                     item.disable();
26445                 }
26446             });
26447           
26448         }else{
26449             if(this.initialized){
26450                 this.tb.items.each(function(item){
26451                     item.enable();
26452                 });
26453             }
26454             
26455         }
26456         // tell the editor that it's been pressed..
26457         this.editor.toggleSourceEdit(sourceEditMode);
26458        
26459     },
26460      /**
26461      * Object collection of toolbar tooltips for the buttons in the editor. The key
26462      * is the command id associated with that button and the value is a valid QuickTips object.
26463      * For example:
26464 <pre><code>
26465 {
26466     bold : {
26467         title: 'Bold (Ctrl+B)',
26468         text: 'Make the selected text bold.',
26469         cls: 'x-html-editor-tip'
26470     },
26471     italic : {
26472         title: 'Italic (Ctrl+I)',
26473         text: 'Make the selected text italic.',
26474         cls: 'x-html-editor-tip'
26475     },
26476     ...
26477 </code></pre>
26478     * @type Object
26479      */
26480     buttonTips : {
26481         bold : {
26482             title: 'Bold (Ctrl+B)',
26483             text: 'Make the selected text bold.',
26484             cls: 'x-html-editor-tip'
26485         },
26486         italic : {
26487             title: 'Italic (Ctrl+I)',
26488             text: 'Make the selected text italic.',
26489             cls: 'x-html-editor-tip'
26490         },
26491         underline : {
26492             title: 'Underline (Ctrl+U)',
26493             text: 'Underline the selected text.',
26494             cls: 'x-html-editor-tip'
26495         },
26496         increasefontsize : {
26497             title: 'Grow Text',
26498             text: 'Increase the font size.',
26499             cls: 'x-html-editor-tip'
26500         },
26501         decreasefontsize : {
26502             title: 'Shrink Text',
26503             text: 'Decrease the font size.',
26504             cls: 'x-html-editor-tip'
26505         },
26506         backcolor : {
26507             title: 'Text Highlight Color',
26508             text: 'Change the background color of the selected text.',
26509             cls: 'x-html-editor-tip'
26510         },
26511         forecolor : {
26512             title: 'Font Color',
26513             text: 'Change the color of the selected text.',
26514             cls: 'x-html-editor-tip'
26515         },
26516         justifyleft : {
26517             title: 'Align Text Left',
26518             text: 'Align text to the left.',
26519             cls: 'x-html-editor-tip'
26520         },
26521         justifycenter : {
26522             title: 'Center Text',
26523             text: 'Center text in the editor.',
26524             cls: 'x-html-editor-tip'
26525         },
26526         justifyright : {
26527             title: 'Align Text Right',
26528             text: 'Align text to the right.',
26529             cls: 'x-html-editor-tip'
26530         },
26531         insertunorderedlist : {
26532             title: 'Bullet List',
26533             text: 'Start a bulleted list.',
26534             cls: 'x-html-editor-tip'
26535         },
26536         insertorderedlist : {
26537             title: 'Numbered List',
26538             text: 'Start a numbered list.',
26539             cls: 'x-html-editor-tip'
26540         },
26541         createlink : {
26542             title: 'Hyperlink',
26543             text: 'Make the selected text a hyperlink.',
26544             cls: 'x-html-editor-tip'
26545         },
26546         sourceedit : {
26547             title: 'Source Edit',
26548             text: 'Switch to source editing mode.',
26549             cls: 'x-html-editor-tip'
26550         }
26551     },
26552     // private
26553     onDestroy : function(){
26554         if(this.rendered){
26555             
26556             this.tb.items.each(function(item){
26557                 if(item.menu){
26558                     item.menu.removeAll();
26559                     if(item.menu.el){
26560                         item.menu.el.destroy();
26561                     }
26562                 }
26563                 item.destroy();
26564             });
26565              
26566         }
26567     },
26568     onFirstFocus: function() {
26569         this.tb.items.each(function(item){
26570            item.enable();
26571         });
26572     }
26573 });
26574
26575
26576
26577
26578 // <script type="text/javascript">
26579 /*
26580  * Based on
26581  * Ext JS Library 1.1.1
26582  * Copyright(c) 2006-2007, Ext JS, LLC.
26583  *  
26584  
26585  */
26586
26587  
26588 /**
26589  * @class Roo.form.HtmlEditor.ToolbarContext
26590  * Context Toolbar
26591  * 
26592  * Usage:
26593  *
26594  new Roo.form.HtmlEditor({
26595     ....
26596     toolbars : [
26597         { xtype: 'ToolbarStandard', styles : {} }
26598         { xtype: 'ToolbarContext', disable : {} }
26599     ]
26600 })
26601
26602      
26603  * 
26604  * @config : {Object} disable List of elements to disable.. (not done yet.)
26605  * @config : {Object} styles  Map of styles available.
26606  * 
26607  */
26608
26609 Roo.form.HtmlEditor.ToolbarContext = function(config)
26610 {
26611     
26612     Roo.apply(this, config);
26613     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
26614     // dont call parent... till later.
26615     this.styles = this.styles || {};
26616 }
26617
26618  
26619
26620 Roo.form.HtmlEditor.ToolbarContext.types = {
26621     'IMG' : {
26622         width : {
26623             title: "Width",
26624             width: 40
26625         },
26626         height:  {
26627             title: "Height",
26628             width: 40
26629         },
26630         align: {
26631             title: "Align",
26632             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
26633             width : 80
26634             
26635         },
26636         border: {
26637             title: "Border",
26638             width: 40
26639         },
26640         alt: {
26641             title: "Alt",
26642             width: 120
26643         },
26644         src : {
26645             title: "Src",
26646             width: 220
26647         }
26648         
26649     },
26650     'A' : {
26651         name : {
26652             title: "Name",
26653             width: 50
26654         },
26655         target:  {
26656             title: "Target",
26657             width: 120
26658         },
26659         href:  {
26660             title: "Href",
26661             width: 220
26662         } // border?
26663         
26664     },
26665     'TABLE' : {
26666         rows : {
26667             title: "Rows",
26668             width: 20
26669         },
26670         cols : {
26671             title: "Cols",
26672             width: 20
26673         },
26674         width : {
26675             title: "Width",
26676             width: 40
26677         },
26678         height : {
26679             title: "Height",
26680             width: 40
26681         },
26682         border : {
26683             title: "Border",
26684             width: 20
26685         }
26686     },
26687     'TD' : {
26688         width : {
26689             title: "Width",
26690             width: 40
26691         },
26692         height : {
26693             title: "Height",
26694             width: 40
26695         },   
26696         align: {
26697             title: "Align",
26698             opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
26699             width: 80
26700         },
26701         valign: {
26702             title: "Valign",
26703             opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
26704             width: 80
26705         },
26706         colspan: {
26707             title: "Colspan",
26708             width: 20
26709             
26710         },
26711          'font-family'  : {
26712             title : "Font",
26713             style : 'fontFamily',
26714             displayField: 'display',
26715             optname : 'font-family',
26716             width: 140
26717         }
26718     },
26719     'INPUT' : {
26720         name : {
26721             title: "name",
26722             width: 120
26723         },
26724         value : {
26725             title: "Value",
26726             width: 120
26727         },
26728         width : {
26729             title: "Width",
26730             width: 40
26731         }
26732     },
26733     'LABEL' : {
26734         'for' : {
26735             title: "For",
26736             width: 120
26737         }
26738     },
26739     'TEXTAREA' : {
26740           name : {
26741             title: "name",
26742             width: 120
26743         },
26744         rows : {
26745             title: "Rows",
26746             width: 20
26747         },
26748         cols : {
26749             title: "Cols",
26750             width: 20
26751         }
26752     },
26753     'SELECT' : {
26754         name : {
26755             title: "name",
26756             width: 120
26757         },
26758         selectoptions : {
26759             title: "Options",
26760             width: 200
26761         }
26762     },
26763     
26764     // should we really allow this??
26765     // should this just be 
26766     'BODY' : {
26767         title : {
26768             title: "Title",
26769             width: 200,
26770             disabled : true
26771         }
26772     },
26773     'SPAN' : {
26774         'font-family'  : {
26775             title : "Font",
26776             style : 'fontFamily',
26777             displayField: 'display',
26778             optname : 'font-family',
26779             width: 140
26780         }
26781     },
26782     'DIV' : {
26783         'font-family'  : {
26784             title : "Font",
26785             style : 'fontFamily',
26786             displayField: 'display',
26787             optname : 'font-family',
26788             width: 140
26789         }
26790     },
26791      'P' : {
26792         'font-family'  : {
26793             title : "Font",
26794             style : 'fontFamily',
26795             displayField: 'display',
26796             optname : 'font-family',
26797             width: 140
26798         }
26799     },
26800     
26801     '*' : {
26802         // empty..
26803     }
26804
26805 };
26806
26807 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
26808 Roo.form.HtmlEditor.ToolbarContext.stores = false;
26809
26810 Roo.form.HtmlEditor.ToolbarContext.options = {
26811         'font-family'  : [ 
26812                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
26813                 [ 'Courier New', 'Courier New'],
26814                 [ 'Tahoma', 'Tahoma'],
26815                 [ 'Times New Roman,serif', 'Times'],
26816                 [ 'Verdana','Verdana' ]
26817         ]
26818 };
26819
26820 // fixme - these need to be configurable..
26821  
26822
26823 Roo.form.HtmlEditor.ToolbarContext.types
26824
26825
26826 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
26827     
26828     tb: false,
26829     
26830     rendered: false,
26831     
26832     editor : false,
26833     /**
26834      * @cfg {Object} disable  List of toolbar elements to disable
26835          
26836      */
26837     disable : false,
26838     /**
26839      * @cfg {Object} styles List of styles 
26840      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
26841      *
26842      * These must be defined in the page, so they get rendered correctly..
26843      * .headline { }
26844      * TD.underline { }
26845      * 
26846      */
26847     styles : false,
26848     
26849     options: false,
26850     
26851     toolbars : false,
26852     
26853     init : function(editor)
26854     {
26855         this.editor = editor;
26856         
26857         
26858         var fid = editor.frameId;
26859         var etb = this;
26860         function btn(id, toggle, handler){
26861             var xid = fid + '-'+ id ;
26862             return {
26863                 id : xid,
26864                 cmd : id,
26865                 cls : 'x-btn-icon x-edit-'+id,
26866                 enableToggle:toggle !== false,
26867                 scope: editor, // was editor...
26868                 handler:handler||editor.relayBtnCmd,
26869                 clickEvent:'mousedown',
26870                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
26871                 tabIndex:-1
26872             };
26873         }
26874         // create a new element.
26875         var wdiv = editor.wrap.createChild({
26876                 tag: 'div'
26877             }, editor.wrap.dom.firstChild.nextSibling, true);
26878         
26879         // can we do this more than once??
26880         
26881          // stop form submits
26882       
26883  
26884         // disable everything...
26885         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
26886         this.toolbars = {};
26887            
26888         for (var i in  ty) {
26889           
26890             this.toolbars[i] = this.buildToolbar(ty[i],i);
26891         }
26892         this.tb = this.toolbars.BODY;
26893         this.tb.el.show();
26894         this.buildFooter();
26895         this.footer.show();
26896         editor.on('hide', function( ) { this.footer.hide() }, this);
26897         editor.on('show', function( ) { this.footer.show() }, this);
26898         
26899          
26900         this.rendered = true;
26901         
26902         // the all the btns;
26903         editor.on('editorevent', this.updateToolbar, this);
26904         // other toolbars need to implement this..
26905         //editor.on('editmodechange', this.updateToolbar, this);
26906     },
26907     
26908     
26909     
26910     /**
26911      * Protected method that will not generally be called directly. It triggers
26912      * a toolbar update by reading the markup state of the current selection in the editor.
26913      */
26914     updateToolbar: function(editor,ev,sel){
26915
26916         //Roo.log(ev);
26917         // capture mouse up - this is handy for selecting images..
26918         // perhaps should go somewhere else...
26919         if(!this.editor.activated){
26920              this.editor.onFirstFocus();
26921             return;
26922         }
26923         
26924         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
26925         // selectNode - might want to handle IE?
26926         if (ev &&
26927             (ev.type == 'mouseup' || ev.type == 'click' ) &&
26928             ev.target && ev.target.tagName == 'IMG') {
26929             // they have click on an image...
26930             // let's see if we can change the selection...
26931             sel = ev.target;
26932          
26933               var nodeRange = sel.ownerDocument.createRange();
26934             try {
26935                 nodeRange.selectNode(sel);
26936             } catch (e) {
26937                 nodeRange.selectNodeContents(sel);
26938             }
26939             //nodeRange.collapse(true);
26940             var s = editor.win.getSelection();
26941             s.removeAllRanges();
26942             s.addRange(nodeRange);
26943         }  
26944         
26945       
26946         var updateFooter = sel ? false : true;
26947         
26948         
26949         var ans = this.editor.getAllAncestors();
26950         
26951         // pick
26952         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
26953         
26954         if (!sel) { 
26955             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editor.doc.body;
26956             sel = sel ? sel : this.editor.doc.body;
26957             sel = sel.tagName.length ? sel : this.editor.doc.body;
26958             
26959         }
26960         // pick a menu that exists..
26961         var tn = sel.tagName.toUpperCase();
26962         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
26963         
26964         tn = sel.tagName.toUpperCase();
26965         
26966         var lastSel = this.tb.selectedNode
26967         
26968         this.tb.selectedNode = sel;
26969         
26970         // if current menu does not match..
26971         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
26972                 
26973             this.tb.el.hide();
26974             ///console.log("show: " + tn);
26975             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
26976             this.tb.el.show();
26977             // update name
26978             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
26979             
26980             
26981             // update attributes
26982             if (this.tb.fields) {
26983                 this.tb.fields.each(function(e) {
26984                     if (e.stylename) {
26985                         e.setValue(sel.style[e.stylename]);
26986                         return;
26987                     } 
26988                    e.setValue(sel.getAttribute(e.attrname));
26989                 });
26990             }
26991             
26992             var hasStyles = false;
26993             for(var i in this.styles) {
26994                 hasStyles = true;
26995                 break;
26996             }
26997             
26998             // update styles
26999             if (hasStyles) { 
27000                 var st = this.tb.fields.item(0);
27001                 
27002                 st.store.removeAll();
27003                
27004                 
27005                 var cn = sel.className.split(/\s+/);
27006                 
27007                 var avs = [];
27008                 if (this.styles['*']) {
27009                     
27010                     Roo.each(this.styles['*'], function(v) {
27011                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
27012                     });
27013                 }
27014                 if (this.styles[tn]) { 
27015                     Roo.each(this.styles[tn], function(v) {
27016                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
27017                     });
27018                 }
27019                 
27020                 st.store.loadData(avs);
27021                 st.collapse();
27022                 st.setValue(cn);
27023             }
27024             // flag our selected Node.
27025             this.tb.selectedNode = sel;
27026            
27027            
27028             Roo.menu.MenuMgr.hideAll();
27029
27030         }
27031         
27032         if (!updateFooter) {
27033             //this.footDisp.dom.innerHTML = ''; 
27034             return;
27035         }
27036         // update the footer
27037         //
27038         var html = '';
27039         
27040         this.footerEls = ans.reverse();
27041         Roo.each(this.footerEls, function(a,i) {
27042             if (!a) { return; }
27043             html += html.length ? ' &gt; '  :  '';
27044             
27045             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
27046             
27047         });
27048        
27049         // 
27050         var sz = this.footDisp.up('td').getSize();
27051         this.footDisp.dom.style.width = (sz.width -10) + 'px';
27052         this.footDisp.dom.style.marginLeft = '5px';
27053         
27054         this.footDisp.dom.style.overflow = 'hidden';
27055         
27056         this.footDisp.dom.innerHTML = html;
27057             
27058         //this.editorsyncValue();
27059     },
27060      
27061     
27062    
27063        
27064     // private
27065     onDestroy : function(){
27066         if(this.rendered){
27067             
27068             this.tb.items.each(function(item){
27069                 if(item.menu){
27070                     item.menu.removeAll();
27071                     if(item.menu.el){
27072                         item.menu.el.destroy();
27073                     }
27074                 }
27075                 item.destroy();
27076             });
27077              
27078         }
27079     },
27080     onFirstFocus: function() {
27081         // need to do this for all the toolbars..
27082         this.tb.items.each(function(item){
27083            item.enable();
27084         });
27085     },
27086     buildToolbar: function(tlist, nm)
27087     {
27088         var editor = this.editor;
27089          // create a new element.
27090         var wdiv = editor.wrap.createChild({
27091                 tag: 'div'
27092             }, editor.wrap.dom.firstChild.nextSibling, true);
27093         
27094        
27095         var tb = new Roo.Toolbar(wdiv);
27096         // add the name..
27097         
27098         tb.add(nm+ ":&nbsp;");
27099         
27100         var styles = [];
27101         for(var i in this.styles) {
27102             styles.push(i);
27103         }
27104         
27105         // styles...
27106         if (styles && styles.length) {
27107             
27108             // this needs a multi-select checkbox...
27109             tb.addField( new Roo.form.ComboBox({
27110                 store: new Roo.data.SimpleStore({
27111                     id : 'val',
27112                     fields: ['val', 'selected'],
27113                     data : [] 
27114                 }),
27115                 name : '-roo-edit-className',
27116                 attrname : 'className',
27117                 displayField: 'val',
27118                 typeAhead: false,
27119                 mode: 'local',
27120                 editable : false,
27121                 triggerAction: 'all',
27122                 emptyText:'Select Style',
27123                 selectOnFocus:true,
27124                 width: 130,
27125                 listeners : {
27126                     'select': function(c, r, i) {
27127                         // initial support only for on class per el..
27128                         tb.selectedNode.className =  r ? r.get('val') : '';
27129                         editor.syncValue();
27130                     }
27131                 }
27132     
27133             }));
27134         }
27135         
27136         var tbc = Roo.form.HtmlEditor.ToolbarContext;
27137         var tbops = tbc.options;
27138         
27139         for (var i in tlist) {
27140             
27141             var item = tlist[i];
27142             tb.add(item.title + ":&nbsp;");
27143             
27144             
27145             //optname == used so you can configure the options available..
27146             var opts = item.opts ? item.opts : false;
27147             if (item.optname) {
27148                 opts = tbops[item.optname];
27149            
27150             }
27151             
27152             if (opts) {
27153                 // opts == pulldown..
27154                 tb.addField( new Roo.form.ComboBox({
27155                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
27156                         id : 'val',
27157                         fields: ['val', 'display'],
27158                         data : opts  
27159                     }),
27160                     name : '-roo-edit-' + i,
27161                     attrname : i,
27162                     stylename : item.style ? item.style : false,
27163                     displayField: item.displayField ? item.displayField : 'val',
27164                     valueField :  'val',
27165                     typeAhead: false,
27166                     mode: typeof(tbc.stores[i]) != 'undefined'  ? 'remote' : 'local',
27167                     editable : false,
27168                     triggerAction: 'all',
27169                     emptyText:'Select',
27170                     selectOnFocus:true,
27171                     width: item.width ? item.width  : 130,
27172                     listeners : {
27173                         'select': function(c, r, i) {
27174                             if (c.stylename) {
27175                                 tb.selectedNode.style[c.stylename] =  r.get('val');
27176                                 return;
27177                             }
27178                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
27179                         }
27180                     }
27181
27182                 }));
27183                 continue;
27184                     
27185                  
27186                 
27187                 tb.addField( new Roo.form.TextField({
27188                     name: i,
27189                     width: 100,
27190                     //allowBlank:false,
27191                     value: ''
27192                 }));
27193                 continue;
27194             }
27195             tb.addField( new Roo.form.TextField({
27196                 name: '-roo-edit-' + i,
27197                 attrname : i,
27198                 
27199                 width: item.width,
27200                 //allowBlank:true,
27201                 value: '',
27202                 listeners: {
27203                     'change' : function(f, nv, ov) {
27204                         tb.selectedNode.setAttribute(f.attrname, nv);
27205                     }
27206                 }
27207             }));
27208              
27209         }
27210         tb.addFill();
27211         var _this = this;
27212         tb.addButton( {
27213             text: 'Remove Tag',
27214     
27215             listeners : {
27216                 click : function ()
27217                 {
27218                     // remove
27219                     // undo does not work.
27220                      
27221                     var sn = tb.selectedNode;
27222                     
27223                     var pn = sn.parentNode;
27224                     
27225                     var stn =  sn.childNodes[0];
27226                     var en = sn.childNodes[sn.childNodes.length - 1 ];
27227                     while (sn.childNodes.length) {
27228                         var node = sn.childNodes[0];
27229                         sn.removeChild(node);
27230                         //Roo.log(node);
27231                         pn.insertBefore(node, sn);
27232                         
27233                     }
27234                     pn.removeChild(sn);
27235                     var range = editor.createRange();
27236         
27237                     range.setStart(stn,0);
27238                     range.setEnd(en,0); //????
27239                     //range.selectNode(sel);
27240                     
27241                     
27242                     var selection = editor.getSelection();
27243                     selection.removeAllRanges();
27244                     selection.addRange(range);
27245                     
27246                     
27247                     
27248                     //_this.updateToolbar(null, null, pn);
27249                     _this.updateToolbar(null, null, null);
27250                     _this.footDisp.dom.innerHTML = ''; 
27251                 }
27252             }
27253             
27254                     
27255                 
27256             
27257         });
27258         
27259         
27260         tb.el.on('click', function(e){
27261             e.preventDefault(); // what does this do?
27262         });
27263         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
27264         tb.el.hide();
27265         tb.name = nm;
27266         // dont need to disable them... as they will get hidden
27267         return tb;
27268          
27269         
27270     },
27271     buildFooter : function()
27272     {
27273         
27274         var fel = this.editor.wrap.createChild();
27275         this.footer = new Roo.Toolbar(fel);
27276         // toolbar has scrolly on left / right?
27277         var footDisp= new Roo.Toolbar.Fill();
27278         var _t = this;
27279         this.footer.add(
27280             {
27281                 text : '&lt;',
27282                 xtype: 'Button',
27283                 handler : function() {
27284                     _t.footDisp.scrollTo('left',0,true)
27285                 }
27286             }
27287         );
27288         this.footer.add( footDisp );
27289         this.footer.add( 
27290             {
27291                 text : '&gt;',
27292                 xtype: 'Button',
27293                 handler : function() {
27294                     // no animation..
27295                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
27296                 }
27297             }
27298         );
27299         var fel = Roo.get(footDisp.el);
27300         fel.addClass('x-editor-context');
27301         this.footDispWrap = fel; 
27302         this.footDispWrap.overflow  = 'hidden';
27303         
27304         this.footDisp = fel.createChild();
27305         this.footDispWrap.on('click', this.onContextClick, this)
27306         
27307         
27308     },
27309     onContextClick : function (ev,dom)
27310     {
27311         ev.preventDefault();
27312         var  cn = dom.className;
27313         //Roo.log(cn);
27314         if (!cn.match(/x-ed-loc-/)) {
27315             return;
27316         }
27317         var n = cn.split('-').pop();
27318         var ans = this.footerEls;
27319         var sel = ans[n];
27320         
27321          // pick
27322         var range = this.editor.createRange();
27323         
27324         range.selectNodeContents(sel);
27325         //range.selectNode(sel);
27326         
27327         
27328         var selection = this.editor.getSelection();
27329         selection.removeAllRanges();
27330         selection.addRange(range);
27331         
27332         
27333         
27334         this.updateToolbar(null, null, sel);
27335         
27336         
27337     }
27338     
27339     
27340     
27341     
27342     
27343 });
27344
27345
27346
27347
27348
27349 /*
27350  * Based on:
27351  * Ext JS Library 1.1.1
27352  * Copyright(c) 2006-2007, Ext JS, LLC.
27353  *
27354  * Originally Released Under LGPL - original licence link has changed is not relivant.
27355  *
27356  * Fork - LGPL
27357  * <script type="text/javascript">
27358  */
27359  
27360 /**
27361  * @class Roo.form.BasicForm
27362  * @extends Roo.util.Observable
27363  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
27364  * @constructor
27365  * @param {String/HTMLElement/Roo.Element} el The form element or its id
27366  * @param {Object} config Configuration options
27367  */
27368 Roo.form.BasicForm = function(el, config){
27369     this.allItems = [];
27370     this.childForms = [];
27371     Roo.apply(this, config);
27372     /*
27373      * The Roo.form.Field items in this form.
27374      * @type MixedCollection
27375      */
27376      
27377      
27378     this.items = new Roo.util.MixedCollection(false, function(o){
27379         return o.id || (o.id = Roo.id());
27380     });
27381     this.addEvents({
27382         /**
27383          * @event beforeaction
27384          * Fires before any action is performed. Return false to cancel the action.
27385          * @param {Form} this
27386          * @param {Action} action The action to be performed
27387          */
27388         beforeaction: true,
27389         /**
27390          * @event actionfailed
27391          * Fires when an action fails.
27392          * @param {Form} this
27393          * @param {Action} action The action that failed
27394          */
27395         actionfailed : true,
27396         /**
27397          * @event actioncomplete
27398          * Fires when an action is completed.
27399          * @param {Form} this
27400          * @param {Action} action The action that completed
27401          */
27402         actioncomplete : true
27403     });
27404     if(el){
27405         this.initEl(el);
27406     }
27407     Roo.form.BasicForm.superclass.constructor.call(this);
27408 };
27409
27410 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
27411     /**
27412      * @cfg {String} method
27413      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
27414      */
27415     /**
27416      * @cfg {DataReader} reader
27417      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
27418      * This is optional as there is built-in support for processing JSON.
27419      */
27420     /**
27421      * @cfg {DataReader} errorReader
27422      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
27423      * This is completely optional as there is built-in support for processing JSON.
27424      */
27425     /**
27426      * @cfg {String} url
27427      * The URL to use for form actions if one isn't supplied in the action options.
27428      */
27429     /**
27430      * @cfg {Boolean} fileUpload
27431      * Set to true if this form is a file upload.
27432      */
27433      
27434     /**
27435      * @cfg {Object} baseParams
27436      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
27437      */
27438      /**
27439      
27440     /**
27441      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
27442      */
27443     timeout: 30,
27444
27445     // private
27446     activeAction : null,
27447
27448     /**
27449      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
27450      * or setValues() data instead of when the form was first created.
27451      */
27452     trackResetOnLoad : false,
27453     
27454     
27455     /**
27456      * childForms - used for multi-tab forms
27457      * @type {Array}
27458      */
27459     childForms : false,
27460     
27461     /**
27462      * allItems - full list of fields.
27463      * @type {Array}
27464      */
27465     allItems : false,
27466     
27467     /**
27468      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
27469      * element by passing it or its id or mask the form itself by passing in true.
27470      * @type Mixed
27471      */
27472     waitMsgTarget : false,
27473
27474     // private
27475     initEl : function(el){
27476         this.el = Roo.get(el);
27477         this.id = this.el.id || Roo.id();
27478         this.el.on('submit', this.onSubmit, this);
27479         this.el.addClass('x-form');
27480     },
27481
27482     // private
27483     onSubmit : function(e){
27484         e.stopEvent();
27485     },
27486
27487     /**
27488      * Returns true if client-side validation on the form is successful.
27489      * @return Boolean
27490      */
27491     isValid : function(){
27492         var valid = true;
27493         this.items.each(function(f){
27494            if(!f.validate()){
27495                valid = false;
27496            }
27497         });
27498         return valid;
27499     },
27500
27501     /**
27502      * Returns true if any fields in this form have changed since their original load.
27503      * @return Boolean
27504      */
27505     isDirty : function(){
27506         var dirty = false;
27507         this.items.each(function(f){
27508            if(f.isDirty()){
27509                dirty = true;
27510                return false;
27511            }
27512         });
27513         return dirty;
27514     },
27515
27516     /**
27517      * Performs a predefined action (submit or load) or custom actions you define on this form.
27518      * @param {String} actionName The name of the action type
27519      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
27520      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
27521      * accept other config options):
27522      * <pre>
27523 Property          Type             Description
27524 ----------------  ---------------  ----------------------------------------------------------------------------------
27525 url               String           The url for the action (defaults to the form's url)
27526 method            String           The form method to use (defaults to the form's method, or POST if not defined)
27527 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
27528 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
27529                                    validate the form on the client (defaults to false)
27530      * </pre>
27531      * @return {BasicForm} this
27532      */
27533     doAction : function(action, options){
27534         if(typeof action == 'string'){
27535             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
27536         }
27537         if(this.fireEvent('beforeaction', this, action) !== false){
27538             this.beforeAction(action);
27539             action.run.defer(100, action);
27540         }
27541         return this;
27542     },
27543
27544     /**
27545      * Shortcut to do a submit action.
27546      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
27547      * @return {BasicForm} this
27548      */
27549     submit : function(options){
27550         this.doAction('submit', options);
27551         return this;
27552     },
27553
27554     /**
27555      * Shortcut to do a load action.
27556      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
27557      * @return {BasicForm} this
27558      */
27559     load : function(options){
27560         this.doAction('load', options);
27561         return this;
27562     },
27563
27564     /**
27565      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
27566      * @param {Record} record The record to edit
27567      * @return {BasicForm} this
27568      */
27569     updateRecord : function(record){
27570         record.beginEdit();
27571         var fs = record.fields;
27572         fs.each(function(f){
27573             var field = this.findField(f.name);
27574             if(field){
27575                 record.set(f.name, field.getValue());
27576             }
27577         }, this);
27578         record.endEdit();
27579         return this;
27580     },
27581
27582     /**
27583      * Loads an Roo.data.Record into this form.
27584      * @param {Record} record The record to load
27585      * @return {BasicForm} this
27586      */
27587     loadRecord : function(record){
27588         this.setValues(record.data);
27589         return this;
27590     },
27591
27592     // private
27593     beforeAction : function(action){
27594         var o = action.options;
27595         
27596        
27597         if(this.waitMsgTarget === true){
27598             this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
27599         }else if(this.waitMsgTarget){
27600             this.waitMsgTarget = Roo.get(this.waitMsgTarget);
27601             this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
27602         }else {
27603             Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
27604         }
27605          
27606     },
27607
27608     // private
27609     afterAction : function(action, success){
27610         this.activeAction = null;
27611         var o = action.options;
27612         
27613         if(this.waitMsgTarget === true){
27614             this.el.unmask();
27615         }else if(this.waitMsgTarget){
27616             this.waitMsgTarget.unmask();
27617         }else{
27618             Roo.MessageBox.updateProgress(1);
27619             Roo.MessageBox.hide();
27620         }
27621          
27622         if(success){
27623             if(o.reset){
27624                 this.reset();
27625             }
27626             Roo.callback(o.success, o.scope, [this, action]);
27627             this.fireEvent('actioncomplete', this, action);
27628             
27629         }else{
27630             
27631             // failure condition..
27632             // we have a scenario where updates need confirming.
27633             // eg. if a locking scenario exists..
27634             // we look for { errors : { needs_confirm : true }} in the response.
27635             if (
27636                 (typeof(action.result) != 'undefined')  &&
27637                 (typeof(action.result.errors) != 'undefined')  &&
27638                 (typeof(action.result.errors.needs_confirm) != 'undefined')
27639            ){
27640                 var _t = this;
27641                 Roo.MessageBox.confirm(
27642                     "Change requires confirmation",
27643                     action.result.errorMsg,
27644                     function(r) {
27645                         if (r != 'yes') {
27646                             return;
27647                         }
27648                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
27649                     }
27650                     
27651                 );
27652                 
27653                 
27654                 
27655                 return;
27656             }
27657             
27658             Roo.callback(o.failure, o.scope, [this, action]);
27659             // show an error message if no failed handler is set..
27660             if (!this.hasListener('actionfailed')) {
27661                 Roo.MessageBox.alert("Error",
27662                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
27663                         action.result.errorMsg :
27664                         "Saving Failed, please check your entries or try again"
27665                 );
27666             }
27667             
27668             this.fireEvent('actionfailed', this, action);
27669         }
27670         
27671     },
27672
27673     /**
27674      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
27675      * @param {String} id The value to search for
27676      * @return Field
27677      */
27678     findField : function(id){
27679         var field = this.items.get(id);
27680         if(!field){
27681             this.items.each(function(f){
27682                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
27683                     field = f;
27684                     return false;
27685                 }
27686             });
27687         }
27688         return field || null;
27689     },
27690
27691     /**
27692      * Add a secondary form to this one, 
27693      * Used to provide tabbed forms. One form is primary, with hidden values 
27694      * which mirror the elements from the other forms.
27695      * 
27696      * @param {Roo.form.Form} form to add.
27697      * 
27698      */
27699     addForm : function(form)
27700     {
27701        
27702         if (this.childForms.indexOf(form) > -1) {
27703             // already added..
27704             return;
27705         }
27706         this.childForms.push(form);
27707         var n = '';
27708         Roo.each(form.allItems, function (fe) {
27709             
27710             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
27711             if (this.findField(n)) { // already added..
27712                 return;
27713             }
27714             var add = new Roo.form.Hidden({
27715                 name : n
27716             });
27717             add.render(this.el);
27718             
27719             this.add( add );
27720         }, this);
27721         
27722     },
27723     /**
27724      * Mark fields in this form invalid in bulk.
27725      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
27726      * @return {BasicForm} this
27727      */
27728     markInvalid : function(errors){
27729         if(errors instanceof Array){
27730             for(var i = 0, len = errors.length; i < len; i++){
27731                 var fieldError = errors[i];
27732                 var f = this.findField(fieldError.id);
27733                 if(f){
27734                     f.markInvalid(fieldError.msg);
27735                 }
27736             }
27737         }else{
27738             var field, id;
27739             for(id in errors){
27740                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
27741                     field.markInvalid(errors[id]);
27742                 }
27743             }
27744         }
27745         Roo.each(this.childForms || [], function (f) {
27746             f.markInvalid(errors);
27747         });
27748         
27749         return this;
27750     },
27751
27752     /**
27753      * Set values for fields in this form in bulk.
27754      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
27755      * @return {BasicForm} this
27756      */
27757     setValues : function(values){
27758         if(values instanceof Array){ // array of objects
27759             for(var i = 0, len = values.length; i < len; i++){
27760                 var v = values[i];
27761                 var f = this.findField(v.id);
27762                 if(f){
27763                     f.setValue(v.value);
27764                     if(this.trackResetOnLoad){
27765                         f.originalValue = f.getValue();
27766                     }
27767                 }
27768             }
27769         }else{ // object hash
27770             var field, id;
27771             for(id in values){
27772                 if(typeof values[id] != 'function' && (field = this.findField(id))){
27773                     
27774                     if (field.setFromData && 
27775                         field.valueField && 
27776                         field.displayField &&
27777                         // combos' with local stores can 
27778                         // be queried via setValue()
27779                         // to set their value..
27780                         (field.store && !field.store.isLocal)
27781                         ) {
27782                         // it's a combo
27783                         var sd = { };
27784                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
27785                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
27786                         field.setFromData(sd);
27787                         
27788                     } else {
27789                         field.setValue(values[id]);
27790                     }
27791                     
27792                     
27793                     if(this.trackResetOnLoad){
27794                         field.originalValue = field.getValue();
27795                     }
27796                 }
27797             }
27798         }
27799          
27800         Roo.each(this.childForms || [], function (f) {
27801             f.setValues(values);
27802         });
27803                 
27804         return this;
27805     },
27806
27807     /**
27808      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
27809      * they are returned as an array.
27810      * @param {Boolean} asString
27811      * @return {Object}
27812      */
27813     getValues : function(asString){
27814         if (this.childForms) {
27815             // copy values from the child forms
27816             Roo.each(this.childForms, function (f) {
27817                 this.setValues(f.getValues());
27818             }, this);
27819         }
27820         
27821         
27822         
27823         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
27824         if(asString === true){
27825             return fs;
27826         }
27827         return Roo.urlDecode(fs);
27828     },
27829     
27830     /**
27831      * Returns the fields in this form as an object with key/value pairs. 
27832      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
27833      * @return {Object}
27834      */
27835     getFieldValues : function(with_hidden)
27836     {
27837         if (this.childForms) {
27838             // copy values from the child forms
27839             // should this call getFieldValues - probably not as we do not currently copy
27840             // hidden fields when we generate..
27841             Roo.each(this.childForms, function (f) {
27842                 this.setValues(f.getValues());
27843             }, this);
27844         }
27845         
27846         var ret = {};
27847         this.items.each(function(f){
27848             if (!f.getName()) {
27849                 return;
27850             }
27851             var v = f.getValue();
27852             if (f.inputType =='radio') {
27853                 if (typeof(ret[f.getName()]) == 'undefined') {
27854                     ret[f.getName()] = ''; // empty..
27855                 }
27856                 
27857                 if (!f.el.dom.checked) {
27858                     return;
27859                     
27860                 }
27861                 v = f.el.dom.value;
27862                 
27863             }
27864             
27865             // not sure if this supported any more..
27866             if ((typeof(v) == 'object') && f.getRawValue) {
27867                 v = f.getRawValue() ; // dates..
27868             }
27869             // combo boxes where name != hiddenName...
27870             if (f.name != f.getName()) {
27871                 ret[f.name] = f.getRawValue();
27872             }
27873             ret[f.getName()] = v;
27874         });
27875         
27876         return ret;
27877     },
27878
27879     /**
27880      * Clears all invalid messages in this form.
27881      * @return {BasicForm} this
27882      */
27883     clearInvalid : function(){
27884         this.items.each(function(f){
27885            f.clearInvalid();
27886         });
27887         
27888         Roo.each(this.childForms || [], function (f) {
27889             f.clearInvalid();
27890         });
27891         
27892         
27893         return this;
27894     },
27895
27896     /**
27897      * Resets this form.
27898      * @return {BasicForm} this
27899      */
27900     reset : function(){
27901         this.items.each(function(f){
27902             f.reset();
27903         });
27904         
27905         Roo.each(this.childForms || [], function (f) {
27906             f.reset();
27907         });
27908        
27909         
27910         return this;
27911     },
27912
27913     /**
27914      * Add Roo.form components to this form.
27915      * @param {Field} field1
27916      * @param {Field} field2 (optional)
27917      * @param {Field} etc (optional)
27918      * @return {BasicForm} this
27919      */
27920     add : function(){
27921         this.items.addAll(Array.prototype.slice.call(arguments, 0));
27922         return this;
27923     },
27924
27925
27926     /**
27927      * Removes a field from the items collection (does NOT remove its markup).
27928      * @param {Field} field
27929      * @return {BasicForm} this
27930      */
27931     remove : function(field){
27932         this.items.remove(field);
27933         return this;
27934     },
27935
27936     /**
27937      * Looks at the fields in this form, checks them for an id attribute,
27938      * and calls applyTo on the existing dom element with that id.
27939      * @return {BasicForm} this
27940      */
27941     render : function(){
27942         this.items.each(function(f){
27943             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
27944                 f.applyTo(f.id);
27945             }
27946         });
27947         return this;
27948     },
27949
27950     /**
27951      * Calls {@link Ext#apply} for all fields in this form with the passed object.
27952      * @param {Object} values
27953      * @return {BasicForm} this
27954      */
27955     applyToFields : function(o){
27956         this.items.each(function(f){
27957            Roo.apply(f, o);
27958         });
27959         return this;
27960     },
27961
27962     /**
27963      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
27964      * @param {Object} values
27965      * @return {BasicForm} this
27966      */
27967     applyIfToFields : function(o){
27968         this.items.each(function(f){
27969            Roo.applyIf(f, o);
27970         });
27971         return this;
27972     }
27973 });
27974
27975 // back compat
27976 Roo.BasicForm = Roo.form.BasicForm;/*
27977  * Based on:
27978  * Ext JS Library 1.1.1
27979  * Copyright(c) 2006-2007, Ext JS, LLC.
27980  *
27981  * Originally Released Under LGPL - original licence link has changed is not relivant.
27982  *
27983  * Fork - LGPL
27984  * <script type="text/javascript">
27985  */
27986
27987 /**
27988  * @class Roo.form.Form
27989  * @extends Roo.form.BasicForm
27990  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
27991  * @constructor
27992  * @param {Object} config Configuration options
27993  */
27994 Roo.form.Form = function(config){
27995     var xitems =  [];
27996     if (config.items) {
27997         xitems = config.items;
27998         delete config.items;
27999     }
28000    
28001     
28002     Roo.form.Form.superclass.constructor.call(this, null, config);
28003     this.url = this.url || this.action;
28004     if(!this.root){
28005         this.root = new Roo.form.Layout(Roo.applyIf({
28006             id: Roo.id()
28007         }, config));
28008     }
28009     this.active = this.root;
28010     /**
28011      * Array of all the buttons that have been added to this form via {@link addButton}
28012      * @type Array
28013      */
28014     this.buttons = [];
28015     this.allItems = [];
28016     this.addEvents({
28017         /**
28018          * @event clientvalidation
28019          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
28020          * @param {Form} this
28021          * @param {Boolean} valid true if the form has passed client-side validation
28022          */
28023         clientvalidation: true,
28024         /**
28025          * @event rendered
28026          * Fires when the form is rendered
28027          * @param {Roo.form.Form} form
28028          */
28029         rendered : true
28030     });
28031     
28032     if (this.progressUrl) {
28033             // push a hidden field onto the list of fields..
28034             this.addxtype( {
28035                     xns: Roo.form, 
28036                     xtype : 'Hidden', 
28037                     name : 'UPLOAD_IDENTIFIER' 
28038             });
28039         }
28040         
28041     
28042     Roo.each(xitems, this.addxtype, this);
28043     
28044     
28045     
28046 };
28047
28048 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
28049     /**
28050      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
28051      */
28052     /**
28053      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
28054      */
28055     /**
28056      * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "center")
28057      */
28058     buttonAlign:'center',
28059
28060     /**
28061      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
28062      */
28063     minButtonWidth:75,
28064
28065     /**
28066      * @cfg {String} labelAlign Valid values are "left," "top" and "right" (defaults to "left").
28067      * This property cascades to child containers if not set.
28068      */
28069     labelAlign:'left',
28070
28071     /**
28072      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
28073      * fires a looping event with that state. This is required to bind buttons to the valid
28074      * state using the config value formBind:true on the button.
28075      */
28076     monitorValid : false,
28077
28078     /**
28079      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
28080      */
28081     monitorPoll : 200,
28082     
28083     /**
28084      * @cfg {String} progressUrl - Url to return progress data 
28085      */
28086     
28087     progressUrl : false,
28088   
28089     /**
28090      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
28091      * fields are added and the column is closed. If no fields are passed the column remains open
28092      * until end() is called.
28093      * @param {Object} config The config to pass to the column
28094      * @param {Field} field1 (optional)
28095      * @param {Field} field2 (optional)
28096      * @param {Field} etc (optional)
28097      * @return Column The column container object
28098      */
28099     column : function(c){
28100         var col = new Roo.form.Column(c);
28101         this.start(col);
28102         if(arguments.length > 1){ // duplicate code required because of Opera
28103             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28104             this.end();
28105         }
28106         return col;
28107     },
28108
28109     /**
28110      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
28111      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
28112      * until end() is called.
28113      * @param {Object} config The config to pass to the fieldset
28114      * @param {Field} field1 (optional)
28115      * @param {Field} field2 (optional)
28116      * @param {Field} etc (optional)
28117      * @return FieldSet The fieldset container object
28118      */
28119     fieldset : function(c){
28120         var fs = new Roo.form.FieldSet(c);
28121         this.start(fs);
28122         if(arguments.length > 1){ // duplicate code required because of Opera
28123             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28124             this.end();
28125         }
28126         return fs;
28127     },
28128
28129     /**
28130      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
28131      * fields are added and the container is closed. If no fields are passed the container remains open
28132      * until end() is called.
28133      * @param {Object} config The config to pass to the Layout
28134      * @param {Field} field1 (optional)
28135      * @param {Field} field2 (optional)
28136      * @param {Field} etc (optional)
28137      * @return Layout The container object
28138      */
28139     container : function(c){
28140         var l = new Roo.form.Layout(c);
28141         this.start(l);
28142         if(arguments.length > 1){ // duplicate code required because of Opera
28143             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
28144             this.end();
28145         }
28146         return l;
28147     },
28148
28149     /**
28150      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
28151      * @param {Object} container A Roo.form.Layout or subclass of Layout
28152      * @return {Form} this
28153      */
28154     start : function(c){
28155         // cascade label info
28156         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
28157         this.active.stack.push(c);
28158         c.ownerCt = this.active;
28159         this.active = c;
28160         return this;
28161     },
28162
28163     /**
28164      * Closes the current open container
28165      * @return {Form} this
28166      */
28167     end : function(){
28168         if(this.active == this.root){
28169             return this;
28170         }
28171         this.active = this.active.ownerCt;
28172         return this;
28173     },
28174
28175     /**
28176      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
28177      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
28178      * as the label of the field.
28179      * @param {Field} field1
28180      * @param {Field} field2 (optional)
28181      * @param {Field} etc. (optional)
28182      * @return {Form} this
28183      */
28184     add : function(){
28185         this.active.stack.push.apply(this.active.stack, arguments);
28186         this.allItems.push.apply(this.allItems,arguments);
28187         var r = [];
28188         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
28189             if(a[i].isFormField){
28190                 r.push(a[i]);
28191             }
28192         }
28193         if(r.length > 0){
28194             Roo.form.Form.superclass.add.apply(this, r);
28195         }
28196         return this;
28197     },
28198     
28199
28200     
28201     
28202     
28203      /**
28204      * Find any element that has been added to a form, using it's ID or name
28205      * This can include framesets, columns etc. along with regular fields..
28206      * @param {String} id - id or name to find.
28207      
28208      * @return {Element} e - or false if nothing found.
28209      */
28210     findbyId : function(id)
28211     {
28212         var ret = false;
28213         if (!id) {
28214             return ret;
28215         }
28216         Roo.each(this.allItems, function(f){
28217             if (f.id == id || f.name == id ){
28218                 ret = f;
28219                 return false;
28220             }
28221         });
28222         return ret;
28223     },
28224
28225     
28226     
28227     /**
28228      * Render this form into the passed container. This should only be called once!
28229      * @param {String/HTMLElement/Element} container The element this component should be rendered into
28230      * @return {Form} this
28231      */
28232     render : function(ct)
28233     {
28234         
28235         
28236         
28237         ct = Roo.get(ct);
28238         var o = this.autoCreate || {
28239             tag: 'form',
28240             method : this.method || 'POST',
28241             id : this.id || Roo.id()
28242         };
28243         this.initEl(ct.createChild(o));
28244
28245         this.root.render(this.el);
28246         
28247        
28248              
28249         this.items.each(function(f){
28250             f.render('x-form-el-'+f.id);
28251         });
28252
28253         if(this.buttons.length > 0){
28254             // tables are required to maintain order and for correct IE layout
28255             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
28256                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
28257                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
28258             }}, null, true);
28259             var tr = tb.getElementsByTagName('tr')[0];
28260             for(var i = 0, len = this.buttons.length; i < len; i++) {
28261                 var b = this.buttons[i];
28262                 var td = document.createElement('td');
28263                 td.className = 'x-form-btn-td';
28264                 b.render(tr.appendChild(td));
28265             }
28266         }
28267         if(this.monitorValid){ // initialize after render
28268             this.startMonitoring();
28269         }
28270         this.fireEvent('rendered', this);
28271         return this;
28272     },
28273
28274     /**
28275      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
28276      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
28277      * object or a valid Roo.DomHelper element config
28278      * @param {Function} handler The function called when the button is clicked
28279      * @param {Object} scope (optional) The scope of the handler function
28280      * @return {Roo.Button}
28281      */
28282     addButton : function(config, handler, scope){
28283         var bc = {
28284             handler: handler,
28285             scope: scope,
28286             minWidth: this.minButtonWidth,
28287             hideParent:true
28288         };
28289         if(typeof config == "string"){
28290             bc.text = config;
28291         }else{
28292             Roo.apply(bc, config);
28293         }
28294         var btn = new Roo.Button(null, bc);
28295         this.buttons.push(btn);
28296         return btn;
28297     },
28298
28299      /**
28300      * Adds a series of form elements (using the xtype property as the factory method.
28301      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
28302      * @param {Object} config 
28303      */
28304     
28305     addxtype : function()
28306     {
28307         var ar = Array.prototype.slice.call(arguments, 0);
28308         var ret = false;
28309         for(var i = 0; i < ar.length; i++) {
28310             if (!ar[i]) {
28311                 continue; // skip -- if this happends something invalid got sent, we 
28312                 // should ignore it, as basically that interface element will not show up
28313                 // and that should be pretty obvious!!
28314             }
28315             
28316             if (Roo.form[ar[i].xtype]) {
28317                 ar[i].form = this;
28318                 var fe = Roo.factory(ar[i], Roo.form);
28319                 if (!ret) {
28320                     ret = fe;
28321                 }
28322                 fe.form = this;
28323                 if (fe.store) {
28324                     fe.store.form = this;
28325                 }
28326                 if (fe.isLayout) {  
28327                          
28328                     this.start(fe);
28329                     this.allItems.push(fe);
28330                     if (fe.items && fe.addxtype) {
28331                         fe.addxtype.apply(fe, fe.items);
28332                         delete fe.items;
28333                     }
28334                      this.end();
28335                     continue;
28336                 }
28337                 
28338                 
28339                  
28340                 this.add(fe);
28341               //  console.log('adding ' + ar[i].xtype);
28342             }
28343             if (ar[i].xtype == 'Button') {  
28344                 //console.log('adding button');
28345                 //console.log(ar[i]);
28346                 this.addButton(ar[i]);
28347                 this.allItems.push(fe);
28348                 continue;
28349             }
28350             
28351             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
28352                 alert('end is not supported on xtype any more, use items');
28353             //    this.end();
28354             //    //console.log('adding end');
28355             }
28356             
28357         }
28358         return ret;
28359     },
28360     
28361     /**
28362      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
28363      * option "monitorValid"
28364      */
28365     startMonitoring : function(){
28366         if(!this.bound){
28367             this.bound = true;
28368             Roo.TaskMgr.start({
28369                 run : this.bindHandler,
28370                 interval : this.monitorPoll || 200,
28371                 scope: this
28372             });
28373         }
28374     },
28375
28376     /**
28377      * Stops monitoring of the valid state of this form
28378      */
28379     stopMonitoring : function(){
28380         this.bound = false;
28381     },
28382
28383     // private
28384     bindHandler : function(){
28385         if(!this.bound){
28386             return false; // stops binding
28387         }
28388         var valid = true;
28389         this.items.each(function(f){
28390             if(!f.isValid(true)){
28391                 valid = false;
28392                 return false;
28393             }
28394         });
28395         for(var i = 0, len = this.buttons.length; i < len; i++){
28396             var btn = this.buttons[i];
28397             if(btn.formBind === true && btn.disabled === valid){
28398                 btn.setDisabled(!valid);
28399             }
28400         }
28401         this.fireEvent('clientvalidation', this, valid);
28402     }
28403     
28404     
28405     
28406     
28407     
28408     
28409     
28410     
28411 });
28412
28413
28414 // back compat
28415 Roo.Form = Roo.form.Form;
28416 /*
28417  * Based on:
28418  * Ext JS Library 1.1.1
28419  * Copyright(c) 2006-2007, Ext JS, LLC.
28420  *
28421  * Originally Released Under LGPL - original licence link has changed is not relivant.
28422  *
28423  * Fork - LGPL
28424  * <script type="text/javascript">
28425  */
28426
28427 // as we use this in bootstrap.
28428 Roo.namespace('Roo.form');
28429  /**
28430  * @class Roo.form.Action
28431  * Internal Class used to handle form actions
28432  * @constructor
28433  * @param {Roo.form.BasicForm} el The form element or its id
28434  * @param {Object} config Configuration options
28435  */
28436
28437  
28438  
28439 // define the action interface
28440 Roo.form.Action = function(form, options){
28441     this.form = form;
28442     this.options = options || {};
28443 };
28444 /**
28445  * Client Validation Failed
28446  * @const 
28447  */
28448 Roo.form.Action.CLIENT_INVALID = 'client';
28449 /**
28450  * Server Validation Failed
28451  * @const 
28452  */
28453 Roo.form.Action.SERVER_INVALID = 'server';
28454  /**
28455  * Connect to Server Failed
28456  * @const 
28457  */
28458 Roo.form.Action.CONNECT_FAILURE = 'connect';
28459 /**
28460  * Reading Data from Server Failed
28461  * @const 
28462  */
28463 Roo.form.Action.LOAD_FAILURE = 'load';
28464
28465 Roo.form.Action.prototype = {
28466     type : 'default',
28467     failureType : undefined,
28468     response : undefined,
28469     result : undefined,
28470
28471     // interface method
28472     run : function(options){
28473
28474     },
28475
28476     // interface method
28477     success : function(response){
28478
28479     },
28480
28481     // interface method
28482     handleResponse : function(response){
28483
28484     },
28485
28486     // default connection failure
28487     failure : function(response){
28488         
28489         this.response = response;
28490         this.failureType = Roo.form.Action.CONNECT_FAILURE;
28491         this.form.afterAction(this, false);
28492     },
28493
28494     processResponse : function(response){
28495         this.response = response;
28496         if(!response.responseText){
28497             return true;
28498         }
28499         this.result = this.handleResponse(response);
28500         return this.result;
28501     },
28502
28503     // utility functions used internally
28504     getUrl : function(appendParams){
28505         var url = this.options.url || this.form.url || this.form.el.dom.action;
28506         if(appendParams){
28507             var p = this.getParams();
28508             if(p){
28509                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
28510             }
28511         }
28512         return url;
28513     },
28514
28515     getMethod : function(){
28516         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
28517     },
28518
28519     getParams : function(){
28520         var bp = this.form.baseParams;
28521         var p = this.options.params;
28522         if(p){
28523             if(typeof p == "object"){
28524                 p = Roo.urlEncode(Roo.applyIf(p, bp));
28525             }else if(typeof p == 'string' && bp){
28526                 p += '&' + Roo.urlEncode(bp);
28527             }
28528         }else if(bp){
28529             p = Roo.urlEncode(bp);
28530         }
28531         return p;
28532     },
28533
28534     createCallback : function(){
28535         return {
28536             success: this.success,
28537             failure: this.failure,
28538             scope: this,
28539             timeout: (this.form.timeout*1000),
28540             upload: this.form.fileUpload ? this.success : undefined
28541         };
28542     }
28543 };
28544
28545 Roo.form.Action.Submit = function(form, options){
28546     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
28547 };
28548
28549 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
28550     type : 'submit',
28551
28552     haveProgress : false,
28553     uploadComplete : false,
28554     
28555     // uploadProgress indicator.
28556     uploadProgress : function()
28557     {
28558         if (!this.form.progressUrl) {
28559             return;
28560         }
28561         
28562         if (!this.haveProgress) {
28563             Roo.MessageBox.progress("Uploading", "Uploading");
28564         }
28565         if (this.uploadComplete) {
28566            Roo.MessageBox.hide();
28567            return;
28568         }
28569         
28570         this.haveProgress = true;
28571    
28572         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
28573         
28574         var c = new Roo.data.Connection();
28575         c.request({
28576             url : this.form.progressUrl,
28577             params: {
28578                 id : uid
28579             },
28580             method: 'GET',
28581             success : function(req){
28582                //console.log(data);
28583                 var rdata = false;
28584                 var edata;
28585                 try  {
28586                    rdata = Roo.decode(req.responseText)
28587                 } catch (e) {
28588                     Roo.log("Invalid data from server..");
28589                     Roo.log(edata);
28590                     return;
28591                 }
28592                 if (!rdata || !rdata.success) {
28593                     Roo.log(rdata);
28594                     Roo.MessageBox.alert(Roo.encode(rdata));
28595                     return;
28596                 }
28597                 var data = rdata.data;
28598                 
28599                 if (this.uploadComplete) {
28600                    Roo.MessageBox.hide();
28601                    return;
28602                 }
28603                    
28604                 if (data){
28605                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
28606                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
28607                     );
28608                 }
28609                 this.uploadProgress.defer(2000,this);
28610             },
28611        
28612             failure: function(data) {
28613                 Roo.log('progress url failed ');
28614                 Roo.log(data);
28615             },
28616             scope : this
28617         });
28618            
28619     },
28620     
28621     
28622     run : function()
28623     {
28624         // run get Values on the form, so it syncs any secondary forms.
28625         this.form.getValues();
28626         
28627         var o = this.options;
28628         var method = this.getMethod();
28629         var isPost = method == 'POST';
28630         if(o.clientValidation === false || this.form.isValid()){
28631             
28632             if (this.form.progressUrl) {
28633                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
28634                     (new Date() * 1) + '' + Math.random());
28635                     
28636             } 
28637             
28638             
28639             Roo.Ajax.request(Roo.apply(this.createCallback(), {
28640                 form:this.form.el.dom,
28641                 url:this.getUrl(!isPost),
28642                 method: method,
28643                 params:isPost ? this.getParams() : null,
28644                 isUpload: this.form.fileUpload
28645             }));
28646             
28647             this.uploadProgress();
28648
28649         }else if (o.clientValidation !== false){ // client validation failed
28650             this.failureType = Roo.form.Action.CLIENT_INVALID;
28651             this.form.afterAction(this, false);
28652         }
28653     },
28654
28655     success : function(response)
28656     {
28657         this.uploadComplete= true;
28658         if (this.haveProgress) {
28659             Roo.MessageBox.hide();
28660         }
28661         
28662         
28663         var result = this.processResponse(response);
28664         if(result === true || result.success){
28665             this.form.afterAction(this, true);
28666             return;
28667         }
28668         if(result.errors){
28669             this.form.markInvalid(result.errors);
28670             this.failureType = Roo.form.Action.SERVER_INVALID;
28671         }
28672         this.form.afterAction(this, false);
28673     },
28674     failure : function(response)
28675     {
28676         this.uploadComplete= true;
28677         if (this.haveProgress) {
28678             Roo.MessageBox.hide();
28679         }
28680         
28681         this.response = response;
28682         this.failureType = Roo.form.Action.CONNECT_FAILURE;
28683         this.form.afterAction(this, false);
28684     },
28685     
28686     handleResponse : function(response){
28687         if(this.form.errorReader){
28688             var rs = this.form.errorReader.read(response);
28689             var errors = [];
28690             if(rs.records){
28691                 for(var i = 0, len = rs.records.length; i < len; i++) {
28692                     var r = rs.records[i];
28693                     errors[i] = r.data;
28694                 }
28695             }
28696             if(errors.length < 1){
28697                 errors = null;
28698             }
28699             return {
28700                 success : rs.success,
28701                 errors : errors
28702             };
28703         }
28704         var ret = false;
28705         try {
28706             ret = Roo.decode(response.responseText);
28707         } catch (e) {
28708             ret = {
28709                 success: false,
28710                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
28711                 errors : []
28712             };
28713         }
28714         return ret;
28715         
28716     }
28717 });
28718
28719
28720 Roo.form.Action.Load = function(form, options){
28721     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
28722     this.reader = this.form.reader;
28723 };
28724
28725 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
28726     type : 'load',
28727
28728     run : function(){
28729         
28730         Roo.Ajax.request(Roo.apply(
28731                 this.createCallback(), {
28732                     method:this.getMethod(),
28733                     url:this.getUrl(false),
28734                     params:this.getParams()
28735         }));
28736     },
28737
28738     success : function(response){
28739         
28740         var result = this.processResponse(response);
28741         if(result === true || !result.success || !result.data){
28742             this.failureType = Roo.form.Action.LOAD_FAILURE;
28743             this.form.afterAction(this, false);
28744             return;
28745         }
28746         this.form.clearInvalid();
28747         this.form.setValues(result.data);
28748         this.form.afterAction(this, true);
28749     },
28750
28751     handleResponse : function(response){
28752         if(this.form.reader){
28753             var rs = this.form.reader.read(response);
28754             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
28755             return {
28756                 success : rs.success,
28757                 data : data
28758             };
28759         }
28760         return Roo.decode(response.responseText);
28761     }
28762 });
28763
28764 Roo.form.Action.ACTION_TYPES = {
28765     'load' : Roo.form.Action.Load,
28766     'submit' : Roo.form.Action.Submit
28767 };/*
28768  * Based on:
28769  * Ext JS Library 1.1.1
28770  * Copyright(c) 2006-2007, Ext JS, LLC.
28771  *
28772  * Originally Released Under LGPL - original licence link has changed is not relivant.
28773  *
28774  * Fork - LGPL
28775  * <script type="text/javascript">
28776  */
28777  
28778 /**
28779  * @class Roo.form.Layout
28780  * @extends Roo.Component
28781  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
28782  * @constructor
28783  * @param {Object} config Configuration options
28784  */
28785 Roo.form.Layout = function(config){
28786     var xitems = [];
28787     if (config.items) {
28788         xitems = config.items;
28789         delete config.items;
28790     }
28791     Roo.form.Layout.superclass.constructor.call(this, config);
28792     this.stack = [];
28793     Roo.each(xitems, this.addxtype, this);
28794      
28795 };
28796
28797 Roo.extend(Roo.form.Layout, Roo.Component, {
28798     /**
28799      * @cfg {String/Object} autoCreate
28800      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
28801      */
28802     /**
28803      * @cfg {String/Object/Function} style
28804      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
28805      * a function which returns such a specification.
28806      */
28807     /**
28808      * @cfg {String} labelAlign
28809      * Valid values are "left," "top" and "right" (defaults to "left")
28810      */
28811     /**
28812      * @cfg {Number} labelWidth
28813      * Fixed width in pixels of all field labels (defaults to undefined)
28814      */
28815     /**
28816      * @cfg {Boolean} clear
28817      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
28818      */
28819     clear : true,
28820     /**
28821      * @cfg {String} labelSeparator
28822      * The separator to use after field labels (defaults to ':')
28823      */
28824     labelSeparator : ':',
28825     /**
28826      * @cfg {Boolean} hideLabels
28827      * True to suppress the display of field labels in this layout (defaults to false)
28828      */
28829     hideLabels : false,
28830
28831     // private
28832     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
28833     
28834     isLayout : true,
28835     
28836     // private
28837     onRender : function(ct, position){
28838         if(this.el){ // from markup
28839             this.el = Roo.get(this.el);
28840         }else {  // generate
28841             var cfg = this.getAutoCreate();
28842             this.el = ct.createChild(cfg, position);
28843         }
28844         if(this.style){
28845             this.el.applyStyles(this.style);
28846         }
28847         if(this.labelAlign){
28848             this.el.addClass('x-form-label-'+this.labelAlign);
28849         }
28850         if(this.hideLabels){
28851             this.labelStyle = "display:none";
28852             this.elementStyle = "padding-left:0;";
28853         }else{
28854             if(typeof this.labelWidth == 'number'){
28855                 this.labelStyle = "width:"+this.labelWidth+"px;";
28856                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
28857             }
28858             if(this.labelAlign == 'top'){
28859                 this.labelStyle = "width:auto;";
28860                 this.elementStyle = "padding-left:0;";
28861             }
28862         }
28863         var stack = this.stack;
28864         var slen = stack.length;
28865         if(slen > 0){
28866             if(!this.fieldTpl){
28867                 var t = new Roo.Template(
28868                     '<div class="x-form-item {5}">',
28869                         '<label for="{0}" style="{2}">{1}{4}</label>',
28870                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
28871                         '</div>',
28872                     '</div><div class="x-form-clear-left"></div>'
28873                 );
28874                 t.disableFormats = true;
28875                 t.compile();
28876                 Roo.form.Layout.prototype.fieldTpl = t;
28877             }
28878             for(var i = 0; i < slen; i++) {
28879                 if(stack[i].isFormField){
28880                     this.renderField(stack[i]);
28881                 }else{
28882                     this.renderComponent(stack[i]);
28883                 }
28884             }
28885         }
28886         if(this.clear){
28887             this.el.createChild({cls:'x-form-clear'});
28888         }
28889     },
28890
28891     // private
28892     renderField : function(f){
28893         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
28894                f.id, //0
28895                f.fieldLabel, //1
28896                f.labelStyle||this.labelStyle||'', //2
28897                this.elementStyle||'', //3
28898                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
28899                f.itemCls||this.itemCls||''  //5
28900        ], true).getPrevSibling());
28901     },
28902
28903     // private
28904     renderComponent : function(c){
28905         c.render(c.isLayout ? this.el : this.el.createChild());    
28906     },
28907     /**
28908      * Adds a object form elements (using the xtype property as the factory method.)
28909      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
28910      * @param {Object} config 
28911      */
28912     addxtype : function(o)
28913     {
28914         // create the lement.
28915         o.form = this.form;
28916         var fe = Roo.factory(o, Roo.form);
28917         this.form.allItems.push(fe);
28918         this.stack.push(fe);
28919         
28920         if (fe.isFormField) {
28921             this.form.items.add(fe);
28922         }
28923          
28924         return fe;
28925     }
28926 });
28927
28928 /**
28929  * @class Roo.form.Column
28930  * @extends Roo.form.Layout
28931  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
28932  * @constructor
28933  * @param {Object} config Configuration options
28934  */
28935 Roo.form.Column = function(config){
28936     Roo.form.Column.superclass.constructor.call(this, config);
28937 };
28938
28939 Roo.extend(Roo.form.Column, Roo.form.Layout, {
28940     /**
28941      * @cfg {Number/String} width
28942      * The fixed width of the column in pixels or CSS value (defaults to "auto")
28943      */
28944     /**
28945      * @cfg {String/Object} autoCreate
28946      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
28947      */
28948
28949     // private
28950     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
28951
28952     // private
28953     onRender : function(ct, position){
28954         Roo.form.Column.superclass.onRender.call(this, ct, position);
28955         if(this.width){
28956             this.el.setWidth(this.width);
28957         }
28958     }
28959 });
28960
28961
28962 /**
28963  * @class Roo.form.Row
28964  * @extends Roo.form.Layout
28965  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
28966  * @constructor
28967  * @param {Object} config Configuration options
28968  */
28969
28970  
28971 Roo.form.Row = function(config){
28972     Roo.form.Row.superclass.constructor.call(this, config);
28973 };
28974  
28975 Roo.extend(Roo.form.Row, Roo.form.Layout, {
28976       /**
28977      * @cfg {Number/String} width
28978      * The fixed width of the column in pixels or CSS value (defaults to "auto")
28979      */
28980     /**
28981      * @cfg {Number/String} height
28982      * The fixed height of the column in pixels or CSS value (defaults to "auto")
28983      */
28984     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
28985     
28986     padWidth : 20,
28987     // private
28988     onRender : function(ct, position){
28989         //console.log('row render');
28990         if(!this.rowTpl){
28991             var t = new Roo.Template(
28992                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
28993                     '<label for="{0}" style="{2}">{1}{4}</label>',
28994                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
28995                     '</div>',
28996                 '</div>'
28997             );
28998             t.disableFormats = true;
28999             t.compile();
29000             Roo.form.Layout.prototype.rowTpl = t;
29001         }
29002         this.fieldTpl = this.rowTpl;
29003         
29004         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
29005         var labelWidth = 100;
29006         
29007         if ((this.labelAlign != 'top')) {
29008             if (typeof this.labelWidth == 'number') {
29009                 labelWidth = this.labelWidth
29010             }
29011             this.padWidth =  20 + labelWidth;
29012             
29013         }
29014         
29015         Roo.form.Column.superclass.onRender.call(this, ct, position);
29016         if(this.width){
29017             this.el.setWidth(this.width);
29018         }
29019         if(this.height){
29020             this.el.setHeight(this.height);
29021         }
29022     },
29023     
29024     // private
29025     renderField : function(f){
29026         f.fieldEl = this.fieldTpl.append(this.el, [
29027                f.id, f.fieldLabel,
29028                f.labelStyle||this.labelStyle||'',
29029                this.elementStyle||'',
29030                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
29031                f.itemCls||this.itemCls||'',
29032                f.width ? f.width + this.padWidth : 160 + this.padWidth
29033        ],true);
29034     }
29035 });
29036  
29037
29038 /**
29039  * @class Roo.form.FieldSet
29040  * @extends Roo.form.Layout
29041  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
29042  * @constructor
29043  * @param {Object} config Configuration options
29044  */
29045 Roo.form.FieldSet = function(config){
29046     Roo.form.FieldSet.superclass.constructor.call(this, config);
29047 };
29048
29049 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
29050     /**
29051      * @cfg {String} legend
29052      * The text to display as the legend for the FieldSet (defaults to '')
29053      */
29054     /**
29055      * @cfg {String/Object} autoCreate
29056      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
29057      */
29058
29059     // private
29060     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
29061
29062     // private
29063     onRender : function(ct, position){
29064         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
29065         if(this.legend){
29066             this.setLegend(this.legend);
29067         }
29068     },
29069
29070     // private
29071     setLegend : function(text){
29072         if(this.rendered){
29073             this.el.child('legend').update(text);
29074         }
29075     }
29076 });/*
29077  * Based on:
29078  * Ext JS Library 1.1.1
29079  * Copyright(c) 2006-2007, Ext JS, LLC.
29080  *
29081  * Originally Released Under LGPL - original licence link has changed is not relivant.
29082  *
29083  * Fork - LGPL
29084  * <script type="text/javascript">
29085  */
29086 /**
29087  * @class Roo.form.VTypes
29088  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
29089  * @singleton
29090  */
29091 Roo.form.VTypes = function(){
29092     // closure these in so they are only created once.
29093     var alpha = /^[a-zA-Z_]+$/;
29094     var alphanum = /^[a-zA-Z0-9_]+$/;
29095     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
29096     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
29097
29098     // All these messages and functions are configurable
29099     return {
29100         /**
29101          * The function used to validate email addresses
29102          * @param {String} value The email address
29103          */
29104         'email' : function(v){
29105             return email.test(v);
29106         },
29107         /**
29108          * The error text to display when the email validation function returns false
29109          * @type String
29110          */
29111         'emailText' : 'This field should be an e-mail address in the format "user@domain.com"',
29112         /**
29113          * The keystroke filter mask to be applied on email input
29114          * @type RegExp
29115          */
29116         'emailMask' : /[a-z0-9_\.\-@]/i,
29117
29118         /**
29119          * The function used to validate URLs
29120          * @param {String} value The URL
29121          */
29122         'url' : function(v){
29123             return url.test(v);
29124         },
29125         /**
29126          * The error text to display when the url validation function returns false
29127          * @type String
29128          */
29129         'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
29130         
29131         /**
29132          * The function used to validate alpha values
29133          * @param {String} value The value
29134          */
29135         'alpha' : function(v){
29136             return alpha.test(v);
29137         },
29138         /**
29139          * The error text to display when the alpha validation function returns false
29140          * @type String
29141          */
29142         'alphaText' : 'This field should only contain letters and _',
29143         /**
29144          * The keystroke filter mask to be applied on alpha input
29145          * @type RegExp
29146          */
29147         'alphaMask' : /[a-z_]/i,
29148
29149         /**
29150          * The function used to validate alphanumeric values
29151          * @param {String} value The value
29152          */
29153         'alphanum' : function(v){
29154             return alphanum.test(v);
29155         },
29156         /**
29157          * The error text to display when the alphanumeric validation function returns false
29158          * @type String
29159          */
29160         'alphanumText' : 'This field should only contain letters, numbers and _',
29161         /**
29162          * The keystroke filter mask to be applied on alphanumeric input
29163          * @type RegExp
29164          */
29165         'alphanumMask' : /[a-z0-9_]/i
29166     };
29167 }();//<script type="text/javascript">
29168
29169 /**
29170  * @class Roo.form.FCKeditor
29171  * @extends Roo.form.TextArea
29172  * Wrapper around the FCKEditor http://www.fckeditor.net
29173  * @constructor
29174  * Creates a new FCKeditor
29175  * @param {Object} config Configuration options
29176  */
29177 Roo.form.FCKeditor = function(config){
29178     Roo.form.FCKeditor.superclass.constructor.call(this, config);
29179     this.addEvents({
29180          /**
29181          * @event editorinit
29182          * Fired when the editor is initialized - you can add extra handlers here..
29183          * @param {FCKeditor} this
29184          * @param {Object} the FCK object.
29185          */
29186         editorinit : true
29187     });
29188     
29189     
29190 };
29191 Roo.form.FCKeditor.editors = { };
29192 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
29193 {
29194     //defaultAutoCreate : {
29195     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
29196     //},
29197     // private
29198     /**
29199      * @cfg {Object} fck options - see fck manual for details.
29200      */
29201     fckconfig : false,
29202     
29203     /**
29204      * @cfg {Object} fck toolbar set (Basic or Default)
29205      */
29206     toolbarSet : 'Basic',
29207     /**
29208      * @cfg {Object} fck BasePath
29209      */ 
29210     basePath : '/fckeditor/',
29211     
29212     
29213     frame : false,
29214     
29215     value : '',
29216     
29217    
29218     onRender : function(ct, position)
29219     {
29220         if(!this.el){
29221             this.defaultAutoCreate = {
29222                 tag: "textarea",
29223                 style:"width:300px;height:60px;",
29224                 autocomplete: "off"
29225             };
29226         }
29227         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
29228         /*
29229         if(this.grow){
29230             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
29231             if(this.preventScrollbars){
29232                 this.el.setStyle("overflow", "hidden");
29233             }
29234             this.el.setHeight(this.growMin);
29235         }
29236         */
29237         //console.log('onrender' + this.getId() );
29238         Roo.form.FCKeditor.editors[this.getId()] = this;
29239          
29240
29241         this.replaceTextarea() ;
29242         
29243     },
29244     
29245     getEditor : function() {
29246         return this.fckEditor;
29247     },
29248     /**
29249      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
29250      * @param {Mixed} value The value to set
29251      */
29252     
29253     
29254     setValue : function(value)
29255     {
29256         //console.log('setValue: ' + value);
29257         
29258         if(typeof(value) == 'undefined') { // not sure why this is happending...
29259             return;
29260         }
29261         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
29262         
29263         //if(!this.el || !this.getEditor()) {
29264         //    this.value = value;
29265             //this.setValue.defer(100,this,[value]);    
29266         //    return;
29267         //} 
29268         
29269         if(!this.getEditor()) {
29270             return;
29271         }
29272         
29273         this.getEditor().SetData(value);
29274         
29275         //
29276
29277     },
29278
29279     /**
29280      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
29281      * @return {Mixed} value The field value
29282      */
29283     getValue : function()
29284     {
29285         
29286         if (this.frame && this.frame.dom.style.display == 'none') {
29287             return Roo.form.FCKeditor.superclass.getValue.call(this);
29288         }
29289         
29290         if(!this.el || !this.getEditor()) {
29291            
29292            // this.getValue.defer(100,this); 
29293             return this.value;
29294         }
29295        
29296         
29297         var value=this.getEditor().GetData();
29298         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
29299         return Roo.form.FCKeditor.superclass.getValue.call(this);
29300         
29301
29302     },
29303
29304     /**
29305      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
29306      * @return {Mixed} value The field value
29307      */
29308     getRawValue : function()
29309     {
29310         if (this.frame && this.frame.dom.style.display == 'none') {
29311             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
29312         }
29313         
29314         if(!this.el || !this.getEditor()) {
29315             //this.getRawValue.defer(100,this); 
29316             return this.value;
29317             return;
29318         }
29319         
29320         
29321         
29322         var value=this.getEditor().GetData();
29323         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
29324         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
29325          
29326     },
29327     
29328     setSize : function(w,h) {
29329         
29330         
29331         
29332         //if (this.frame && this.frame.dom.style.display == 'none') {
29333         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
29334         //    return;
29335         //}
29336         //if(!this.el || !this.getEditor()) {
29337         //    this.setSize.defer(100,this, [w,h]); 
29338         //    return;
29339         //}
29340         
29341         
29342         
29343         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
29344         
29345         this.frame.dom.setAttribute('width', w);
29346         this.frame.dom.setAttribute('height', h);
29347         this.frame.setSize(w,h);
29348         
29349     },
29350     
29351     toggleSourceEdit : function(value) {
29352         
29353       
29354          
29355         this.el.dom.style.display = value ? '' : 'none';
29356         this.frame.dom.style.display = value ?  'none' : '';
29357         
29358     },
29359     
29360     
29361     focus: function(tag)
29362     {
29363         if (this.frame.dom.style.display == 'none') {
29364             return Roo.form.FCKeditor.superclass.focus.call(this);
29365         }
29366         if(!this.el || !this.getEditor()) {
29367             this.focus.defer(100,this, [tag]); 
29368             return;
29369         }
29370         
29371         
29372         
29373         
29374         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
29375         this.getEditor().Focus();
29376         if (tgs.length) {
29377             if (!this.getEditor().Selection.GetSelection()) {
29378                 this.focus.defer(100,this, [tag]); 
29379                 return;
29380             }
29381             
29382             
29383             var r = this.getEditor().EditorDocument.createRange();
29384             r.setStart(tgs[0],0);
29385             r.setEnd(tgs[0],0);
29386             this.getEditor().Selection.GetSelection().removeAllRanges();
29387             this.getEditor().Selection.GetSelection().addRange(r);
29388             this.getEditor().Focus();
29389         }
29390         
29391     },
29392     
29393     
29394     
29395     replaceTextarea : function()
29396     {
29397         if ( document.getElementById( this.getId() + '___Frame' ) )
29398             return ;
29399         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
29400         //{
29401             // We must check the elements firstly using the Id and then the name.
29402         var oTextarea = document.getElementById( this.getId() );
29403         
29404         var colElementsByName = document.getElementsByName( this.getId() ) ;
29405          
29406         oTextarea.style.display = 'none' ;
29407
29408         if ( oTextarea.tabIndex ) {            
29409             this.TabIndex = oTextarea.tabIndex ;
29410         }
29411         
29412         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
29413         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
29414         this.frame = Roo.get(this.getId() + '___Frame')
29415     },
29416     
29417     _getConfigHtml : function()
29418     {
29419         var sConfig = '' ;
29420
29421         for ( var o in this.fckconfig ) {
29422             sConfig += sConfig.length > 0  ? '&amp;' : '';
29423             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
29424         }
29425
29426         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
29427     },
29428     
29429     
29430     _getIFrameHtml : function()
29431     {
29432         var sFile = 'fckeditor.html' ;
29433         /* no idea what this is about..
29434         try
29435         {
29436             if ( (/fcksource=true/i).test( window.top.location.search ) )
29437                 sFile = 'fckeditor.original.html' ;
29438         }
29439         catch (e) { 
29440         */
29441
29442         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
29443         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
29444         
29445         
29446         var html = '<iframe id="' + this.getId() +
29447             '___Frame" src="' + sLink +
29448             '" width="' + this.width +
29449             '" height="' + this.height + '"' +
29450             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
29451             ' frameborder="0" scrolling="no"></iframe>' ;
29452
29453         return html ;
29454     },
29455     
29456     _insertHtmlBefore : function( html, element )
29457     {
29458         if ( element.insertAdjacentHTML )       {
29459             // IE
29460             element.insertAdjacentHTML( 'beforeBegin', html ) ;
29461         } else { // Gecko
29462             var oRange = document.createRange() ;
29463             oRange.setStartBefore( element ) ;
29464             var oFragment = oRange.createContextualFragment( html );
29465             element.parentNode.insertBefore( oFragment, element ) ;
29466         }
29467     }
29468     
29469     
29470   
29471     
29472     
29473     
29474     
29475
29476 });
29477
29478 //Roo.reg('fckeditor', Roo.form.FCKeditor);
29479
29480 function FCKeditor_OnComplete(editorInstance){
29481     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
29482     f.fckEditor = editorInstance;
29483     //console.log("loaded");
29484     f.fireEvent('editorinit', f, editorInstance);
29485
29486   
29487
29488  
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504 //<script type="text/javascript">
29505 /**
29506  * @class Roo.form.GridField
29507  * @extends Roo.form.Field
29508  * Embed a grid (or editable grid into a form)
29509  * STATUS ALPHA
29510  * 
29511  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
29512  * it needs 
29513  * xgrid.store = Roo.data.Store
29514  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
29515  * xgrid.store.reader = Roo.data.JsonReader 
29516  * 
29517  * 
29518  * @constructor
29519  * Creates a new GridField
29520  * @param {Object} config Configuration options
29521  */
29522 Roo.form.GridField = function(config){
29523     Roo.form.GridField.superclass.constructor.call(this, config);
29524      
29525 };
29526
29527 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
29528     /**
29529      * @cfg {Number} width  - used to restrict width of grid..
29530      */
29531     width : 100,
29532     /**
29533      * @cfg {Number} height - used to restrict height of grid..
29534      */
29535     height : 50,
29536      /**
29537      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
29538          * 
29539          *}
29540      */
29541     xgrid : false, 
29542     /**
29543      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29544      * {tag: "input", type: "checkbox", autocomplete: "off"})
29545      */
29546    // defaultAutoCreate : { tag: 'div' },
29547     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
29548     /**
29549      * @cfg {String} addTitle Text to include for adding a title.
29550      */
29551     addTitle : false,
29552     //
29553     onResize : function(){
29554         Roo.form.Field.superclass.onResize.apply(this, arguments);
29555     },
29556
29557     initEvents : function(){
29558         // Roo.form.Checkbox.superclass.initEvents.call(this);
29559         // has no events...
29560        
29561     },
29562
29563
29564     getResizeEl : function(){
29565         return this.wrap;
29566     },
29567
29568     getPositionEl : function(){
29569         return this.wrap;
29570     },
29571
29572     // private
29573     onRender : function(ct, position){
29574         
29575         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
29576         var style = this.style;
29577         delete this.style;
29578         
29579         Roo.form.GridField.superclass.onRender.call(this, ct, position);
29580         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
29581         this.viewEl = this.wrap.createChild({ tag: 'div' });
29582         if (style) {
29583             this.viewEl.applyStyles(style);
29584         }
29585         if (this.width) {
29586             this.viewEl.setWidth(this.width);
29587         }
29588         if (this.height) {
29589             this.viewEl.setHeight(this.height);
29590         }
29591         //if(this.inputValue !== undefined){
29592         //this.setValue(this.value);
29593         
29594         
29595         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
29596         
29597         
29598         this.grid.render();
29599         this.grid.getDataSource().on('remove', this.refreshValue, this);
29600         this.grid.getDataSource().on('update', this.refreshValue, this);
29601         this.grid.on('afteredit', this.refreshValue, this);
29602  
29603     },
29604      
29605     
29606     /**
29607      * Sets the value of the item. 
29608      * @param {String} either an object  or a string..
29609      */
29610     setValue : function(v){
29611         //this.value = v;
29612         v = v || []; // empty set..
29613         // this does not seem smart - it really only affects memoryproxy grids..
29614         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
29615             var ds = this.grid.getDataSource();
29616             // assumes a json reader..
29617             var data = {}
29618             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
29619             ds.loadData( data);
29620         }
29621         // clear selection so it does not get stale.
29622         if (this.grid.sm) { 
29623             this.grid.sm.clearSelections();
29624         }
29625         
29626         Roo.form.GridField.superclass.setValue.call(this, v);
29627         this.refreshValue();
29628         // should load data in the grid really....
29629     },
29630     
29631     // private
29632     refreshValue: function() {
29633          var val = [];
29634         this.grid.getDataSource().each(function(r) {
29635             val.push(r.data);
29636         });
29637         this.el.dom.value = Roo.encode(val);
29638     }
29639     
29640      
29641     
29642     
29643 });/*
29644  * Based on:
29645  * Ext JS Library 1.1.1
29646  * Copyright(c) 2006-2007, Ext JS, LLC.
29647  *
29648  * Originally Released Under LGPL - original licence link has changed is not relivant.
29649  *
29650  * Fork - LGPL
29651  * <script type="text/javascript">
29652  */
29653 /**
29654  * @class Roo.form.DisplayField
29655  * @extends Roo.form.Field
29656  * A generic Field to display non-editable data.
29657  * @constructor
29658  * Creates a new Display Field item.
29659  * @param {Object} config Configuration options
29660  */
29661 Roo.form.DisplayField = function(config){
29662     Roo.form.DisplayField.superclass.constructor.call(this, config);
29663     
29664 };
29665
29666 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
29667     inputType:      'hidden',
29668     allowBlank:     true,
29669     readOnly:         true,
29670     
29671  
29672     /**
29673      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
29674      */
29675     focusClass : undefined,
29676     /**
29677      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
29678      */
29679     fieldClass: 'x-form-field',
29680     
29681      /**
29682      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
29683      */
29684     valueRenderer: undefined,
29685     
29686     width: 100,
29687     /**
29688      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29689      * {tag: "input", type: "checkbox", autocomplete: "off"})
29690      */
29691      
29692  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
29693
29694     onResize : function(){
29695         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
29696         
29697     },
29698
29699     initEvents : function(){
29700         // Roo.form.Checkbox.superclass.initEvents.call(this);
29701         // has no events...
29702        
29703     },
29704
29705
29706     getResizeEl : function(){
29707         return this.wrap;
29708     },
29709
29710     getPositionEl : function(){
29711         return this.wrap;
29712     },
29713
29714     // private
29715     onRender : function(ct, position){
29716         
29717         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
29718         //if(this.inputValue !== undefined){
29719         this.wrap = this.el.wrap();
29720         
29721         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
29722         
29723         if (this.bodyStyle) {
29724             this.viewEl.applyStyles(this.bodyStyle);
29725         }
29726         //this.viewEl.setStyle('padding', '2px');
29727         
29728         this.setValue(this.value);
29729         
29730     },
29731 /*
29732     // private
29733     initValue : Roo.emptyFn,
29734
29735   */
29736
29737         // private
29738     onClick : function(){
29739         
29740     },
29741
29742     /**
29743      * Sets the checked state of the checkbox.
29744      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
29745      */
29746     setValue : function(v){
29747         this.value = v;
29748         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
29749         // this might be called before we have a dom element..
29750         if (!this.viewEl) {
29751             return;
29752         }
29753         this.viewEl.dom.innerHTML = html;
29754         Roo.form.DisplayField.superclass.setValue.call(this, v);
29755
29756     }
29757 });/*
29758  * 
29759  * Licence- LGPL
29760  * 
29761  */
29762
29763 /**
29764  * @class Roo.form.DayPicker
29765  * @extends Roo.form.Field
29766  * A Day picker show [M] [T] [W] ....
29767  * @constructor
29768  * Creates a new Day Picker
29769  * @param {Object} config Configuration options
29770  */
29771 Roo.form.DayPicker= function(config){
29772     Roo.form.DayPicker.superclass.constructor.call(this, config);
29773      
29774 };
29775
29776 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
29777     /**
29778      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
29779      */
29780     focusClass : undefined,
29781     /**
29782      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
29783      */
29784     fieldClass: "x-form-field",
29785    
29786     /**
29787      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
29788      * {tag: "input", type: "checkbox", autocomplete: "off"})
29789      */
29790     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
29791     
29792    
29793     actionMode : 'viewEl', 
29794     //
29795     // private
29796  
29797     inputType : 'hidden',
29798     
29799      
29800     inputElement: false, // real input element?
29801     basedOn: false, // ????
29802     
29803     isFormField: true, // not sure where this is needed!!!!
29804
29805     onResize : function(){
29806         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
29807         if(!this.boxLabel){
29808             this.el.alignTo(this.wrap, 'c-c');
29809         }
29810     },
29811
29812     initEvents : function(){
29813         Roo.form.Checkbox.superclass.initEvents.call(this);
29814         this.el.on("click", this.onClick,  this);
29815         this.el.on("change", this.onClick,  this);
29816     },
29817
29818
29819     getResizeEl : function(){
29820         return this.wrap;
29821     },
29822
29823     getPositionEl : function(){
29824         return this.wrap;
29825     },
29826
29827     
29828     // private
29829     onRender : function(ct, position){
29830         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
29831        
29832         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
29833         
29834         var r1 = '<table><tr>';
29835         var r2 = '<tr class="x-form-daypick-icons">';
29836         for (var i=0; i < 7; i++) {
29837             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
29838             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
29839         }
29840         
29841         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
29842         viewEl.select('img').on('click', this.onClick, this);
29843         this.viewEl = viewEl;   
29844         
29845         
29846         // this will not work on Chrome!!!
29847         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
29848         this.el.on('propertychange', this.setFromHidden,  this);  //ie
29849         
29850         
29851           
29852
29853     },
29854
29855     // private
29856     initValue : Roo.emptyFn,
29857
29858     /**
29859      * Returns the checked state of the checkbox.
29860      * @return {Boolean} True if checked, else false
29861      */
29862     getValue : function(){
29863         return this.el.dom.value;
29864         
29865     },
29866
29867         // private
29868     onClick : function(e){ 
29869         //this.setChecked(!this.checked);
29870         Roo.get(e.target).toggleClass('x-menu-item-checked');
29871         this.refreshValue();
29872         //if(this.el.dom.checked != this.checked){
29873         //    this.setValue(this.el.dom.checked);
29874        // }
29875     },
29876     
29877     // private
29878     refreshValue : function()
29879     {
29880         var val = '';
29881         this.viewEl.select('img',true).each(function(e,i,n)  {
29882             val += e.is(".x-menu-item-checked") ? String(n) : '';
29883         });
29884         this.setValue(val, true);
29885     },
29886
29887     /**
29888      * Sets the checked state of the checkbox.
29889      * On is always based on a string comparison between inputValue and the param.
29890      * @param {Boolean/String} value - the value to set 
29891      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
29892      */
29893     setValue : function(v,suppressEvent){
29894         if (!this.el.dom) {
29895             return;
29896         }
29897         var old = this.el.dom.value ;
29898         this.el.dom.value = v;
29899         if (suppressEvent) {
29900             return ;
29901         }
29902          
29903         // update display..
29904         this.viewEl.select('img',true).each(function(e,i,n)  {
29905             
29906             var on = e.is(".x-menu-item-checked");
29907             var newv = v.indexOf(String(n)) > -1;
29908             if (on != newv) {
29909                 e.toggleClass('x-menu-item-checked');
29910             }
29911             
29912         });
29913         
29914         
29915         this.fireEvent('change', this, v, old);
29916         
29917         
29918     },
29919    
29920     // handle setting of hidden value by some other method!!?!?
29921     setFromHidden: function()
29922     {
29923         if(!this.el){
29924             return;
29925         }
29926         //console.log("SET FROM HIDDEN");
29927         //alert('setFrom hidden');
29928         this.setValue(this.el.dom.value);
29929     },
29930     
29931     onDestroy : function()
29932     {
29933         if(this.viewEl){
29934             Roo.get(this.viewEl).remove();
29935         }
29936          
29937         Roo.form.DayPicker.superclass.onDestroy.call(this);
29938     }
29939
29940 });/*
29941  * RooJS Library 1.1.1
29942  * Copyright(c) 2008-2011  Alan Knowles
29943  *
29944  * License - LGPL
29945  */
29946  
29947
29948 /**
29949  * @class Roo.form.ComboCheck
29950  * @extends Roo.form.ComboBox
29951  * A combobox for multiple select items.
29952  *
29953  * FIXME - could do with a reset button..
29954  * 
29955  * @constructor
29956  * Create a new ComboCheck
29957  * @param {Object} config Configuration options
29958  */
29959 Roo.form.ComboCheck = function(config){
29960     Roo.form.ComboCheck.superclass.constructor.call(this, config);
29961     // should verify some data...
29962     // like
29963     // hiddenName = required..
29964     // displayField = required
29965     // valudField == required
29966     var req= [ 'hiddenName', 'displayField', 'valueField' ];
29967     var _t = this;
29968     Roo.each(req, function(e) {
29969         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
29970             throw "Roo.form.ComboCheck : missing value for: " + e;
29971         }
29972     });
29973     
29974     
29975 };
29976
29977 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
29978      
29979      
29980     editable : false,
29981      
29982     selectedClass: 'x-menu-item-checked', 
29983     
29984     // private
29985     onRender : function(ct, position){
29986         var _t = this;
29987         
29988         
29989         
29990         if(!this.tpl){
29991             var cls = 'x-combo-list';
29992
29993             
29994             this.tpl =  new Roo.Template({
29995                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
29996                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
29997                    '<span>{' + this.displayField + '}</span>' +
29998                     '</div>' 
29999                 
30000             });
30001         }
30002  
30003         
30004         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
30005         this.view.singleSelect = false;
30006         this.view.multiSelect = true;
30007         this.view.toggleSelect = true;
30008         this.pageTb.add(new Roo.Toolbar.Fill(), {
30009             
30010             text: 'Done',
30011             handler: function()
30012             {
30013                 _t.collapse();
30014             }
30015         });
30016     },
30017     
30018     onViewOver : function(e, t){
30019         // do nothing...
30020         return;
30021         
30022     },
30023     
30024     onViewClick : function(doFocus,index){
30025         return;
30026         
30027     },
30028     select: function () {
30029         //Roo.log("SELECT CALLED");
30030     },
30031      
30032     selectByValue : function(xv, scrollIntoView){
30033         var ar = this.getValueArray();
30034         var sels = [];
30035         
30036         Roo.each(ar, function(v) {
30037             if(v === undefined || v === null){
30038                 return;
30039             }
30040             var r = this.findRecord(this.valueField, v);
30041             if(r){
30042                 sels.push(this.store.indexOf(r))
30043                 
30044             }
30045         },this);
30046         this.view.select(sels);
30047         return false;
30048     },
30049     
30050     
30051     
30052     onSelect : function(record, index){
30053        // Roo.log("onselect Called");
30054        // this is only called by the clear button now..
30055         this.view.clearSelections();
30056         this.setValue('[]');
30057         if (this.value != this.valueBefore) {
30058             this.fireEvent('change', this, this.value, this.valueBefore);
30059             this.valueBefore = this.value;
30060         }
30061     },
30062     getValueArray : function()
30063     {
30064         var ar = [] ;
30065         
30066         try {
30067             //Roo.log(this.value);
30068             if (typeof(this.value) == 'undefined') {
30069                 return [];
30070             }
30071             var ar = Roo.decode(this.value);
30072             return  ar instanceof Array ? ar : []; //?? valid?
30073             
30074         } catch(e) {
30075             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
30076             return [];
30077         }
30078          
30079     },
30080     expand : function ()
30081     {
30082         
30083         Roo.form.ComboCheck.superclass.expand.call(this);
30084         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
30085         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
30086         
30087
30088     },
30089     
30090     collapse : function(){
30091         Roo.form.ComboCheck.superclass.collapse.call(this);
30092         var sl = this.view.getSelectedIndexes();
30093         var st = this.store;
30094         var nv = [];
30095         var tv = [];
30096         var r;
30097         Roo.each(sl, function(i) {
30098             r = st.getAt(i);
30099             nv.push(r.get(this.valueField));
30100         },this);
30101         this.setValue(Roo.encode(nv));
30102         if (this.value != this.valueBefore) {
30103
30104             this.fireEvent('change', this, this.value, this.valueBefore);
30105             this.valueBefore = this.value;
30106         }
30107         
30108     },
30109     
30110     setValue : function(v){
30111         // Roo.log(v);
30112         this.value = v;
30113         
30114         var vals = this.getValueArray();
30115         var tv = [];
30116         Roo.each(vals, function(k) {
30117             var r = this.findRecord(this.valueField, k);
30118             if(r){
30119                 tv.push(r.data[this.displayField]);
30120             }else if(this.valueNotFoundText !== undefined){
30121                 tv.push( this.valueNotFoundText );
30122             }
30123         },this);
30124        // Roo.log(tv);
30125         
30126         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
30127         this.hiddenField.value = v;
30128         this.value = v;
30129     }
30130     
30131 });/*
30132  * Based on:
30133  * Ext JS Library 1.1.1
30134  * Copyright(c) 2006-2007, Ext JS, LLC.
30135  *
30136  * Originally Released Under LGPL - original licence link has changed is not relivant.
30137  *
30138  * Fork - LGPL
30139  * <script type="text/javascript">
30140  */
30141  
30142 /**
30143  * @class Roo.form.Signature
30144  * @extends Roo.form.Field
30145  * Signature field.  
30146  * @constructor
30147  * 
30148  * @param {Object} config Configuration options
30149  */
30150
30151 Roo.form.Signature = function(config){
30152     Roo.form.Signature.superclass.constructor.call(this, config);
30153     
30154     this.addEvents({// not in used??
30155          /**
30156          * @event confirm
30157          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
30158              * @param {Roo.form.Signature} combo This combo box
30159              */
30160         'confirm' : true,
30161         /**
30162          * @event reset
30163          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
30164              * @param {Roo.form.ComboBox} combo This combo box
30165              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
30166              */
30167         'reset' : true
30168     });
30169 };
30170
30171 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
30172     /**
30173      * @cfg {Object} labels Label to use when rendering a form.
30174      * defaults to 
30175      * labels : { 
30176      *      clear : "Clear",
30177      *      confirm : "Confirm"
30178      *  }
30179      */
30180     labels : { 
30181         clear : "Clear",
30182         confirm : "Confirm"
30183     },
30184     /**
30185      * @cfg {Number} width The signature panel width (defaults to 300)
30186      */
30187     width: 300,
30188     /**
30189      * @cfg {Number} height The signature panel height (defaults to 100)
30190      */
30191     height : 100,
30192     /**
30193      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
30194      */
30195     allowBlank : false,
30196     
30197     //private
30198     // {Object} signPanel The signature SVG panel element (defaults to {})
30199     signPanel : {},
30200     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
30201     isMouseDown : false,
30202     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
30203     isConfirmed : false,
30204     // {String} signatureTmp SVG mapping string (defaults to empty string)
30205     signatureTmp : '',
30206     
30207     
30208     defaultAutoCreate : { // modified by initCompnoent..
30209         tag: "input",
30210         type:"hidden"
30211     },
30212
30213     // private
30214     onRender : function(ct, position){
30215         
30216         Roo.form.Signature.superclass.onRender.call(this, ct, position);
30217         
30218         this.wrap = this.el.wrap({
30219             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
30220         });
30221         
30222         this.createToolbar(this);
30223         this.signPanel = this.wrap.createChild({
30224                 tag: 'div',
30225                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
30226             }, this.el
30227         );
30228             
30229         this.svgID = Roo.id();
30230         this.svgEl = this.signPanel.createChild({
30231               xmlns : 'http://www.w3.org/2000/svg',
30232               tag : 'svg',
30233               id : this.svgID + "-svg",
30234               width: this.width,
30235               height: this.height,
30236               viewBox: '0 0 '+this.width+' '+this.height,
30237               cn : [
30238                 {
30239                     tag: "rect",
30240                     id: this.svgID + "-svg-r",
30241                     width: this.width,
30242                     height: this.height,
30243                     fill: "#ffa"
30244                 },
30245                 {
30246                     tag: "line",
30247                     id: this.svgID + "-svg-l",
30248                     x1: "0", // start
30249                     y1: (this.height*0.8), // start set the line in 80% of height
30250                     x2: this.width, // end
30251                     y2: (this.height*0.8), // end set the line in 80% of height
30252                     'stroke': "#666",
30253                     'stroke-width': "1",
30254                     'stroke-dasharray': "3",
30255                     'shape-rendering': "crispEdges",
30256                     'pointer-events': "none"
30257                 },
30258                 {
30259                     tag: "path",
30260                     id: this.svgID + "-svg-p",
30261                     'stroke': "navy",
30262                     'stroke-width': "3",
30263                     'fill': "none",
30264                     'pointer-events': 'none'
30265                 }
30266               ]
30267         });
30268         this.createSVG();
30269         this.svgBox = this.svgEl.dom.getScreenCTM();
30270     },
30271     createSVG : function(){ 
30272         var svg = this.signPanel;
30273         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
30274         var t = this;
30275
30276         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
30277         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
30278         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
30279         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
30280         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
30281         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
30282         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
30283         
30284     },
30285     isTouchEvent : function(e){
30286         return e.type.match(/^touch/);
30287     },
30288     getCoords : function (e) {
30289         var pt    = this.svgEl.dom.createSVGPoint();
30290         pt.x = e.clientX; 
30291         pt.y = e.clientY;
30292         if (this.isTouchEvent(e)) {
30293             pt.x =  e.targetTouches[0].clientX 
30294             pt.y = e.targetTouches[0].clientY;
30295         }
30296         var a = this.svgEl.dom.getScreenCTM();
30297         var b = a.inverse();
30298         var mx = pt.matrixTransform(b);
30299         return mx.x + ',' + mx.y;
30300     },
30301     //mouse event headler 
30302     down : function (e) {
30303         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
30304         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
30305         
30306         this.isMouseDown = true;
30307         
30308         e.preventDefault();
30309     },
30310     move : function (e) {
30311         if (this.isMouseDown) {
30312             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
30313             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
30314         }
30315         
30316         e.preventDefault();
30317     },
30318     up : function (e) {
30319         this.isMouseDown = false;
30320         var sp = this.signatureTmp.split(' ');
30321         
30322         if(sp.length > 1){
30323             if(!sp[sp.length-2].match(/^L/)){
30324                 sp.pop();
30325                 sp.pop();
30326                 sp.push("");
30327                 this.signatureTmp = sp.join(" ");
30328             }
30329         }
30330         if(this.getValue() != this.signatureTmp){
30331             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
30332             this.isConfirmed = false;
30333         }
30334         e.preventDefault();
30335     },
30336     
30337     /**
30338      * Protected method that will not generally be called directly. It
30339      * is called when the editor creates its toolbar. Override this method if you need to
30340      * add custom toolbar buttons.
30341      * @param {HtmlEditor} editor
30342      */
30343     createToolbar : function(editor){
30344          function btn(id, toggle, handler){
30345             var xid = fid + '-'+ id ;
30346             return {
30347                 id : xid,
30348                 cmd : id,
30349                 cls : 'x-btn-icon x-edit-'+id,
30350                 enableToggle:toggle !== false,
30351                 scope: editor, // was editor...
30352                 handler:handler||editor.relayBtnCmd,
30353                 clickEvent:'mousedown',
30354                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
30355                 tabIndex:-1
30356             };
30357         }
30358         
30359         
30360         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
30361         this.tb = tb;
30362         this.tb.add(
30363            {
30364                 cls : ' x-signature-btn x-signature-'+id,
30365                 scope: editor, // was editor...
30366                 handler: this.reset,
30367                 clickEvent:'mousedown',
30368                 text: this.labels.clear
30369             },
30370             {
30371                  xtype : 'Fill',
30372                  xns: Roo.Toolbar
30373             }, 
30374             {
30375                 cls : '  x-signature-btn x-signature-'+id,
30376                 scope: editor, // was editor...
30377                 handler: this.confirmHandler,
30378                 clickEvent:'mousedown',
30379                 text: this.labels.confirm
30380             }
30381         );
30382     
30383     },
30384     //public
30385     /**
30386      * when user is clicked confirm then show this image.....
30387      * 
30388      * @return {String} Image Data URI
30389      */
30390     getImageDataURI : function(){
30391         var svg = this.svgEl.dom.parentNode.innerHTML;
30392         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
30393         return src; 
30394     },
30395     /**
30396      * 
30397      * @return {Boolean} this.isConfirmed
30398      */
30399     getConfirmed : function(){
30400         return this.isConfirmed;
30401     },
30402     /**
30403      * 
30404      * @return {Number} this.width
30405      */
30406     getWidth : function(){
30407         return this.width;
30408     },
30409     /**
30410      * 
30411      * @return {Number} this.height
30412      */
30413     getHeight : function(){
30414         return this.height;
30415     },
30416     // private
30417     getSignature : function(){
30418         return this.signatureTmp;
30419     },
30420     // private
30421     reset : function(){
30422         this.signatureTmp = '';
30423         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
30424         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
30425         this.isConfirmed = false;
30426         Roo.form.Signature.superclass.reset.call(this);
30427     },
30428     setSignature : function(s){
30429         this.signatureTmp = s;
30430         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
30431         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
30432         this.setValue(s);
30433         this.isConfirmed = false;
30434         Roo.form.Signature.superclass.reset.call(this);
30435     }, 
30436     test : function(){
30437 //        Roo.log(this.signPanel.dom.contentWindow.up())
30438     },
30439     //private
30440     setConfirmed : function(){
30441         
30442         
30443         
30444 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
30445     },
30446     // private
30447     confirmHandler : function(){
30448         if(!this.getSignature()){
30449             return;
30450         }
30451         
30452         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
30453         this.setValue(this.getSignature());
30454         this.isConfirmed = true;
30455         
30456         this.fireEvent('confirm', this);
30457     },
30458     // private
30459     // Subclasses should provide the validation implementation by overriding this
30460     validateValue : function(value){
30461         if(this.allowBlank){
30462             return true;
30463         }
30464         
30465         if(this.isConfirmed){
30466             return true;
30467         }
30468         return false;
30469     }
30470 });/*
30471  * Based on:
30472  * Ext JS Library 1.1.1
30473  * Copyright(c) 2006-2007, Ext JS, LLC.
30474  *
30475  * Originally Released Under LGPL - original licence link has changed is not relivant.
30476  *
30477  * Fork - LGPL
30478  * <script type="text/javascript">
30479  */
30480  
30481
30482 /**
30483  * @class Roo.form.ComboBox
30484  * @extends Roo.form.TriggerField
30485  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
30486  * @constructor
30487  * Create a new ComboBox.
30488  * @param {Object} config Configuration options
30489  */
30490 Roo.form.Select = function(config){
30491     Roo.form.Select.superclass.constructor.call(this, config);
30492      
30493 };
30494
30495 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
30496     /**
30497      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
30498      */
30499     /**
30500      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
30501      * rendering into an Roo.Editor, defaults to false)
30502      */
30503     /**
30504      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
30505      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
30506      */
30507     /**
30508      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
30509      */
30510     /**
30511      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
30512      * the dropdown list (defaults to undefined, with no header element)
30513      */
30514
30515      /**
30516      * @cfg {String/Roo.Template} tpl The template to use to render the output
30517      */
30518      
30519     // private
30520     defaultAutoCreate : {tag: "select"  },
30521     /**
30522      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
30523      */
30524     listWidth: undefined,
30525     /**
30526      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
30527      * mode = 'remote' or 'text' if mode = 'local')
30528      */
30529     displayField: undefined,
30530     /**
30531      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
30532      * mode = 'remote' or 'value' if mode = 'local'). 
30533      * Note: use of a valueField requires the user make a selection
30534      * in order for a value to be mapped.
30535      */
30536     valueField: undefined,
30537     
30538     
30539     /**
30540      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
30541      * field's data value (defaults to the underlying DOM element's name)
30542      */
30543     hiddenName: undefined,
30544     /**
30545      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
30546      */
30547     listClass: '',
30548     /**
30549      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
30550      */
30551     selectedClass: 'x-combo-selected',
30552     /**
30553      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
30554      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
30555      * which displays a downward arrow icon).
30556      */
30557     triggerClass : 'x-form-arrow-trigger',
30558     /**
30559      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
30560      */
30561     shadow:'sides',
30562     /**
30563      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
30564      * anchor positions (defaults to 'tl-bl')
30565      */
30566     listAlign: 'tl-bl?',
30567     /**
30568      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
30569      */
30570     maxHeight: 300,
30571     /**
30572      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
30573      * query specified by the allQuery config option (defaults to 'query')
30574      */
30575     triggerAction: 'query',
30576     /**
30577      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
30578      * (defaults to 4, does not apply if editable = false)
30579      */
30580     minChars : 4,
30581     /**
30582      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
30583      * delay (typeAheadDelay) if it matches a known value (defaults to false)
30584      */
30585     typeAhead: false,
30586     /**
30587      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
30588      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
30589      */
30590     queryDelay: 500,
30591     /**
30592      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
30593      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
30594      */
30595     pageSize: 0,
30596     /**
30597      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
30598      * when editable = true (defaults to false)
30599      */
30600     selectOnFocus:false,
30601     /**
30602      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
30603      */
30604     queryParam: 'query',
30605     /**
30606      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
30607      * when mode = 'remote' (defaults to 'Loading...')
30608      */
30609     loadingText: 'Loading...',
30610     /**
30611      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
30612      */
30613     resizable: false,
30614     /**
30615      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
30616      */
30617     handleHeight : 8,
30618     /**
30619      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
30620      * traditional select (defaults to true)
30621      */
30622     editable: true,
30623     /**
30624      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
30625      */
30626     allQuery: '',
30627     /**
30628      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
30629      */
30630     mode: 'remote',
30631     /**
30632      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
30633      * listWidth has a higher value)
30634      */
30635     minListWidth : 70,
30636     /**
30637      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
30638      * allow the user to set arbitrary text into the field (defaults to false)
30639      */
30640     forceSelection:false,
30641     /**
30642      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
30643      * if typeAhead = true (defaults to 250)
30644      */
30645     typeAheadDelay : 250,
30646     /**
30647      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
30648      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
30649      */
30650     valueNotFoundText : undefined,
30651     
30652     /**
30653      * @cfg {String} defaultValue The value displayed after loading the store.
30654      */
30655     defaultValue: '',
30656     
30657     /**
30658      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
30659      */
30660     blockFocus : false,
30661     
30662     /**
30663      * @cfg {Boolean} disableClear Disable showing of clear button.
30664      */
30665     disableClear : false,
30666     /**
30667      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
30668      */
30669     alwaysQuery : false,
30670     
30671     //private
30672     addicon : false,
30673     editicon: false,
30674     
30675     // element that contains real text value.. (when hidden is used..)
30676      
30677     // private
30678     onRender : function(ct, position){
30679         Roo.form.Field.prototype.onRender.call(this, ct, position);
30680         
30681         if(this.store){
30682             this.store.on('beforeload', this.onBeforeLoad, this);
30683             this.store.on('load', this.onLoad, this);
30684             this.store.on('loadexception', this.onLoadException, this);
30685             this.store.load({});
30686         }
30687         
30688         
30689         
30690     },
30691
30692     // private
30693     initEvents : function(){
30694         //Roo.form.ComboBox.superclass.initEvents.call(this);
30695  
30696     },
30697
30698     onDestroy : function(){
30699        
30700         if(this.store){
30701             this.store.un('beforeload', this.onBeforeLoad, this);
30702             this.store.un('load', this.onLoad, this);
30703             this.store.un('loadexception', this.onLoadException, this);
30704         }
30705         //Roo.form.ComboBox.superclass.onDestroy.call(this);
30706     },
30707
30708     // private
30709     fireKey : function(e){
30710         if(e.isNavKeyPress() && !this.list.isVisible()){
30711             this.fireEvent("specialkey", this, e);
30712         }
30713     },
30714
30715     // private
30716     onResize: function(w, h){
30717         
30718         return; 
30719     
30720         
30721     },
30722
30723     /**
30724      * Allow or prevent the user from directly editing the field text.  If false is passed,
30725      * the user will only be able to select from the items defined in the dropdown list.  This method
30726      * is the runtime equivalent of setting the 'editable' config option at config time.
30727      * @param {Boolean} value True to allow the user to directly edit the field text
30728      */
30729     setEditable : function(value){
30730          
30731     },
30732
30733     // private
30734     onBeforeLoad : function(){
30735         
30736         Roo.log("Select before load");
30737         return;
30738     
30739         this.innerList.update(this.loadingText ?
30740                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
30741         //this.restrictHeight();
30742         this.selectedIndex = -1;
30743     },
30744
30745     // private
30746     onLoad : function(){
30747
30748     
30749         var dom = this.el.dom;
30750         dom.innerHTML = '';
30751          var od = dom.ownerDocument;
30752          
30753         if (this.emptyText) {
30754             var op = od.createElement('option');
30755             op.setAttribute('value', '');
30756             op.innerHTML = String.format('{0}', this.emptyText);
30757             dom.appendChild(op);
30758         }
30759         if(this.store.getCount() > 0){
30760            
30761             var vf = this.valueField;
30762             var df = this.displayField;
30763             this.store.data.each(function(r) {
30764                 // which colmsn to use... testing - cdoe / title..
30765                 var op = od.createElement('option');
30766                 op.setAttribute('value', r.data[vf]);
30767                 op.innerHTML = String.format('{0}', r.data[df]);
30768                 dom.appendChild(op);
30769             });
30770             if (typeof(this.defaultValue != 'undefined')) {
30771                 this.setValue(this.defaultValue);
30772             }
30773             
30774              
30775         }else{
30776             //this.onEmptyResults();
30777         }
30778         //this.el.focus();
30779     },
30780     // private
30781     onLoadException : function()
30782     {
30783         dom.innerHTML = '';
30784             
30785         Roo.log("Select on load exception");
30786         return;
30787     
30788         this.collapse();
30789         Roo.log(this.store.reader.jsonData);
30790         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
30791             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
30792         }
30793         
30794         
30795     },
30796     // private
30797     onTypeAhead : function(){
30798          
30799     },
30800
30801     // private
30802     onSelect : function(record, index){
30803         Roo.log('on select?');
30804         return;
30805         if(this.fireEvent('beforeselect', this, record, index) !== false){
30806             this.setFromData(index > -1 ? record.data : false);
30807             this.collapse();
30808             this.fireEvent('select', this, record, index);
30809         }
30810     },
30811
30812     /**
30813      * Returns the currently selected field value or empty string if no value is set.
30814      * @return {String} value The selected value
30815      */
30816     getValue : function(){
30817         var dom = this.el.dom;
30818         this.value = dom.options[dom.selectedIndex].value;
30819         return this.value;
30820         
30821     },
30822
30823     /**
30824      * Clears any text/value currently set in the field
30825      */
30826     clearValue : function(){
30827         this.value = '';
30828         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
30829         
30830     },
30831
30832     /**
30833      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
30834      * will be displayed in the field.  If the value does not match the data value of an existing item,
30835      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
30836      * Otherwise the field will be blank (although the value will still be set).
30837      * @param {String} value The value to match
30838      */
30839     setValue : function(v){
30840         var d = this.el.dom;
30841         for (var i =0; i < d.options.length;i++) {
30842             if (v == d.options[i].value) {
30843                 d.selectedIndex = i;
30844                 this.value = v;
30845                 return;
30846             }
30847         }
30848         this.clearValue();
30849     },
30850     /**
30851      * @property {Object} the last set data for the element
30852      */
30853     
30854     lastData : false,
30855     /**
30856      * Sets the value of the field based on a object which is related to the record format for the store.
30857      * @param {Object} value the value to set as. or false on reset?
30858      */
30859     setFromData : function(o){
30860         Roo.log('setfrom data?');
30861          
30862         
30863         
30864     },
30865     // private
30866     reset : function(){
30867         this.clearValue();
30868     },
30869     // private
30870     findRecord : function(prop, value){
30871         
30872         return false;
30873     
30874         var record;
30875         if(this.store.getCount() > 0){
30876             this.store.each(function(r){
30877                 if(r.data[prop] == value){
30878                     record = r;
30879                     return false;
30880                 }
30881                 return true;
30882             });
30883         }
30884         return record;
30885     },
30886     
30887     getName: function()
30888     {
30889         // returns hidden if it's set..
30890         if (!this.rendered) {return ''};
30891         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
30892         
30893     },
30894      
30895
30896     
30897
30898     // private
30899     onEmptyResults : function(){
30900         Roo.log('empty results');
30901         //this.collapse();
30902     },
30903
30904     /**
30905      * Returns true if the dropdown list is expanded, else false.
30906      */
30907     isExpanded : function(){
30908         return false;
30909     },
30910
30911     /**
30912      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
30913      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
30914      * @param {String} value The data value of the item to select
30915      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
30916      * selected item if it is not currently in view (defaults to true)
30917      * @return {Boolean} True if the value matched an item in the list, else false
30918      */
30919     selectByValue : function(v, scrollIntoView){
30920         Roo.log('select By Value');
30921         return false;
30922     
30923         if(v !== undefined && v !== null){
30924             var r = this.findRecord(this.valueField || this.displayField, v);
30925             if(r){
30926                 this.select(this.store.indexOf(r), scrollIntoView);
30927                 return true;
30928             }
30929         }
30930         return false;
30931     },
30932
30933     /**
30934      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
30935      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
30936      * @param {Number} index The zero-based index of the list item to select
30937      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
30938      * selected item if it is not currently in view (defaults to true)
30939      */
30940     select : function(index, scrollIntoView){
30941         Roo.log('select ');
30942         return  ;
30943         
30944         this.selectedIndex = index;
30945         this.view.select(index);
30946         if(scrollIntoView !== false){
30947             var el = this.view.getNode(index);
30948             if(el){
30949                 this.innerList.scrollChildIntoView(el, false);
30950             }
30951         }
30952     },
30953
30954       
30955
30956     // private
30957     validateBlur : function(){
30958         
30959         return;
30960         
30961     },
30962
30963     // private
30964     initQuery : function(){
30965         this.doQuery(this.getRawValue());
30966     },
30967
30968     // private
30969     doForce : function(){
30970         if(this.el.dom.value.length > 0){
30971             this.el.dom.value =
30972                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
30973              
30974         }
30975     },
30976
30977     /**
30978      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
30979      * query allowing the query action to be canceled if needed.
30980      * @param {String} query The SQL query to execute
30981      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
30982      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
30983      * saved in the current store (defaults to false)
30984      */
30985     doQuery : function(q, forceAll){
30986         
30987         Roo.log('doQuery?');
30988         if(q === undefined || q === null){
30989             q = '';
30990         }
30991         var qe = {
30992             query: q,
30993             forceAll: forceAll,
30994             combo: this,
30995             cancel:false
30996         };
30997         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
30998             return false;
30999         }
31000         q = qe.query;
31001         forceAll = qe.forceAll;
31002         if(forceAll === true || (q.length >= this.minChars)){
31003             if(this.lastQuery != q || this.alwaysQuery){
31004                 this.lastQuery = q;
31005                 if(this.mode == 'local'){
31006                     this.selectedIndex = -1;
31007                     if(forceAll){
31008                         this.store.clearFilter();
31009                     }else{
31010                         this.store.filter(this.displayField, q);
31011                     }
31012                     this.onLoad();
31013                 }else{
31014                     this.store.baseParams[this.queryParam] = q;
31015                     this.store.load({
31016                         params: this.getParams(q)
31017                     });
31018                     this.expand();
31019                 }
31020             }else{
31021                 this.selectedIndex = -1;
31022                 this.onLoad();   
31023             }
31024         }
31025     },
31026
31027     // private
31028     getParams : function(q){
31029         var p = {};
31030         //p[this.queryParam] = q;
31031         if(this.pageSize){
31032             p.start = 0;
31033             p.limit = this.pageSize;
31034         }
31035         return p;
31036     },
31037
31038     /**
31039      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
31040      */
31041     collapse : function(){
31042         
31043     },
31044
31045     // private
31046     collapseIf : function(e){
31047         
31048     },
31049
31050     /**
31051      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
31052      */
31053     expand : function(){
31054         
31055     } ,
31056
31057     // private
31058      
31059
31060     /** 
31061     * @cfg {Boolean} grow 
31062     * @hide 
31063     */
31064     /** 
31065     * @cfg {Number} growMin 
31066     * @hide 
31067     */
31068     /** 
31069     * @cfg {Number} growMax 
31070     * @hide 
31071     */
31072     /**
31073      * @hide
31074      * @method autoSize
31075      */
31076     
31077     setWidth : function()
31078     {
31079         
31080     },
31081     getResizeEl : function(){
31082         return this.el;
31083     }
31084 });//<script type="text/javasscript">
31085  
31086
31087 /**
31088  * @class Roo.DDView
31089  * A DnD enabled version of Roo.View.
31090  * @param {Element/String} container The Element in which to create the View.
31091  * @param {String} tpl The template string used to create the markup for each element of the View
31092  * @param {Object} config The configuration properties. These include all the config options of
31093  * {@link Roo.View} plus some specific to this class.<br>
31094  * <p>
31095  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
31096  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
31097  * <p>
31098  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
31099 .x-view-drag-insert-above {
31100         border-top:1px dotted #3366cc;
31101 }
31102 .x-view-drag-insert-below {
31103         border-bottom:1px dotted #3366cc;
31104 }
31105 </code></pre>
31106  * 
31107  */
31108  
31109 Roo.DDView = function(container, tpl, config) {
31110     Roo.DDView.superclass.constructor.apply(this, arguments);
31111     this.getEl().setStyle("outline", "0px none");
31112     this.getEl().unselectable();
31113     if (this.dragGroup) {
31114                 this.setDraggable(this.dragGroup.split(","));
31115     }
31116     if (this.dropGroup) {
31117                 this.setDroppable(this.dropGroup.split(","));
31118     }
31119     if (this.deletable) {
31120         this.setDeletable();
31121     }
31122     this.isDirtyFlag = false;
31123         this.addEvents({
31124                 "drop" : true
31125         });
31126 };
31127
31128 Roo.extend(Roo.DDView, Roo.View, {
31129 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
31130 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
31131 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
31132 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
31133
31134         isFormField: true,
31135
31136         reset: Roo.emptyFn,
31137         
31138         clearInvalid: Roo.form.Field.prototype.clearInvalid,
31139
31140         validate: function() {
31141                 return true;
31142         },
31143         
31144         destroy: function() {
31145                 this.purgeListeners();
31146                 this.getEl.removeAllListeners();
31147                 this.getEl().remove();
31148                 if (this.dragZone) {
31149                         if (this.dragZone.destroy) {
31150                                 this.dragZone.destroy();
31151                         }
31152                 }
31153                 if (this.dropZone) {
31154                         if (this.dropZone.destroy) {
31155                                 this.dropZone.destroy();
31156                         }
31157                 }
31158         },
31159
31160 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
31161         getName: function() {
31162                 return this.name;
31163         },
31164
31165 /**     Loads the View from a JSON string representing the Records to put into the Store. */
31166         setValue: function(v) {
31167                 if (!this.store) {
31168                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
31169                 }
31170                 var data = {};
31171                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
31172                 this.store.proxy = new Roo.data.MemoryProxy(data);
31173                 this.store.load();
31174         },
31175
31176 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
31177         getValue: function() {
31178                 var result = '(';
31179                 this.store.each(function(rec) {
31180                         result += rec.id + ',';
31181                 });
31182                 return result.substr(0, result.length - 1) + ')';
31183         },
31184         
31185         getIds: function() {
31186                 var i = 0, result = new Array(this.store.getCount());
31187                 this.store.each(function(rec) {
31188                         result[i++] = rec.id;
31189                 });
31190                 return result;
31191         },
31192         
31193         isDirty: function() {
31194                 return this.isDirtyFlag;
31195         },
31196
31197 /**
31198  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
31199  *      whole Element becomes the target, and this causes the drop gesture to append.
31200  */
31201     getTargetFromEvent : function(e) {
31202                 var target = e.getTarget();
31203                 while ((target !== null) && (target.parentNode != this.el.dom)) {
31204                 target = target.parentNode;
31205                 }
31206                 if (!target) {
31207                         target = this.el.dom.lastChild || this.el.dom;
31208                 }
31209                 return target;
31210     },
31211
31212 /**
31213  *      Create the drag data which consists of an object which has the property "ddel" as
31214  *      the drag proxy element. 
31215  */
31216     getDragData : function(e) {
31217         var target = this.findItemFromChild(e.getTarget());
31218                 if(target) {
31219                         this.handleSelection(e);
31220                         var selNodes = this.getSelectedNodes();
31221             var dragData = {
31222                 source: this,
31223                 copy: this.copy || (this.allowCopy && e.ctrlKey),
31224                 nodes: selNodes,
31225                 records: []
31226                         };
31227                         var selectedIndices = this.getSelectedIndexes();
31228                         for (var i = 0; i < selectedIndices.length; i++) {
31229                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
31230                         }
31231                         if (selNodes.length == 1) {
31232                                 dragData.ddel = target.cloneNode(true); // the div element
31233                         } else {
31234                                 var div = document.createElement('div'); // create the multi element drag "ghost"
31235                                 div.className = 'multi-proxy';
31236                                 for (var i = 0, len = selNodes.length; i < len; i++) {
31237                                         div.appendChild(selNodes[i].cloneNode(true));
31238                                 }
31239                                 dragData.ddel = div;
31240                         }
31241             //console.log(dragData)
31242             //console.log(dragData.ddel.innerHTML)
31243                         return dragData;
31244                 }
31245         //console.log('nodragData')
31246                 return false;
31247     },
31248     
31249 /**     Specify to which ddGroup items in this DDView may be dragged. */
31250     setDraggable: function(ddGroup) {
31251         if (ddGroup instanceof Array) {
31252                 Roo.each(ddGroup, this.setDraggable, this);
31253                 return;
31254         }
31255         if (this.dragZone) {
31256                 this.dragZone.addToGroup(ddGroup);
31257         } else {
31258                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
31259                                 containerScroll: true,
31260                                 ddGroup: ddGroup 
31261
31262                         });
31263 //                      Draggability implies selection. DragZone's mousedown selects the element.
31264                         if (!this.multiSelect) { this.singleSelect = true; }
31265
31266 //                      Wire the DragZone's handlers up to methods in *this*
31267                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
31268                 }
31269     },
31270
31271 /**     Specify from which ddGroup this DDView accepts drops. */
31272     setDroppable: function(ddGroup) {
31273         if (ddGroup instanceof Array) {
31274                 Roo.each(ddGroup, this.setDroppable, this);
31275                 return;
31276         }
31277         if (this.dropZone) {
31278                 this.dropZone.addToGroup(ddGroup);
31279         } else {
31280                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
31281                                 containerScroll: true,
31282                                 ddGroup: ddGroup
31283                         });
31284
31285 //                      Wire the DropZone's handlers up to methods in *this*
31286                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
31287                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
31288                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
31289                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
31290                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
31291                 }
31292     },
31293
31294 /**     Decide whether to drop above or below a View node. */
31295     getDropPoint : function(e, n, dd){
31296         if (n == this.el.dom) { return "above"; }
31297                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
31298                 var c = t + (b - t) / 2;
31299                 var y = Roo.lib.Event.getPageY(e);
31300                 if(y <= c) {
31301                         return "above";
31302                 }else{
31303                         return "below";
31304                 }
31305     },
31306
31307     onNodeEnter : function(n, dd, e, data){
31308                 return false;
31309     },
31310     
31311     onNodeOver : function(n, dd, e, data){
31312                 var pt = this.getDropPoint(e, n, dd);
31313                 // set the insert point style on the target node
31314                 var dragElClass = this.dropNotAllowed;
31315                 if (pt) {
31316                         var targetElClass;
31317                         if (pt == "above"){
31318                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
31319                                 targetElClass = "x-view-drag-insert-above";
31320                         } else {
31321                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
31322                                 targetElClass = "x-view-drag-insert-below";
31323                         }
31324                         if (this.lastInsertClass != targetElClass){
31325                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
31326                                 this.lastInsertClass = targetElClass;
31327                         }
31328                 }
31329                 return dragElClass;
31330         },
31331
31332     onNodeOut : function(n, dd, e, data){
31333                 this.removeDropIndicators(n);
31334     },
31335
31336     onNodeDrop : function(n, dd, e, data){
31337         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
31338                 return false;
31339         }
31340         var pt = this.getDropPoint(e, n, dd);
31341                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
31342                 if (pt == "below") { insertAt++; }
31343                 for (var i = 0; i < data.records.length; i++) {
31344                         var r = data.records[i];
31345                         var dup = this.store.getById(r.id);
31346                         if (dup && (dd != this.dragZone)) {
31347                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
31348                         } else {
31349                                 if (data.copy) {
31350                                         this.store.insert(insertAt++, r.copy());
31351                                 } else {
31352                                         data.source.isDirtyFlag = true;
31353                                         r.store.remove(r);
31354                                         this.store.insert(insertAt++, r);
31355                                 }
31356                                 this.isDirtyFlag = true;
31357                         }
31358                 }
31359                 this.dragZone.cachedTarget = null;
31360                 return true;
31361     },
31362
31363     removeDropIndicators : function(n){
31364                 if(n){
31365                         Roo.fly(n).removeClass([
31366                                 "x-view-drag-insert-above",
31367                                 "x-view-drag-insert-below"]);
31368                         this.lastInsertClass = "_noclass";
31369                 }
31370     },
31371
31372 /**
31373  *      Utility method. Add a delete option to the DDView's context menu.
31374  *      @param {String} imageUrl The URL of the "delete" icon image.
31375  */
31376         setDeletable: function(imageUrl) {
31377                 if (!this.singleSelect && !this.multiSelect) {
31378                         this.singleSelect = true;
31379                 }
31380                 var c = this.getContextMenu();
31381                 this.contextMenu.on("itemclick", function(item) {
31382                         switch (item.id) {
31383                                 case "delete":
31384                                         this.remove(this.getSelectedIndexes());
31385                                         break;
31386                         }
31387                 }, this);
31388                 this.contextMenu.add({
31389                         icon: imageUrl,
31390                         id: "delete",
31391                         text: 'Delete'
31392                 });
31393         },
31394         
31395 /**     Return the context menu for this DDView. */
31396         getContextMenu: function() {
31397                 if (!this.contextMenu) {
31398 //                      Create the View's context menu
31399                         this.contextMenu = new Roo.menu.Menu({
31400                                 id: this.id + "-contextmenu"
31401                         });
31402                         this.el.on("contextmenu", this.showContextMenu, this);
31403                 }
31404                 return this.contextMenu;
31405         },
31406         
31407         disableContextMenu: function() {
31408                 if (this.contextMenu) {
31409                         this.el.un("contextmenu", this.showContextMenu, this);
31410                 }
31411         },
31412
31413         showContextMenu: function(e, item) {
31414         item = this.findItemFromChild(e.getTarget());
31415                 if (item) {
31416                         e.stopEvent();
31417                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
31418                         this.contextMenu.showAt(e.getXY());
31419             }
31420     },
31421
31422 /**
31423  *      Remove {@link Roo.data.Record}s at the specified indices.
31424  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
31425  */
31426     remove: function(selectedIndices) {
31427                 selectedIndices = [].concat(selectedIndices);
31428                 for (var i = 0; i < selectedIndices.length; i++) {
31429                         var rec = this.store.getAt(selectedIndices[i]);
31430                         this.store.remove(rec);
31431                 }
31432     },
31433
31434 /**
31435  *      Double click fires the event, but also, if this is draggable, and there is only one other
31436  *      related DropZone, it transfers the selected node.
31437  */
31438     onDblClick : function(e){
31439         var item = this.findItemFromChild(e.getTarget());
31440         if(item){
31441             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
31442                 return false;
31443             }
31444             if (this.dragGroup) {
31445                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
31446                     while (targets.indexOf(this.dropZone) > -1) {
31447                             targets.remove(this.dropZone);
31448                                 }
31449                     if (targets.length == 1) {
31450                                         this.dragZone.cachedTarget = null;
31451                         var el = Roo.get(targets[0].getEl());
31452                         var box = el.getBox(true);
31453                         targets[0].onNodeDrop(el.dom, {
31454                                 target: el.dom,
31455                                 xy: [box.x, box.y + box.height - 1]
31456                         }, null, this.getDragData(e));
31457                     }
31458                 }
31459         }
31460     },
31461     
31462     handleSelection: function(e) {
31463                 this.dragZone.cachedTarget = null;
31464         var item = this.findItemFromChild(e.getTarget());
31465         if (!item) {
31466                 this.clearSelections(true);
31467                 return;
31468         }
31469                 if (item && (this.multiSelect || this.singleSelect)){
31470                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
31471                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
31472                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
31473                                 this.unselect(item);
31474                         } else {
31475                                 this.select(item, this.multiSelect && e.ctrlKey);
31476                                 this.lastSelection = item;
31477                         }
31478                 }
31479     },
31480
31481     onItemClick : function(item, index, e){
31482                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
31483                         return false;
31484                 }
31485                 return true;
31486     },
31487
31488     unselect : function(nodeInfo, suppressEvent){
31489                 var node = this.getNode(nodeInfo);
31490                 if(node && this.isSelected(node)){
31491                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
31492                                 Roo.fly(node).removeClass(this.selectedClass);
31493                                 this.selections.remove(node);
31494                                 if(!suppressEvent){
31495                                         this.fireEvent("selectionchange", this, this.selections);
31496                                 }
31497                         }
31498                 }
31499     }
31500 });
31501 /*
31502  * Based on:
31503  * Ext JS Library 1.1.1
31504  * Copyright(c) 2006-2007, Ext JS, LLC.
31505  *
31506  * Originally Released Under LGPL - original licence link has changed is not relivant.
31507  *
31508  * Fork - LGPL
31509  * <script type="text/javascript">
31510  */
31511  
31512 /**
31513  * @class Roo.LayoutManager
31514  * @extends Roo.util.Observable
31515  * Base class for layout managers.
31516  */
31517 Roo.LayoutManager = function(container, config){
31518     Roo.LayoutManager.superclass.constructor.call(this);
31519     this.el = Roo.get(container);
31520     // ie scrollbar fix
31521     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
31522         document.body.scroll = "no";
31523     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
31524         this.el.position('relative');
31525     }
31526     this.id = this.el.id;
31527     this.el.addClass("x-layout-container");
31528     /** false to disable window resize monitoring @type Boolean */
31529     this.monitorWindowResize = true;
31530     this.regions = {};
31531     this.addEvents({
31532         /**
31533          * @event layout
31534          * Fires when a layout is performed. 
31535          * @param {Roo.LayoutManager} this
31536          */
31537         "layout" : true,
31538         /**
31539          * @event regionresized
31540          * Fires when the user resizes a region. 
31541          * @param {Roo.LayoutRegion} region The resized region
31542          * @param {Number} newSize The new size (width for east/west, height for north/south)
31543          */
31544         "regionresized" : true,
31545         /**
31546          * @event regioncollapsed
31547          * Fires when a region is collapsed. 
31548          * @param {Roo.LayoutRegion} region The collapsed region
31549          */
31550         "regioncollapsed" : true,
31551         /**
31552          * @event regionexpanded
31553          * Fires when a region is expanded.  
31554          * @param {Roo.LayoutRegion} region The expanded region
31555          */
31556         "regionexpanded" : true
31557     });
31558     this.updating = false;
31559     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
31560 };
31561
31562 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
31563     /**
31564      * Returns true if this layout is currently being updated
31565      * @return {Boolean}
31566      */
31567     isUpdating : function(){
31568         return this.updating; 
31569     },
31570     
31571     /**
31572      * Suspend the LayoutManager from doing auto-layouts while
31573      * making multiple add or remove calls
31574      */
31575     beginUpdate : function(){
31576         this.updating = true;    
31577     },
31578     
31579     /**
31580      * Restore auto-layouts and optionally disable the manager from performing a layout
31581      * @param {Boolean} noLayout true to disable a layout update 
31582      */
31583     endUpdate : function(noLayout){
31584         this.updating = false;
31585         if(!noLayout){
31586             this.layout();
31587         }    
31588     },
31589     
31590     layout: function(){
31591         
31592     },
31593     
31594     onRegionResized : function(region, newSize){
31595         this.fireEvent("regionresized", region, newSize);
31596         this.layout();
31597     },
31598     
31599     onRegionCollapsed : function(region){
31600         this.fireEvent("regioncollapsed", region);
31601     },
31602     
31603     onRegionExpanded : function(region){
31604         this.fireEvent("regionexpanded", region);
31605     },
31606         
31607     /**
31608      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
31609      * performs box-model adjustments.
31610      * @return {Object} The size as an object {width: (the width), height: (the height)}
31611      */
31612     getViewSize : function(){
31613         var size;
31614         if(this.el.dom != document.body){
31615             size = this.el.getSize();
31616         }else{
31617             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
31618         }
31619         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
31620         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
31621         return size;
31622     },
31623     
31624     /**
31625      * Returns the Element this layout is bound to.
31626      * @return {Roo.Element}
31627      */
31628     getEl : function(){
31629         return this.el;
31630     },
31631     
31632     /**
31633      * Returns the specified region.
31634      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
31635      * @return {Roo.LayoutRegion}
31636      */
31637     getRegion : function(target){
31638         return this.regions[target.toLowerCase()];
31639     },
31640     
31641     onWindowResize : function(){
31642         if(this.monitorWindowResize){
31643             this.layout();
31644         }
31645     }
31646 });/*
31647  * Based on:
31648  * Ext JS Library 1.1.1
31649  * Copyright(c) 2006-2007, Ext JS, LLC.
31650  *
31651  * Originally Released Under LGPL - original licence link has changed is not relivant.
31652  *
31653  * Fork - LGPL
31654  * <script type="text/javascript">
31655  */
31656 /**
31657  * @class Roo.BorderLayout
31658  * @extends Roo.LayoutManager
31659  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
31660  * please see: <br><br>
31661  * <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>
31662  * <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>
31663  * Example:
31664  <pre><code>
31665  var layout = new Roo.BorderLayout(document.body, {
31666     north: {
31667         initialSize: 25,
31668         titlebar: false
31669     },
31670     west: {
31671         split:true,
31672         initialSize: 200,
31673         minSize: 175,
31674         maxSize: 400,
31675         titlebar: true,
31676         collapsible: true
31677     },
31678     east: {
31679         split:true,
31680         initialSize: 202,
31681         minSize: 175,
31682         maxSize: 400,
31683         titlebar: true,
31684         collapsible: true
31685     },
31686     south: {
31687         split:true,
31688         initialSize: 100,
31689         minSize: 100,
31690         maxSize: 200,
31691         titlebar: true,
31692         collapsible: true
31693     },
31694     center: {
31695         titlebar: true,
31696         autoScroll:true,
31697         resizeTabs: true,
31698         minTabWidth: 50,
31699         preferredTabWidth: 150
31700     }
31701 });
31702
31703 // shorthand
31704 var CP = Roo.ContentPanel;
31705
31706 layout.beginUpdate();
31707 layout.add("north", new CP("north", "North"));
31708 layout.add("south", new CP("south", {title: "South", closable: true}));
31709 layout.add("west", new CP("west", {title: "West"}));
31710 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
31711 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
31712 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
31713 layout.getRegion("center").showPanel("center1");
31714 layout.endUpdate();
31715 </code></pre>
31716
31717 <b>The container the layout is rendered into can be either the body element or any other element.
31718 If it is not the body element, the container needs to either be an absolute positioned element,
31719 or you will need to add "position:relative" to the css of the container.  You will also need to specify
31720 the container size if it is not the body element.</b>
31721
31722 * @constructor
31723 * Create a new BorderLayout
31724 * @param {String/HTMLElement/Element} container The container this layout is bound to
31725 * @param {Object} config Configuration options
31726  */
31727 Roo.BorderLayout = function(container, config){
31728     config = config || {};
31729     Roo.BorderLayout.superclass.constructor.call(this, container, config);
31730     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
31731     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
31732         var target = this.factory.validRegions[i];
31733         if(config[target]){
31734             this.addRegion(target, config[target]);
31735         }
31736     }
31737 };
31738
31739 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
31740     /**
31741      * Creates and adds a new region if it doesn't already exist.
31742      * @param {String} target The target region key (north, south, east, west or center).
31743      * @param {Object} config The regions config object
31744      * @return {BorderLayoutRegion} The new region
31745      */
31746     addRegion : function(target, config){
31747         if(!this.regions[target]){
31748             var r = this.factory.create(target, this, config);
31749             this.bindRegion(target, r);
31750         }
31751         return this.regions[target];
31752     },
31753
31754     // private (kinda)
31755     bindRegion : function(name, r){
31756         this.regions[name] = r;
31757         r.on("visibilitychange", this.layout, this);
31758         r.on("paneladded", this.layout, this);
31759         r.on("panelremoved", this.layout, this);
31760         r.on("invalidated", this.layout, this);
31761         r.on("resized", this.onRegionResized, this);
31762         r.on("collapsed", this.onRegionCollapsed, this);
31763         r.on("expanded", this.onRegionExpanded, this);
31764     },
31765
31766     /**
31767      * Performs a layout update.
31768      */
31769     layout : function(){
31770         if(this.updating) return;
31771         var size = this.getViewSize();
31772         var w = size.width;
31773         var h = size.height;
31774         var centerW = w;
31775         var centerH = h;
31776         var centerY = 0;
31777         var centerX = 0;
31778         //var x = 0, y = 0;
31779
31780         var rs = this.regions;
31781         var north = rs["north"];
31782         var south = rs["south"]; 
31783         var west = rs["west"];
31784         var east = rs["east"];
31785         var center = rs["center"];
31786         //if(this.hideOnLayout){ // not supported anymore
31787             //c.el.setStyle("display", "none");
31788         //}
31789         if(north && north.isVisible()){
31790             var b = north.getBox();
31791             var m = north.getMargins();
31792             b.width = w - (m.left+m.right);
31793             b.x = m.left;
31794             b.y = m.top;
31795             centerY = b.height + b.y + m.bottom;
31796             centerH -= centerY;
31797             north.updateBox(this.safeBox(b));
31798         }
31799         if(south && south.isVisible()){
31800             var b = south.getBox();
31801             var m = south.getMargins();
31802             b.width = w - (m.left+m.right);
31803             b.x = m.left;
31804             var totalHeight = (b.height + m.top + m.bottom);
31805             b.y = h - totalHeight + m.top;
31806             centerH -= totalHeight;
31807             south.updateBox(this.safeBox(b));
31808         }
31809         if(west && west.isVisible()){
31810             var b = west.getBox();
31811             var m = west.getMargins();
31812             b.height = centerH - (m.top+m.bottom);
31813             b.x = m.left;
31814             b.y = centerY + m.top;
31815             var totalWidth = (b.width + m.left + m.right);
31816             centerX += totalWidth;
31817             centerW -= totalWidth;
31818             west.updateBox(this.safeBox(b));
31819         }
31820         if(east && east.isVisible()){
31821             var b = east.getBox();
31822             var m = east.getMargins();
31823             b.height = centerH - (m.top+m.bottom);
31824             var totalWidth = (b.width + m.left + m.right);
31825             b.x = w - totalWidth + m.left;
31826             b.y = centerY + m.top;
31827             centerW -= totalWidth;
31828             east.updateBox(this.safeBox(b));
31829         }
31830         if(center){
31831             var m = center.getMargins();
31832             var centerBox = {
31833                 x: centerX + m.left,
31834                 y: centerY + m.top,
31835                 width: centerW - (m.left+m.right),
31836                 height: centerH - (m.top+m.bottom)
31837             };
31838             //if(this.hideOnLayout){
31839                 //center.el.setStyle("display", "block");
31840             //}
31841             center.updateBox(this.safeBox(centerBox));
31842         }
31843         this.el.repaint();
31844         this.fireEvent("layout", this);
31845     },
31846
31847     // private
31848     safeBox : function(box){
31849         box.width = Math.max(0, box.width);
31850         box.height = Math.max(0, box.height);
31851         return box;
31852     },
31853
31854     /**
31855      * Adds a ContentPanel (or subclass) to this layout.
31856      * @param {String} target The target region key (north, south, east, west or center).
31857      * @param {Roo.ContentPanel} panel The panel to add
31858      * @return {Roo.ContentPanel} The added panel
31859      */
31860     add : function(target, panel){
31861          
31862         target = target.toLowerCase();
31863         return this.regions[target].add(panel);
31864     },
31865
31866     /**
31867      * Remove a ContentPanel (or subclass) to this layout.
31868      * @param {String} target The target region key (north, south, east, west or center).
31869      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
31870      * @return {Roo.ContentPanel} The removed panel
31871      */
31872     remove : function(target, panel){
31873         target = target.toLowerCase();
31874         return this.regions[target].remove(panel);
31875     },
31876
31877     /**
31878      * Searches all regions for a panel with the specified id
31879      * @param {String} panelId
31880      * @return {Roo.ContentPanel} The panel or null if it wasn't found
31881      */
31882     findPanel : function(panelId){
31883         var rs = this.regions;
31884         for(var target in rs){
31885             if(typeof rs[target] != "function"){
31886                 var p = rs[target].getPanel(panelId);
31887                 if(p){
31888                     return p;
31889                 }
31890             }
31891         }
31892         return null;
31893     },
31894
31895     /**
31896      * Searches all regions for a panel with the specified id and activates (shows) it.
31897      * @param {String/ContentPanel} panelId The panels id or the panel itself
31898      * @return {Roo.ContentPanel} The shown panel or null
31899      */
31900     showPanel : function(panelId) {
31901       var rs = this.regions;
31902       for(var target in rs){
31903          var r = rs[target];
31904          if(typeof r != "function"){
31905             if(r.hasPanel(panelId)){
31906                return r.showPanel(panelId);
31907             }
31908          }
31909       }
31910       return null;
31911    },
31912
31913    /**
31914      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
31915      * @param {Roo.state.Provider} provider (optional) An alternate state provider
31916      */
31917     restoreState : function(provider){
31918         if(!provider){
31919             provider = Roo.state.Manager;
31920         }
31921         var sm = new Roo.LayoutStateManager();
31922         sm.init(this, provider);
31923     },
31924
31925     /**
31926      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
31927      * object should contain properties for each region to add ContentPanels to, and each property's value should be
31928      * a valid ContentPanel config object.  Example:
31929      * <pre><code>
31930 // Create the main layout
31931 var layout = new Roo.BorderLayout('main-ct', {
31932     west: {
31933         split:true,
31934         minSize: 175,
31935         titlebar: true
31936     },
31937     center: {
31938         title:'Components'
31939     }
31940 }, 'main-ct');
31941
31942 // Create and add multiple ContentPanels at once via configs
31943 layout.batchAdd({
31944    west: {
31945        id: 'source-files',
31946        autoCreate:true,
31947        title:'Ext Source Files',
31948        autoScroll:true,
31949        fitToFrame:true
31950    },
31951    center : {
31952        el: cview,
31953        autoScroll:true,
31954        fitToFrame:true,
31955        toolbar: tb,
31956        resizeEl:'cbody'
31957    }
31958 });
31959 </code></pre>
31960      * @param {Object} regions An object containing ContentPanel configs by region name
31961      */
31962     batchAdd : function(regions){
31963         this.beginUpdate();
31964         for(var rname in regions){
31965             var lr = this.regions[rname];
31966             if(lr){
31967                 this.addTypedPanels(lr, regions[rname]);
31968             }
31969         }
31970         this.endUpdate();
31971     },
31972
31973     // private
31974     addTypedPanels : function(lr, ps){
31975         if(typeof ps == 'string'){
31976             lr.add(new Roo.ContentPanel(ps));
31977         }
31978         else if(ps instanceof Array){
31979             for(var i =0, len = ps.length; i < len; i++){
31980                 this.addTypedPanels(lr, ps[i]);
31981             }
31982         }
31983         else if(!ps.events){ // raw config?
31984             var el = ps.el;
31985             delete ps.el; // prevent conflict
31986             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
31987         }
31988         else {  // panel object assumed!
31989             lr.add(ps);
31990         }
31991     },
31992     /**
31993      * Adds a xtype elements to the layout.
31994      * <pre><code>
31995
31996 layout.addxtype({
31997        xtype : 'ContentPanel',
31998        region: 'west',
31999        items: [ .... ]
32000    }
32001 );
32002
32003 layout.addxtype({
32004         xtype : 'NestedLayoutPanel',
32005         region: 'west',
32006         layout: {
32007            center: { },
32008            west: { }   
32009         },
32010         items : [ ... list of content panels or nested layout panels.. ]
32011    }
32012 );
32013 </code></pre>
32014      * @param {Object} cfg Xtype definition of item to add.
32015      */
32016     addxtype : function(cfg)
32017     {
32018         // basically accepts a pannel...
32019         // can accept a layout region..!?!?
32020         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
32021         
32022         if (!cfg.xtype.match(/Panel$/)) {
32023             return false;
32024         }
32025         var ret = false;
32026         
32027         if (typeof(cfg.region) == 'undefined') {
32028             Roo.log("Failed to add Panel, region was not set");
32029             Roo.log(cfg);
32030             return false;
32031         }
32032         var region = cfg.region;
32033         delete cfg.region;
32034         
32035           
32036         var xitems = [];
32037         if (cfg.items) {
32038             xitems = cfg.items;
32039             delete cfg.items;
32040         }
32041         var nb = false;
32042         
32043         switch(cfg.xtype) 
32044         {
32045             case 'ContentPanel':  // ContentPanel (el, cfg)
32046             case 'ScrollPanel':  // ContentPanel (el, cfg)
32047             case 'ViewPanel': 
32048                 if(cfg.autoCreate) {
32049                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
32050                 } else {
32051                     var el = this.el.createChild();
32052                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
32053                 }
32054                 
32055                 this.add(region, ret);
32056                 break;
32057             
32058             
32059             case 'TreePanel': // our new panel!
32060                 cfg.el = this.el.createChild();
32061                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
32062                 this.add(region, ret);
32063                 break;
32064             
32065             case 'NestedLayoutPanel': 
32066                 // create a new Layout (which is  a Border Layout...
32067                 var el = this.el.createChild();
32068                 var clayout = cfg.layout;
32069                 delete cfg.layout;
32070                 clayout.items   = clayout.items  || [];
32071                 // replace this exitems with the clayout ones..
32072                 xitems = clayout.items;
32073                  
32074                 
32075                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
32076                     cfg.background = false;
32077                 }
32078                 var layout = new Roo.BorderLayout(el, clayout);
32079                 
32080                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
32081                 //console.log('adding nested layout panel '  + cfg.toSource());
32082                 this.add(region, ret);
32083                 nb = {}; /// find first...
32084                 break;
32085                 
32086             case 'GridPanel': 
32087             
32088                 // needs grid and region
32089                 
32090                 //var el = this.getRegion(region).el.createChild();
32091                 var el = this.el.createChild();
32092                 // create the grid first...
32093                 
32094                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
32095                 delete cfg.grid;
32096                 if (region == 'center' && this.active ) {
32097                     cfg.background = false;
32098                 }
32099                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
32100                 
32101                 this.add(region, ret);
32102                 if (cfg.background) {
32103                     ret.on('activate', function(gp) {
32104                         if (!gp.grid.rendered) {
32105                             gp.grid.render();
32106                         }
32107                     });
32108                 } else {
32109                     grid.render();
32110                 }
32111                 break;
32112            
32113            
32114            
32115                 
32116                 
32117                 
32118             default: 
32119                 alert("Can not add '" + cfg.xtype + "' to BorderLayout");
32120                 return null;
32121              // GridPanel (grid, cfg)
32122             
32123         }
32124         this.beginUpdate();
32125         // add children..
32126         var region = '';
32127         var abn = {};
32128         Roo.each(xitems, function(i)  {
32129             region = nb && i.region ? i.region : false;
32130             
32131             var add = ret.addxtype(i);
32132            
32133             if (region) {
32134                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
32135                 if (!i.background) {
32136                     abn[region] = nb[region] ;
32137                 }
32138             }
32139             
32140         });
32141         this.endUpdate();
32142
32143         // make the last non-background panel active..
32144         //if (nb) { Roo.log(abn); }
32145         if (nb) {
32146             
32147             for(var r in abn) {
32148                 region = this.getRegion(r);
32149                 if (region) {
32150                     // tried using nb[r], but it does not work..
32151                      
32152                     region.showPanel(abn[r]);
32153                    
32154                 }
32155             }
32156         }
32157         return ret;
32158         
32159     }
32160 });
32161
32162 /**
32163  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
32164  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
32165  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
32166  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
32167  * <pre><code>
32168 // shorthand
32169 var CP = Roo.ContentPanel;
32170
32171 var layout = Roo.BorderLayout.create({
32172     north: {
32173         initialSize: 25,
32174         titlebar: false,
32175         panels: [new CP("north", "North")]
32176     },
32177     west: {
32178         split:true,
32179         initialSize: 200,
32180         minSize: 175,
32181         maxSize: 400,
32182         titlebar: true,
32183         collapsible: true,
32184         panels: [new CP("west", {title: "West"})]
32185     },
32186     east: {
32187         split:true,
32188         initialSize: 202,
32189         minSize: 175,
32190         maxSize: 400,
32191         titlebar: true,
32192         collapsible: true,
32193         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
32194     },
32195     south: {
32196         split:true,
32197         initialSize: 100,
32198         minSize: 100,
32199         maxSize: 200,
32200         titlebar: true,
32201         collapsible: true,
32202         panels: [new CP("south", {title: "South", closable: true})]
32203     },
32204     center: {
32205         titlebar: true,
32206         autoScroll:true,
32207         resizeTabs: true,
32208         minTabWidth: 50,
32209         preferredTabWidth: 150,
32210         panels: [
32211             new CP("center1", {title: "Close Me", closable: true}),
32212             new CP("center2", {title: "Center Panel", closable: false})
32213         ]
32214     }
32215 }, document.body);
32216
32217 layout.getRegion("center").showPanel("center1");
32218 </code></pre>
32219  * @param config
32220  * @param targetEl
32221  */
32222 Roo.BorderLayout.create = function(config, targetEl){
32223     var layout = new Roo.BorderLayout(targetEl || document.body, config);
32224     layout.beginUpdate();
32225     var regions = Roo.BorderLayout.RegionFactory.validRegions;
32226     for(var j = 0, jlen = regions.length; j < jlen; j++){
32227         var lr = regions[j];
32228         if(layout.regions[lr] && config[lr].panels){
32229             var r = layout.regions[lr];
32230             var ps = config[lr].panels;
32231             layout.addTypedPanels(r, ps);
32232         }
32233     }
32234     layout.endUpdate();
32235     return layout;
32236 };
32237
32238 // private
32239 Roo.BorderLayout.RegionFactory = {
32240     // private
32241     validRegions : ["north","south","east","west","center"],
32242
32243     // private
32244     create : function(target, mgr, config){
32245         target = target.toLowerCase();
32246         if(config.lightweight || config.basic){
32247             return new Roo.BasicLayoutRegion(mgr, config, target);
32248         }
32249         switch(target){
32250             case "north":
32251                 return new Roo.NorthLayoutRegion(mgr, config);
32252             case "south":
32253                 return new Roo.SouthLayoutRegion(mgr, config);
32254             case "east":
32255                 return new Roo.EastLayoutRegion(mgr, config);
32256             case "west":
32257                 return new Roo.WestLayoutRegion(mgr, config);
32258             case "center":
32259                 return new Roo.CenterLayoutRegion(mgr, config);
32260         }
32261         throw 'Layout region "'+target+'" not supported.';
32262     }
32263 };/*
32264  * Based on:
32265  * Ext JS Library 1.1.1
32266  * Copyright(c) 2006-2007, Ext JS, LLC.
32267  *
32268  * Originally Released Under LGPL - original licence link has changed is not relivant.
32269  *
32270  * Fork - LGPL
32271  * <script type="text/javascript">
32272  */
32273  
32274 /**
32275  * @class Roo.BasicLayoutRegion
32276  * @extends Roo.util.Observable
32277  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
32278  * and does not have a titlebar, tabs or any other features. All it does is size and position 
32279  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
32280  */
32281 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
32282     this.mgr = mgr;
32283     this.position  = pos;
32284     this.events = {
32285         /**
32286          * @scope Roo.BasicLayoutRegion
32287          */
32288         
32289         /**
32290          * @event beforeremove
32291          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
32292          * @param {Roo.LayoutRegion} this
32293          * @param {Roo.ContentPanel} panel The panel
32294          * @param {Object} e The cancel event object
32295          */
32296         "beforeremove" : true,
32297         /**
32298          * @event invalidated
32299          * Fires when the layout for this region is changed.
32300          * @param {Roo.LayoutRegion} this
32301          */
32302         "invalidated" : true,
32303         /**
32304          * @event visibilitychange
32305          * Fires when this region is shown or hidden 
32306          * @param {Roo.LayoutRegion} this
32307          * @param {Boolean} visibility true or false
32308          */
32309         "visibilitychange" : true,
32310         /**
32311          * @event paneladded
32312          * Fires when a panel is added. 
32313          * @param {Roo.LayoutRegion} this
32314          * @param {Roo.ContentPanel} panel The panel
32315          */
32316         "paneladded" : true,
32317         /**
32318          * @event panelremoved
32319          * Fires when a panel is removed. 
32320          * @param {Roo.LayoutRegion} this
32321          * @param {Roo.ContentPanel} panel The panel
32322          */
32323         "panelremoved" : true,
32324         /**
32325          * @event collapsed
32326          * Fires when this region is collapsed.
32327          * @param {Roo.LayoutRegion} this
32328          */
32329         "collapsed" : true,
32330         /**
32331          * @event expanded
32332          * Fires when this region is expanded.
32333          * @param {Roo.LayoutRegion} this
32334          */
32335         "expanded" : true,
32336         /**
32337          * @event slideshow
32338          * Fires when this region is slid into view.
32339          * @param {Roo.LayoutRegion} this
32340          */
32341         "slideshow" : true,
32342         /**
32343          * @event slidehide
32344          * Fires when this region slides out of view. 
32345          * @param {Roo.LayoutRegion} this
32346          */
32347         "slidehide" : true,
32348         /**
32349          * @event panelactivated
32350          * Fires when a panel is activated. 
32351          * @param {Roo.LayoutRegion} this
32352          * @param {Roo.ContentPanel} panel The activated panel
32353          */
32354         "panelactivated" : true,
32355         /**
32356          * @event resized
32357          * Fires when the user resizes this region. 
32358          * @param {Roo.LayoutRegion} this
32359          * @param {Number} newSize The new size (width for east/west, height for north/south)
32360          */
32361         "resized" : true
32362     };
32363     /** A collection of panels in this region. @type Roo.util.MixedCollection */
32364     this.panels = new Roo.util.MixedCollection();
32365     this.panels.getKey = this.getPanelId.createDelegate(this);
32366     this.box = null;
32367     this.activePanel = null;
32368     // ensure listeners are added...
32369     
32370     if (config.listeners || config.events) {
32371         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
32372             listeners : config.listeners || {},
32373             events : config.events || {}
32374         });
32375     }
32376     
32377     if(skipConfig !== true){
32378         this.applyConfig(config);
32379     }
32380 };
32381
32382 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
32383     getPanelId : function(p){
32384         return p.getId();
32385     },
32386     
32387     applyConfig : function(config){
32388         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
32389         this.config = config;
32390         
32391     },
32392     
32393     /**
32394      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
32395      * the width, for horizontal (north, south) the height.
32396      * @param {Number} newSize The new width or height
32397      */
32398     resizeTo : function(newSize){
32399         var el = this.el ? this.el :
32400                  (this.activePanel ? this.activePanel.getEl() : null);
32401         if(el){
32402             switch(this.position){
32403                 case "east":
32404                 case "west":
32405                     el.setWidth(newSize);
32406                     this.fireEvent("resized", this, newSize);
32407                 break;
32408                 case "north":
32409                 case "south":
32410                     el.setHeight(newSize);
32411                     this.fireEvent("resized", this, newSize);
32412                 break;                
32413             }
32414         }
32415     },
32416     
32417     getBox : function(){
32418         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
32419     },
32420     
32421     getMargins : function(){
32422         return this.margins;
32423     },
32424     
32425     updateBox : function(box){
32426         this.box = box;
32427         var el = this.activePanel.getEl();
32428         el.dom.style.left = box.x + "px";
32429         el.dom.style.top = box.y + "px";
32430         this.activePanel.setSize(box.width, box.height);
32431     },
32432     
32433     /**
32434      * Returns the container element for this region.
32435      * @return {Roo.Element}
32436      */
32437     getEl : function(){
32438         return this.activePanel;
32439     },
32440     
32441     /**
32442      * Returns true if this region is currently visible.
32443      * @return {Boolean}
32444      */
32445     isVisible : function(){
32446         return this.activePanel ? true : false;
32447     },
32448     
32449     setActivePanel : function(panel){
32450         panel = this.getPanel(panel);
32451         if(this.activePanel && this.activePanel != panel){
32452             this.activePanel.setActiveState(false);
32453             this.activePanel.getEl().setLeftTop(-10000,-10000);
32454         }
32455         this.activePanel = panel;
32456         panel.setActiveState(true);
32457         if(this.box){
32458             panel.setSize(this.box.width, this.box.height);
32459         }
32460         this.fireEvent("panelactivated", this, panel);
32461         this.fireEvent("invalidated");
32462     },
32463     
32464     /**
32465      * Show the specified panel.
32466      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
32467      * @return {Roo.ContentPanel} The shown panel or null
32468      */
32469     showPanel : function(panel){
32470         if(panel = this.getPanel(panel)){
32471             this.setActivePanel(panel);
32472         }
32473         return panel;
32474     },
32475     
32476     /**
32477      * Get the active panel for this region.
32478      * @return {Roo.ContentPanel} The active panel or null
32479      */
32480     getActivePanel : function(){
32481         return this.activePanel;
32482     },
32483     
32484     /**
32485      * Add the passed ContentPanel(s)
32486      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
32487      * @return {Roo.ContentPanel} The panel added (if only one was added)
32488      */
32489     add : function(panel){
32490         if(arguments.length > 1){
32491             for(var i = 0, len = arguments.length; i < len; i++) {
32492                 this.add(arguments[i]);
32493             }
32494             return null;
32495         }
32496         if(this.hasPanel(panel)){
32497             this.showPanel(panel);
32498             return panel;
32499         }
32500         var el = panel.getEl();
32501         if(el.dom.parentNode != this.mgr.el.dom){
32502             this.mgr.el.dom.appendChild(el.dom);
32503         }
32504         if(panel.setRegion){
32505             panel.setRegion(this);
32506         }
32507         this.panels.add(panel);
32508         el.setStyle("position", "absolute");
32509         if(!panel.background){
32510             this.setActivePanel(panel);
32511             if(this.config.initialSize && this.panels.getCount()==1){
32512                 this.resizeTo(this.config.initialSize);
32513             }
32514         }
32515         this.fireEvent("paneladded", this, panel);
32516         return panel;
32517     },
32518     
32519     /**
32520      * Returns true if the panel is in this region.
32521      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
32522      * @return {Boolean}
32523      */
32524     hasPanel : function(panel){
32525         if(typeof panel == "object"){ // must be panel obj
32526             panel = panel.getId();
32527         }
32528         return this.getPanel(panel) ? true : false;
32529     },
32530     
32531     /**
32532      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
32533      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
32534      * @param {Boolean} preservePanel Overrides the config preservePanel option
32535      * @return {Roo.ContentPanel} The panel that was removed
32536      */
32537     remove : function(panel, preservePanel){
32538         panel = this.getPanel(panel);
32539         if(!panel){
32540             return null;
32541         }
32542         var e = {};
32543         this.fireEvent("beforeremove", this, panel, e);
32544         if(e.cancel === true){
32545             return null;
32546         }
32547         var panelId = panel.getId();
32548         this.panels.removeKey(panelId);
32549         return panel;
32550     },
32551     
32552     /**
32553      * Returns the panel specified or null if it's not in this region.
32554      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
32555      * @return {Roo.ContentPanel}
32556      */
32557     getPanel : function(id){
32558         if(typeof id == "object"){ // must be panel obj
32559             return id;
32560         }
32561         return this.panels.get(id);
32562     },
32563     
32564     /**
32565      * Returns this regions position (north/south/east/west/center).
32566      * @return {String} 
32567      */
32568     getPosition: function(){
32569         return this.position;    
32570     }
32571 });/*
32572  * Based on:
32573  * Ext JS Library 1.1.1
32574  * Copyright(c) 2006-2007, Ext JS, LLC.
32575  *
32576  * Originally Released Under LGPL - original licence link has changed is not relivant.
32577  *
32578  * Fork - LGPL
32579  * <script type="text/javascript">
32580  */
32581  
32582 /**
32583  * @class Roo.LayoutRegion
32584  * @extends Roo.BasicLayoutRegion
32585  * This class represents a region in a layout manager.
32586  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
32587  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
32588  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
32589  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
32590  * @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})
32591  * @cfg {String}    tabPosition     "top" or "bottom" (defaults to "bottom")
32592  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
32593  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
32594  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
32595  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
32596  * @cfg {String}    title           The title for the region (overrides panel titles)
32597  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
32598  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
32599  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
32600  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
32601  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
32602  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
32603  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
32604  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
32605  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
32606  * @cfg {Boolean}   showPin         True to show a pin button
32607  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
32608  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
32609  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
32610  * @cfg {Number}    width           For East/West panels
32611  * @cfg {Number}    height          For North/South panels
32612  * @cfg {Boolean}   split           To show the splitter
32613  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
32614  */
32615 Roo.LayoutRegion = function(mgr, config, pos){
32616     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
32617     var dh = Roo.DomHelper;
32618     /** This region's container element 
32619     * @type Roo.Element */
32620     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
32621     /** This region's title element 
32622     * @type Roo.Element */
32623
32624     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
32625         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
32626         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
32627     ]}, true);
32628     this.titleEl.enableDisplayMode();
32629     /** This region's title text element 
32630     * @type HTMLElement */
32631     this.titleTextEl = this.titleEl.dom.firstChild;
32632     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
32633     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
32634     this.closeBtn.enableDisplayMode();
32635     this.closeBtn.on("click", this.closeClicked, this);
32636     this.closeBtn.hide();
32637
32638     this.createBody(config);
32639     this.visible = true;
32640     this.collapsed = false;
32641
32642     if(config.hideWhenEmpty){
32643         this.hide();
32644         this.on("paneladded", this.validateVisibility, this);
32645         this.on("panelremoved", this.validateVisibility, this);
32646     }
32647     this.applyConfig(config);
32648 };
32649
32650 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
32651
32652     createBody : function(){
32653         /** This region's body element 
32654         * @type Roo.Element */
32655         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
32656     },
32657
32658     applyConfig : function(c){
32659         if(c.collapsible && this.position != "center" && !this.collapsedEl){
32660             var dh = Roo.DomHelper;
32661             if(c.titlebar !== false){
32662                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
32663                 this.collapseBtn.on("click", this.collapse, this);
32664                 this.collapseBtn.enableDisplayMode();
32665
32666                 if(c.showPin === true || this.showPin){
32667                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
32668                     this.stickBtn.enableDisplayMode();
32669                     this.stickBtn.on("click", this.expand, this);
32670                     this.stickBtn.hide();
32671                 }
32672             }
32673             /** This region's collapsed element
32674             * @type Roo.Element */
32675             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
32676                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
32677             ]}, true);
32678             if(c.floatable !== false){
32679                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
32680                this.collapsedEl.on("click", this.collapseClick, this);
32681             }
32682
32683             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
32684                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
32685                    id: "message", unselectable: "on", style:{"float":"left"}});
32686                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
32687              }
32688             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
32689             this.expandBtn.on("click", this.expand, this);
32690         }
32691         if(this.collapseBtn){
32692             this.collapseBtn.setVisible(c.collapsible == true);
32693         }
32694         this.cmargins = c.cmargins || this.cmargins ||
32695                          (this.position == "west" || this.position == "east" ?
32696                              {top: 0, left: 2, right:2, bottom: 0} :
32697                              {top: 2, left: 0, right:0, bottom: 2});
32698         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
32699         this.bottomTabs = c.tabPosition != "top";
32700         this.autoScroll = c.autoScroll || false;
32701         if(this.autoScroll){
32702             this.bodyEl.setStyle("overflow", "auto");
32703         }else{
32704             this.bodyEl.setStyle("overflow", "hidden");
32705         }
32706         //if(c.titlebar !== false){
32707             if((!c.titlebar && !c.title) || c.titlebar === false){
32708                 this.titleEl.hide();
32709             }else{
32710                 this.titleEl.show();
32711                 if(c.title){
32712                     this.titleTextEl.innerHTML = c.title;
32713                 }
32714             }
32715         //}
32716         this.duration = c.duration || .30;
32717         this.slideDuration = c.slideDuration || .45;
32718         this.config = c;
32719         if(c.collapsed){
32720             this.collapse(true);
32721         }
32722         if(c.hidden){
32723             this.hide();
32724         }
32725     },
32726     /**
32727      * Returns true if this region is currently visible.
32728      * @return {Boolean}
32729      */
32730     isVisible : function(){
32731         return this.visible;
32732     },
32733
32734     /**
32735      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
32736      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
32737      */
32738     setCollapsedTitle : function(title){
32739         title = title || "&#160;";
32740         if(this.collapsedTitleTextEl){
32741             this.collapsedTitleTextEl.innerHTML = title;
32742         }
32743     },
32744
32745     getBox : function(){
32746         var b;
32747         if(!this.collapsed){
32748             b = this.el.getBox(false, true);
32749         }else{
32750             b = this.collapsedEl.getBox(false, true);
32751         }
32752         return b;
32753     },
32754
32755     getMargins : function(){
32756         return this.collapsed ? this.cmargins : this.margins;
32757     },
32758
32759     highlight : function(){
32760         this.el.addClass("x-layout-panel-dragover");
32761     },
32762
32763     unhighlight : function(){
32764         this.el.removeClass("x-layout-panel-dragover");
32765     },
32766
32767     updateBox : function(box){
32768         this.box = box;
32769         if(!this.collapsed){
32770             this.el.dom.style.left = box.x + "px";
32771             this.el.dom.style.top = box.y + "px";
32772             this.updateBody(box.width, box.height);
32773         }else{
32774             this.collapsedEl.dom.style.left = box.x + "px";
32775             this.collapsedEl.dom.style.top = box.y + "px";
32776             this.collapsedEl.setSize(box.width, box.height);
32777         }
32778         if(this.tabs){
32779             this.tabs.autoSizeTabs();
32780         }
32781     },
32782
32783     updateBody : function(w, h){
32784         if(w !== null){
32785             this.el.setWidth(w);
32786             w -= this.el.getBorderWidth("rl");
32787             if(this.config.adjustments){
32788                 w += this.config.adjustments[0];
32789             }
32790         }
32791         if(h !== null){
32792             this.el.setHeight(h);
32793             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
32794             h -= this.el.getBorderWidth("tb");
32795             if(this.config.adjustments){
32796                 h += this.config.adjustments[1];
32797             }
32798             this.bodyEl.setHeight(h);
32799             if(this.tabs){
32800                 h = this.tabs.syncHeight(h);
32801             }
32802         }
32803         if(this.panelSize){
32804             w = w !== null ? w : this.panelSize.width;
32805             h = h !== null ? h : this.panelSize.height;
32806         }
32807         if(this.activePanel){
32808             var el = this.activePanel.getEl();
32809             w = w !== null ? w : el.getWidth();
32810             h = h !== null ? h : el.getHeight();
32811             this.panelSize = {width: w, height: h};
32812             this.activePanel.setSize(w, h);
32813         }
32814         if(Roo.isIE && this.tabs){
32815             this.tabs.el.repaint();
32816         }
32817     },
32818
32819     /**
32820      * Returns the container element for this region.
32821      * @return {Roo.Element}
32822      */
32823     getEl : function(){
32824         return this.el;
32825     },
32826
32827     /**
32828      * Hides this region.
32829      */
32830     hide : function(){
32831         if(!this.collapsed){
32832             this.el.dom.style.left = "-2000px";
32833             this.el.hide();
32834         }else{
32835             this.collapsedEl.dom.style.left = "-2000px";
32836             this.collapsedEl.hide();
32837         }
32838         this.visible = false;
32839         this.fireEvent("visibilitychange", this, false);
32840     },
32841
32842     /**
32843      * Shows this region if it was previously hidden.
32844      */
32845     show : function(){
32846         if(!this.collapsed){
32847             this.el.show();
32848         }else{
32849             this.collapsedEl.show();
32850         }
32851         this.visible = true;
32852         this.fireEvent("visibilitychange", this, true);
32853     },
32854
32855     closeClicked : function(){
32856         if(this.activePanel){
32857             this.remove(this.activePanel);
32858         }
32859     },
32860
32861     collapseClick : function(e){
32862         if(this.isSlid){
32863            e.stopPropagation();
32864            this.slideIn();
32865         }else{
32866            e.stopPropagation();
32867            this.slideOut();
32868         }
32869     },
32870
32871     /**
32872      * Collapses this region.
32873      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
32874      */
32875     collapse : function(skipAnim){
32876         if(this.collapsed) return;
32877         this.collapsed = true;
32878         if(this.split){
32879             this.split.el.hide();
32880         }
32881         if(this.config.animate && skipAnim !== true){
32882             this.fireEvent("invalidated", this);
32883             this.animateCollapse();
32884         }else{
32885             this.el.setLocation(-20000,-20000);
32886             this.el.hide();
32887             this.collapsedEl.show();
32888             this.fireEvent("collapsed", this);
32889             this.fireEvent("invalidated", this);
32890         }
32891     },
32892
32893     animateCollapse : function(){
32894         // overridden
32895     },
32896
32897     /**
32898      * Expands this region if it was previously collapsed.
32899      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
32900      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
32901      */
32902     expand : function(e, skipAnim){
32903         if(e) e.stopPropagation();
32904         if(!this.collapsed || this.el.hasActiveFx()) return;
32905         if(this.isSlid){
32906             this.afterSlideIn();
32907             skipAnim = true;
32908         }
32909         this.collapsed = false;
32910         if(this.config.animate && skipAnim !== true){
32911             this.animateExpand();
32912         }else{
32913             this.el.show();
32914             if(this.split){
32915                 this.split.el.show();
32916             }
32917             this.collapsedEl.setLocation(-2000,-2000);
32918             this.collapsedEl.hide();
32919             this.fireEvent("invalidated", this);
32920             this.fireEvent("expanded", this);
32921         }
32922     },
32923
32924     animateExpand : function(){
32925         // overridden
32926     },
32927
32928     initTabs : function()
32929     {
32930         this.bodyEl.setStyle("overflow", "hidden");
32931         var ts = new Roo.TabPanel(
32932                 this.bodyEl.dom,
32933                 {
32934                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
32935                     disableTooltips: this.config.disableTabTips,
32936                     toolbar : this.config.toolbar
32937                 }
32938         );
32939         if(this.config.hideTabs){
32940             ts.stripWrap.setDisplayed(false);
32941         }
32942         this.tabs = ts;
32943         ts.resizeTabs = this.config.resizeTabs === true;
32944         ts.minTabWidth = this.config.minTabWidth || 40;
32945         ts.maxTabWidth = this.config.maxTabWidth || 250;
32946         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
32947         ts.monitorResize = false;
32948         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
32949         ts.bodyEl.addClass('x-layout-tabs-body');
32950         this.panels.each(this.initPanelAsTab, this);
32951     },
32952
32953     initPanelAsTab : function(panel){
32954         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
32955                     this.config.closeOnTab && panel.isClosable());
32956         if(panel.tabTip !== undefined){
32957             ti.setTooltip(panel.tabTip);
32958         }
32959         ti.on("activate", function(){
32960               this.setActivePanel(panel);
32961         }, this);
32962         if(this.config.closeOnTab){
32963             ti.on("beforeclose", function(t, e){
32964                 e.cancel = true;
32965                 this.remove(panel);
32966             }, this);
32967         }
32968         return ti;
32969     },
32970
32971     updatePanelTitle : function(panel, title){
32972         if(this.activePanel == panel){
32973             this.updateTitle(title);
32974         }
32975         if(this.tabs){
32976             var ti = this.tabs.getTab(panel.getEl().id);
32977             ti.setText(title);
32978             if(panel.tabTip !== undefined){
32979                 ti.setTooltip(panel.tabTip);
32980             }
32981         }
32982     },
32983
32984     updateTitle : function(title){
32985         if(this.titleTextEl && !this.config.title){
32986             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
32987         }
32988     },
32989
32990     setActivePanel : function(panel){
32991         panel = this.getPanel(panel);
32992         if(this.activePanel && this.activePanel != panel){
32993             this.activePanel.setActiveState(false);
32994         }
32995         this.activePanel = panel;
32996         panel.setActiveState(true);
32997         if(this.panelSize){
32998             panel.setSize(this.panelSize.width, this.panelSize.height);
32999         }
33000         if(this.closeBtn){
33001             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
33002         }
33003         this.updateTitle(panel.getTitle());
33004         if(this.tabs){
33005             this.fireEvent("invalidated", this);
33006         }
33007         this.fireEvent("panelactivated", this, panel);
33008     },
33009
33010     /**
33011      * Shows the specified panel.
33012      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
33013      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
33014      */
33015     showPanel : function(panel){
33016         if(panel = this.getPanel(panel)){
33017             if(this.tabs){
33018                 var tab = this.tabs.getTab(panel.getEl().id);
33019                 if(tab.isHidden()){
33020                     this.tabs.unhideTab(tab.id);
33021                 }
33022                 tab.activate();
33023             }else{
33024                 this.setActivePanel(panel);
33025             }
33026         }
33027         return panel;
33028     },
33029
33030     /**
33031      * Get the active panel for this region.
33032      * @return {Roo.ContentPanel} The active panel or null
33033      */
33034     getActivePanel : function(){
33035         return this.activePanel;
33036     },
33037
33038     validateVisibility : function(){
33039         if(this.panels.getCount() < 1){
33040             this.updateTitle("&#160;");
33041             this.closeBtn.hide();
33042             this.hide();
33043         }else{
33044             if(!this.isVisible()){
33045                 this.show();
33046             }
33047         }
33048     },
33049
33050     /**
33051      * Adds the passed ContentPanel(s) to this region.
33052      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
33053      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
33054      */
33055     add : function(panel){
33056         if(arguments.length > 1){
33057             for(var i = 0, len = arguments.length; i < len; i++) {
33058                 this.add(arguments[i]);
33059             }
33060             return null;
33061         }
33062         if(this.hasPanel(panel)){
33063             this.showPanel(panel);
33064             return panel;
33065         }
33066         panel.setRegion(this);
33067         this.panels.add(panel);
33068         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
33069             this.bodyEl.dom.appendChild(panel.getEl().dom);
33070             if(panel.background !== true){
33071                 this.setActivePanel(panel);
33072             }
33073             this.fireEvent("paneladded", this, panel);
33074             return panel;
33075         }
33076         if(!this.tabs){
33077             this.initTabs();
33078         }else{
33079             this.initPanelAsTab(panel);
33080         }
33081         if(panel.background !== true){
33082             this.tabs.activate(panel.getEl().id);
33083         }
33084         this.fireEvent("paneladded", this, panel);
33085         return panel;
33086     },
33087
33088     /**
33089      * Hides the tab for the specified panel.
33090      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
33091      */
33092     hidePanel : function(panel){
33093         if(this.tabs && (panel = this.getPanel(panel))){
33094             this.tabs.hideTab(panel.getEl().id);
33095         }
33096     },
33097
33098     /**
33099      * Unhides the tab for a previously hidden panel.
33100      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
33101      */
33102     unhidePanel : function(panel){
33103         if(this.tabs && (panel = this.getPanel(panel))){
33104             this.tabs.unhideTab(panel.getEl().id);
33105         }
33106     },
33107
33108     clearPanels : function(){
33109         while(this.panels.getCount() > 0){
33110              this.remove(this.panels.first());
33111         }
33112     },
33113
33114     /**
33115      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
33116      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
33117      * @param {Boolean} preservePanel Overrides the config preservePanel option
33118      * @return {Roo.ContentPanel} The panel that was removed
33119      */
33120     remove : function(panel, preservePanel){
33121         panel = this.getPanel(panel);
33122         if(!panel){
33123             return null;
33124         }
33125         var e = {};
33126         this.fireEvent("beforeremove", this, panel, e);
33127         if(e.cancel === true){
33128             return null;
33129         }
33130         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
33131         var panelId = panel.getId();
33132         this.panels.removeKey(panelId);
33133         if(preservePanel){
33134             document.body.appendChild(panel.getEl().dom);
33135         }
33136         if(this.tabs){
33137             this.tabs.removeTab(panel.getEl().id);
33138         }else if (!preservePanel){
33139             this.bodyEl.dom.removeChild(panel.getEl().dom);
33140         }
33141         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
33142             var p = this.panels.first();
33143             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
33144             tempEl.appendChild(p.getEl().dom);
33145             this.bodyEl.update("");
33146             this.bodyEl.dom.appendChild(p.getEl().dom);
33147             tempEl = null;
33148             this.updateTitle(p.getTitle());
33149             this.tabs = null;
33150             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
33151             this.setActivePanel(p);
33152         }
33153         panel.setRegion(null);
33154         if(this.activePanel == panel){
33155             this.activePanel = null;
33156         }
33157         if(this.config.autoDestroy !== false && preservePanel !== true){
33158             try{panel.destroy();}catch(e){}
33159         }
33160         this.fireEvent("panelremoved", this, panel);
33161         return panel;
33162     },
33163
33164     /**
33165      * Returns the TabPanel component used by this region
33166      * @return {Roo.TabPanel}
33167      */
33168     getTabs : function(){
33169         return this.tabs;
33170     },
33171
33172     createTool : function(parentEl, className){
33173         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
33174             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
33175         btn.addClassOnOver("x-layout-tools-button-over");
33176         return btn;
33177     }
33178 });/*
33179  * Based on:
33180  * Ext JS Library 1.1.1
33181  * Copyright(c) 2006-2007, Ext JS, LLC.
33182  *
33183  * Originally Released Under LGPL - original licence link has changed is not relivant.
33184  *
33185  * Fork - LGPL
33186  * <script type="text/javascript">
33187  */
33188  
33189
33190
33191 /**
33192  * @class Roo.SplitLayoutRegion
33193  * @extends Roo.LayoutRegion
33194  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
33195  */
33196 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
33197     this.cursor = cursor;
33198     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
33199 };
33200
33201 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
33202     splitTip : "Drag to resize.",
33203     collapsibleSplitTip : "Drag to resize. Double click to hide.",
33204     useSplitTips : false,
33205
33206     applyConfig : function(config){
33207         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
33208         if(config.split){
33209             if(!this.split){
33210                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
33211                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
33212                 /** The SplitBar for this region 
33213                 * @type Roo.SplitBar */
33214                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
33215                 this.split.on("moved", this.onSplitMove, this);
33216                 this.split.useShim = config.useShim === true;
33217                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
33218                 if(this.useSplitTips){
33219                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
33220                 }
33221                 if(config.collapsible){
33222                     this.split.el.on("dblclick", this.collapse,  this);
33223                 }
33224             }
33225             if(typeof config.minSize != "undefined"){
33226                 this.split.minSize = config.minSize;
33227             }
33228             if(typeof config.maxSize != "undefined"){
33229                 this.split.maxSize = config.maxSize;
33230             }
33231             if(config.hideWhenEmpty || config.hidden || config.collapsed){
33232                 this.hideSplitter();
33233             }
33234         }
33235     },
33236
33237     getHMaxSize : function(){
33238          var cmax = this.config.maxSize || 10000;
33239          var center = this.mgr.getRegion("center");
33240          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
33241     },
33242
33243     getVMaxSize : function(){
33244          var cmax = this.config.maxSize || 10000;
33245          var center = this.mgr.getRegion("center");
33246          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
33247     },
33248
33249     onSplitMove : function(split, newSize){
33250         this.fireEvent("resized", this, newSize);
33251     },
33252     
33253     /** 
33254      * Returns the {@link Roo.SplitBar} for this region.
33255      * @return {Roo.SplitBar}
33256      */
33257     getSplitBar : function(){
33258         return this.split;
33259     },
33260     
33261     hide : function(){
33262         this.hideSplitter();
33263         Roo.SplitLayoutRegion.superclass.hide.call(this);
33264     },
33265
33266     hideSplitter : function(){
33267         if(this.split){
33268             this.split.el.setLocation(-2000,-2000);
33269             this.split.el.hide();
33270         }
33271     },
33272
33273     show : function(){
33274         if(this.split){
33275             this.split.el.show();
33276         }
33277         Roo.SplitLayoutRegion.superclass.show.call(this);
33278     },
33279     
33280     beforeSlide: function(){
33281         if(Roo.isGecko){// firefox overflow auto bug workaround
33282             this.bodyEl.clip();
33283             if(this.tabs) this.tabs.bodyEl.clip();
33284             if(this.activePanel){
33285                 this.activePanel.getEl().clip();
33286                 
33287                 if(this.activePanel.beforeSlide){
33288                     this.activePanel.beforeSlide();
33289                 }
33290             }
33291         }
33292     },
33293     
33294     afterSlide : function(){
33295         if(Roo.isGecko){// firefox overflow auto bug workaround
33296             this.bodyEl.unclip();
33297             if(this.tabs) this.tabs.bodyEl.unclip();
33298             if(this.activePanel){
33299                 this.activePanel.getEl().unclip();
33300                 if(this.activePanel.afterSlide){
33301                     this.activePanel.afterSlide();
33302                 }
33303             }
33304         }
33305     },
33306
33307     initAutoHide : function(){
33308         if(this.autoHide !== false){
33309             if(!this.autoHideHd){
33310                 var st = new Roo.util.DelayedTask(this.slideIn, this);
33311                 this.autoHideHd = {
33312                     "mouseout": function(e){
33313                         if(!e.within(this.el, true)){
33314                             st.delay(500);
33315                         }
33316                     },
33317                     "mouseover" : function(e){
33318                         st.cancel();
33319                     },
33320                     scope : this
33321                 };
33322             }
33323             this.el.on(this.autoHideHd);
33324         }
33325     },
33326
33327     clearAutoHide : function(){
33328         if(this.autoHide !== false){
33329             this.el.un("mouseout", this.autoHideHd.mouseout);
33330             this.el.un("mouseover", this.autoHideHd.mouseover);
33331         }
33332     },
33333
33334     clearMonitor : function(){
33335         Roo.get(document).un("click", this.slideInIf, this);
33336     },
33337
33338     // these names are backwards but not changed for compat
33339     slideOut : function(){
33340         if(this.isSlid || this.el.hasActiveFx()){
33341             return;
33342         }
33343         this.isSlid = true;
33344         if(this.collapseBtn){
33345             this.collapseBtn.hide();
33346         }
33347         this.closeBtnState = this.closeBtn.getStyle('display');
33348         this.closeBtn.hide();
33349         if(this.stickBtn){
33350             this.stickBtn.show();
33351         }
33352         this.el.show();
33353         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
33354         this.beforeSlide();
33355         this.el.setStyle("z-index", 10001);
33356         this.el.slideIn(this.getSlideAnchor(), {
33357             callback: function(){
33358                 this.afterSlide();
33359                 this.initAutoHide();
33360                 Roo.get(document).on("click", this.slideInIf, this);
33361                 this.fireEvent("slideshow", this);
33362             },
33363             scope: this,
33364             block: true
33365         });
33366     },
33367
33368     afterSlideIn : function(){
33369         this.clearAutoHide();
33370         this.isSlid = false;
33371         this.clearMonitor();
33372         this.el.setStyle("z-index", "");
33373         if(this.collapseBtn){
33374             this.collapseBtn.show();
33375         }
33376         this.closeBtn.setStyle('display', this.closeBtnState);
33377         if(this.stickBtn){
33378             this.stickBtn.hide();
33379         }
33380         this.fireEvent("slidehide", this);
33381     },
33382
33383     slideIn : function(cb){
33384         if(!this.isSlid || this.el.hasActiveFx()){
33385             Roo.callback(cb);
33386             return;
33387         }
33388         this.isSlid = false;
33389         this.beforeSlide();
33390         this.el.slideOut(this.getSlideAnchor(), {
33391             callback: function(){
33392                 this.el.setLeftTop(-10000, -10000);
33393                 this.afterSlide();
33394                 this.afterSlideIn();
33395                 Roo.callback(cb);
33396             },
33397             scope: this,
33398             block: true
33399         });
33400     },
33401     
33402     slideInIf : function(e){
33403         if(!e.within(this.el)){
33404             this.slideIn();
33405         }
33406     },
33407
33408     animateCollapse : function(){
33409         this.beforeSlide();
33410         this.el.setStyle("z-index", 20000);
33411         var anchor = this.getSlideAnchor();
33412         this.el.slideOut(anchor, {
33413             callback : function(){
33414                 this.el.setStyle("z-index", "");
33415                 this.collapsedEl.slideIn(anchor, {duration:.3});
33416                 this.afterSlide();
33417                 this.el.setLocation(-10000,-10000);
33418                 this.el.hide();
33419                 this.fireEvent("collapsed", this);
33420             },
33421             scope: this,
33422             block: true
33423         });
33424     },
33425
33426     animateExpand : function(){
33427         this.beforeSlide();
33428         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
33429         this.el.setStyle("z-index", 20000);
33430         this.collapsedEl.hide({
33431             duration:.1
33432         });
33433         this.el.slideIn(this.getSlideAnchor(), {
33434             callback : function(){
33435                 this.el.setStyle("z-index", "");
33436                 this.afterSlide();
33437                 if(this.split){
33438                     this.split.el.show();
33439                 }
33440                 this.fireEvent("invalidated", this);
33441                 this.fireEvent("expanded", this);
33442             },
33443             scope: this,
33444             block: true
33445         });
33446     },
33447
33448     anchors : {
33449         "west" : "left",
33450         "east" : "right",
33451         "north" : "top",
33452         "south" : "bottom"
33453     },
33454
33455     sanchors : {
33456         "west" : "l",
33457         "east" : "r",
33458         "north" : "t",
33459         "south" : "b"
33460     },
33461
33462     canchors : {
33463         "west" : "tl-tr",
33464         "east" : "tr-tl",
33465         "north" : "tl-bl",
33466         "south" : "bl-tl"
33467     },
33468
33469     getAnchor : function(){
33470         return this.anchors[this.position];
33471     },
33472
33473     getCollapseAnchor : function(){
33474         return this.canchors[this.position];
33475     },
33476
33477     getSlideAnchor : function(){
33478         return this.sanchors[this.position];
33479     },
33480
33481     getAlignAdj : function(){
33482         var cm = this.cmargins;
33483         switch(this.position){
33484             case "west":
33485                 return [0, 0];
33486             break;
33487             case "east":
33488                 return [0, 0];
33489             break;
33490             case "north":
33491                 return [0, 0];
33492             break;
33493             case "south":
33494                 return [0, 0];
33495             break;
33496         }
33497     },
33498
33499     getExpandAdj : function(){
33500         var c = this.collapsedEl, cm = this.cmargins;
33501         switch(this.position){
33502             case "west":
33503                 return [-(cm.right+c.getWidth()+cm.left), 0];
33504             break;
33505             case "east":
33506                 return [cm.right+c.getWidth()+cm.left, 0];
33507             break;
33508             case "north":
33509                 return [0, -(cm.top+cm.bottom+c.getHeight())];
33510             break;
33511             case "south":
33512                 return [0, cm.top+cm.bottom+c.getHeight()];
33513             break;
33514         }
33515     }
33516 });/*
33517  * Based on:
33518  * Ext JS Library 1.1.1
33519  * Copyright(c) 2006-2007, Ext JS, LLC.
33520  *
33521  * Originally Released Under LGPL - original licence link has changed is not relivant.
33522  *
33523  * Fork - LGPL
33524  * <script type="text/javascript">
33525  */
33526 /*
33527  * These classes are private internal classes
33528  */
33529 Roo.CenterLayoutRegion = function(mgr, config){
33530     Roo.LayoutRegion.call(this, mgr, config, "center");
33531     this.visible = true;
33532     this.minWidth = config.minWidth || 20;
33533     this.minHeight = config.minHeight || 20;
33534 };
33535
33536 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
33537     hide : function(){
33538         // center panel can't be hidden
33539     },
33540     
33541     show : function(){
33542         // center panel can't be hidden
33543     },
33544     
33545     getMinWidth: function(){
33546         return this.minWidth;
33547     },
33548     
33549     getMinHeight: function(){
33550         return this.minHeight;
33551     }
33552 });
33553
33554
33555 Roo.NorthLayoutRegion = function(mgr, config){
33556     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
33557     if(this.split){
33558         this.split.placement = Roo.SplitBar.TOP;
33559         this.split.orientation = Roo.SplitBar.VERTICAL;
33560         this.split.el.addClass("x-layout-split-v");
33561     }
33562     var size = config.initialSize || config.height;
33563     if(typeof size != "undefined"){
33564         this.el.setHeight(size);
33565     }
33566 };
33567 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
33568     orientation: Roo.SplitBar.VERTICAL,
33569     getBox : function(){
33570         if(this.collapsed){
33571             return this.collapsedEl.getBox();
33572         }
33573         var box = this.el.getBox();
33574         if(this.split){
33575             box.height += this.split.el.getHeight();
33576         }
33577         return box;
33578     },
33579     
33580     updateBox : function(box){
33581         if(this.split && !this.collapsed){
33582             box.height -= this.split.el.getHeight();
33583             this.split.el.setLeft(box.x);
33584             this.split.el.setTop(box.y+box.height);
33585             this.split.el.setWidth(box.width);
33586         }
33587         if(this.collapsed){
33588             this.updateBody(box.width, null);
33589         }
33590         Roo.LayoutRegion.prototype.updateBox.call(this, box);
33591     }
33592 });
33593
33594 Roo.SouthLayoutRegion = function(mgr, config){
33595     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
33596     if(this.split){
33597         this.split.placement = Roo.SplitBar.BOTTOM;
33598         this.split.orientation = Roo.SplitBar.VERTICAL;
33599         this.split.el.addClass("x-layout-split-v");
33600     }
33601     var size = config.initialSize || config.height;
33602     if(typeof size != "undefined"){
33603         this.el.setHeight(size);
33604     }
33605 };
33606 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
33607     orientation: Roo.SplitBar.VERTICAL,
33608     getBox : function(){
33609         if(this.collapsed){
33610             return this.collapsedEl.getBox();
33611         }
33612         var box = this.el.getBox();
33613         if(this.split){
33614             var sh = this.split.el.getHeight();
33615             box.height += sh;
33616             box.y -= sh;
33617         }
33618         return box;
33619     },
33620     
33621     updateBox : function(box){
33622         if(this.split && !this.collapsed){
33623             var sh = this.split.el.getHeight();
33624             box.height -= sh;
33625             box.y += sh;
33626             this.split.el.setLeft(box.x);
33627             this.split.el.setTop(box.y-sh);
33628             this.split.el.setWidth(box.width);
33629         }
33630         if(this.collapsed){
33631             this.updateBody(box.width, null);
33632         }
33633         Roo.LayoutRegion.prototype.updateBox.call(this, box);
33634     }
33635 });
33636
33637 Roo.EastLayoutRegion = function(mgr, config){
33638     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
33639     if(this.split){
33640         this.split.placement = Roo.SplitBar.RIGHT;
33641         this.split.orientation = Roo.SplitBar.HORIZONTAL;
33642         this.split.el.addClass("x-layout-split-h");
33643     }
33644     var size = config.initialSize || config.width;
33645     if(typeof size != "undefined"){
33646         this.el.setWidth(size);
33647     }
33648 };
33649 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
33650     orientation: Roo.SplitBar.HORIZONTAL,
33651     getBox : function(){
33652         if(this.collapsed){
33653             return this.collapsedEl.getBox();
33654         }
33655         var box = this.el.getBox();
33656         if(this.split){
33657             var sw = this.split.el.getWidth();
33658             box.width += sw;
33659             box.x -= sw;
33660         }
33661         return box;
33662     },
33663
33664     updateBox : function(box){
33665         if(this.split && !this.collapsed){
33666             var sw = this.split.el.getWidth();
33667             box.width -= sw;
33668             this.split.el.setLeft(box.x);
33669             this.split.el.setTop(box.y);
33670             this.split.el.setHeight(box.height);
33671             box.x += sw;
33672         }
33673         if(this.collapsed){
33674             this.updateBody(null, box.height);
33675         }
33676         Roo.LayoutRegion.prototype.updateBox.call(this, box);
33677     }
33678 });
33679
33680 Roo.WestLayoutRegion = function(mgr, config){
33681     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
33682     if(this.split){
33683         this.split.placement = Roo.SplitBar.LEFT;
33684         this.split.orientation = Roo.SplitBar.HORIZONTAL;
33685         this.split.el.addClass("x-layout-split-h");
33686     }
33687     var size = config.initialSize || config.width;
33688     if(typeof size != "undefined"){
33689         this.el.setWidth(size);
33690     }
33691 };
33692 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
33693     orientation: Roo.SplitBar.HORIZONTAL,
33694     getBox : function(){
33695         if(this.collapsed){
33696             return this.collapsedEl.getBox();
33697         }
33698         var box = this.el.getBox();
33699         if(this.split){
33700             box.width += this.split.el.getWidth();
33701         }
33702         return box;
33703     },
33704     
33705     updateBox : function(box){
33706         if(this.split && !this.collapsed){
33707             var sw = this.split.el.getWidth();
33708             box.width -= sw;
33709             this.split.el.setLeft(box.x+box.width);
33710             this.split.el.setTop(box.y);
33711             this.split.el.setHeight(box.height);
33712         }
33713         if(this.collapsed){
33714             this.updateBody(null, box.height);
33715         }
33716         Roo.LayoutRegion.prototype.updateBox.call(this, box);
33717     }
33718 });
33719 /*
33720  * Based on:
33721  * Ext JS Library 1.1.1
33722  * Copyright(c) 2006-2007, Ext JS, LLC.
33723  *
33724  * Originally Released Under LGPL - original licence link has changed is not relivant.
33725  *
33726  * Fork - LGPL
33727  * <script type="text/javascript">
33728  */
33729  
33730  
33731 /*
33732  * Private internal class for reading and applying state
33733  */
33734 Roo.LayoutStateManager = function(layout){
33735      // default empty state
33736      this.state = {
33737         north: {},
33738         south: {},
33739         east: {},
33740         west: {}       
33741     };
33742 };
33743
33744 Roo.LayoutStateManager.prototype = {
33745     init : function(layout, provider){
33746         this.provider = provider;
33747         var state = provider.get(layout.id+"-layout-state");
33748         if(state){
33749             var wasUpdating = layout.isUpdating();
33750             if(!wasUpdating){
33751                 layout.beginUpdate();
33752             }
33753             for(var key in state){
33754                 if(typeof state[key] != "function"){
33755                     var rstate = state[key];
33756                     var r = layout.getRegion(key);
33757                     if(r && rstate){
33758                         if(rstate.size){
33759                             r.resizeTo(rstate.size);
33760                         }
33761                         if(rstate.collapsed == true){
33762                             r.collapse(true);
33763                         }else{
33764                             r.expand(null, true);
33765                         }
33766                     }
33767                 }
33768             }
33769             if(!wasUpdating){
33770                 layout.endUpdate();
33771             }
33772             this.state = state; 
33773         }
33774         this.layout = layout;
33775         layout.on("regionresized", this.onRegionResized, this);
33776         layout.on("regioncollapsed", this.onRegionCollapsed, this);
33777         layout.on("regionexpanded", this.onRegionExpanded, this);
33778     },
33779     
33780     storeState : function(){
33781         this.provider.set(this.layout.id+"-layout-state", this.state);
33782     },
33783     
33784     onRegionResized : function(region, newSize){
33785         this.state[region.getPosition()].size = newSize;
33786         this.storeState();
33787     },
33788     
33789     onRegionCollapsed : function(region){
33790         this.state[region.getPosition()].collapsed = true;
33791         this.storeState();
33792     },
33793     
33794     onRegionExpanded : function(region){
33795         this.state[region.getPosition()].collapsed = false;
33796         this.storeState();
33797     }
33798 };/*
33799  * Based on:
33800  * Ext JS Library 1.1.1
33801  * Copyright(c) 2006-2007, Ext JS, LLC.
33802  *
33803  * Originally Released Under LGPL - original licence link has changed is not relivant.
33804  *
33805  * Fork - LGPL
33806  * <script type="text/javascript">
33807  */
33808 /**
33809  * @class Roo.ContentPanel
33810  * @extends Roo.util.Observable
33811  * A basic ContentPanel element.
33812  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
33813  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
33814  * @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
33815  * @cfg {Boolean}   closable      True if the panel can be closed/removed
33816  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
33817  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
33818  * @cfg {Toolbar}   toolbar       A toolbar for this panel
33819  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
33820  * @cfg {String} title          The title for this panel
33821  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
33822  * @cfg {String} url            Calls {@link #setUrl} with this value
33823  * @cfg {String} region         (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
33824  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
33825  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
33826  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
33827
33828  * @constructor
33829  * Create a new ContentPanel.
33830  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
33831  * @param {String/Object} config A string to set only the title or a config object
33832  * @param {String} content (optional) Set the HTML content for this panel
33833  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
33834  */
33835 Roo.ContentPanel = function(el, config, content){
33836     
33837      
33838     /*
33839     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
33840         config = el;
33841         el = Roo.id();
33842     }
33843     if (config && config.parentLayout) { 
33844         el = config.parentLayout.el.createChild(); 
33845     }
33846     */
33847     if(el.autoCreate){ // xtype is available if this is called from factory
33848         config = el;
33849         el = Roo.id();
33850     }
33851     this.el = Roo.get(el);
33852     if(!this.el && config && config.autoCreate){
33853         if(typeof config.autoCreate == "object"){
33854             if(!config.autoCreate.id){
33855                 config.autoCreate.id = config.id||el;
33856             }
33857             this.el = Roo.DomHelper.append(document.body,
33858                         config.autoCreate, true);
33859         }else{
33860             this.el = Roo.DomHelper.append(document.body,
33861                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
33862         }
33863     }
33864     this.closable = false;
33865     this.loaded = false;
33866     this.active = false;
33867     if(typeof config == "string"){
33868         this.title = config;
33869     }else{
33870         Roo.apply(this, config);
33871     }
33872     
33873     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
33874         this.wrapEl = this.el.wrap();
33875         this.toolbar.container = this.el.insertSibling(false, 'before');
33876         this.toolbar = new Roo.Toolbar(this.toolbar);
33877     }
33878     
33879     // xtype created footer. - not sure if will work as we normally have to render first..
33880     if (this.footer && !this.footer.el && this.footer.xtype) {
33881         if (!this.wrapEl) {
33882             this.wrapEl = this.el.wrap();
33883         }
33884     
33885         this.footer.container = this.wrapEl.createChild();
33886          
33887         this.footer = Roo.factory(this.footer, Roo);
33888         
33889     }
33890     
33891     if(this.resizeEl){
33892         this.resizeEl = Roo.get(this.resizeEl, true);
33893     }else{
33894         this.resizeEl = this.el;
33895     }
33896     // handle view.xtype
33897     
33898  
33899     
33900     
33901     this.addEvents({
33902         /**
33903          * @event activate
33904          * Fires when this panel is activated. 
33905          * @param {Roo.ContentPanel} this
33906          */
33907         "activate" : true,
33908         /**
33909          * @event deactivate
33910          * Fires when this panel is activated. 
33911          * @param {Roo.ContentPanel} this
33912          */
33913         "deactivate" : true,
33914
33915         /**
33916          * @event resize
33917          * Fires when this panel is resized if fitToFrame is true.
33918          * @param {Roo.ContentPanel} this
33919          * @param {Number} width The width after any component adjustments
33920          * @param {Number} height The height after any component adjustments
33921          */
33922         "resize" : true,
33923         
33924          /**
33925          * @event render
33926          * Fires when this tab is created
33927          * @param {Roo.ContentPanel} this
33928          */
33929         "render" : true
33930         
33931         
33932         
33933     });
33934     
33935
33936     
33937     
33938     if(this.autoScroll){
33939         this.resizeEl.setStyle("overflow", "auto");
33940     } else {
33941         // fix randome scrolling
33942         this.el.on('scroll', function() {
33943             Roo.log('fix random scolling');
33944             this.scrollTo('top',0); 
33945         });
33946     }
33947     content = content || this.content;
33948     if(content){
33949         this.setContent(content);
33950     }
33951     if(config && config.url){
33952         this.setUrl(this.url, this.params, this.loadOnce);
33953     }
33954     
33955     
33956     
33957     Roo.ContentPanel.superclass.constructor.call(this);
33958     
33959     if (this.view && typeof(this.view.xtype) != 'undefined') {
33960         this.view.el = this.el.appendChild(document.createElement("div"));
33961         this.view = Roo.factory(this.view); 
33962         this.view.render  &&  this.view.render(false, '');  
33963     }
33964     
33965     
33966     this.fireEvent('render', this);
33967 };
33968
33969 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
33970     tabTip:'',
33971     setRegion : function(region){
33972         this.region = region;
33973         if(region){
33974            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
33975         }else{
33976            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
33977         } 
33978     },
33979     
33980     /**
33981      * Returns the toolbar for this Panel if one was configured. 
33982      * @return {Roo.Toolbar} 
33983      */
33984     getToolbar : function(){
33985         return this.toolbar;
33986     },
33987     
33988     setActiveState : function(active){
33989         this.active = active;
33990         if(!active){
33991             this.fireEvent("deactivate", this);
33992         }else{
33993             this.fireEvent("activate", this);
33994         }
33995     },
33996     /**
33997      * Updates this panel's element
33998      * @param {String} content The new content
33999      * @param {Boolean} loadScripts (optional) true to look for and process scripts
34000     */
34001     setContent : function(content, loadScripts){
34002         this.el.update(content, loadScripts);
34003     },
34004
34005     ignoreResize : function(w, h){
34006         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
34007             return true;
34008         }else{
34009             this.lastSize = {width: w, height: h};
34010             return false;
34011         }
34012     },
34013     /**
34014      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
34015      * @return {Roo.UpdateManager} The UpdateManager
34016      */
34017     getUpdateManager : function(){
34018         return this.el.getUpdateManager();
34019     },
34020      /**
34021      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
34022      * @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:
34023 <pre><code>
34024 panel.load({
34025     url: "your-url.php",
34026     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
34027     callback: yourFunction,
34028     scope: yourObject, //(optional scope)
34029     discardUrl: false,
34030     nocache: false,
34031     text: "Loading...",
34032     timeout: 30,
34033     scripts: false
34034 });
34035 </code></pre>
34036      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
34037      * 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.
34038      * @param {String/Object} params (optional) The parameters to pass as either a URL encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2}
34039      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
34040      * @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.
34041      * @return {Roo.ContentPanel} this
34042      */
34043     load : function(){
34044         var um = this.el.getUpdateManager();
34045         um.update.apply(um, arguments);
34046         return this;
34047     },
34048
34049
34050     /**
34051      * 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.
34052      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
34053      * @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)
34054      * @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)
34055      * @return {Roo.UpdateManager} The UpdateManager
34056      */
34057     setUrl : function(url, params, loadOnce){
34058         if(this.refreshDelegate){
34059             this.removeListener("activate", this.refreshDelegate);
34060         }
34061         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
34062         this.on("activate", this.refreshDelegate);
34063         return this.el.getUpdateManager();
34064     },
34065     
34066     _handleRefresh : function(url, params, loadOnce){
34067         if(!loadOnce || !this.loaded){
34068             var updater = this.el.getUpdateManager();
34069             updater.update(url, params, this._setLoaded.createDelegate(this));
34070         }
34071     },
34072     
34073     _setLoaded : function(){
34074         this.loaded = true;
34075     }, 
34076     
34077     /**
34078      * Returns this panel's id
34079      * @return {String} 
34080      */
34081     getId : function(){
34082         return this.el.id;
34083     },
34084     
34085     /** 
34086      * Returns this panel's element - used by regiosn to add.
34087      * @return {Roo.Element} 
34088      */
34089     getEl : function(){
34090         return this.wrapEl || this.el;
34091     },
34092     
34093     adjustForComponents : function(width, height)
34094     {
34095         //Roo.log('adjustForComponents ');
34096         if(this.resizeEl != this.el){
34097             width -= this.el.getFrameWidth('lr');
34098             height -= this.el.getFrameWidth('tb');
34099         }
34100         if(this.toolbar){
34101             var te = this.toolbar.getEl();
34102             height -= te.getHeight();
34103             te.setWidth(width);
34104         }
34105         if(this.footer){
34106             var te = this.footer.getEl();
34107             Roo.log("footer:" + te.getHeight());
34108             
34109             height -= te.getHeight();
34110             te.setWidth(width);
34111         }
34112         
34113         
34114         if(this.adjustments){
34115             width += this.adjustments[0];
34116             height += this.adjustments[1];
34117         }
34118         return {"width": width, "height": height};
34119     },
34120     
34121     setSize : function(width, height){
34122         if(this.fitToFrame && !this.ignoreResize(width, height)){
34123             if(this.fitContainer && this.resizeEl != this.el){
34124                 this.el.setSize(width, height);
34125             }
34126             var size = this.adjustForComponents(width, height);
34127             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
34128             this.fireEvent('resize', this, size.width, size.height);
34129         }
34130     },
34131     
34132     /**
34133      * Returns this panel's title
34134      * @return {String} 
34135      */
34136     getTitle : function(){
34137         return this.title;
34138     },
34139     
34140     /**
34141      * Set this panel's title
34142      * @param {String} title
34143      */
34144     setTitle : function(title){
34145         this.title = title;
34146         if(this.region){
34147             this.region.updatePanelTitle(this, title);
34148         }
34149     },
34150     
34151     /**
34152      * Returns true is this panel was configured to be closable
34153      * @return {Boolean} 
34154      */
34155     isClosable : function(){
34156         return this.closable;
34157     },
34158     
34159     beforeSlide : function(){
34160         this.el.clip();
34161         this.resizeEl.clip();
34162     },
34163     
34164     afterSlide : function(){
34165         this.el.unclip();
34166         this.resizeEl.unclip();
34167     },
34168     
34169     /**
34170      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
34171      *   Will fail silently if the {@link #setUrl} method has not been called.
34172      *   This does not activate the panel, just updates its content.
34173      */
34174     refresh : function(){
34175         if(this.refreshDelegate){
34176            this.loaded = false;
34177            this.refreshDelegate();
34178         }
34179     },
34180     
34181     /**
34182      * Destroys this panel
34183      */
34184     destroy : function(){
34185         this.el.removeAllListeners();
34186         var tempEl = document.createElement("span");
34187         tempEl.appendChild(this.el.dom);
34188         tempEl.innerHTML = "";
34189         this.el.remove();
34190         this.el = null;
34191     },
34192     
34193     /**
34194      * form - if the content panel contains a form - this is a reference to it.
34195      * @type {Roo.form.Form}
34196      */
34197     form : false,
34198     /**
34199      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
34200      *    This contains a reference to it.
34201      * @type {Roo.View}
34202      */
34203     view : false,
34204     
34205       /**
34206      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
34207      * <pre><code>
34208
34209 layout.addxtype({
34210        xtype : 'Form',
34211        items: [ .... ]
34212    }
34213 );
34214
34215 </code></pre>
34216      * @param {Object} cfg Xtype definition of item to add.
34217      */
34218     
34219     addxtype : function(cfg) {
34220         // add form..
34221         if (cfg.xtype.match(/^Form$/)) {
34222             
34223             var el;
34224             //if (this.footer) {
34225             //    el = this.footer.container.insertSibling(false, 'before');
34226             //} else {
34227                 el = this.el.createChild();
34228             //}
34229
34230             this.form = new  Roo.form.Form(cfg);
34231             
34232             
34233             if ( this.form.allItems.length) this.form.render(el.dom);
34234             return this.form;
34235         }
34236         // should only have one of theses..
34237         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
34238             // views.. should not be just added - used named prop 'view''
34239             
34240             cfg.el = this.el.appendChild(document.createElement("div"));
34241             // factory?
34242             
34243             var ret = new Roo.factory(cfg);
34244              
34245              ret.render && ret.render(false, ''); // render blank..
34246             this.view = ret;
34247             return ret;
34248         }
34249         return false;
34250     }
34251 });
34252
34253 /**
34254  * @class Roo.GridPanel
34255  * @extends Roo.ContentPanel
34256  * @constructor
34257  * Create a new GridPanel.
34258  * @param {Roo.grid.Grid} grid The grid for this panel
34259  * @param {String/Object} config A string to set only the panel's title, or a config object
34260  */
34261 Roo.GridPanel = function(grid, config){
34262     
34263   
34264     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
34265         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
34266         
34267     this.wrapper.dom.appendChild(grid.getGridEl().dom);
34268     
34269     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
34270     
34271     if(this.toolbar){
34272         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
34273     }
34274     // xtype created footer. - not sure if will work as we normally have to render first..
34275     if (this.footer && !this.footer.el && this.footer.xtype) {
34276         
34277         this.footer.container = this.grid.getView().getFooterPanel(true);
34278         this.footer.dataSource = this.grid.dataSource;
34279         this.footer = Roo.factory(this.footer, Roo);
34280         
34281     }
34282     
34283     grid.monitorWindowResize = false; // turn off autosizing
34284     grid.autoHeight = false;
34285     grid.autoWidth = false;
34286     this.grid = grid;
34287     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
34288 };
34289
34290 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
34291     getId : function(){
34292         return this.grid.id;
34293     },
34294     
34295     /**
34296      * Returns the grid for this panel
34297      * @return {Roo.grid.Grid} 
34298      */
34299     getGrid : function(){
34300         return this.grid;    
34301     },
34302     
34303     setSize : function(width, height){
34304         if(!this.ignoreResize(width, height)){
34305             var grid = this.grid;
34306             var size = this.adjustForComponents(width, height);
34307             grid.getGridEl().setSize(size.width, size.height);
34308             grid.autoSize();
34309         }
34310     },
34311     
34312     beforeSlide : function(){
34313         this.grid.getView().scroller.clip();
34314     },
34315     
34316     afterSlide : function(){
34317         this.grid.getView().scroller.unclip();
34318     },
34319     
34320     destroy : function(){
34321         this.grid.destroy();
34322         delete this.grid;
34323         Roo.GridPanel.superclass.destroy.call(this); 
34324     }
34325 });
34326
34327
34328 /**
34329  * @class Roo.NestedLayoutPanel
34330  * @extends Roo.ContentPanel
34331  * @constructor
34332  * Create a new NestedLayoutPanel.
34333  * 
34334  * 
34335  * @param {Roo.BorderLayout} layout The layout for this panel
34336  * @param {String/Object} config A string to set only the title or a config object
34337  */
34338 Roo.NestedLayoutPanel = function(layout, config)
34339 {
34340     // construct with only one argument..
34341     /* FIXME - implement nicer consturctors
34342     if (layout.layout) {
34343         config = layout;
34344         layout = config.layout;
34345         delete config.layout;
34346     }
34347     if (layout.xtype && !layout.getEl) {
34348         // then layout needs constructing..
34349         layout = Roo.factory(layout, Roo);
34350     }
34351     */
34352     
34353     
34354     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
34355     
34356     layout.monitorWindowResize = false; // turn off autosizing
34357     this.layout = layout;
34358     this.layout.getEl().addClass("x-layout-nested-layout");
34359     
34360     
34361     
34362     
34363 };
34364
34365 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
34366
34367     setSize : function(width, height){
34368         if(!this.ignoreResize(width, height)){
34369             var size = this.adjustForComponents(width, height);
34370             var el = this.layout.getEl();
34371             el.setSize(size.width, size.height);
34372             var touch = el.dom.offsetWidth;
34373             this.layout.layout();
34374             // ie requires a double layout on the first pass
34375             if(Roo.isIE && !this.initialized){
34376                 this.initialized = true;
34377                 this.layout.layout();
34378             }
34379         }
34380     },
34381     
34382     // activate all subpanels if not currently active..
34383     
34384     setActiveState : function(active){
34385         this.active = active;
34386         if(!active){
34387             this.fireEvent("deactivate", this);
34388             return;
34389         }
34390         
34391         this.fireEvent("activate", this);
34392         // not sure if this should happen before or after..
34393         if (!this.layout) {
34394             return; // should not happen..
34395         }
34396         var reg = false;
34397         for (var r in this.layout.regions) {
34398             reg = this.layout.getRegion(r);
34399             if (reg.getActivePanel()) {
34400                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
34401                 reg.setActivePanel(reg.getActivePanel());
34402                 continue;
34403             }
34404             if (!reg.panels.length) {
34405                 continue;
34406             }
34407             reg.showPanel(reg.getPanel(0));
34408         }
34409         
34410         
34411         
34412         
34413     },
34414     
34415     /**
34416      * Returns the nested BorderLayout for this panel
34417      * @return {Roo.BorderLayout} 
34418      */
34419     getLayout : function(){
34420         return this.layout;
34421     },
34422     
34423      /**
34424      * Adds a xtype elements to the layout of the nested panel
34425      * <pre><code>
34426
34427 panel.addxtype({
34428        xtype : 'ContentPanel',
34429        region: 'west',
34430        items: [ .... ]
34431    }
34432 );
34433
34434 panel.addxtype({
34435         xtype : 'NestedLayoutPanel',
34436         region: 'west',
34437         layout: {
34438            center: { },
34439            west: { }   
34440         },
34441         items : [ ... list of content panels or nested layout panels.. ]
34442    }
34443 );
34444 </code></pre>
34445      * @param {Object} cfg Xtype definition of item to add.
34446      */
34447     addxtype : function(cfg) {
34448         return this.layout.addxtype(cfg);
34449     
34450     }
34451 });
34452
34453 Roo.ScrollPanel = function(el, config, content){
34454     config = config || {};
34455     config.fitToFrame = true;
34456     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
34457     
34458     this.el.dom.style.overflow = "hidden";
34459     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
34460     this.el.removeClass("x-layout-inactive-content");
34461     this.el.on("mousewheel", this.onWheel, this);
34462
34463     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
34464     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
34465     up.unselectable(); down.unselectable();
34466     up.on("click", this.scrollUp, this);
34467     down.on("click", this.scrollDown, this);
34468     up.addClassOnOver("x-scroller-btn-over");
34469     down.addClassOnOver("x-scroller-btn-over");
34470     up.addClassOnClick("x-scroller-btn-click");
34471     down.addClassOnClick("x-scroller-btn-click");
34472     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
34473
34474     this.resizeEl = this.el;
34475     this.el = wrap; this.up = up; this.down = down;
34476 };
34477
34478 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
34479     increment : 100,
34480     wheelIncrement : 5,
34481     scrollUp : function(){
34482         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
34483     },
34484
34485     scrollDown : function(){
34486         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
34487     },
34488
34489     afterScroll : function(){
34490         var el = this.resizeEl;
34491         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
34492         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
34493         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
34494     },
34495
34496     setSize : function(){
34497         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
34498         this.afterScroll();
34499     },
34500
34501     onWheel : function(e){
34502         var d = e.getWheelDelta();
34503         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
34504         this.afterScroll();
34505         e.stopEvent();
34506     },
34507
34508     setContent : function(content, loadScripts){
34509         this.resizeEl.update(content, loadScripts);
34510     }
34511
34512 });
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522 /**
34523  * @class Roo.TreePanel
34524  * @extends Roo.ContentPanel
34525  * @constructor
34526  * Create a new TreePanel. - defaults to fit/scoll contents.
34527  * @param {String/Object} config A string to set only the panel's title, or a config object
34528  * @cfg {Roo.tree.TreePanel} tree The tree TreePanel, with config etc.
34529  */
34530 Roo.TreePanel = function(config){
34531     var el = config.el;
34532     var tree = config.tree;
34533     delete config.tree; 
34534     delete config.el; // hopefull!
34535     
34536     // wrapper for IE7 strict & safari scroll issue
34537     
34538     var treeEl = el.createChild();
34539     config.resizeEl = treeEl;
34540     
34541     
34542     
34543     Roo.TreePanel.superclass.constructor.call(this, el, config);
34544  
34545  
34546     this.tree = new Roo.tree.TreePanel(treeEl , tree);
34547     //console.log(tree);
34548     this.on('activate', function()
34549     {
34550         if (this.tree.rendered) {
34551             return;
34552         }
34553         //console.log('render tree');
34554         this.tree.render();
34555     });
34556     // this should not be needed.. - it's actually the 'el' that resizes?
34557     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
34558     
34559     //this.on('resize',  function (cp, w, h) {
34560     //        this.tree.innerCt.setWidth(w);
34561     //        this.tree.innerCt.setHeight(h);
34562     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
34563     //});
34564
34565         
34566     
34567 };
34568
34569 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
34570     fitToFrame : true,
34571     autoScroll : true
34572 });
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584 /*
34585  * Based on:
34586  * Ext JS Library 1.1.1
34587  * Copyright(c) 2006-2007, Ext JS, LLC.
34588  *
34589  * Originally Released Under LGPL - original licence link has changed is not relivant.
34590  *
34591  * Fork - LGPL
34592  * <script type="text/javascript">
34593  */
34594  
34595
34596 /**
34597  * @class Roo.ReaderLayout
34598  * @extends Roo.BorderLayout
34599  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
34600  * center region containing two nested regions (a top one for a list view and one for item preview below),
34601  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
34602  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
34603  * expedites the setup of the overall layout and regions for this common application style.
34604  * Example:
34605  <pre><code>
34606 var reader = new Roo.ReaderLayout();
34607 var CP = Roo.ContentPanel;  // shortcut for adding
34608
34609 reader.beginUpdate();
34610 reader.add("north", new CP("north", "North"));
34611 reader.add("west", new CP("west", {title: "West"}));
34612 reader.add("east", new CP("east", {title: "East"}));
34613
34614 reader.regions.listView.add(new CP("listView", "List"));
34615 reader.regions.preview.add(new CP("preview", "Preview"));
34616 reader.endUpdate();
34617 </code></pre>
34618 * @constructor
34619 * Create a new ReaderLayout
34620 * @param {Object} config Configuration options
34621 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
34622 * document.body if omitted)
34623 */
34624 Roo.ReaderLayout = function(config, renderTo){
34625     var c = config || {size:{}};
34626     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
34627         north: c.north !== false ? Roo.apply({
34628             split:false,
34629             initialSize: 32,
34630             titlebar: false
34631         }, c.north) : false,
34632         west: c.west !== false ? Roo.apply({
34633             split:true,
34634             initialSize: 200,
34635             minSize: 175,
34636             maxSize: 400,
34637             titlebar: true,
34638             collapsible: true,
34639             animate: true,
34640             margins:{left:5,right:0,bottom:5,top:5},
34641             cmargins:{left:5,right:5,bottom:5,top:5}
34642         }, c.west) : false,
34643         east: c.east !== false ? Roo.apply({
34644             split:true,
34645             initialSize: 200,
34646             minSize: 175,
34647             maxSize: 400,
34648             titlebar: true,
34649             collapsible: true,
34650             animate: true,
34651             margins:{left:0,right:5,bottom:5,top:5},
34652             cmargins:{left:5,right:5,bottom:5,top:5}
34653         }, c.east) : false,
34654         center: Roo.apply({
34655             tabPosition: 'top',
34656             autoScroll:false,
34657             closeOnTab: true,
34658             titlebar:false,
34659             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
34660         }, c.center)
34661     });
34662
34663     this.el.addClass('x-reader');
34664
34665     this.beginUpdate();
34666
34667     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
34668         south: c.preview !== false ? Roo.apply({
34669             split:true,
34670             initialSize: 200,
34671             minSize: 100,
34672             autoScroll:true,
34673             collapsible:true,
34674             titlebar: true,
34675             cmargins:{top:5,left:0, right:0, bottom:0}
34676         }, c.preview) : false,
34677         center: Roo.apply({
34678             autoScroll:false,
34679             titlebar:false,
34680             minHeight:200
34681         }, c.listView)
34682     });
34683     this.add('center', new Roo.NestedLayoutPanel(inner,
34684             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
34685
34686     this.endUpdate();
34687
34688     this.regions.preview = inner.getRegion('south');
34689     this.regions.listView = inner.getRegion('center');
34690 };
34691
34692 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
34693  * Based on:
34694  * Ext JS Library 1.1.1
34695  * Copyright(c) 2006-2007, Ext JS, LLC.
34696  *
34697  * Originally Released Under LGPL - original licence link has changed is not relivant.
34698  *
34699  * Fork - LGPL
34700  * <script type="text/javascript">
34701  */
34702  
34703 /**
34704  * @class Roo.grid.Grid
34705  * @extends Roo.util.Observable
34706  * This class represents the primary interface of a component based grid control.
34707  * <br><br>Usage:<pre><code>
34708  var grid = new Roo.grid.Grid("my-container-id", {
34709      ds: myDataStore,
34710      cm: myColModel,
34711      selModel: mySelectionModel,
34712      autoSizeColumns: true,
34713      monitorWindowResize: false,
34714      trackMouseOver: true
34715  });
34716  // set any options
34717  grid.render();
34718  * </code></pre>
34719  * <b>Common Problems:</b><br/>
34720  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
34721  * element will correct this<br/>
34722  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
34723  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
34724  * are unpredictable.<br/>
34725  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
34726  * grid to calculate dimensions/offsets.<br/>
34727   * @constructor
34728  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
34729  * The container MUST have some type of size defined for the grid to fill. The container will be
34730  * automatically set to position relative if it isn't already.
34731  * @param {Object} config A config object that sets properties on this grid.
34732  */
34733 Roo.grid.Grid = function(container, config){
34734         // initialize the container
34735         this.container = Roo.get(container);
34736         this.container.update("");
34737         this.container.setStyle("overflow", "hidden");
34738     this.container.addClass('x-grid-container');
34739
34740     this.id = this.container.id;
34741
34742     Roo.apply(this, config);
34743     // check and correct shorthanded configs
34744     if(this.ds){
34745         this.dataSource = this.ds;
34746         delete this.ds;
34747     }
34748     if(this.cm){
34749         this.colModel = this.cm;
34750         delete this.cm;
34751     }
34752     if(this.sm){
34753         this.selModel = this.sm;
34754         delete this.sm;
34755     }
34756
34757     if (this.selModel) {
34758         this.selModel = Roo.factory(this.selModel, Roo.grid);
34759         this.sm = this.selModel;
34760         this.sm.xmodule = this.xmodule || false;
34761     }
34762     if (typeof(this.colModel.config) == 'undefined') {
34763         this.colModel = new Roo.grid.ColumnModel(this.colModel);
34764         this.cm = this.colModel;
34765         this.cm.xmodule = this.xmodule || false;
34766     }
34767     if (this.dataSource) {
34768         this.dataSource= Roo.factory(this.dataSource, Roo.data);
34769         this.ds = this.dataSource;
34770         this.ds.xmodule = this.xmodule || false;
34771          
34772     }
34773     
34774     
34775     
34776     if(this.width){
34777         this.container.setWidth(this.width);
34778     }
34779
34780     if(this.height){
34781         this.container.setHeight(this.height);
34782     }
34783     /** @private */
34784         this.addEvents({
34785         // raw events
34786         /**
34787          * @event click
34788          * The raw click event for the entire grid.
34789          * @param {Roo.EventObject} e
34790          */
34791         "click" : true,
34792         /**
34793          * @event dblclick
34794          * The raw dblclick event for the entire grid.
34795          * @param {Roo.EventObject} e
34796          */
34797         "dblclick" : true,
34798         /**
34799          * @event contextmenu
34800          * The raw contextmenu event for the entire grid.
34801          * @param {Roo.EventObject} e
34802          */
34803         "contextmenu" : true,
34804         /**
34805          * @event mousedown
34806          * The raw mousedown event for the entire grid.
34807          * @param {Roo.EventObject} e
34808          */
34809         "mousedown" : true,
34810         /**
34811          * @event mouseup
34812          * The raw mouseup event for the entire grid.
34813          * @param {Roo.EventObject} e
34814          */
34815         "mouseup" : true,
34816         /**
34817          * @event mouseover
34818          * The raw mouseover event for the entire grid.
34819          * @param {Roo.EventObject} e
34820          */
34821         "mouseover" : true,
34822         /**
34823          * @event mouseout
34824          * The raw mouseout event for the entire grid.
34825          * @param {Roo.EventObject} e
34826          */
34827         "mouseout" : true,
34828         /**
34829          * @event keypress
34830          * The raw keypress event for the entire grid.
34831          * @param {Roo.EventObject} e
34832          */
34833         "keypress" : true,
34834         /**
34835          * @event keydown
34836          * The raw keydown event for the entire grid.
34837          * @param {Roo.EventObject} e
34838          */
34839         "keydown" : true,
34840
34841         // custom events
34842
34843         /**
34844          * @event cellclick
34845          * Fires when a cell is clicked
34846          * @param {Grid} this
34847          * @param {Number} rowIndex
34848          * @param {Number} columnIndex
34849          * @param {Roo.EventObject} e
34850          */
34851         "cellclick" : true,
34852         /**
34853          * @event celldblclick
34854          * Fires when a cell is double clicked
34855          * @param {Grid} this
34856          * @param {Number} rowIndex
34857          * @param {Number} columnIndex
34858          * @param {Roo.EventObject} e
34859          */
34860         "celldblclick" : true,
34861         /**
34862          * @event rowclick
34863          * Fires when a row is clicked
34864          * @param {Grid} this
34865          * @param {Number} rowIndex
34866          * @param {Roo.EventObject} e
34867          */
34868         "rowclick" : true,
34869         /**
34870          * @event rowdblclick
34871          * Fires when a row is double clicked
34872          * @param {Grid} this
34873          * @param {Number} rowIndex
34874          * @param {Roo.EventObject} e
34875          */
34876         "rowdblclick" : true,
34877         /**
34878          * @event headerclick
34879          * Fires when a header is clicked
34880          * @param {Grid} this
34881          * @param {Number} columnIndex
34882          * @param {Roo.EventObject} e
34883          */
34884         "headerclick" : true,
34885         /**
34886          * @event headerdblclick
34887          * Fires when a header cell is double clicked
34888          * @param {Grid} this
34889          * @param {Number} columnIndex
34890          * @param {Roo.EventObject} e
34891          */
34892         "headerdblclick" : true,
34893         /**
34894          * @event rowcontextmenu
34895          * Fires when a row is right clicked
34896          * @param {Grid} this
34897          * @param {Number} rowIndex
34898          * @param {Roo.EventObject} e
34899          */
34900         "rowcontextmenu" : true,
34901         /**
34902          * @event cellcontextmenu
34903          * Fires when a cell is right clicked
34904          * @param {Grid} this
34905          * @param {Number} rowIndex
34906          * @param {Number} cellIndex
34907          * @param {Roo.EventObject} e
34908          */
34909          "cellcontextmenu" : true,
34910         /**
34911          * @event headercontextmenu
34912          * Fires when a header is right clicked
34913          * @param {Grid} this
34914          * @param {Number} columnIndex
34915          * @param {Roo.EventObject} e
34916          */
34917         "headercontextmenu" : true,
34918         /**
34919          * @event bodyscroll
34920          * Fires when the body element is scrolled
34921          * @param {Number} scrollLeft
34922          * @param {Number} scrollTop
34923          */
34924         "bodyscroll" : true,
34925         /**
34926          * @event columnresize
34927          * Fires when the user resizes a column
34928          * @param {Number} columnIndex
34929          * @param {Number} newSize
34930          */
34931         "columnresize" : true,
34932         /**
34933          * @event columnmove
34934          * Fires when the user moves a column
34935          * @param {Number} oldIndex
34936          * @param {Number} newIndex
34937          */
34938         "columnmove" : true,
34939         /**
34940          * @event startdrag
34941          * Fires when row(s) start being dragged
34942          * @param {Grid} this
34943          * @param {Roo.GridDD} dd The drag drop object
34944          * @param {event} e The raw browser event
34945          */
34946         "startdrag" : true,
34947         /**
34948          * @event enddrag
34949          * Fires when a drag operation is complete
34950          * @param {Grid} this
34951          * @param {Roo.GridDD} dd The drag drop object
34952          * @param {event} e The raw browser event
34953          */
34954         "enddrag" : true,
34955         /**
34956          * @event dragdrop
34957          * Fires when dragged row(s) are dropped on a valid DD target
34958          * @param {Grid} this
34959          * @param {Roo.GridDD} dd The drag drop object
34960          * @param {String} targetId The target drag drop object
34961          * @param {event} e The raw browser event
34962          */
34963         "dragdrop" : true,
34964         /**
34965          * @event dragover
34966          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
34967          * @param {Grid} this
34968          * @param {Roo.GridDD} dd The drag drop object
34969          * @param {String} targetId The target drag drop object
34970          * @param {event} e The raw browser event
34971          */
34972         "dragover" : true,
34973         /**
34974          * @event dragenter
34975          *  Fires when the dragged row(s) first cross another DD target while being dragged
34976          * @param {Grid} this
34977          * @param {Roo.GridDD} dd The drag drop object
34978          * @param {String} targetId The target drag drop object
34979          * @param {event} e The raw browser event
34980          */
34981         "dragenter" : true,
34982         /**
34983          * @event dragout
34984          * Fires when the dragged row(s) leave another DD target while being dragged
34985          * @param {Grid} this
34986          * @param {Roo.GridDD} dd The drag drop object
34987          * @param {String} targetId The target drag drop object
34988          * @param {event} e The raw browser event
34989          */
34990         "dragout" : true,
34991         /**
34992          * @event rowclass
34993          * Fires when a row is rendered, so you can change add a style to it.
34994          * @param {GridView} gridview   The grid view
34995          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
34996          */
34997         'rowclass' : true,
34998
34999         /**
35000          * @event render
35001          * Fires when the grid is rendered
35002          * @param {Grid} grid
35003          */
35004         'render' : true
35005     });
35006
35007     Roo.grid.Grid.superclass.constructor.call(this);
35008 };
35009 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
35010     
35011     /**
35012      * @cfg {String} ddGroup - drag drop group.
35013      */
35014
35015     /**
35016      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
35017      */
35018     minColumnWidth : 25,
35019
35020     /**
35021      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
35022      * <b>on initial render.</b> It is more efficient to explicitly size the columns
35023      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
35024      */
35025     autoSizeColumns : false,
35026
35027     /**
35028      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
35029      */
35030     autoSizeHeaders : true,
35031
35032     /**
35033      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
35034      */
35035     monitorWindowResize : true,
35036
35037     /**
35038      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
35039      * rows measured to get a columns size. Default is 0 (all rows).
35040      */
35041     maxRowsToMeasure : 0,
35042
35043     /**
35044      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
35045      */
35046     trackMouseOver : true,
35047
35048     /**
35049     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
35050     */
35051     
35052     /**
35053     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
35054     */
35055     enableDragDrop : false,
35056     
35057     /**
35058     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
35059     */
35060     enableColumnMove : true,
35061     
35062     /**
35063     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
35064     */
35065     enableColumnHide : true,
35066     
35067     /**
35068     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
35069     */
35070     enableRowHeightSync : false,
35071     
35072     /**
35073     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
35074     */
35075     stripeRows : true,
35076     
35077     /**
35078     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
35079     */
35080     autoHeight : false,
35081
35082     /**
35083      * @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.
35084      */
35085     autoExpandColumn : false,
35086
35087     /**
35088     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
35089     * Default is 50.
35090     */
35091     autoExpandMin : 50,
35092
35093     /**
35094     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
35095     */
35096     autoExpandMax : 1000,
35097
35098     /**
35099     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
35100     */
35101     view : null,
35102
35103     /**
35104     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
35105     */
35106     loadMask : false,
35107     /**
35108     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
35109     */
35110     dropTarget: false,
35111     
35112    
35113     
35114     // private
35115     rendered : false,
35116
35117     /**
35118     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
35119     * of a fixed width. Default is false.
35120     */
35121     /**
35122     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
35123     */
35124     /**
35125      * Called once after all setup has been completed and the grid is ready to be rendered.
35126      * @return {Roo.grid.Grid} this
35127      */
35128     render : function()
35129     {
35130         var c = this.container;
35131         // try to detect autoHeight/width mode
35132         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
35133             this.autoHeight = true;
35134         }
35135         var view = this.getView();
35136         view.init(this);
35137
35138         c.on("click", this.onClick, this);
35139         c.on("dblclick", this.onDblClick, this);
35140         c.on("contextmenu", this.onContextMenu, this);
35141         c.on("keydown", this.onKeyDown, this);
35142         if (Roo.isTouch) {
35143             c.on("touchstart", this.onTouchStart, this);
35144         }
35145
35146         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
35147
35148         this.getSelectionModel().init(this);
35149
35150         view.render();
35151
35152         if(this.loadMask){
35153             this.loadMask = new Roo.LoadMask(this.container,
35154                     Roo.apply({store:this.dataSource}, this.loadMask));
35155         }
35156         
35157         
35158         if (this.toolbar && this.toolbar.xtype) {
35159             this.toolbar.container = this.getView().getHeaderPanel(true);
35160             this.toolbar = new Roo.Toolbar(this.toolbar);
35161         }
35162         if (this.footer && this.footer.xtype) {
35163             this.footer.dataSource = this.getDataSource();
35164             this.footer.container = this.getView().getFooterPanel(true);
35165             this.footer = Roo.factory(this.footer, Roo);
35166         }
35167         if (this.dropTarget && this.dropTarget.xtype) {
35168             delete this.dropTarget.xtype;
35169             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
35170         }
35171         
35172         
35173         this.rendered = true;
35174         this.fireEvent('render', this);
35175         return this;
35176     },
35177
35178         /**
35179          * Reconfigures the grid to use a different Store and Column Model.
35180          * The View will be bound to the new objects and refreshed.
35181          * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
35182          * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
35183          */
35184     reconfigure : function(dataSource, colModel){
35185         if(this.loadMask){
35186             this.loadMask.destroy();
35187             this.loadMask = new Roo.LoadMask(this.container,
35188                     Roo.apply({store:dataSource}, this.loadMask));
35189         }
35190         this.view.bind(dataSource, colModel);
35191         this.dataSource = dataSource;
35192         this.colModel = colModel;
35193         this.view.refresh(true);
35194     },
35195
35196     // private
35197     onKeyDown : function(e){
35198         this.fireEvent("keydown", e);
35199     },
35200
35201     /**
35202      * Destroy this grid.
35203      * @param {Boolean} removeEl True to remove the element
35204      */
35205     destroy : function(removeEl, keepListeners){
35206         if(this.loadMask){
35207             this.loadMask.destroy();
35208         }
35209         var c = this.container;
35210         c.removeAllListeners();
35211         this.view.destroy();
35212         this.colModel.purgeListeners();
35213         if(!keepListeners){
35214             this.purgeListeners();
35215         }
35216         c.update("");
35217         if(removeEl === true){
35218             c.remove();
35219         }
35220     },
35221
35222     // private
35223     processEvent : function(name, e){
35224         // does this fire select???
35225         Roo.log('grid:processEvent '  + name);
35226         
35227         if (name != 'touchstart' ) {
35228             this.fireEvent(name, e);    
35229         }
35230         
35231         var t = e.getTarget();
35232         var v = this.view;
35233         var header = v.findHeaderIndex(t);
35234         if(header !== false){
35235             this.fireEvent("header" + (name == 'touchstart' ? 'click' : name), this, header, e);
35236         }else{
35237             var row = v.findRowIndex(t);
35238             var cell = v.findCellIndex(t);
35239             if (name == 'touchstart') {
35240                 // first touch is always a click.
35241                 // hopefull this happens after selection is updated.?
35242                 name = false;
35243                 
35244                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
35245                     var cs = this.selModel.getSelectedCell();
35246                     if (row == cs[0] && cell == cs[1]){
35247                         name = 'dblclick';
35248                     }
35249                 }
35250                 if (typeof(this.selModel.getSelections) != 'undefined') {
35251                     var cs = this.selModel.getSelections();
35252                     var ds = this.dataSource;
35253                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
35254                         name = 'dblclick';
35255                     }
35256                 }
35257                 if (!name) {
35258                     return;
35259                 }
35260             }
35261             
35262             
35263             if(row !== false){
35264                 this.fireEvent("row" + name, this, row, e);
35265                 if(cell !== false){
35266                     this.fireEvent("cell" + name, this, row, cell, e);
35267                 }
35268             }
35269         }
35270     },
35271
35272     // private
35273     onClick : function(e){
35274         this.processEvent("click", e);
35275     },
35276    // private
35277     onTouchStart : function(e){
35278         this.processEvent("touchstart", e);
35279     },
35280
35281     // private
35282     onContextMenu : function(e, t){
35283         this.processEvent("contextmenu", e);
35284     },
35285
35286     // private
35287     onDblClick : function(e){
35288         this.processEvent("dblclick", e);
35289     },
35290
35291     // private
35292     walkCells : function(row, col, step, fn, scope){
35293         var cm = this.colModel, clen = cm.getColumnCount();
35294         var ds = this.dataSource, rlen = ds.getCount(), first = true;
35295         if(step < 0){
35296             if(col < 0){
35297                 row--;
35298                 first = false;
35299             }
35300             while(row >= 0){
35301                 if(!first){
35302                     col = clen-1;
35303                 }
35304                 first = false;
35305                 while(col >= 0){
35306                     if(fn.call(scope || this, row, col, cm) === true){
35307                         return [row, col];
35308                     }
35309                     col--;
35310                 }
35311                 row--;
35312             }
35313         } else {
35314             if(col >= clen){
35315                 row++;
35316                 first = false;
35317             }
35318             while(row < rlen){
35319                 if(!first){
35320                     col = 0;
35321                 }
35322                 first = false;
35323                 while(col < clen){
35324                     if(fn.call(scope || this, row, col, cm) === true){
35325                         return [row, col];
35326                     }
35327                     col++;
35328                 }
35329                 row++;
35330             }
35331         }
35332         return null;
35333     },
35334
35335     // private
35336     getSelections : function(){
35337         return this.selModel.getSelections();
35338     },
35339
35340     /**
35341      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
35342      * but if manual update is required this method will initiate it.
35343      */
35344     autoSize : function(){
35345         if(this.rendered){
35346             this.view.layout();
35347             if(this.view.adjustForScroll){
35348                 this.view.adjustForScroll();
35349             }
35350         }
35351     },
35352
35353     /**
35354      * Returns the grid's underlying element.
35355      * @return {Element} The element
35356      */
35357     getGridEl : function(){
35358         return this.container;
35359     },
35360
35361     // private for compatibility, overridden by editor grid
35362     stopEditing : function(){},
35363
35364     /**
35365      * Returns the grid's SelectionModel.
35366      * @return {SelectionModel}
35367      */
35368     getSelectionModel : function(){
35369         if(!this.selModel){
35370             this.selModel = new Roo.grid.RowSelectionModel();
35371         }
35372         return this.selModel;
35373     },
35374
35375     /**
35376      * Returns the grid's DataSource.
35377      * @return {DataSource}
35378      */
35379     getDataSource : function(){
35380         return this.dataSource;
35381     },
35382
35383     /**
35384      * Returns the grid's ColumnModel.
35385      * @return {ColumnModel}
35386      */
35387     getColumnModel : function(){
35388         return this.colModel;
35389     },
35390
35391     /**
35392      * Returns the grid's GridView object.
35393      * @return {GridView}
35394      */
35395     getView : function(){
35396         if(!this.view){
35397             this.view = new Roo.grid.GridView(this.viewConfig);
35398         }
35399         return this.view;
35400     },
35401     /**
35402      * Called to get grid's drag proxy text, by default returns this.ddText.
35403      * @return {String}
35404      */
35405     getDragDropText : function(){
35406         var count = this.selModel.getCount();
35407         return String.format(this.ddText, count, count == 1 ? '' : 's');
35408     }
35409 });
35410 /**
35411  * Configures the text is the drag proxy (defaults to "%0 selected row(s)").
35412  * %0 is replaced with the number of selected rows.
35413  * @type String
35414  */
35415 Roo.grid.Grid.prototype.ddText = "{0} selected row{1}";/*
35416  * Based on:
35417  * Ext JS Library 1.1.1
35418  * Copyright(c) 2006-2007, Ext JS, LLC.
35419  *
35420  * Originally Released Under LGPL - original licence link has changed is not relivant.
35421  *
35422  * Fork - LGPL
35423  * <script type="text/javascript">
35424  */
35425  
35426 Roo.grid.AbstractGridView = function(){
35427         this.grid = null;
35428         
35429         this.events = {
35430             "beforerowremoved" : true,
35431             "beforerowsinserted" : true,
35432             "beforerefresh" : true,
35433             "rowremoved" : true,
35434             "rowsinserted" : true,
35435             "rowupdated" : true,
35436             "refresh" : true
35437         };
35438     Roo.grid.AbstractGridView.superclass.constructor.call(this);
35439 };
35440
35441 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
35442     rowClass : "x-grid-row",
35443     cellClass : "x-grid-cell",
35444     tdClass : "x-grid-td",
35445     hdClass : "x-grid-hd",
35446     splitClass : "x-grid-hd-split",
35447     
35448         init: function(grid){
35449         this.grid = grid;
35450                 var cid = this.grid.getGridEl().id;
35451         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
35452         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
35453         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
35454         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
35455         },
35456         
35457         getColumnRenderers : function(){
35458         var renderers = [];
35459         var cm = this.grid.colModel;
35460         var colCount = cm.getColumnCount();
35461         for(var i = 0; i < colCount; i++){
35462             renderers[i] = cm.getRenderer(i);
35463         }
35464         return renderers;
35465     },
35466     
35467     getColumnIds : function(){
35468         var ids = [];
35469         var cm = this.grid.colModel;
35470         var colCount = cm.getColumnCount();
35471         for(var i = 0; i < colCount; i++){
35472             ids[i] = cm.getColumnId(i);
35473         }
35474         return ids;
35475     },
35476     
35477     getDataIndexes : function(){
35478         if(!this.indexMap){
35479             this.indexMap = this.buildIndexMap();
35480         }
35481         return this.indexMap.colToData;
35482     },
35483     
35484     getColumnIndexByDataIndex : function(dataIndex){
35485         if(!this.indexMap){
35486             this.indexMap = this.buildIndexMap();
35487         }
35488         return this.indexMap.dataToCol[dataIndex];
35489     },
35490     
35491     /**
35492      * Set a css style for a column dynamically. 
35493      * @param {Number} colIndex The index of the column
35494      * @param {String} name The css property name
35495      * @param {String} value The css value
35496      */
35497     setCSSStyle : function(colIndex, name, value){
35498         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
35499         Roo.util.CSS.updateRule(selector, name, value);
35500     },
35501     
35502     generateRules : function(cm){
35503         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
35504         Roo.util.CSS.removeStyleSheet(rulesId);
35505         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
35506             var cid = cm.getColumnId(i);
35507             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
35508                          this.tdSelector, cid, " {\n}\n",
35509                          this.hdSelector, cid, " {\n}\n",
35510                          this.splitSelector, cid, " {\n}\n");
35511         }
35512         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
35513     }
35514 });/*
35515  * Based on:
35516  * Ext JS Library 1.1.1
35517  * Copyright(c) 2006-2007, Ext JS, LLC.
35518  *
35519  * Originally Released Under LGPL - original licence link has changed is not relivant.
35520  *
35521  * Fork - LGPL
35522  * <script type="text/javascript">
35523  */
35524
35525 // private
35526 // This is a support class used internally by the Grid components
35527 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
35528     this.grid = grid;
35529     this.view = grid.getView();
35530     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
35531     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
35532     if(hd2){
35533         this.setHandleElId(Roo.id(hd));
35534         this.setOuterHandleElId(Roo.id(hd2));
35535     }
35536     this.scroll = false;
35537 };
35538 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
35539     maxDragWidth: 120,
35540     getDragData : function(e){
35541         var t = Roo.lib.Event.getTarget(e);
35542         var h = this.view.findHeaderCell(t);
35543         if(h){
35544             return {ddel: h.firstChild, header:h};
35545         }
35546         return false;
35547     },
35548
35549     onInitDrag : function(e){
35550         this.view.headersDisabled = true;
35551         var clone = this.dragData.ddel.cloneNode(true);
35552         clone.id = Roo.id();
35553         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
35554         this.proxy.update(clone);
35555         return true;
35556     },
35557
35558     afterValidDrop : function(){
35559         var v = this.view;
35560         setTimeout(function(){
35561             v.headersDisabled = false;
35562         }, 50);
35563     },
35564
35565     afterInvalidDrop : function(){
35566         var v = this.view;
35567         setTimeout(function(){
35568             v.headersDisabled = false;
35569         }, 50);
35570     }
35571 });
35572 /*
35573  * Based on:
35574  * Ext JS Library 1.1.1
35575  * Copyright(c) 2006-2007, Ext JS, LLC.
35576  *
35577  * Originally Released Under LGPL - original licence link has changed is not relivant.
35578  *
35579  * Fork - LGPL
35580  * <script type="text/javascript">
35581  */
35582 // private
35583 // This is a support class used internally by the Grid components
35584 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
35585     this.grid = grid;
35586     this.view = grid.getView();
35587     // split the proxies so they don't interfere with mouse events
35588     this.proxyTop = Roo.DomHelper.append(document.body, {
35589         cls:"col-move-top", html:"&#160;"
35590     }, true);
35591     this.proxyBottom = Roo.DomHelper.append(document.body, {
35592         cls:"col-move-bottom", html:"&#160;"
35593     }, true);
35594     this.proxyTop.hide = this.proxyBottom.hide = function(){
35595         this.setLeftTop(-100,-100);
35596         this.setStyle("visibility", "hidden");
35597     };
35598     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
35599     // temporarily disabled
35600     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
35601     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
35602 };
35603 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
35604     proxyOffsets : [-4, -9],
35605     fly: Roo.Element.fly,
35606
35607     getTargetFromEvent : function(e){
35608         var t = Roo.lib.Event.getTarget(e);
35609         var cindex = this.view.findCellIndex(t);
35610         if(cindex !== false){
35611             return this.view.getHeaderCell(cindex);
35612         }
35613         return null;
35614     },
35615
35616     nextVisible : function(h){
35617         var v = this.view, cm = this.grid.colModel;
35618         h = h.nextSibling;
35619         while(h){
35620             if(!cm.isHidden(v.getCellIndex(h))){
35621                 return h;
35622             }
35623             h = h.nextSibling;
35624         }
35625         return null;
35626     },
35627
35628     prevVisible : function(h){
35629         var v = this.view, cm = this.grid.colModel;
35630         h = h.prevSibling;
35631         while(h){
35632             if(!cm.isHidden(v.getCellIndex(h))){
35633                 return h;
35634             }
35635             h = h.prevSibling;
35636         }
35637         return null;
35638     },
35639
35640     positionIndicator : function(h, n, e){
35641         var x = Roo.lib.Event.getPageX(e);
35642         var r = Roo.lib.Dom.getRegion(n.firstChild);
35643         var px, pt, py = r.top + this.proxyOffsets[1];
35644         if((r.right - x) <= (r.right-r.left)/2){
35645             px = r.right+this.view.borderWidth;
35646             pt = "after";
35647         }else{
35648             px = r.left;
35649             pt = "before";
35650         }
35651         var oldIndex = this.view.getCellIndex(h);
35652         var newIndex = this.view.getCellIndex(n);
35653
35654         if(this.grid.colModel.isFixed(newIndex)){
35655             return false;
35656         }
35657
35658         var locked = this.grid.colModel.isLocked(newIndex);
35659
35660         if(pt == "after"){
35661             newIndex++;
35662         }
35663         if(oldIndex < newIndex){
35664             newIndex--;
35665         }
35666         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
35667             return false;
35668         }
35669         px +=  this.proxyOffsets[0];
35670         this.proxyTop.setLeftTop(px, py);
35671         this.proxyTop.show();
35672         if(!this.bottomOffset){
35673             this.bottomOffset = this.view.mainHd.getHeight();
35674         }
35675         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
35676         this.proxyBottom.show();
35677         return pt;
35678     },
35679
35680     onNodeEnter : function(n, dd, e, data){
35681         if(data.header != n){
35682             this.positionIndicator(data.header, n, e);
35683         }
35684     },
35685
35686     onNodeOver : function(n, dd, e, data){
35687         var result = false;
35688         if(data.header != n){
35689             result = this.positionIndicator(data.header, n, e);
35690         }
35691         if(!result){
35692             this.proxyTop.hide();
35693             this.proxyBottom.hide();
35694         }
35695         return result ? this.dropAllowed : this.dropNotAllowed;
35696     },
35697
35698     onNodeOut : function(n, dd, e, data){
35699         this.proxyTop.hide();
35700         this.proxyBottom.hide();
35701     },
35702
35703     onNodeDrop : function(n, dd, e, data){
35704         var h = data.header;
35705         if(h != n){
35706             var cm = this.grid.colModel;
35707             var x = Roo.lib.Event.getPageX(e);
35708             var r = Roo.lib.Dom.getRegion(n.firstChild);
35709             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
35710             var oldIndex = this.view.getCellIndex(h);
35711             var newIndex = this.view.getCellIndex(n);
35712             var locked = cm.isLocked(newIndex);
35713             if(pt == "after"){
35714                 newIndex++;
35715             }
35716             if(oldIndex < newIndex){
35717                 newIndex--;
35718             }
35719             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
35720                 return false;
35721             }
35722             cm.setLocked(oldIndex, locked, true);
35723             cm.moveColumn(oldIndex, newIndex);
35724             this.grid.fireEvent("columnmove", oldIndex, newIndex);
35725             return true;
35726         }
35727         return false;
35728     }
35729 });
35730 /*
35731  * Based on:
35732  * Ext JS Library 1.1.1
35733  * Copyright(c) 2006-2007, Ext JS, LLC.
35734  *
35735  * Originally Released Under LGPL - original licence link has changed is not relivant.
35736  *
35737  * Fork - LGPL
35738  * <script type="text/javascript">
35739  */
35740   
35741 /**
35742  * @class Roo.grid.GridView
35743  * @extends Roo.util.Observable
35744  *
35745  * @constructor
35746  * @param {Object} config
35747  */
35748 Roo.grid.GridView = function(config){
35749     Roo.grid.GridView.superclass.constructor.call(this);
35750     this.el = null;
35751
35752     Roo.apply(this, config);
35753 };
35754
35755 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
35756
35757     unselectable :  'unselectable="on"',
35758     unselectableCls :  'x-unselectable',
35759     
35760     
35761     rowClass : "x-grid-row",
35762
35763     cellClass : "x-grid-col",
35764
35765     tdClass : "x-grid-td",
35766
35767     hdClass : "x-grid-hd",
35768
35769     splitClass : "x-grid-split",
35770
35771     sortClasses : ["sort-asc", "sort-desc"],
35772
35773     enableMoveAnim : false,
35774
35775     hlColor: "C3DAF9",
35776
35777     dh : Roo.DomHelper,
35778
35779     fly : Roo.Element.fly,
35780
35781     css : Roo.util.CSS,
35782
35783     borderWidth: 1,
35784
35785     splitOffset: 3,
35786
35787     scrollIncrement : 22,
35788
35789     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
35790
35791     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
35792
35793     bind : function(ds, cm){
35794         if(this.ds){
35795             this.ds.un("load", this.onLoad, this);
35796             this.ds.un("datachanged", this.onDataChange, this);
35797             this.ds.un("add", this.onAdd, this);
35798             this.ds.un("remove", this.onRemove, this);
35799             this.ds.un("update", this.onUpdate, this);
35800             this.ds.un("clear", this.onClear, this);
35801         }
35802         if(ds){
35803             ds.on("load", this.onLoad, this);
35804             ds.on("datachanged", this.onDataChange, this);
35805             ds.on("add", this.onAdd, this);
35806             ds.on("remove", this.onRemove, this);
35807             ds.on("update", this.onUpdate, this);
35808             ds.on("clear", this.onClear, this);
35809         }
35810         this.ds = ds;
35811
35812         if(this.cm){
35813             this.cm.un("widthchange", this.onColWidthChange, this);
35814             this.cm.un("headerchange", this.onHeaderChange, this);
35815             this.cm.un("hiddenchange", this.onHiddenChange, this);
35816             this.cm.un("columnmoved", this.onColumnMove, this);
35817             this.cm.un("columnlockchange", this.onColumnLock, this);
35818         }
35819         if(cm){
35820             this.generateRules(cm);
35821             cm.on("widthchange", this.onColWidthChange, this);
35822             cm.on("headerchange", this.onHeaderChange, this);
35823             cm.on("hiddenchange", this.onHiddenChange, this);
35824             cm.on("columnmoved", this.onColumnMove, this);
35825             cm.on("columnlockchange", this.onColumnLock, this);
35826         }
35827         this.cm = cm;
35828     },
35829
35830     init: function(grid){
35831         Roo.grid.GridView.superclass.init.call(this, grid);
35832
35833         this.bind(grid.dataSource, grid.colModel);
35834
35835         grid.on("headerclick", this.handleHeaderClick, this);
35836
35837         if(grid.trackMouseOver){
35838             grid.on("mouseover", this.onRowOver, this);
35839             grid.on("mouseout", this.onRowOut, this);
35840         }
35841         grid.cancelTextSelection = function(){};
35842         this.gridId = grid.id;
35843
35844         var tpls = this.templates || {};
35845
35846         if(!tpls.master){
35847             tpls.master = new Roo.Template(
35848                '<div class="x-grid" hidefocus="true">',
35849                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
35850                   '<div class="x-grid-topbar"></div>',
35851                   '<div class="x-grid-scroller"><div></div></div>',
35852                   '<div class="x-grid-locked">',
35853                       '<div class="x-grid-header">{lockedHeader}</div>',
35854                       '<div class="x-grid-body">{lockedBody}</div>',
35855                   "</div>",
35856                   '<div class="x-grid-viewport">',
35857                       '<div class="x-grid-header">{header}</div>',
35858                       '<div class="x-grid-body">{body}</div>',
35859                   "</div>",
35860                   '<div class="x-grid-bottombar"></div>',
35861                  
35862                   '<div class="x-grid-resize-proxy">&#160;</div>',
35863                "</div>"
35864             );
35865             tpls.master.disableformats = true;
35866         }
35867
35868         if(!tpls.header){
35869             tpls.header = new Roo.Template(
35870                '<table border="0" cellspacing="0" cellpadding="0">',
35871                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
35872                "</table>{splits}"
35873             );
35874             tpls.header.disableformats = true;
35875         }
35876         tpls.header.compile();
35877
35878         if(!tpls.hcell){
35879             tpls.hcell = new Roo.Template(
35880                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
35881                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
35882                 "</div></td>"
35883              );
35884              tpls.hcell.disableFormats = true;
35885         }
35886         tpls.hcell.compile();
35887
35888         if(!tpls.hsplit){
35889             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
35890                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
35891             tpls.hsplit.disableFormats = true;
35892         }
35893         tpls.hsplit.compile();
35894
35895         if(!tpls.body){
35896             tpls.body = new Roo.Template(
35897                '<table border="0" cellspacing="0" cellpadding="0">',
35898                "<tbody>{rows}</tbody>",
35899                "</table>"
35900             );
35901             tpls.body.disableFormats = true;
35902         }
35903         tpls.body.compile();
35904
35905         if(!tpls.row){
35906             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
35907             tpls.row.disableFormats = true;
35908         }
35909         tpls.row.compile();
35910
35911         if(!tpls.cell){
35912             tpls.cell = new Roo.Template(
35913                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
35914                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
35915                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
35916                 "</td>"
35917             );
35918             tpls.cell.disableFormats = true;
35919         }
35920         tpls.cell.compile();
35921
35922         this.templates = tpls;
35923     },
35924
35925     // remap these for backwards compat
35926     onColWidthChange : function(){
35927         this.updateColumns.apply(this, arguments);
35928     },
35929     onHeaderChange : function(){
35930         this.updateHeaders.apply(this, arguments);
35931     }, 
35932     onHiddenChange : function(){
35933         this.handleHiddenChange.apply(this, arguments);
35934     },
35935     onColumnMove : function(){
35936         this.handleColumnMove.apply(this, arguments);
35937     },
35938     onColumnLock : function(){
35939         this.handleLockChange.apply(this, arguments);
35940     },
35941
35942     onDataChange : function(){
35943         this.refresh();
35944         this.updateHeaderSortState();
35945     },
35946
35947     onClear : function(){
35948         this.refresh();
35949     },
35950
35951     onUpdate : function(ds, record){
35952         this.refreshRow(record);
35953     },
35954
35955     refreshRow : function(record){
35956         var ds = this.ds, index;
35957         if(typeof record == 'number'){
35958             index = record;
35959             record = ds.getAt(index);
35960         }else{
35961             index = ds.indexOf(record);
35962         }
35963         this.insertRows(ds, index, index, true);
35964         this.onRemove(ds, record, index+1, true);
35965         this.syncRowHeights(index, index);
35966         this.layout();
35967         this.fireEvent("rowupdated", this, index, record);
35968     },
35969
35970     onAdd : function(ds, records, index){
35971         this.insertRows(ds, index, index + (records.length-1));
35972     },
35973
35974     onRemove : function(ds, record, index, isUpdate){
35975         if(isUpdate !== true){
35976             this.fireEvent("beforerowremoved", this, index, record);
35977         }
35978         var bt = this.getBodyTable(), lt = this.getLockedTable();
35979         if(bt.rows[index]){
35980             bt.firstChild.removeChild(bt.rows[index]);
35981         }
35982         if(lt.rows[index]){
35983             lt.firstChild.removeChild(lt.rows[index]);
35984         }
35985         if(isUpdate !== true){
35986             this.stripeRows(index);
35987             this.syncRowHeights(index, index);
35988             this.layout();
35989             this.fireEvent("rowremoved", this, index, record);
35990         }
35991     },
35992
35993     onLoad : function(){
35994         this.scrollToTop();
35995     },
35996
35997     /**
35998      * Scrolls the grid to the top
35999      */
36000     scrollToTop : function(){
36001         if(this.scroller){
36002             this.scroller.dom.scrollTop = 0;
36003             this.syncScroll();
36004         }
36005     },
36006
36007     /**
36008      * Gets a panel in the header of the grid that can be used for toolbars etc.
36009      * After modifying the contents of this panel a call to grid.autoSize() may be
36010      * required to register any changes in size.
36011      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
36012      * @return Roo.Element
36013      */
36014     getHeaderPanel : function(doShow){
36015         if(doShow){
36016             this.headerPanel.show();
36017         }
36018         return this.headerPanel;
36019     },
36020
36021     /**
36022      * Gets a panel in the footer of the grid that can be used for toolbars etc.
36023      * After modifying the contents of this panel a call to grid.autoSize() may be
36024      * required to register any changes in size.
36025      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
36026      * @return Roo.Element
36027      */
36028     getFooterPanel : function(doShow){
36029         if(doShow){
36030             this.footerPanel.show();
36031         }
36032         return this.footerPanel;
36033     },
36034
36035     initElements : function(){
36036         var E = Roo.Element;
36037         var el = this.grid.getGridEl().dom.firstChild;
36038         var cs = el.childNodes;
36039
36040         this.el = new E(el);
36041         
36042          this.focusEl = new E(el.firstChild);
36043         this.focusEl.swallowEvent("click", true);
36044         
36045         this.headerPanel = new E(cs[1]);
36046         this.headerPanel.enableDisplayMode("block");
36047
36048         this.scroller = new E(cs[2]);
36049         this.scrollSizer = new E(this.scroller.dom.firstChild);
36050
36051         this.lockedWrap = new E(cs[3]);
36052         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
36053         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
36054
36055         this.mainWrap = new E(cs[4]);
36056         this.mainHd = new E(this.mainWrap.dom.firstChild);
36057         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
36058
36059         this.footerPanel = new E(cs[5]);
36060         this.footerPanel.enableDisplayMode("block");
36061
36062         this.resizeProxy = new E(cs[6]);
36063
36064         this.headerSelector = String.format(
36065            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
36066            this.lockedHd.id, this.mainHd.id
36067         );
36068
36069         this.splitterSelector = String.format(
36070            '#{0} div.x-grid-split, #{1} div.x-grid-split',
36071            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
36072         );
36073     },
36074     idToCssName : function(s)
36075     {
36076         return s.replace(/[^a-z0-9]+/ig, '-');
36077     },
36078
36079     getHeaderCell : function(index){
36080         return Roo.DomQuery.select(this.headerSelector)[index];
36081     },
36082
36083     getHeaderCellMeasure : function(index){
36084         return this.getHeaderCell(index).firstChild;
36085     },
36086
36087     getHeaderCellText : function(index){
36088         return this.getHeaderCell(index).firstChild.firstChild;
36089     },
36090
36091     getLockedTable : function(){
36092         return this.lockedBody.dom.firstChild;
36093     },
36094
36095     getBodyTable : function(){
36096         return this.mainBody.dom.firstChild;
36097     },
36098
36099     getLockedRow : function(index){
36100         return this.getLockedTable().rows[index];
36101     },
36102
36103     getRow : function(index){
36104         return this.getBodyTable().rows[index];
36105     },
36106
36107     getRowComposite : function(index){
36108         if(!this.rowEl){
36109             this.rowEl = new Roo.CompositeElementLite();
36110         }
36111         var els = [], lrow, mrow;
36112         if(lrow = this.getLockedRow(index)){
36113             els.push(lrow);
36114         }
36115         if(mrow = this.getRow(index)){
36116             els.push(mrow);
36117         }
36118         this.rowEl.elements = els;
36119         return this.rowEl;
36120     },
36121     /**
36122      * Gets the 'td' of the cell
36123      * 
36124      * @param {Integer} rowIndex row to select
36125      * @param {Integer} colIndex column to select
36126      * 
36127      * @return {Object} 
36128      */
36129     getCell : function(rowIndex, colIndex){
36130         var locked = this.cm.getLockedCount();
36131         var source;
36132         if(colIndex < locked){
36133             source = this.lockedBody.dom.firstChild;
36134         }else{
36135             source = this.mainBody.dom.firstChild;
36136             colIndex -= locked;
36137         }
36138         return source.rows[rowIndex].childNodes[colIndex];
36139     },
36140
36141     getCellText : function(rowIndex, colIndex){
36142         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
36143     },
36144
36145     getCellBox : function(cell){
36146         var b = this.fly(cell).getBox();
36147         if(Roo.isOpera){ // opera fails to report the Y
36148             b.y = cell.offsetTop + this.mainBody.getY();
36149         }
36150         return b;
36151     },
36152
36153     getCellIndex : function(cell){
36154         var id = String(cell.className).match(this.cellRE);
36155         if(id){
36156             return parseInt(id[1], 10);
36157         }
36158         return 0;
36159     },
36160
36161     findHeaderIndex : function(n){
36162         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
36163         return r ? this.getCellIndex(r) : false;
36164     },
36165
36166     findHeaderCell : function(n){
36167         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
36168         return r ? r : false;
36169     },
36170
36171     findRowIndex : function(n){
36172         if(!n){
36173             return false;
36174         }
36175         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
36176         return r ? r.rowIndex : false;
36177     },
36178
36179     findCellIndex : function(node){
36180         var stop = this.el.dom;
36181         while(node && node != stop){
36182             if(this.findRE.test(node.className)){
36183                 return this.getCellIndex(node);
36184             }
36185             node = node.parentNode;
36186         }
36187         return false;
36188     },
36189
36190     getColumnId : function(index){
36191         return this.cm.getColumnId(index);
36192     },
36193
36194     getSplitters : function()
36195     {
36196         if(this.splitterSelector){
36197            return Roo.DomQuery.select(this.splitterSelector);
36198         }else{
36199             return null;
36200       }
36201     },
36202
36203     getSplitter : function(index){
36204         return this.getSplitters()[index];
36205     },
36206
36207     onRowOver : function(e, t){
36208         var row;
36209         if((row = this.findRowIndex(t)) !== false){
36210             this.getRowComposite(row).addClass("x-grid-row-over");
36211         }
36212     },
36213
36214     onRowOut : function(e, t){
36215         var row;
36216         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
36217             this.getRowComposite(row).removeClass("x-grid-row-over");
36218         }
36219     },
36220
36221     renderHeaders : function(){
36222         var cm = this.cm;
36223         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
36224         var cb = [], lb = [], sb = [], lsb = [], p = {};
36225         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
36226             p.cellId = "x-grid-hd-0-" + i;
36227             p.splitId = "x-grid-csplit-0-" + i;
36228             p.id = cm.getColumnId(i);
36229             p.title = cm.getColumnTooltip(i) || "";
36230             p.value = cm.getColumnHeader(i) || "";
36231             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
36232             if(!cm.isLocked(i)){
36233                 cb[cb.length] = ct.apply(p);
36234                 sb[sb.length] = st.apply(p);
36235             }else{
36236                 lb[lb.length] = ct.apply(p);
36237                 lsb[lsb.length] = st.apply(p);
36238             }
36239         }
36240         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
36241                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
36242     },
36243
36244     updateHeaders : function(){
36245         var html = this.renderHeaders();
36246         this.lockedHd.update(html[0]);
36247         this.mainHd.update(html[1]);
36248     },
36249
36250     /**
36251      * Focuses the specified row.
36252      * @param {Number} row The row index
36253      */
36254     focusRow : function(row)
36255     {
36256         //Roo.log('GridView.focusRow');
36257         var x = this.scroller.dom.scrollLeft;
36258         this.focusCell(row, 0, false);
36259         this.scroller.dom.scrollLeft = x;
36260     },
36261
36262     /**
36263      * Focuses the specified cell.
36264      * @param {Number} row The row index
36265      * @param {Number} col The column index
36266      * @param {Boolean} hscroll false to disable horizontal scrolling
36267      */
36268     focusCell : function(row, col, hscroll)
36269     {
36270         //Roo.log('GridView.focusCell');
36271         var el = this.ensureVisible(row, col, hscroll);
36272         this.focusEl.alignTo(el, "tl-tl");
36273         if(Roo.isGecko){
36274             this.focusEl.focus();
36275         }else{
36276             this.focusEl.focus.defer(1, this.focusEl);
36277         }
36278     },
36279
36280     /**
36281      * Scrolls the specified cell into view
36282      * @param {Number} row The row index
36283      * @param {Number} col The column index
36284      * @param {Boolean} hscroll false to disable horizontal scrolling
36285      */
36286     ensureVisible : function(row, col, hscroll)
36287     {
36288         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
36289         //return null; //disable for testing.
36290         if(typeof row != "number"){
36291             row = row.rowIndex;
36292         }
36293         if(row < 0 && row >= this.ds.getCount()){
36294             return  null;
36295         }
36296         col = (col !== undefined ? col : 0);
36297         var cm = this.grid.colModel;
36298         while(cm.isHidden(col)){
36299             col++;
36300         }
36301
36302         var el = this.getCell(row, col);
36303         if(!el){
36304             return null;
36305         }
36306         var c = this.scroller.dom;
36307
36308         var ctop = parseInt(el.offsetTop, 10);
36309         var cleft = parseInt(el.offsetLeft, 10);
36310         var cbot = ctop + el.offsetHeight;
36311         var cright = cleft + el.offsetWidth;
36312         
36313         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
36314         var stop = parseInt(c.scrollTop, 10);
36315         var sleft = parseInt(c.scrollLeft, 10);
36316         var sbot = stop + ch;
36317         var sright = sleft + c.clientWidth;
36318         /*
36319         Roo.log('GridView.ensureVisible:' +
36320                 ' ctop:' + ctop +
36321                 ' c.clientHeight:' + c.clientHeight +
36322                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
36323                 ' stop:' + stop +
36324                 ' cbot:' + cbot +
36325                 ' sbot:' + sbot +
36326                 ' ch:' + ch  
36327                 );
36328         */
36329         if(ctop < stop){
36330              c.scrollTop = ctop;
36331             //Roo.log("set scrolltop to ctop DISABLE?");
36332         }else if(cbot > sbot){
36333             //Roo.log("set scrolltop to cbot-ch");
36334             c.scrollTop = cbot-ch;
36335         }
36336         
36337         if(hscroll !== false){
36338             if(cleft < sleft){
36339                 c.scrollLeft = cleft;
36340             }else if(cright > sright){
36341                 c.scrollLeft = cright-c.clientWidth;
36342             }
36343         }
36344          
36345         return el;
36346     },
36347
36348     updateColumns : function(){
36349         this.grid.stopEditing();
36350         var cm = this.grid.colModel, colIds = this.getColumnIds();
36351         //var totalWidth = cm.getTotalWidth();
36352         var pos = 0;
36353         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
36354             //if(cm.isHidden(i)) continue;
36355             var w = cm.getColumnWidth(i);
36356             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
36357             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
36358         }
36359         this.updateSplitters();
36360     },
36361
36362     generateRules : function(cm){
36363         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
36364         Roo.util.CSS.removeStyleSheet(rulesId);
36365         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
36366             var cid = cm.getColumnId(i);
36367             var align = '';
36368             if(cm.config[i].align){
36369                 align = 'text-align:'+cm.config[i].align+';';
36370             }
36371             var hidden = '';
36372             if(cm.isHidden(i)){
36373                 hidden = 'display:none;';
36374             }
36375             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
36376             ruleBuf.push(
36377                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
36378                     this.hdSelector, cid, " {\n", align, width, "}\n",
36379                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
36380                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
36381         }
36382         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
36383     },
36384
36385     updateSplitters : function(){
36386         var cm = this.cm, s = this.getSplitters();
36387         if(s){ // splitters not created yet
36388             var pos = 0, locked = true;
36389             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
36390                 if(cm.isHidden(i)) continue;
36391                 var w = cm.getColumnWidth(i); // make sure it's a number
36392                 if(!cm.isLocked(i) && locked){
36393                     pos = 0;
36394                     locked = false;
36395                 }
36396                 pos += w;
36397                 s[i].style.left = (pos-this.splitOffset) + "px";
36398             }
36399         }
36400     },
36401
36402     handleHiddenChange : function(colModel, colIndex, hidden){
36403         if(hidden){
36404             this.hideColumn(colIndex);
36405         }else{
36406             this.unhideColumn(colIndex);
36407         }
36408     },
36409
36410     hideColumn : function(colIndex){
36411         var cid = this.getColumnId(colIndex);
36412         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
36413         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
36414         if(Roo.isSafari){
36415             this.updateHeaders();
36416         }
36417         this.updateSplitters();
36418         this.layout();
36419     },
36420
36421     unhideColumn : function(colIndex){
36422         var cid = this.getColumnId(colIndex);
36423         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
36424         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
36425
36426         if(Roo.isSafari){
36427             this.updateHeaders();
36428         }
36429         this.updateSplitters();
36430         this.layout();
36431     },
36432
36433     insertRows : function(dm, firstRow, lastRow, isUpdate){
36434         if(firstRow == 0 && lastRow == dm.getCount()-1){
36435             this.refresh();
36436         }else{
36437             if(!isUpdate){
36438                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
36439             }
36440             var s = this.getScrollState();
36441             var markup = this.renderRows(firstRow, lastRow);
36442             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
36443             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
36444             this.restoreScroll(s);
36445             if(!isUpdate){
36446                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
36447                 this.syncRowHeights(firstRow, lastRow);
36448                 this.stripeRows(firstRow);
36449                 this.layout();
36450             }
36451         }
36452     },
36453
36454     bufferRows : function(markup, target, index){
36455         var before = null, trows = target.rows, tbody = target.tBodies[0];
36456         if(index < trows.length){
36457             before = trows[index];
36458         }
36459         var b = document.createElement("div");
36460         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
36461         var rows = b.firstChild.rows;
36462         for(var i = 0, len = rows.length; i < len; i++){
36463             if(before){
36464                 tbody.insertBefore(rows[0], before);
36465             }else{
36466                 tbody.appendChild(rows[0]);
36467             }
36468         }
36469         b.innerHTML = "";
36470         b = null;
36471     },
36472
36473     deleteRows : function(dm, firstRow, lastRow){
36474         if(dm.getRowCount()<1){
36475             this.fireEvent("beforerefresh", this);
36476             this.mainBody.update("");
36477             this.lockedBody.update("");
36478             this.fireEvent("refresh", this);
36479         }else{
36480             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
36481             var bt = this.getBodyTable();
36482             var tbody = bt.firstChild;
36483             var rows = bt.rows;
36484             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
36485                 tbody.removeChild(rows[firstRow]);
36486             }
36487             this.stripeRows(firstRow);
36488             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
36489         }
36490     },
36491
36492     updateRows : function(dataSource, firstRow, lastRow){
36493         var s = this.getScrollState();
36494         this.refresh();
36495         this.restoreScroll(s);
36496     },
36497
36498     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
36499         if(!noRefresh){
36500            this.refresh();
36501         }
36502         this.updateHeaderSortState();
36503     },
36504
36505     getScrollState : function(){
36506         
36507         var sb = this.scroller.dom;
36508         return {left: sb.scrollLeft, top: sb.scrollTop};
36509     },
36510
36511     stripeRows : function(startRow){
36512         if(!this.grid.stripeRows || this.ds.getCount() < 1){
36513             return;
36514         }
36515         startRow = startRow || 0;
36516         var rows = this.getBodyTable().rows;
36517         var lrows = this.getLockedTable().rows;
36518         var cls = ' x-grid-row-alt ';
36519         for(var i = startRow, len = rows.length; i < len; i++){
36520             var row = rows[i], lrow = lrows[i];
36521             var isAlt = ((i+1) % 2 == 0);
36522             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
36523             if(isAlt == hasAlt){
36524                 continue;
36525             }
36526             if(isAlt){
36527                 row.className += " x-grid-row-alt";
36528             }else{
36529                 row.className = row.className.replace("x-grid-row-alt", "");
36530             }
36531             if(lrow){
36532                 lrow.className = row.className;
36533             }
36534         }
36535     },
36536
36537     restoreScroll : function(state){
36538         //Roo.log('GridView.restoreScroll');
36539         var sb = this.scroller.dom;
36540         sb.scrollLeft = state.left;
36541         sb.scrollTop = state.top;
36542         this.syncScroll();
36543     },
36544
36545     syncScroll : function(){
36546         //Roo.log('GridView.syncScroll');
36547         var sb = this.scroller.dom;
36548         var sh = this.mainHd.dom;
36549         var bs = this.mainBody.dom;
36550         var lv = this.lockedBody.dom;
36551         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
36552         lv.scrollTop = bs.scrollTop = sb.scrollTop;
36553     },
36554
36555     handleScroll : function(e){
36556         this.syncScroll();
36557         var sb = this.scroller.dom;
36558         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
36559         e.stopEvent();
36560     },
36561
36562     handleWheel : function(e){
36563         var d = e.getWheelDelta();
36564         this.scroller.dom.scrollTop -= d*22;
36565         // set this here to prevent jumpy scrolling on large tables
36566         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
36567         e.stopEvent();
36568     },
36569
36570     renderRows : function(startRow, endRow){
36571         // pull in all the crap needed to render rows
36572         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
36573         var colCount = cm.getColumnCount();
36574
36575         if(ds.getCount() < 1){
36576             return ["", ""];
36577         }
36578
36579         // build a map for all the columns
36580         var cs = [];
36581         for(var i = 0; i < colCount; i++){
36582             var name = cm.getDataIndex(i);
36583             cs[i] = {
36584                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
36585                 renderer : cm.getRenderer(i),
36586                 id : cm.getColumnId(i),
36587                 locked : cm.isLocked(i)
36588             };
36589         }
36590
36591         startRow = startRow || 0;
36592         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
36593
36594         // records to render
36595         var rs = ds.getRange(startRow, endRow);
36596
36597         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
36598     },
36599
36600     // As much as I hate to duplicate code, this was branched because FireFox really hates
36601     // [].join("") on strings. The performance difference was substantial enough to
36602     // branch this function
36603     doRender : Roo.isGecko ?
36604             function(cs, rs, ds, startRow, colCount, stripe){
36605                 var ts = this.templates, ct = ts.cell, rt = ts.row;
36606                 // buffers
36607                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
36608                 
36609                 var hasListener = this.grid.hasListener('rowclass');
36610                 var rowcfg = {};
36611                 for(var j = 0, len = rs.length; j < len; j++){
36612                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
36613                     for(var i = 0; i < colCount; i++){
36614                         c = cs[i];
36615                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
36616                         p.id = c.id;
36617                         p.css = p.attr = "";
36618                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
36619                         if(p.value == undefined || p.value === "") p.value = "&#160;";
36620                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
36621                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
36622                         }
36623                         var markup = ct.apply(p);
36624                         if(!c.locked){
36625                             cb+= markup;
36626                         }else{
36627                             lcb+= markup;
36628                         }
36629                     }
36630                     var alt = [];
36631                     if(stripe && ((rowIndex+1) % 2 == 0)){
36632                         alt.push("x-grid-row-alt")
36633                     }
36634                     if(r.dirty){
36635                         alt.push(  " x-grid-dirty-row");
36636                     }
36637                     rp.cells = lcb;
36638                     if(this.getRowClass){
36639                         alt.push(this.getRowClass(r, rowIndex));
36640                     }
36641                     if (hasListener) {
36642                         rowcfg = {
36643                              
36644                             record: r,
36645                             rowIndex : rowIndex,
36646                             rowClass : ''
36647                         }
36648                         this.grid.fireEvent('rowclass', this, rowcfg);
36649                         alt.push(rowcfg.rowClass);
36650                     }
36651                     rp.alt = alt.join(" ");
36652                     lbuf+= rt.apply(rp);
36653                     rp.cells = cb;
36654                     buf+=  rt.apply(rp);
36655                 }
36656                 return [lbuf, buf];
36657             } :
36658             function(cs, rs, ds, startRow, colCount, stripe){
36659                 var ts = this.templates, ct = ts.cell, rt = ts.row;
36660                 // buffers
36661                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
36662                 var hasListener = this.grid.hasListener('rowclass');
36663  
36664                 var rowcfg = {};
36665                 for(var j = 0, len = rs.length; j < len; j++){
36666                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
36667                     for(var i = 0; i < colCount; i++){
36668                         c = cs[i];
36669                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
36670                         p.id = c.id;
36671                         p.css = p.attr = "";
36672                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
36673                         if(p.value == undefined || p.value === "") p.value = "&#160;";
36674                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
36675                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
36676                         }
36677                         
36678                         var markup = ct.apply(p);
36679                         if(!c.locked){
36680                             cb[cb.length] = markup;
36681                         }else{
36682                             lcb[lcb.length] = markup;
36683                         }
36684                     }
36685                     var alt = [];
36686                     if(stripe && ((rowIndex+1) % 2 == 0)){
36687                         alt.push( "x-grid-row-alt");
36688                     }
36689                     if(r.dirty){
36690                         alt.push(" x-grid-dirty-row");
36691                     }
36692                     rp.cells = lcb;
36693                     if(this.getRowClass){
36694                         alt.push( this.getRowClass(r, rowIndex));
36695                     }
36696                     if (hasListener) {
36697                         rowcfg = {
36698                              
36699                             record: r,
36700                             rowIndex : rowIndex,
36701                             rowClass : ''
36702                         }
36703                         this.grid.fireEvent('rowclass', this, rowcfg);
36704                         alt.push(rowcfg.rowClass);
36705                     }
36706                     rp.alt = alt.join(" ");
36707                     rp.cells = lcb.join("");
36708                     lbuf[lbuf.length] = rt.apply(rp);
36709                     rp.cells = cb.join("");
36710                     buf[buf.length] =  rt.apply(rp);
36711                 }
36712                 return [lbuf.join(""), buf.join("")];
36713             },
36714
36715     renderBody : function(){
36716         var markup = this.renderRows();
36717         var bt = this.templates.body;
36718         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
36719     },
36720
36721     /**
36722      * Refreshes the grid
36723      * @param {Boolean} headersToo
36724      */
36725     refresh : function(headersToo){
36726         this.fireEvent("beforerefresh", this);
36727         this.grid.stopEditing();
36728         var result = this.renderBody();
36729         this.lockedBody.update(result[0]);
36730         this.mainBody.update(result[1]);
36731         if(headersToo === true){
36732             this.updateHeaders();
36733             this.updateColumns();
36734             this.updateSplitters();
36735             this.updateHeaderSortState();
36736         }
36737         this.syncRowHeights();
36738         this.layout();
36739         this.fireEvent("refresh", this);
36740     },
36741
36742     handleColumnMove : function(cm, oldIndex, newIndex){
36743         this.indexMap = null;
36744         var s = this.getScrollState();
36745         this.refresh(true);
36746         this.restoreScroll(s);
36747         this.afterMove(newIndex);
36748     },
36749
36750     afterMove : function(colIndex){
36751         if(this.enableMoveAnim && Roo.enableFx){
36752             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
36753         }
36754         // if multisort - fix sortOrder, and reload..
36755         if (this.grid.dataSource.multiSort) {
36756             // the we can call sort again..
36757             var dm = this.grid.dataSource;
36758             var cm = this.grid.colModel;
36759             var so = [];
36760             for(var i = 0; i < cm.config.length; i++ ) {
36761                 
36762                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
36763                     continue; // dont' bother, it's not in sort list or being set.
36764                 }
36765                 
36766                 so.push(cm.config[i].dataIndex);
36767             };
36768             dm.sortOrder = so;
36769             dm.load(dm.lastOptions);
36770             
36771             
36772         }
36773         
36774     },
36775
36776     updateCell : function(dm, rowIndex, dataIndex){
36777         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
36778         if(typeof colIndex == "undefined"){ // not present in grid
36779             return;
36780         }
36781         var cm = this.grid.colModel;
36782         var cell = this.getCell(rowIndex, colIndex);
36783         var cellText = this.getCellText(rowIndex, colIndex);
36784
36785         var p = {
36786             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
36787             id : cm.getColumnId(colIndex),
36788             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
36789         };
36790         var renderer = cm.getRenderer(colIndex);
36791         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
36792         if(typeof val == "undefined" || val === "") val = "&#160;";
36793         cellText.innerHTML = val;
36794         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
36795         this.syncRowHeights(rowIndex, rowIndex);
36796     },
36797
36798     calcColumnWidth : function(colIndex, maxRowsToMeasure){
36799         var maxWidth = 0;
36800         if(this.grid.autoSizeHeaders){
36801             var h = this.getHeaderCellMeasure(colIndex);
36802             maxWidth = Math.max(maxWidth, h.scrollWidth);
36803         }
36804         var tb, index;
36805         if(this.cm.isLocked(colIndex)){
36806             tb = this.getLockedTable();
36807             index = colIndex;
36808         }else{
36809             tb = this.getBodyTable();
36810             index = colIndex - this.cm.getLockedCount();
36811         }
36812         if(tb && tb.rows){
36813             var rows = tb.rows;
36814             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
36815             for(var i = 0; i < stopIndex; i++){
36816                 var cell = rows[i].childNodes[index].firstChild;
36817                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
36818             }
36819         }
36820         return maxWidth + /*margin for error in IE*/ 5;
36821     },
36822     /**
36823      * Autofit a column to its content.
36824      * @param {Number} colIndex
36825      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
36826      */
36827      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
36828          if(this.cm.isHidden(colIndex)){
36829              return; // can't calc a hidden column
36830          }
36831         if(forceMinSize){
36832             var cid = this.cm.getColumnId(colIndex);
36833             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
36834            if(this.grid.autoSizeHeaders){
36835                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
36836            }
36837         }
36838         var newWidth = this.calcColumnWidth(colIndex);
36839         this.cm.setColumnWidth(colIndex,
36840             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
36841         if(!suppressEvent){
36842             this.grid.fireEvent("columnresize", colIndex, newWidth);
36843         }
36844     },
36845
36846     /**
36847      * Autofits all columns to their content and then expands to fit any extra space in the grid
36848      */
36849      autoSizeColumns : function(){
36850         var cm = this.grid.colModel;
36851         var colCount = cm.getColumnCount();
36852         for(var i = 0; i < colCount; i++){
36853             this.autoSizeColumn(i, true, true);
36854         }
36855         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
36856             this.fitColumns();
36857         }else{
36858             this.updateColumns();
36859             this.layout();
36860         }
36861     },
36862
36863     /**
36864      * Autofits all columns to the grid's width proportionate with their current size
36865      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
36866      */
36867     fitColumns : function(reserveScrollSpace){
36868         var cm = this.grid.colModel;
36869         var colCount = cm.getColumnCount();
36870         var cols = [];
36871         var width = 0;
36872         var i, w;
36873         for (i = 0; i < colCount; i++){
36874             if(!cm.isHidden(i) && !cm.isFixed(i)){
36875                 w = cm.getColumnWidth(i);
36876                 cols.push(i);
36877                 cols.push(w);
36878                 width += w;
36879             }
36880         }
36881         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
36882         if(reserveScrollSpace){
36883             avail -= 17;
36884         }
36885         var frac = (avail - cm.getTotalWidth())/width;
36886         while (cols.length){
36887             w = cols.pop();
36888             i = cols.pop();
36889             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
36890         }
36891         this.updateColumns();
36892         this.layout();
36893     },
36894
36895     onRowSelect : function(rowIndex){
36896         var row = this.getRowComposite(rowIndex);
36897         row.addClass("x-grid-row-selected");
36898     },
36899
36900     onRowDeselect : function(rowIndex){
36901         var row = this.getRowComposite(rowIndex);
36902         row.removeClass("x-grid-row-selected");
36903     },
36904
36905     onCellSelect : function(row, col){
36906         var cell = this.getCell(row, col);
36907         if(cell){
36908             Roo.fly(cell).addClass("x-grid-cell-selected");
36909         }
36910     },
36911
36912     onCellDeselect : function(row, col){
36913         var cell = this.getCell(row, col);
36914         if(cell){
36915             Roo.fly(cell).removeClass("x-grid-cell-selected");
36916         }
36917     },
36918
36919     updateHeaderSortState : function(){
36920         
36921         // sort state can be single { field: xxx, direction : yyy}
36922         // or   { xxx=>ASC , yyy : DESC ..... }
36923         
36924         var mstate = {};
36925         if (!this.ds.multiSort) { 
36926             var state = this.ds.getSortState();
36927             if(!state){
36928                 return;
36929             }
36930             mstate[state.field] = state.direction;
36931             // FIXME... - this is not used here.. but might be elsewhere..
36932             this.sortState = state;
36933             
36934         } else {
36935             mstate = this.ds.sortToggle;
36936         }
36937         //remove existing sort classes..
36938         
36939         var sc = this.sortClasses;
36940         var hds = this.el.select(this.headerSelector).removeClass(sc);
36941         
36942         for(var f in mstate) {
36943         
36944             var sortColumn = this.cm.findColumnIndex(f);
36945             
36946             if(sortColumn != -1){
36947                 var sortDir = mstate[f];        
36948                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
36949             }
36950         }
36951         
36952          
36953         
36954     },
36955
36956
36957     handleHeaderClick : function(g, index){
36958         if(this.headersDisabled){
36959             return;
36960         }
36961         var dm = g.dataSource, cm = g.colModel;
36962         if(!cm.isSortable(index)){
36963             return;
36964         }
36965         g.stopEditing();
36966         
36967         if (dm.multiSort) {
36968             // update the sortOrder
36969             var so = [];
36970             for(var i = 0; i < cm.config.length; i++ ) {
36971                 
36972                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
36973                     continue; // dont' bother, it's not in sort list or being set.
36974                 }
36975                 
36976                 so.push(cm.config[i].dataIndex);
36977             };
36978             dm.sortOrder = so;
36979         }
36980         
36981         
36982         dm.sort(cm.getDataIndex(index));
36983     },
36984
36985
36986     destroy : function(){
36987         if(this.colMenu){
36988             this.colMenu.removeAll();
36989             Roo.menu.MenuMgr.unregister(this.colMenu);
36990             this.colMenu.getEl().remove();
36991             delete this.colMenu;
36992         }
36993         if(this.hmenu){
36994             this.hmenu.removeAll();
36995             Roo.menu.MenuMgr.unregister(this.hmenu);
36996             this.hmenu.getEl().remove();
36997             delete this.hmenu;
36998         }
36999         if(this.grid.enableColumnMove){
37000             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
37001             if(dds){
37002                 for(var dd in dds){
37003                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
37004                         var elid = dds[dd].dragElId;
37005                         dds[dd].unreg();
37006                         Roo.get(elid).remove();
37007                     } else if(dds[dd].config.isTarget){
37008                         dds[dd].proxyTop.remove();
37009                         dds[dd].proxyBottom.remove();
37010                         dds[dd].unreg();
37011                     }
37012                     if(Roo.dd.DDM.locationCache[dd]){
37013                         delete Roo.dd.DDM.locationCache[dd];
37014                     }
37015                 }
37016                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
37017             }
37018         }
37019         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
37020         this.bind(null, null);
37021         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
37022     },
37023
37024     handleLockChange : function(){
37025         this.refresh(true);
37026     },
37027
37028     onDenyColumnLock : function(){
37029
37030     },
37031
37032     onDenyColumnHide : function(){
37033
37034     },
37035
37036     handleHdMenuClick : function(item){
37037         var index = this.hdCtxIndex;
37038         var cm = this.cm, ds = this.ds;
37039         switch(item.id){
37040             case "asc":
37041                 ds.sort(cm.getDataIndex(index), "ASC");
37042                 break;
37043             case "desc":
37044                 ds.sort(cm.getDataIndex(index), "DESC");
37045                 break;
37046             case "lock":
37047                 var lc = cm.getLockedCount();
37048                 if(cm.getColumnCount(true) <= lc+1){
37049                     this.onDenyColumnLock();
37050                     return;
37051                 }
37052                 if(lc != index){
37053                     cm.setLocked(index, true, true);
37054                     cm.moveColumn(index, lc);
37055                     this.grid.fireEvent("columnmove", index, lc);
37056                 }else{
37057                     cm.setLocked(index, true);
37058                 }
37059             break;
37060             case "unlock":
37061                 var lc = cm.getLockedCount();
37062                 if((lc-1) != index){
37063                     cm.setLocked(index, false, true);
37064                     cm.moveColumn(index, lc-1);
37065                     this.grid.fireEvent("columnmove", index, lc-1);
37066                 }else{
37067                     cm.setLocked(index, false);
37068                 }
37069             break;
37070             default:
37071                 index = cm.getIndexById(item.id.substr(4));
37072                 if(index != -1){
37073                     if(item.checked && cm.getColumnCount(true) <= 1){
37074                         this.onDenyColumnHide();
37075                         return false;
37076                     }
37077                     cm.setHidden(index, item.checked);
37078                 }
37079         }
37080         return true;
37081     },
37082
37083     beforeColMenuShow : function(){
37084         var cm = this.cm,  colCount = cm.getColumnCount();
37085         this.colMenu.removeAll();
37086         for(var i = 0; i < colCount; i++){
37087             this.colMenu.add(new Roo.menu.CheckItem({
37088                 id: "col-"+cm.getColumnId(i),
37089                 text: cm.getColumnHeader(i),
37090                 checked: !cm.isHidden(i),
37091                 hideOnClick:false
37092             }));
37093         }
37094     },
37095
37096     handleHdCtx : function(g, index, e){
37097         e.stopEvent();
37098         var hd = this.getHeaderCell(index);
37099         this.hdCtxIndex = index;
37100         var ms = this.hmenu.items, cm = this.cm;
37101         ms.get("asc").setDisabled(!cm.isSortable(index));
37102         ms.get("desc").setDisabled(!cm.isSortable(index));
37103         if(this.grid.enableColLock !== false){
37104             ms.get("lock").setDisabled(cm.isLocked(index));
37105             ms.get("unlock").setDisabled(!cm.isLocked(index));
37106         }
37107         this.hmenu.show(hd, "tl-bl");
37108     },
37109
37110     handleHdOver : function(e){
37111         var hd = this.findHeaderCell(e.getTarget());
37112         if(hd && !this.headersDisabled){
37113             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
37114                this.fly(hd).addClass("x-grid-hd-over");
37115             }
37116         }
37117     },
37118
37119     handleHdOut : function(e){
37120         var hd = this.findHeaderCell(e.getTarget());
37121         if(hd){
37122             this.fly(hd).removeClass("x-grid-hd-over");
37123         }
37124     },
37125
37126     handleSplitDblClick : function(e, t){
37127         var i = this.getCellIndex(t);
37128         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
37129             this.autoSizeColumn(i, true);
37130             this.layout();
37131         }
37132     },
37133
37134     render : function(){
37135
37136         var cm = this.cm;
37137         var colCount = cm.getColumnCount();
37138
37139         if(this.grid.monitorWindowResize === true){
37140             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
37141         }
37142         var header = this.renderHeaders();
37143         var body = this.templates.body.apply({rows:""});
37144         var html = this.templates.master.apply({
37145             lockedBody: body,
37146             body: body,
37147             lockedHeader: header[0],
37148             header: header[1]
37149         });
37150
37151         //this.updateColumns();
37152
37153         this.grid.getGridEl().dom.innerHTML = html;
37154
37155         this.initElements();
37156         
37157         // a kludge to fix the random scolling effect in webkit
37158         this.el.on("scroll", function() {
37159             this.el.dom.scrollTop=0; // hopefully not recursive..
37160         },this);
37161
37162         this.scroller.on("scroll", this.handleScroll, this);
37163         this.lockedBody.on("mousewheel", this.handleWheel, this);
37164         this.mainBody.on("mousewheel", this.handleWheel, this);
37165
37166         this.mainHd.on("mouseover", this.handleHdOver, this);
37167         this.mainHd.on("mouseout", this.handleHdOut, this);
37168         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
37169                 {delegate: "."+this.splitClass});
37170
37171         this.lockedHd.on("mouseover", this.handleHdOver, this);
37172         this.lockedHd.on("mouseout", this.handleHdOut, this);
37173         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
37174                 {delegate: "."+this.splitClass});
37175
37176         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
37177             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
37178         }
37179
37180         this.updateSplitters();
37181
37182         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
37183             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
37184             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
37185         }
37186
37187         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
37188             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
37189             this.hmenu.add(
37190                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
37191                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
37192             );
37193             if(this.grid.enableColLock !== false){
37194                 this.hmenu.add('-',
37195                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
37196                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
37197                 );
37198             }
37199             if(this.grid.enableColumnHide !== false){
37200
37201                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
37202                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
37203                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
37204
37205                 this.hmenu.add('-',
37206                     {id:"columns", text: this.columnsText, menu: this.colMenu}
37207                 );
37208             }
37209             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
37210
37211             this.grid.on("headercontextmenu", this.handleHdCtx, this);
37212         }
37213
37214         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
37215             this.dd = new Roo.grid.GridDragZone(this.grid, {
37216                 ddGroup : this.grid.ddGroup || 'GridDD'
37217             });
37218             
37219         }
37220
37221         /*
37222         for(var i = 0; i < colCount; i++){
37223             if(cm.isHidden(i)){
37224                 this.hideColumn(i);
37225             }
37226             if(cm.config[i].align){
37227                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
37228                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
37229             }
37230         }*/
37231         
37232         this.updateHeaderSortState();
37233
37234         this.beforeInitialResize();
37235         this.layout(true);
37236
37237         // two part rendering gives faster view to the user
37238         this.renderPhase2.defer(1, this);
37239     },
37240
37241     renderPhase2 : function(){
37242         // render the rows now
37243         this.refresh();
37244         if(this.grid.autoSizeColumns){
37245             this.autoSizeColumns();
37246         }
37247     },
37248
37249     beforeInitialResize : function(){
37250
37251     },
37252
37253     onColumnSplitterMoved : function(i, w){
37254         this.userResized = true;
37255         var cm = this.grid.colModel;
37256         cm.setColumnWidth(i, w, true);
37257         var cid = cm.getColumnId(i);
37258         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
37259         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
37260         this.updateSplitters();
37261         this.layout();
37262         this.grid.fireEvent("columnresize", i, w);
37263     },
37264
37265     syncRowHeights : function(startIndex, endIndex){
37266         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
37267             startIndex = startIndex || 0;
37268             var mrows = this.getBodyTable().rows;
37269             var lrows = this.getLockedTable().rows;
37270             var len = mrows.length-1;
37271             endIndex = Math.min(endIndex || len, len);
37272             for(var i = startIndex; i <= endIndex; i++){
37273                 var m = mrows[i], l = lrows[i];
37274                 var h = Math.max(m.offsetHeight, l.offsetHeight);
37275                 m.style.height = l.style.height = h + "px";
37276             }
37277         }
37278     },
37279
37280     layout : function(initialRender, is2ndPass){
37281         var g = this.grid;
37282         var auto = g.autoHeight;
37283         var scrollOffset = 16;
37284         var c = g.getGridEl(), cm = this.cm,
37285                 expandCol = g.autoExpandColumn,
37286                 gv = this;
37287         //c.beginMeasure();
37288
37289         if(!c.dom.offsetWidth){ // display:none?
37290             if(initialRender){
37291                 this.lockedWrap.show();
37292                 this.mainWrap.show();
37293             }
37294             return;
37295         }
37296
37297         var hasLock = this.cm.isLocked(0);
37298
37299         var tbh = this.headerPanel.getHeight();
37300         var bbh = this.footerPanel.getHeight();
37301
37302         if(auto){
37303             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
37304             var newHeight = ch + c.getBorderWidth("tb");
37305             if(g.maxHeight){
37306                 newHeight = Math.min(g.maxHeight, newHeight);
37307             }
37308             c.setHeight(newHeight);
37309         }
37310
37311         if(g.autoWidth){
37312             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
37313         }
37314
37315         var s = this.scroller;
37316
37317         var csize = c.getSize(true);
37318
37319         this.el.setSize(csize.width, csize.height);
37320
37321         this.headerPanel.setWidth(csize.width);
37322         this.footerPanel.setWidth(csize.width);
37323
37324         var hdHeight = this.mainHd.getHeight();
37325         var vw = csize.width;
37326         var vh = csize.height - (tbh + bbh);
37327
37328         s.setSize(vw, vh);
37329
37330         var bt = this.getBodyTable();
37331         var ltWidth = hasLock ?
37332                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
37333
37334         var scrollHeight = bt.offsetHeight;
37335         var scrollWidth = ltWidth + bt.offsetWidth;
37336         var vscroll = false, hscroll = false;
37337
37338         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
37339
37340         var lw = this.lockedWrap, mw = this.mainWrap;
37341         var lb = this.lockedBody, mb = this.mainBody;
37342
37343         setTimeout(function(){
37344             var t = s.dom.offsetTop;
37345             var w = s.dom.clientWidth,
37346                 h = s.dom.clientHeight;
37347
37348             lw.setTop(t);
37349             lw.setSize(ltWidth, h);
37350
37351             mw.setLeftTop(ltWidth, t);
37352             mw.setSize(w-ltWidth, h);
37353
37354             lb.setHeight(h-hdHeight);
37355             mb.setHeight(h-hdHeight);
37356
37357             if(is2ndPass !== true && !gv.userResized && expandCol){
37358                 // high speed resize without full column calculation
37359                 
37360                 var ci = cm.getIndexById(expandCol);
37361                 if (ci < 0) {
37362                     ci = cm.findColumnIndex(expandCol);
37363                 }
37364                 ci = Math.max(0, ci); // make sure it's got at least the first col.
37365                 var expandId = cm.getColumnId(ci);
37366                 var  tw = cm.getTotalWidth(false);
37367                 var currentWidth = cm.getColumnWidth(ci);
37368                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
37369                 if(currentWidth != cw){
37370                     cm.setColumnWidth(ci, cw, true);
37371                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
37372                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
37373                     gv.updateSplitters();
37374                     gv.layout(false, true);
37375                 }
37376             }
37377
37378             if(initialRender){
37379                 lw.show();
37380                 mw.show();
37381             }
37382             //c.endMeasure();
37383         }, 10);
37384     },
37385
37386     onWindowResize : function(){
37387         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
37388             return;
37389         }
37390         this.layout();
37391     },
37392
37393     appendFooter : function(parentEl){
37394         return null;
37395     },
37396
37397     sortAscText : "Sort Ascending",
37398     sortDescText : "Sort Descending",
37399     lockText : "Lock Column",
37400     unlockText : "Unlock Column",
37401     columnsText : "Columns"
37402 });
37403
37404
37405 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
37406     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
37407     this.proxy.el.addClass('x-grid3-col-dd');
37408 };
37409
37410 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
37411     handleMouseDown : function(e){
37412
37413     },
37414
37415     callHandleMouseDown : function(e){
37416         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
37417     }
37418 });
37419 /*
37420  * Based on:
37421  * Ext JS Library 1.1.1
37422  * Copyright(c) 2006-2007, Ext JS, LLC.
37423  *
37424  * Originally Released Under LGPL - original licence link has changed is not relivant.
37425  *
37426  * Fork - LGPL
37427  * <script type="text/javascript">
37428  */
37429  
37430 // private
37431 // This is a support class used internally by the Grid components
37432 Roo.grid.SplitDragZone = function(grid, hd, hd2){
37433     this.grid = grid;
37434     this.view = grid.getView();
37435     this.proxy = this.view.resizeProxy;
37436     Roo.grid.SplitDragZone.superclass.constructor.call(this, hd,
37437         "gridSplitters" + this.grid.getGridEl().id, {
37438         dragElId : Roo.id(this.proxy.dom), resizeFrame:false
37439     });
37440     this.setHandleElId(Roo.id(hd));
37441     this.setOuterHandleElId(Roo.id(hd2));
37442     this.scroll = false;
37443 };
37444 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
37445     fly: Roo.Element.fly,
37446
37447     b4StartDrag : function(x, y){
37448         this.view.headersDisabled = true;
37449         this.proxy.setHeight(this.view.mainWrap.getHeight());
37450         var w = this.cm.getColumnWidth(this.cellIndex);
37451         var minw = Math.max(w-this.grid.minColumnWidth, 0);
37452         this.resetConstraints();
37453         this.setXConstraint(minw, 1000);
37454         this.setYConstraint(0, 0);
37455         this.minX = x - minw;
37456         this.maxX = x + 1000;
37457         this.startPos = x;
37458         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
37459     },
37460
37461
37462     handleMouseDown : function(e){
37463         ev = Roo.EventObject.setEvent(e);
37464         var t = this.fly(ev.getTarget());
37465         if(t.hasClass("x-grid-split")){
37466             this.cellIndex = this.view.getCellIndex(t.dom);
37467             this.split = t.dom;
37468             this.cm = this.grid.colModel;
37469             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
37470                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
37471             }
37472         }
37473     },
37474
37475     endDrag : function(e){
37476         this.view.headersDisabled = false;
37477         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
37478         var diff = endX - this.startPos;
37479         this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
37480     },
37481
37482     autoOffset : function(){
37483         this.setDelta(0,0);
37484     }
37485 });/*
37486  * Based on:
37487  * Ext JS Library 1.1.1
37488  * Copyright(c) 2006-2007, Ext JS, LLC.
37489  *
37490  * Originally Released Under LGPL - original licence link has changed is not relivant.
37491  *
37492  * Fork - LGPL
37493  * <script type="text/javascript">
37494  */
37495  
37496 // private
37497 // This is a support class used internally by the Grid components
37498 Roo.grid.GridDragZone = function(grid, config){
37499     this.view = grid.getView();
37500     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
37501     if(this.view.lockedBody){
37502         this.setHandleElId(Roo.id(this.view.mainBody.dom));
37503         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
37504     }
37505     this.scroll = false;
37506     this.grid = grid;
37507     this.ddel = document.createElement('div');
37508     this.ddel.className = 'x-grid-dd-wrap';
37509 };
37510
37511 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
37512     ddGroup : "GridDD",
37513
37514     getDragData : function(e){
37515         var t = Roo.lib.Event.getTarget(e);
37516         var rowIndex = this.view.findRowIndex(t);
37517         var sm = this.grid.selModel;
37518             
37519         //Roo.log(rowIndex);
37520         
37521         if (sm.getSelectedCell) {
37522             // cell selection..
37523             if (!sm.getSelectedCell()) {
37524                 return false;
37525             }
37526             if (rowIndex != sm.getSelectedCell()[0]) {
37527                 return false;
37528             }
37529         
37530         }
37531         
37532         if(rowIndex !== false){
37533             
37534             // if editorgrid.. 
37535             
37536             
37537             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
37538                
37539             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
37540               //  
37541             //}
37542             if (e.hasModifier()){
37543                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
37544             }
37545             
37546             Roo.log("getDragData");
37547             
37548             return {
37549                 grid: this.grid,
37550                 ddel: this.ddel,
37551                 rowIndex: rowIndex,
37552                 selections:sm.getSelections ? sm.getSelections() : (
37553                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : []
37554                 )
37555             };
37556         }
37557         return false;
37558     },
37559
37560     onInitDrag : function(e){
37561         var data = this.dragData;
37562         this.ddel.innerHTML = this.grid.getDragDropText();
37563         this.proxy.update(this.ddel);
37564         // fire start drag?
37565     },
37566
37567     afterRepair : function(){
37568         this.dragging = false;
37569     },
37570
37571     getRepairXY : function(e, data){
37572         return false;
37573     },
37574
37575     onEndDrag : function(data, e){
37576         // fire end drag?
37577     },
37578
37579     onValidDrop : function(dd, e, id){
37580         // fire drag drop?
37581         this.hideProxy();
37582     },
37583
37584     beforeInvalidDrop : function(e, id){
37585
37586     }
37587 });/*
37588  * Based on:
37589  * Ext JS Library 1.1.1
37590  * Copyright(c) 2006-2007, Ext JS, LLC.
37591  *
37592  * Originally Released Under LGPL - original licence link has changed is not relivant.
37593  *
37594  * Fork - LGPL
37595  * <script type="text/javascript">
37596  */
37597  
37598
37599 /**
37600  * @class Roo.grid.ColumnModel
37601  * @extends Roo.util.Observable
37602  * This is the default implementation of a ColumnModel used by the Grid. It defines
37603  * the columns in the grid.
37604  * <br>Usage:<br>
37605  <pre><code>
37606  var colModel = new Roo.grid.ColumnModel([
37607         {header: "Ticker", width: 60, sortable: true, locked: true},
37608         {header: "Company Name", width: 150, sortable: true},
37609         {header: "Market Cap.", width: 100, sortable: true},
37610         {header: "$ Sales", width: 100, sortable: true, renderer: money},
37611         {header: "Employees", width: 100, sortable: true, resizable: false}
37612  ]);
37613  </code></pre>
37614  * <p>
37615  
37616  * The config options listed for this class are options which may appear in each
37617  * individual column definition.
37618  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
37619  * @constructor
37620  * @param {Object} config An Array of column config objects. See this class's
37621  * config objects for details.
37622 */
37623 Roo.grid.ColumnModel = function(config){
37624         /**
37625      * The config passed into the constructor
37626      */
37627     this.config = config;
37628     this.lookup = {};
37629
37630     // if no id, create one
37631     // if the column does not have a dataIndex mapping,
37632     // map it to the order it is in the config
37633     for(var i = 0, len = config.length; i < len; i++){
37634         var c = config[i];
37635         if(typeof c.dataIndex == "undefined"){
37636             c.dataIndex = i;
37637         }
37638         if(typeof c.renderer == "string"){
37639             c.renderer = Roo.util.Format[c.renderer];
37640         }
37641         if(typeof c.id == "undefined"){
37642             c.id = Roo.id();
37643         }
37644         if(c.editor && c.editor.xtype){
37645             c.editor  = Roo.factory(c.editor, Roo.grid);
37646         }
37647         if(c.editor && c.editor.isFormField){
37648             c.editor = new Roo.grid.GridEditor(c.editor);
37649         }
37650         this.lookup[c.id] = c;
37651     }
37652
37653     /**
37654      * The width of columns which have no width specified (defaults to 100)
37655      * @type Number
37656      */
37657     this.defaultWidth = 100;
37658
37659     /**
37660      * Default sortable of columns which have no sortable specified (defaults to false)
37661      * @type Boolean
37662      */
37663     this.defaultSortable = false;
37664
37665     this.addEvents({
37666         /**
37667              * @event widthchange
37668              * Fires when the width of a column changes.
37669              * @param {ColumnModel} this
37670              * @param {Number} columnIndex The column index
37671              * @param {Number} newWidth The new width
37672              */
37673             "widthchange": true,
37674         /**
37675              * @event headerchange
37676              * Fires when the text of a header changes.
37677              * @param {ColumnModel} this
37678              * @param {Number} columnIndex The column index
37679              * @param {Number} newText The new header text
37680              */
37681             "headerchange": true,
37682         /**
37683              * @event hiddenchange
37684              * Fires when a column is hidden or "unhidden".
37685              * @param {ColumnModel} this
37686              * @param {Number} columnIndex The column index
37687              * @param {Boolean} hidden true if hidden, false otherwise
37688              */
37689             "hiddenchange": true,
37690             /**
37691          * @event columnmoved
37692          * Fires when a column is moved.
37693          * @param {ColumnModel} this
37694          * @param {Number} oldIndex
37695          * @param {Number} newIndex
37696          */
37697         "columnmoved" : true,
37698         /**
37699          * @event columlockchange
37700          * Fires when a column's locked state is changed
37701          * @param {ColumnModel} this
37702          * @param {Number} colIndex
37703          * @param {Boolean} locked true if locked
37704          */
37705         "columnlockchange" : true
37706     });
37707     Roo.grid.ColumnModel.superclass.constructor.call(this);
37708 };
37709 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
37710     /**
37711      * @cfg {String} header The header text to display in the Grid view.
37712      */
37713     /**
37714      * @cfg {String} dataIndex (Optional) The name of the field in the grid's {@link Roo.data.Store}'s
37715      * {@link Roo.data.Record} definition from which to draw the column's value. If not
37716      * specified, the column's index is used as an index into the Record's data Array.
37717      */
37718     /**
37719      * @cfg {Number} width (Optional) The initial width in pixels of the column. Using this
37720      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
37721      */
37722     /**
37723      * @cfg {Boolean} sortable (Optional) True if sorting is to be allowed on this column.
37724      * Defaults to the value of the {@link #defaultSortable} property.
37725      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
37726      */
37727     /**
37728      * @cfg {Boolean} locked (Optional) True to lock the column in place while scrolling the Grid.  Defaults to false.
37729      */
37730     /**
37731      * @cfg {Boolean} fixed (Optional) True if the column width cannot be changed.  Defaults to false.
37732      */
37733     /**
37734      * @cfg {Boolean} resizable (Optional) False to disable column resizing. Defaults to true.
37735      */
37736     /**
37737      * @cfg {Boolean} hidden (Optional) True to hide the column. Defaults to false.
37738      */
37739     /**
37740      * @cfg {Function} renderer (Optional) A function used to generate HTML markup for a cell
37741      * given the cell's data value. See {@link #setRenderer}. If not specified, the
37742      * default renderer uses the raw data value.
37743      */
37744        /**
37745      * @cfg {Roo.grid.GridEditor} editor (Optional) For grid editors - returns the grid editor 
37746      */
37747     /**
37748      * @cfg {String} align (Optional) Set the CSS text-align property of the column.  Defaults to undefined.
37749      */
37750
37751     /**
37752      * Returns the id of the column at the specified index.
37753      * @param {Number} index The column index
37754      * @return {String} the id
37755      */
37756     getColumnId : function(index){
37757         return this.config[index].id;
37758     },
37759
37760     /**
37761      * Returns the column for a specified id.
37762      * @param {String} id The column id
37763      * @return {Object} the column
37764      */
37765     getColumnById : function(id){
37766         return this.lookup[id];
37767     },
37768
37769     
37770     /**
37771      * Returns the column for a specified dataIndex.
37772      * @param {String} dataIndex The column dataIndex
37773      * @return {Object|Boolean} the column or false if not found
37774      */
37775     getColumnByDataIndex: function(dataIndex){
37776         var index = this.findColumnIndex(dataIndex);
37777         return index > -1 ? this.config[index] : false;
37778     },
37779     
37780     /**
37781      * Returns the index for a specified column id.
37782      * @param {String} id The column id
37783      * @return {Number} the index, or -1 if not found
37784      */
37785     getIndexById : function(id){
37786         for(var i = 0, len = this.config.length; i < len; i++){
37787             if(this.config[i].id == id){
37788                 return i;
37789             }
37790         }
37791         return -1;
37792     },
37793     
37794     /**
37795      * Returns the index for a specified column dataIndex.
37796      * @param {String} dataIndex The column dataIndex
37797      * @return {Number} the index, or -1 if not found
37798      */
37799     
37800     findColumnIndex : function(dataIndex){
37801         for(var i = 0, len = this.config.length; i < len; i++){
37802             if(this.config[i].dataIndex == dataIndex){
37803                 return i;
37804             }
37805         }
37806         return -1;
37807     },
37808     
37809     
37810     moveColumn : function(oldIndex, newIndex){
37811         var c = this.config[oldIndex];
37812         this.config.splice(oldIndex, 1);
37813         this.config.splice(newIndex, 0, c);
37814         this.dataMap = null;
37815         this.fireEvent("columnmoved", this, oldIndex, newIndex);
37816     },
37817
37818     isLocked : function(colIndex){
37819         return this.config[colIndex].locked === true;
37820     },
37821
37822     setLocked : function(colIndex, value, suppressEvent){
37823         if(this.isLocked(colIndex) == value){
37824             return;
37825         }
37826         this.config[colIndex].locked = value;
37827         if(!suppressEvent){
37828             this.fireEvent("columnlockchange", this, colIndex, value);
37829         }
37830     },
37831
37832     getTotalLockedWidth : function(){
37833         var totalWidth = 0;
37834         for(var i = 0; i < this.config.length; i++){
37835             if(this.isLocked(i) && !this.isHidden(i)){
37836                 this.totalWidth += this.getColumnWidth(i);
37837             }
37838         }
37839         return totalWidth;
37840     },
37841
37842     getLockedCount : function(){
37843         for(var i = 0, len = this.config.length; i < len; i++){
37844             if(!this.isLocked(i)){
37845                 return i;
37846             }
37847         }
37848     },
37849
37850     /**
37851      * Returns the number of columns.
37852      * @return {Number}
37853      */
37854     getColumnCount : function(visibleOnly){
37855         if(visibleOnly === true){
37856             var c = 0;
37857             for(var i = 0, len = this.config.length; i < len; i++){
37858                 if(!this.isHidden(i)){
37859                     c++;
37860                 }
37861             }
37862             return c;
37863         }
37864         return this.config.length;
37865     },
37866
37867     /**
37868      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
37869      * @param {Function} fn
37870      * @param {Object} scope (optional)
37871      * @return {Array} result
37872      */
37873     getColumnsBy : function(fn, scope){
37874         var r = [];
37875         for(var i = 0, len = this.config.length; i < len; i++){
37876             var c = this.config[i];
37877             if(fn.call(scope||this, c, i) === true){
37878                 r[r.length] = c;
37879             }
37880         }
37881         return r;
37882     },
37883
37884     /**
37885      * Returns true if the specified column is sortable.
37886      * @param {Number} col The column index
37887      * @return {Boolean}
37888      */
37889     isSortable : function(col){
37890         if(typeof this.config[col].sortable == "undefined"){
37891             return this.defaultSortable;
37892         }
37893         return this.config[col].sortable;
37894     },
37895
37896     /**
37897      * Returns the rendering (formatting) function defined for the column.
37898      * @param {Number} col The column index.
37899      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
37900      */
37901     getRenderer : function(col){
37902         if(!this.config[col].renderer){
37903             return Roo.grid.ColumnModel.defaultRenderer;
37904         }
37905         return this.config[col].renderer;
37906     },
37907
37908     /**
37909      * Sets the rendering (formatting) function for a column.
37910      * @param {Number} col The column index
37911      * @param {Function} fn The function to use to process the cell's raw data
37912      * to return HTML markup for the grid view. The render function is called with
37913      * the following parameters:<ul>
37914      * <li>Data value.</li>
37915      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
37916      * <li>css A CSS style string to apply to the table cell.</li>
37917      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
37918      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
37919      * <li>Row index</li>
37920      * <li>Column index</li>
37921      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
37922      */
37923     setRenderer : function(col, fn){
37924         this.config[col].renderer = fn;
37925     },
37926
37927     /**
37928      * Returns the width for the specified column.
37929      * @param {Number} col The column index
37930      * @return {Number}
37931      */
37932     getColumnWidth : function(col){
37933         return this.config[col].width * 1 || this.defaultWidth;
37934     },
37935
37936     /**
37937      * Sets the width for a column.
37938      * @param {Number} col The column index
37939      * @param {Number} width The new width
37940      */
37941     setColumnWidth : function(col, width, suppressEvent){
37942         this.config[col].width = width;
37943         this.totalWidth = null;
37944         if(!suppressEvent){
37945              this.fireEvent("widthchange", this, col, width);
37946         }
37947     },
37948
37949     /**
37950      * Returns the total width of all columns.
37951      * @param {Boolean} includeHidden True to include hidden column widths
37952      * @return {Number}
37953      */
37954     getTotalWidth : function(includeHidden){
37955         if(!this.totalWidth){
37956             this.totalWidth = 0;
37957             for(var i = 0, len = this.config.length; i < len; i++){
37958                 if(includeHidden || !this.isHidden(i)){
37959                     this.totalWidth += this.getColumnWidth(i);
37960                 }
37961             }
37962         }
37963         return this.totalWidth;
37964     },
37965
37966     /**
37967      * Returns the header for the specified column.
37968      * @param {Number} col The column index
37969      * @return {String}
37970      */
37971     getColumnHeader : function(col){
37972         return this.config[col].header;
37973     },
37974
37975     /**
37976      * Sets the header for a column.
37977      * @param {Number} col The column index
37978      * @param {String} header The new header
37979      */
37980     setColumnHeader : function(col, header){
37981         this.config[col].header = header;
37982         this.fireEvent("headerchange", this, col, header);
37983     },
37984
37985     /**
37986      * Returns the tooltip for the specified column.
37987      * @param {Number} col The column index
37988      * @return {String}
37989      */
37990     getColumnTooltip : function(col){
37991             return this.config[col].tooltip;
37992     },
37993     /**
37994      * Sets the tooltip for a column.
37995      * @param {Number} col The column index
37996      * @param {String} tooltip The new tooltip
37997      */
37998     setColumnTooltip : function(col, tooltip){
37999             this.config[col].tooltip = tooltip;
38000     },
38001
38002     /**
38003      * Returns the dataIndex for the specified column.
38004      * @param {Number} col The column index
38005      * @return {Number}
38006      */
38007     getDataIndex : function(col){
38008         return this.config[col].dataIndex;
38009     },
38010
38011     /**
38012      * Sets the dataIndex for a column.
38013      * @param {Number} col The column index
38014      * @param {Number} dataIndex The new dataIndex
38015      */
38016     setDataIndex : function(col, dataIndex){
38017         this.config[col].dataIndex = dataIndex;
38018     },
38019
38020     
38021     
38022     /**
38023      * Returns true if the cell is editable.
38024      * @param {Number} colIndex The column index
38025      * @param {Number} rowIndex The row index
38026      * @return {Boolean}
38027      */
38028     isCellEditable : function(colIndex, rowIndex){
38029         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
38030     },
38031
38032     /**
38033      * Returns the editor defined for the cell/column.
38034      * return false or null to disable editing.
38035      * @param {Number} colIndex The column index
38036      * @param {Number} rowIndex The row index
38037      * @return {Object}
38038      */
38039     getCellEditor : function(colIndex, rowIndex){
38040         return this.config[colIndex].editor;
38041     },
38042
38043     /**
38044      * Sets if a column is editable.
38045      * @param {Number} col The column index
38046      * @param {Boolean} editable True if the column is editable
38047      */
38048     setEditable : function(col, editable){
38049         this.config[col].editable = editable;
38050     },
38051
38052
38053     /**
38054      * Returns true if the column is hidden.
38055      * @param {Number} colIndex The column index
38056      * @return {Boolean}
38057      */
38058     isHidden : function(colIndex){
38059         return this.config[colIndex].hidden;
38060     },
38061
38062
38063     /**
38064      * Returns true if the column width cannot be changed
38065      */
38066     isFixed : function(colIndex){
38067         return this.config[colIndex].fixed;
38068     },
38069
38070     /**
38071      * Returns true if the column can be resized
38072      * @return {Boolean}
38073      */
38074     isResizable : function(colIndex){
38075         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
38076     },
38077     /**
38078      * Sets if a column is hidden.
38079      * @param {Number} colIndex The column index
38080      * @param {Boolean} hidden True if the column is hidden
38081      */
38082     setHidden : function(colIndex, hidden){
38083         this.config[colIndex].hidden = hidden;
38084         this.totalWidth = null;
38085         this.fireEvent("hiddenchange", this, colIndex, hidden);
38086     },
38087
38088     /**
38089      * Sets the editor for a column.
38090      * @param {Number} col The column index
38091      * @param {Object} editor The editor object
38092      */
38093     setEditor : function(col, editor){
38094         this.config[col].editor = editor;
38095     }
38096 });
38097
38098 Roo.grid.ColumnModel.defaultRenderer = function(value){
38099         if(typeof value == "string" && value.length < 1){
38100             return "&#160;";
38101         }
38102         return value;
38103 };
38104
38105 // Alias for backwards compatibility
38106 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
38107 /*
38108  * Based on:
38109  * Ext JS Library 1.1.1
38110  * Copyright(c) 2006-2007, Ext JS, LLC.
38111  *
38112  * Originally Released Under LGPL - original licence link has changed is not relivant.
38113  *
38114  * Fork - LGPL
38115  * <script type="text/javascript">
38116  */
38117
38118 /**
38119  * @class Roo.grid.AbstractSelectionModel
38120  * @extends Roo.util.Observable
38121  * Abstract base class for grid SelectionModels.  It provides the interface that should be
38122  * implemented by descendant classes.  This class should not be directly instantiated.
38123  * @constructor
38124  */
38125 Roo.grid.AbstractSelectionModel = function(){
38126     this.locked = false;
38127     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
38128 };
38129
38130 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
38131     /** @ignore Called by the grid automatically. Do not call directly. */
38132     init : function(grid){
38133         this.grid = grid;
38134         this.initEvents();
38135     },
38136
38137     /**
38138      * Locks the selections.
38139      */
38140     lock : function(){
38141         this.locked = true;
38142     },
38143
38144     /**
38145      * Unlocks the selections.
38146      */
38147     unlock : function(){
38148         this.locked = false;
38149     },
38150
38151     /**
38152      * Returns true if the selections are locked.
38153      * @return {Boolean}
38154      */
38155     isLocked : function(){
38156         return this.locked;
38157     }
38158 });/*
38159  * Based on:
38160  * Ext JS Library 1.1.1
38161  * Copyright(c) 2006-2007, Ext JS, LLC.
38162  *
38163  * Originally Released Under LGPL - original licence link has changed is not relivant.
38164  *
38165  * Fork - LGPL
38166  * <script type="text/javascript">
38167  */
38168 /**
38169  * @extends Roo.grid.AbstractSelectionModel
38170  * @class Roo.grid.RowSelectionModel
38171  * The default SelectionModel used by {@link Roo.grid.Grid}.
38172  * It supports multiple selections and keyboard selection/navigation. 
38173  * @constructor
38174  * @param {Object} config
38175  */
38176 Roo.grid.RowSelectionModel = function(config){
38177     Roo.apply(this, config);
38178     this.selections = new Roo.util.MixedCollection(false, function(o){
38179         return o.id;
38180     });
38181
38182     this.last = false;
38183     this.lastActive = false;
38184
38185     this.addEvents({
38186         /**
38187              * @event selectionchange
38188              * Fires when the selection changes
38189              * @param {SelectionModel} this
38190              */
38191             "selectionchange" : true,
38192         /**
38193              * @event afterselectionchange
38194              * Fires after the selection changes (eg. by key press or clicking)
38195              * @param {SelectionModel} this
38196              */
38197             "afterselectionchange" : true,
38198         /**
38199              * @event beforerowselect
38200              * Fires when a row is selected being selected, return false to cancel.
38201              * @param {SelectionModel} this
38202              * @param {Number} rowIndex The selected index
38203              * @param {Boolean} keepExisting False if other selections will be cleared
38204              */
38205             "beforerowselect" : true,
38206         /**
38207              * @event rowselect
38208              * Fires when a row is selected.
38209              * @param {SelectionModel} this
38210              * @param {Number} rowIndex The selected index
38211              * @param {Roo.data.Record} r The record
38212              */
38213             "rowselect" : true,
38214         /**
38215              * @event rowdeselect
38216              * Fires when a row is deselected.
38217              * @param {SelectionModel} this
38218              * @param {Number} rowIndex The selected index
38219              */
38220         "rowdeselect" : true
38221     });
38222     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
38223     this.locked = false;
38224 };
38225
38226 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
38227     /**
38228      * @cfg {Boolean} singleSelect
38229      * True to allow selection of only one row at a time (defaults to false)
38230      */
38231     singleSelect : false,
38232
38233     // private
38234     initEvents : function(){
38235
38236         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
38237             this.grid.on("mousedown", this.handleMouseDown, this);
38238         }else{ // allow click to work like normal
38239             this.grid.on("rowclick", this.handleDragableRowClick, this);
38240         }
38241
38242         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
38243             "up" : function(e){
38244                 if(!e.shiftKey){
38245                     this.selectPrevious(e.shiftKey);
38246                 }else if(this.last !== false && this.lastActive !== false){
38247                     var last = this.last;
38248                     this.selectRange(this.last,  this.lastActive-1);
38249                     this.grid.getView().focusRow(this.lastActive);
38250                     if(last !== false){
38251                         this.last = last;
38252                     }
38253                 }else{
38254                     this.selectFirstRow();
38255                 }
38256                 this.fireEvent("afterselectionchange", this);
38257             },
38258             "down" : function(e){
38259                 if(!e.shiftKey){
38260                     this.selectNext(e.shiftKey);
38261                 }else if(this.last !== false && this.lastActive !== false){
38262                     var last = this.last;
38263                     this.selectRange(this.last,  this.lastActive+1);
38264                     this.grid.getView().focusRow(this.lastActive);
38265                     if(last !== false){
38266                         this.last = last;
38267                     }
38268                 }else{
38269                     this.selectFirstRow();
38270                 }
38271                 this.fireEvent("afterselectionchange", this);
38272             },
38273             scope: this
38274         });
38275
38276         var view = this.grid.view;
38277         view.on("refresh", this.onRefresh, this);
38278         view.on("rowupdated", this.onRowUpdated, this);
38279         view.on("rowremoved", this.onRemove, this);
38280     },
38281
38282     // private
38283     onRefresh : function(){
38284         var ds = this.grid.dataSource, i, v = this.grid.view;
38285         var s = this.selections;
38286         s.each(function(r){
38287             if((i = ds.indexOfId(r.id)) != -1){
38288                 v.onRowSelect(i);
38289             }else{
38290                 s.remove(r);
38291             }
38292         });
38293     },
38294
38295     // private
38296     onRemove : function(v, index, r){
38297         this.selections.remove(r);
38298     },
38299
38300     // private
38301     onRowUpdated : function(v, index, r){
38302         if(this.isSelected(r)){
38303             v.onRowSelect(index);
38304         }
38305     },
38306
38307     /**
38308      * Select records.
38309      * @param {Array} records The records to select
38310      * @param {Boolean} keepExisting (optional) True to keep existing selections
38311      */
38312     selectRecords : function(records, keepExisting){
38313         if(!keepExisting){
38314             this.clearSelections();
38315         }
38316         var ds = this.grid.dataSource;
38317         for(var i = 0, len = records.length; i < len; i++){
38318             this.selectRow(ds.indexOf(records[i]), true);
38319         }
38320     },
38321
38322     /**
38323      * Gets the number of selected rows.
38324      * @return {Number}
38325      */
38326     getCount : function(){
38327         return this.selections.length;
38328     },
38329
38330     /**
38331      * Selects the first row in the grid.
38332      */
38333     selectFirstRow : function(){
38334         this.selectRow(0);
38335     },
38336
38337     /**
38338      * Select the last row.
38339      * @param {Boolean} keepExisting (optional) True to keep existing selections
38340      */
38341     selectLastRow : function(keepExisting){
38342         this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting);
38343     },
38344
38345     /**
38346      * Selects the row immediately following the last selected row.
38347      * @param {Boolean} keepExisting (optional) True to keep existing selections
38348      */
38349     selectNext : function(keepExisting){
38350         if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){
38351             this.selectRow(this.last+1, keepExisting);
38352             this.grid.getView().focusRow(this.last);
38353         }
38354     },
38355
38356     /**
38357      * Selects the row that precedes the last selected row.
38358      * @param {Boolean} keepExisting (optional) True to keep existing selections
38359      */
38360     selectPrevious : function(keepExisting){
38361         if(this.last){
38362             this.selectRow(this.last-1, keepExisting);
38363             this.grid.getView().focusRow(this.last);
38364         }
38365     },
38366
38367     /**
38368      * Returns the selected records
38369      * @return {Array} Array of selected records
38370      */
38371     getSelections : function(){
38372         return [].concat(this.selections.items);
38373     },
38374
38375     /**
38376      * Returns the first selected record.
38377      * @return {Record}
38378      */
38379     getSelected : function(){
38380         return this.selections.itemAt(0);
38381     },
38382
38383
38384     /**
38385      * Clears all selections.
38386      */
38387     clearSelections : function(fast){
38388         if(this.locked) return;
38389         if(fast !== true){
38390             var ds = this.grid.dataSource;
38391             var s = this.selections;
38392             s.each(function(r){
38393                 this.deselectRow(ds.indexOfId(r.id));
38394             }, this);
38395             s.clear();
38396         }else{
38397             this.selections.clear();
38398         }
38399         this.last = false;
38400     },
38401
38402
38403     /**
38404      * Selects all rows.
38405      */
38406     selectAll : function(){
38407         if(this.locked) return;
38408         this.selections.clear();
38409         for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){
38410             this.selectRow(i, true);
38411         }
38412     },
38413
38414     /**
38415      * Returns True if there is a selection.
38416      * @return {Boolean}
38417      */
38418     hasSelection : function(){
38419         return this.selections.length > 0;
38420     },
38421
38422     /**
38423      * Returns True if the specified row is selected.
38424      * @param {Number/Record} record The record or index of the record to check
38425      * @return {Boolean}
38426      */
38427     isSelected : function(index){
38428         var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index;
38429         return (r && this.selections.key(r.id) ? true : false);
38430     },
38431
38432     /**
38433      * Returns True if the specified record id is selected.
38434      * @param {String} id The id of record to check
38435      * @return {Boolean}
38436      */
38437     isIdSelected : function(id){
38438         return (this.selections.key(id) ? true : false);
38439     },
38440
38441     // private
38442     handleMouseDown : function(e, t){
38443         var view = this.grid.getView(), rowIndex;
38444         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
38445             return;
38446         };
38447         if(e.shiftKey && this.last !== false){
38448             var last = this.last;
38449             this.selectRange(last, rowIndex, e.ctrlKey);
38450             this.last = last; // reset the last
38451             view.focusRow(rowIndex);
38452         }else{
38453             var isSelected = this.isSelected(rowIndex);
38454             if(e.button !== 0 && isSelected){
38455                 view.focusRow(rowIndex);
38456             }else if(e.ctrlKey && isSelected){
38457                 this.deselectRow(rowIndex);
38458             }else if(!isSelected){
38459                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
38460                 view.focusRow(rowIndex);
38461             }
38462         }
38463         this.fireEvent("afterselectionchange", this);
38464     },
38465     // private
38466     handleDragableRowClick :  function(grid, rowIndex, e) 
38467     {
38468         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
38469             this.selectRow(rowIndex, false);
38470             grid.view.focusRow(rowIndex);
38471              this.fireEvent("afterselectionchange", this);
38472         }
38473     },
38474     
38475     /**
38476      * Selects multiple rows.
38477      * @param {Array} rows Array of the indexes of the row to select
38478      * @param {Boolean} keepExisting (optional) True to keep existing selections
38479      */
38480     selectRows : function(rows, keepExisting){
38481         if(!keepExisting){
38482             this.clearSelections();
38483         }
38484         for(var i = 0, len = rows.length; i < len; i++){
38485             this.selectRow(rows[i], true);
38486         }
38487     },
38488
38489     /**
38490      * Selects a range of rows. All rows in between startRow and endRow are also selected.
38491      * @param {Number} startRow The index of the first row in the range
38492      * @param {Number} endRow The index of the last row in the range
38493      * @param {Boolean} keepExisting (optional) True to retain existing selections
38494      */
38495     selectRange : function(startRow, endRow, keepExisting){
38496         if(this.locked) return;
38497         if(!keepExisting){
38498             this.clearSelections();
38499         }
38500         if(startRow <= endRow){
38501             for(var i = startRow; i <= endRow; i++){
38502                 this.selectRow(i, true);
38503             }
38504         }else{
38505             for(var i = startRow; i >= endRow; i--){
38506                 this.selectRow(i, true);
38507             }
38508         }
38509     },
38510
38511     /**
38512      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
38513      * @param {Number} startRow The index of the first row in the range
38514      * @param {Number} endRow The index of the last row in the range
38515      */
38516     deselectRange : function(startRow, endRow, preventViewNotify){
38517         if(this.locked) return;
38518         for(var i = startRow; i <= endRow; i++){
38519             this.deselectRow(i, preventViewNotify);
38520         }
38521     },
38522
38523     /**
38524      * Selects a row.
38525      * @param {Number} row The index of the row to select
38526      * @param {Boolean} keepExisting (optional) True to keep existing selections
38527      */
38528     selectRow : function(index, keepExisting, preventViewNotify){
38529         if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return;
38530         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
38531             if(!keepExisting || this.singleSelect){
38532                 this.clearSelections();
38533             }
38534             var r = this.grid.dataSource.getAt(index);
38535             this.selections.add(r);
38536             this.last = this.lastActive = index;
38537             if(!preventViewNotify){
38538                 this.grid.getView().onRowSelect(index);
38539             }
38540             this.fireEvent("rowselect", this, index, r);
38541             this.fireEvent("selectionchange", this);
38542         }
38543     },
38544
38545     /**
38546      * Deselects a row.
38547      * @param {Number} row The index of the row to deselect
38548      */
38549     deselectRow : function(index, preventViewNotify){
38550         if(this.locked) return;
38551         if(this.last == index){
38552             this.last = false;
38553         }
38554         if(this.lastActive == index){
38555             this.lastActive = false;
38556         }
38557         var r = this.grid.dataSource.getAt(index);
38558         this.selections.remove(r);
38559         if(!preventViewNotify){
38560             this.grid.getView().onRowDeselect(index);
38561         }
38562         this.fireEvent("rowdeselect", this, index);
38563         this.fireEvent("selectionchange", this);
38564     },
38565
38566     // private
38567     restoreLast : function(){
38568         if(this._last){
38569             this.last = this._last;
38570         }
38571     },
38572
38573     // private
38574     acceptsNav : function(row, col, cm){
38575         return !cm.isHidden(col) && cm.isCellEditable(col, row);
38576     },
38577
38578     // private
38579     onEditorKey : function(field, e){
38580         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
38581         if(k == e.TAB){
38582             e.stopEvent();
38583             ed.completeEdit();
38584             if(e.shiftKey){
38585                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
38586             }else{
38587                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
38588             }
38589         }else if(k == e.ENTER && !e.ctrlKey){
38590             e.stopEvent();
38591             ed.completeEdit();
38592             if(e.shiftKey){
38593                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
38594             }else{
38595                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
38596             }
38597         }else if(k == e.ESC){
38598             ed.cancelEdit();
38599         }
38600         if(newCell){
38601             g.startEditing(newCell[0], newCell[1]);
38602         }
38603     }
38604 });/*
38605  * Based on:
38606  * Ext JS Library 1.1.1
38607  * Copyright(c) 2006-2007, Ext JS, LLC.
38608  *
38609  * Originally Released Under LGPL - original licence link has changed is not relivant.
38610  *
38611  * Fork - LGPL
38612  * <script type="text/javascript">
38613  */
38614 /**
38615  * @class Roo.grid.CellSelectionModel
38616  * @extends Roo.grid.AbstractSelectionModel
38617  * This class provides the basic implementation for cell selection in a grid.
38618  * @constructor
38619  * @param {Object} config The object containing the configuration of this model.
38620  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
38621  */
38622 Roo.grid.CellSelectionModel = function(config){
38623     Roo.apply(this, config);
38624
38625     this.selection = null;
38626
38627     this.addEvents({
38628         /**
38629              * @event beforerowselect
38630              * Fires before a cell is selected.
38631              * @param {SelectionModel} this
38632              * @param {Number} rowIndex The selected row index
38633              * @param {Number} colIndex The selected cell index
38634              */
38635             "beforecellselect" : true,
38636         /**
38637              * @event cellselect
38638              * Fires when a cell is selected.
38639              * @param {SelectionModel} this
38640              * @param {Number} rowIndex The selected row index
38641              * @param {Number} colIndex The selected cell index
38642              */
38643             "cellselect" : true,
38644         /**
38645              * @event selectionchange
38646              * Fires when the active selection changes.
38647              * @param {SelectionModel} this
38648              * @param {Object} selection null for no selection or an object (o) with two properties
38649                 <ul>
38650                 <li>o.record: the record object for the row the selection is in</li>
38651                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
38652                 </ul>
38653              */
38654             "selectionchange" : true,
38655         /**
38656              * @event tabend
38657              * Fires when the tab (or enter) was pressed on the last editable cell
38658              * You can use this to trigger add new row.
38659              * @param {SelectionModel} this
38660              */
38661             "tabend" : true,
38662          /**
38663              * @event beforeeditnext
38664              * Fires before the next editable sell is made active
38665              * You can use this to skip to another cell or fire the tabend
38666              *    if you set cell to false
38667              * @param {Object} eventdata object : { cell : [ row, col ] } 
38668              */
38669             "beforeeditnext" : true
38670     });
38671     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
38672 };
38673
38674 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
38675     
38676     enter_is_tab: false,
38677
38678     /** @ignore */
38679     initEvents : function(){
38680         this.grid.on("mousedown", this.handleMouseDown, this);
38681         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
38682         var view = this.grid.view;
38683         view.on("refresh", this.onViewChange, this);
38684         view.on("rowupdated", this.onRowUpdated, this);
38685         view.on("beforerowremoved", this.clearSelections, this);
38686         view.on("beforerowsinserted", this.clearSelections, this);
38687         if(this.grid.isEditor){
38688             this.grid.on("beforeedit", this.beforeEdit,  this);
38689         }
38690     },
38691
38692         //private
38693     beforeEdit : function(e){
38694         this.select(e.row, e.column, false, true, e.record);
38695     },
38696
38697         //private
38698     onRowUpdated : function(v, index, r){
38699         if(this.selection && this.selection.record == r){
38700             v.onCellSelect(index, this.selection.cell[1]);
38701         }
38702     },
38703
38704         //private
38705     onViewChange : function(){
38706         this.clearSelections(true);
38707     },
38708
38709         /**
38710          * Returns the currently selected cell,.
38711          * @return {Array} The selected cell (row, column) or null if none selected.
38712          */
38713     getSelectedCell : function(){
38714         return this.selection ? this.selection.cell : null;
38715     },
38716
38717     /**
38718      * Clears all selections.
38719      * @param {Boolean} true to prevent the gridview from being notified about the change.
38720      */
38721     clearSelections : function(preventNotify){
38722         var s = this.selection;
38723         if(s){
38724             if(preventNotify !== true){
38725                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
38726             }
38727             this.selection = null;
38728             this.fireEvent("selectionchange", this, null);
38729         }
38730     },
38731
38732     /**
38733      * Returns true if there is a selection.
38734      * @return {Boolean}
38735      */
38736     hasSelection : function(){
38737         return this.selection ? true : false;
38738     },
38739
38740     /** @ignore */
38741     handleMouseDown : function(e, t){
38742         var v = this.grid.getView();
38743         if(this.isLocked()){
38744             return;
38745         };
38746         var row = v.findRowIndex(t);
38747         var cell = v.findCellIndex(t);
38748         if(row !== false && cell !== false){
38749             this.select(row, cell);
38750         }
38751     },
38752
38753     /**
38754      * Selects a cell.
38755      * @param {Number} rowIndex
38756      * @param {Number} collIndex
38757      */
38758     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
38759         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
38760             this.clearSelections();
38761             r = r || this.grid.dataSource.getAt(rowIndex);
38762             this.selection = {
38763                 record : r,
38764                 cell : [rowIndex, colIndex]
38765             };
38766             if(!preventViewNotify){
38767                 var v = this.grid.getView();
38768                 v.onCellSelect(rowIndex, colIndex);
38769                 if(preventFocus !== true){
38770                     v.focusCell(rowIndex, colIndex);
38771                 }
38772             }
38773             this.fireEvent("cellselect", this, rowIndex, colIndex);
38774             this.fireEvent("selectionchange", this, this.selection);
38775         }
38776     },
38777
38778         //private
38779     isSelectable : function(rowIndex, colIndex, cm){
38780         return !cm.isHidden(colIndex);
38781     },
38782
38783     /** @ignore */
38784     handleKeyDown : function(e){
38785         //Roo.log('Cell Sel Model handleKeyDown');
38786         if(!e.isNavKeyPress()){
38787             return;
38788         }
38789         var g = this.grid, s = this.selection;
38790         if(!s){
38791             e.stopEvent();
38792             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
38793             if(cell){
38794                 this.select(cell[0], cell[1]);
38795             }
38796             return;
38797         }
38798         var sm = this;
38799         var walk = function(row, col, step){
38800             return g.walkCells(row, col, step, sm.isSelectable,  sm);
38801         };
38802         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
38803         var newCell;
38804
38805       
38806
38807         switch(k){
38808             case e.TAB:
38809                 // handled by onEditorKey
38810                 if (g.isEditor && g.editing) {
38811                     return;
38812                 }
38813                 if(e.shiftKey) {
38814                     newCell = walk(r, c-1, -1);
38815                 } else {
38816                     newCell = walk(r, c+1, 1);
38817                 }
38818                 break;
38819             
38820             case e.DOWN:
38821                newCell = walk(r+1, c, 1);
38822                 break;
38823             
38824             case e.UP:
38825                 newCell = walk(r-1, c, -1);
38826                 break;
38827             
38828             case e.RIGHT:
38829                 newCell = walk(r, c+1, 1);
38830                 break;
38831             
38832             case e.LEFT:
38833                 newCell = walk(r, c-1, -1);
38834                 break;
38835             
38836             case e.ENTER:
38837                 
38838                 if(g.isEditor && !g.editing){
38839                    g.startEditing(r, c);
38840                    e.stopEvent();
38841                    return;
38842                 }
38843                 
38844                 
38845              break;
38846         };
38847         if(newCell){
38848             this.select(newCell[0], newCell[1]);
38849             e.stopEvent();
38850             
38851         }
38852     },
38853
38854     acceptsNav : function(row, col, cm){
38855         return !cm.isHidden(col) && cm.isCellEditable(col, row);
38856     },
38857     /**
38858      * Selects a cell.
38859      * @param {Number} field (not used) - as it's normally used as a listener
38860      * @param {Number} e - event - fake it by using
38861      *
38862      * var e = Roo.EventObjectImpl.prototype;
38863      * e.keyCode = e.TAB
38864      *
38865      * 
38866      */
38867     onEditorKey : function(field, e){
38868         
38869         var k = e.getKey(),
38870             newCell,
38871             g = this.grid,
38872             ed = g.activeEditor,
38873             forward = false;
38874         ///Roo.log('onEditorKey' + k);
38875         
38876         
38877         if (this.enter_is_tab && k == e.ENTER) {
38878             k = e.TAB;
38879         }
38880         
38881         if(k == e.TAB){
38882             if(e.shiftKey){
38883                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
38884             }else{
38885                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
38886                 forward = true;
38887             }
38888             
38889             e.stopEvent();
38890             
38891         } else if(k == e.ENTER &&  !e.ctrlKey){
38892             ed.completeEdit();
38893             e.stopEvent();
38894             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
38895         
38896                 } else if(k == e.ESC){
38897             ed.cancelEdit();
38898         }
38899                 
38900         if (newCell) {
38901             var ecall = { cell : newCell, forward : forward };
38902             this.fireEvent('beforeeditnext', ecall );
38903             newCell = ecall.cell;
38904                         forward = ecall.forward;
38905         }
38906                 
38907         if(newCell){
38908             //Roo.log('next cell after edit');
38909             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
38910         } else if (forward) {
38911             // tabbed past last
38912             this.fireEvent.defer(100, this, ['tabend',this]);
38913         }
38914     }
38915 });/*
38916  * Based on:
38917  * Ext JS Library 1.1.1
38918  * Copyright(c) 2006-2007, Ext JS, LLC.
38919  *
38920  * Originally Released Under LGPL - original licence link has changed is not relivant.
38921  *
38922  * Fork - LGPL
38923  * <script type="text/javascript">
38924  */
38925  
38926 /**
38927  * @class Roo.grid.EditorGrid
38928  * @extends Roo.grid.Grid
38929  * Class for creating and editable grid.
38930  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
38931  * The container MUST have some type of size defined for the grid to fill. The container will be 
38932  * automatically set to position relative if it isn't already.
38933  * @param {Object} dataSource The data model to bind to
38934  * @param {Object} colModel The column model with info about this grid's columns
38935  */
38936 Roo.grid.EditorGrid = function(container, config){
38937     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
38938     this.getGridEl().addClass("xedit-grid");
38939
38940     if(!this.selModel){
38941         this.selModel = new Roo.grid.CellSelectionModel();
38942     }
38943
38944     this.activeEditor = null;
38945
38946         this.addEvents({
38947             /**
38948              * @event beforeedit
38949              * Fires before cell editing is triggered. The edit event object has the following properties <br />
38950              * <ul style="padding:5px;padding-left:16px;">
38951              * <li>grid - This grid</li>
38952              * <li>record - The record being edited</li>
38953              * <li>field - The field name being edited</li>
38954              * <li>value - The value for the field being edited.</li>
38955              * <li>row - The grid row index</li>
38956              * <li>column - The grid column index</li>
38957              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
38958              * </ul>
38959              * @param {Object} e An edit event (see above for description)
38960              */
38961             "beforeedit" : true,
38962             /**
38963              * @event afteredit
38964              * Fires after a cell is edited. <br />
38965              * <ul style="padding:5px;padding-left:16px;">
38966              * <li>grid - This grid</li>
38967              * <li>record - The record being edited</li>
38968              * <li>field - The field name being edited</li>
38969              * <li>value - The value being set</li>
38970              * <li>originalValue - The original value for the field, before the edit.</li>
38971              * <li>row - The grid row index</li>
38972              * <li>column - The grid column index</li>
38973              * </ul>
38974              * @param {Object} e An edit event (see above for description)
38975              */
38976             "afteredit" : true,
38977             /**
38978              * @event validateedit
38979              * Fires after a cell is edited, but before the value is set in the record. 
38980          * You can use this to modify the value being set in the field, Return false
38981              * to cancel the change. The edit event object has the following properties <br />
38982              * <ul style="padding:5px;padding-left:16px;">
38983          * <li>editor - This editor</li>
38984              * <li>grid - This grid</li>
38985              * <li>record - The record being edited</li>
38986              * <li>field - The field name being edited</li>
38987              * <li>value - The value being set</li>
38988              * <li>originalValue - The original value for the field, before the edit.</li>
38989              * <li>row - The grid row index</li>
38990              * <li>column - The grid column index</li>
38991              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
38992              * </ul>
38993              * @param {Object} e An edit event (see above for description)
38994              */
38995             "validateedit" : true
38996         });
38997     this.on("bodyscroll", this.stopEditing,  this);
38998     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
38999 };
39000
39001 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
39002     /**
39003      * @cfg {Number} clicksToEdit
39004      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
39005      */
39006     clicksToEdit: 2,
39007
39008     // private
39009     isEditor : true,
39010     // private
39011     trackMouseOver: false, // causes very odd FF errors
39012
39013     onCellDblClick : function(g, row, col){
39014         this.startEditing(row, col);
39015     },
39016
39017     onEditComplete : function(ed, value, startValue){
39018         this.editing = false;
39019         this.activeEditor = null;
39020         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
39021         var r = ed.record;
39022         var field = this.colModel.getDataIndex(ed.col);
39023         var e = {
39024             grid: this,
39025             record: r,
39026             field: field,
39027             originalValue: startValue,
39028             value: value,
39029             row: ed.row,
39030             column: ed.col,
39031             cancel:false,
39032             editor: ed
39033         };
39034         var cell = Roo.get(this.view.getCell(ed.row,ed.col))
39035         cell.show();
39036           
39037         if(String(value) !== String(startValue)){
39038             
39039             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
39040                 r.set(field, e.value);
39041                 // if we are dealing with a combo box..
39042                 // then we also set the 'name' colum to be the displayField
39043                 if (ed.field.displayField && ed.field.name) {
39044                     r.set(ed.field.name, ed.field.el.dom.value);
39045                 }
39046                 
39047                 delete e.cancel; //?? why!!!
39048                 this.fireEvent("afteredit", e);
39049             }
39050         } else {
39051             this.fireEvent("afteredit", e); // always fire it!
39052         }
39053         this.view.focusCell(ed.row, ed.col);
39054     },
39055
39056     /**
39057      * Starts editing the specified for the specified row/column
39058      * @param {Number} rowIndex
39059      * @param {Number} colIndex
39060      */
39061     startEditing : function(row, col){
39062         this.stopEditing();
39063         if(this.colModel.isCellEditable(col, row)){
39064             this.view.ensureVisible(row, col, true);
39065           
39066             var r = this.dataSource.getAt(row);
39067             var field = this.colModel.getDataIndex(col);
39068             var cell = Roo.get(this.view.getCell(row,col));
39069             var e = {
39070                 grid: this,
39071                 record: r,
39072                 field: field,
39073                 value: r.data[field],
39074                 row: row,
39075                 column: col,
39076                 cancel:false 
39077             };
39078             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
39079                 this.editing = true;
39080                 var ed = this.colModel.getCellEditor(col, row);
39081                 
39082                 if (!ed) {
39083                     return;
39084                 }
39085                 if(!ed.rendered){
39086                     ed.render(ed.parentEl || document.body);
39087                 }
39088                 ed.field.reset();
39089                
39090                 cell.hide();
39091                 
39092                 (function(){ // complex but required for focus issues in safari, ie and opera
39093                     ed.row = row;
39094                     ed.col = col;
39095                     ed.record = r;
39096                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
39097                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
39098                     this.activeEditor = ed;
39099                     var v = r.data[field];
39100                     ed.startEdit(this.view.getCell(row, col), v);
39101                     // combo's with 'displayField and name set
39102                     if (ed.field.displayField && ed.field.name) {
39103                         ed.field.el.dom.value = r.data[ed.field.name];
39104                     }
39105                     
39106                     
39107                 }).defer(50, this);
39108             }
39109         }
39110     },
39111         
39112     /**
39113      * Stops any active editing
39114      */
39115     stopEditing : function(){
39116         if(this.activeEditor){
39117             this.activeEditor.completeEdit();
39118         }
39119         this.activeEditor = null;
39120     },
39121         
39122          /**
39123      * Called to get grid's drag proxy text, by default returns this.ddText.
39124      * @return {String}
39125      */
39126     getDragDropText : function(){
39127         var count = this.selModel.getSelectedCell() ? 1 : 0;
39128         return String.format(this.ddText, count, count == 1 ? '' : 's');
39129     }
39130         
39131 });/*
39132  * Based on:
39133  * Ext JS Library 1.1.1
39134  * Copyright(c) 2006-2007, Ext JS, LLC.
39135  *
39136  * Originally Released Under LGPL - original licence link has changed is not relivant.
39137  *
39138  * Fork - LGPL
39139  * <script type="text/javascript">
39140  */
39141
39142 // private - not really -- you end up using it !
39143 // This is a support class used internally by the Grid components
39144
39145 /**
39146  * @class Roo.grid.GridEditor
39147  * @extends Roo.Editor
39148  * Class for creating and editable grid elements.
39149  * @param {Object} config any settings (must include field)
39150  */
39151 Roo.grid.GridEditor = function(field, config){
39152     if (!config && field.field) {
39153         config = field;
39154         field = Roo.factory(config.field, Roo.form);
39155     }
39156     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
39157     field.monitorTab = false;
39158 };
39159
39160 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
39161     
39162     /**
39163      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
39164      */
39165     
39166     alignment: "tl-tl",
39167     autoSize: "width",
39168     hideEl : false,
39169     cls: "x-small-editor x-grid-editor",
39170     shim:false,
39171     shadow:"frame"
39172 });/*
39173  * Based on:
39174  * Ext JS Library 1.1.1
39175  * Copyright(c) 2006-2007, Ext JS, LLC.
39176  *
39177  * Originally Released Under LGPL - original licence link has changed is not relivant.
39178  *
39179  * Fork - LGPL
39180  * <script type="text/javascript">
39181  */
39182   
39183
39184   
39185 Roo.grid.PropertyRecord = Roo.data.Record.create([
39186     {name:'name',type:'string'},  'value'
39187 ]);
39188
39189
39190 Roo.grid.PropertyStore = function(grid, source){
39191     this.grid = grid;
39192     this.store = new Roo.data.Store({
39193         recordType : Roo.grid.PropertyRecord
39194     });
39195     this.store.on('update', this.onUpdate,  this);
39196     if(source){
39197         this.setSource(source);
39198     }
39199     Roo.grid.PropertyStore.superclass.constructor.call(this);
39200 };
39201
39202
39203
39204 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
39205     setSource : function(o){
39206         this.source = o;
39207         this.store.removeAll();
39208         var data = [];
39209         for(var k in o){
39210             if(this.isEditableValue(o[k])){
39211                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
39212             }
39213         }
39214         this.store.loadRecords({records: data}, {}, true);
39215     },
39216
39217     onUpdate : function(ds, record, type){
39218         if(type == Roo.data.Record.EDIT){
39219             var v = record.data['value'];
39220             var oldValue = record.modified['value'];
39221             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
39222                 this.source[record.id] = v;
39223                 record.commit();
39224                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
39225             }else{
39226                 record.reject();
39227             }
39228         }
39229     },
39230
39231     getProperty : function(row){
39232        return this.store.getAt(row);
39233     },
39234
39235     isEditableValue: function(val){
39236         if(val && val instanceof Date){
39237             return true;
39238         }else if(typeof val == 'object' || typeof val == 'function'){
39239             return false;
39240         }
39241         return true;
39242     },
39243
39244     setValue : function(prop, value){
39245         this.source[prop] = value;
39246         this.store.getById(prop).set('value', value);
39247     },
39248
39249     getSource : function(){
39250         return this.source;
39251     }
39252 });
39253
39254 Roo.grid.PropertyColumnModel = function(grid, store){
39255     this.grid = grid;
39256     var g = Roo.grid;
39257     g.PropertyColumnModel.superclass.constructor.call(this, [
39258         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
39259         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
39260     ]);
39261     this.store = store;
39262     this.bselect = Roo.DomHelper.append(document.body, {
39263         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
39264             {tag: 'option', value: 'true', html: 'true'},
39265             {tag: 'option', value: 'false', html: 'false'}
39266         ]
39267     });
39268     Roo.id(this.bselect);
39269     var f = Roo.form;
39270     this.editors = {
39271         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
39272         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
39273         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
39274         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
39275         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
39276     };
39277     this.renderCellDelegate = this.renderCell.createDelegate(this);
39278     this.renderPropDelegate = this.renderProp.createDelegate(this);
39279 };
39280
39281 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
39282     
39283     
39284     nameText : 'Name',
39285     valueText : 'Value',
39286     
39287     dateFormat : 'm/j/Y',
39288     
39289     
39290     renderDate : function(dateVal){
39291         return dateVal.dateFormat(this.dateFormat);
39292     },
39293
39294     renderBool : function(bVal){
39295         return bVal ? 'true' : 'false';
39296     },
39297
39298     isCellEditable : function(colIndex, rowIndex){
39299         return colIndex == 1;
39300     },
39301
39302     getRenderer : function(col){
39303         return col == 1 ?
39304             this.renderCellDelegate : this.renderPropDelegate;
39305     },
39306
39307     renderProp : function(v){
39308         return this.getPropertyName(v);
39309     },
39310
39311     renderCell : function(val){
39312         var rv = val;
39313         if(val instanceof Date){
39314             rv = this.renderDate(val);
39315         }else if(typeof val == 'boolean'){
39316             rv = this.renderBool(val);
39317         }
39318         return Roo.util.Format.htmlEncode(rv);
39319     },
39320
39321     getPropertyName : function(name){
39322         var pn = this.grid.propertyNames;
39323         return pn && pn[name] ? pn[name] : name;
39324     },
39325
39326     getCellEditor : function(colIndex, rowIndex){
39327         var p = this.store.getProperty(rowIndex);
39328         var n = p.data['name'], val = p.data['value'];
39329         
39330         if(typeof(this.grid.customEditors[n]) == 'string'){
39331             return this.editors[this.grid.customEditors[n]];
39332         }
39333         if(typeof(this.grid.customEditors[n]) != 'undefined'){
39334             return this.grid.customEditors[n];
39335         }
39336         if(val instanceof Date){
39337             return this.editors['date'];
39338         }else if(typeof val == 'number'){
39339             return this.editors['number'];
39340         }else if(typeof val == 'boolean'){
39341             return this.editors['boolean'];
39342         }else{
39343             return this.editors['string'];
39344         }
39345     }
39346 });
39347
39348 /**
39349  * @class Roo.grid.PropertyGrid
39350  * @extends Roo.grid.EditorGrid
39351  * This class represents the  interface of a component based property grid control.
39352  * <br><br>Usage:<pre><code>
39353  var grid = new Roo.grid.PropertyGrid("my-container-id", {
39354       
39355  });
39356  // set any options
39357  grid.render();
39358  * </code></pre>
39359   
39360  * @constructor
39361  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
39362  * The container MUST have some type of size defined for the grid to fill. The container will be
39363  * automatically set to position relative if it isn't already.
39364  * @param {Object} config A config object that sets properties on this grid.
39365  */
39366 Roo.grid.PropertyGrid = function(container, config){
39367     config = config || {};
39368     var store = new Roo.grid.PropertyStore(this);
39369     this.store = store;
39370     var cm = new Roo.grid.PropertyColumnModel(this, store);
39371     store.store.sort('name', 'ASC');
39372     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
39373         ds: store.store,
39374         cm: cm,
39375         enableColLock:false,
39376         enableColumnMove:false,
39377         stripeRows:false,
39378         trackMouseOver: false,
39379         clicksToEdit:1
39380     }, config));
39381     this.getGridEl().addClass('x-props-grid');
39382     this.lastEditRow = null;
39383     this.on('columnresize', this.onColumnResize, this);
39384     this.addEvents({
39385          /**
39386              * @event beforepropertychange
39387              * Fires before a property changes (return false to stop?)
39388              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
39389              * @param {String} id Record Id
39390              * @param {String} newval New Value
39391          * @param {String} oldval Old Value
39392              */
39393         "beforepropertychange": true,
39394         /**
39395              * @event propertychange
39396              * Fires after a property changes
39397              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
39398              * @param {String} id Record Id
39399              * @param {String} newval New Value
39400          * @param {String} oldval Old Value
39401              */
39402         "propertychange": true
39403     });
39404     this.customEditors = this.customEditors || {};
39405 };
39406 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
39407     
39408      /**
39409      * @cfg {Object} customEditors map of colnames=> custom editors.
39410      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
39411      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
39412      * false disables editing of the field.
39413          */
39414     
39415       /**
39416      * @cfg {Object} propertyNames map of property Names to their displayed value
39417          */
39418     
39419     render : function(){
39420         Roo.grid.PropertyGrid.superclass.render.call(this);
39421         this.autoSize.defer(100, this);
39422     },
39423
39424     autoSize : function(){
39425         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
39426         if(this.view){
39427             this.view.fitColumns();
39428         }
39429     },
39430
39431     onColumnResize : function(){
39432         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
39433         this.autoSize();
39434     },
39435     /**
39436      * Sets the data for the Grid
39437      * accepts a Key => Value object of all the elements avaiable.
39438      * @param {Object} data  to appear in grid.
39439      */
39440     setSource : function(source){
39441         this.store.setSource(source);
39442         //this.autoSize();
39443     },
39444     /**
39445      * Gets all the data from the grid.
39446      * @return {Object} data  data stored in grid
39447      */
39448     getSource : function(){
39449         return this.store.getSource();
39450     }
39451 });/*
39452  * Based on:
39453  * Ext JS Library 1.1.1
39454  * Copyright(c) 2006-2007, Ext JS, LLC.
39455  *
39456  * Originally Released Under LGPL - original licence link has changed is not relivant.
39457  *
39458  * Fork - LGPL
39459  * <script type="text/javascript">
39460  */
39461  
39462 /**
39463  * @class Roo.LoadMask
39464  * A simple utility class for generically masking elements while loading data.  If the element being masked has
39465  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
39466  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
39467  * element's UpdateManager load indicator and will be destroyed after the initial load.
39468  * @constructor
39469  * Create a new LoadMask
39470  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
39471  * @param {Object} config The config object
39472  */
39473 Roo.LoadMask = function(el, config){
39474     this.el = Roo.get(el);
39475     Roo.apply(this, config);
39476     if(this.store){
39477         this.store.on('beforeload', this.onBeforeLoad, this);
39478         this.store.on('load', this.onLoad, this);
39479         this.store.on('loadexception', this.onLoadException, this);
39480         this.removeMask = false;
39481     }else{
39482         var um = this.el.getUpdateManager();
39483         um.showLoadIndicator = false; // disable the default indicator
39484         um.on('beforeupdate', this.onBeforeLoad, this);
39485         um.on('update', this.onLoad, this);
39486         um.on('failure', this.onLoad, this);
39487         this.removeMask = true;
39488     }
39489 };
39490
39491 Roo.LoadMask.prototype = {
39492     /**
39493      * @cfg {Boolean} removeMask
39494      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
39495      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
39496      */
39497     /**
39498      * @cfg {String} msg
39499      * The text to display in a centered loading message box (defaults to 'Loading...')
39500      */
39501     msg : 'Loading...',
39502     /**
39503      * @cfg {String} msgCls
39504      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
39505      */
39506     msgCls : 'x-mask-loading',
39507
39508     /**
39509      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
39510      * @type Boolean
39511      */
39512     disabled: false,
39513
39514     /**
39515      * Disables the mask to prevent it from being displayed
39516      */
39517     disable : function(){
39518        this.disabled = true;
39519     },
39520
39521     /**
39522      * Enables the mask so that it can be displayed
39523      */
39524     enable : function(){
39525         this.disabled = false;
39526     },
39527     
39528     onLoadException : function()
39529     {
39530         Roo.log(arguments);
39531         
39532         if (typeof(arguments[3]) != 'undefined') {
39533             Roo.MessageBox.alert("Error loading",arguments[3]);
39534         } 
39535         /*
39536         try {
39537             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
39538                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
39539             }   
39540         } catch(e) {
39541             
39542         }
39543         */
39544     
39545         
39546         
39547         this.el.unmask(this.removeMask);
39548     },
39549     // private
39550     onLoad : function()
39551     {
39552         this.el.unmask(this.removeMask);
39553     },
39554
39555     // private
39556     onBeforeLoad : function(){
39557         if(!this.disabled){
39558             this.el.mask(this.msg, this.msgCls);
39559         }
39560     },
39561
39562     // private
39563     destroy : function(){
39564         if(this.store){
39565             this.store.un('beforeload', this.onBeforeLoad, this);
39566             this.store.un('load', this.onLoad, this);
39567             this.store.un('loadexception', this.onLoadException, this);
39568         }else{
39569             var um = this.el.getUpdateManager();
39570             um.un('beforeupdate', this.onBeforeLoad, this);
39571             um.un('update', this.onLoad, this);
39572             um.un('failure', this.onLoad, this);
39573         }
39574     }
39575 };/*
39576  * Based on:
39577  * Ext JS Library 1.1.1
39578  * Copyright(c) 2006-2007, Ext JS, LLC.
39579  *
39580  * Originally Released Under LGPL - original licence link has changed is not relivant.
39581  *
39582  * Fork - LGPL
39583  * <script type="text/javascript">
39584  */
39585
39586
39587 /**
39588  * @class Roo.XTemplate
39589  * @extends Roo.Template
39590  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
39591 <pre><code>
39592 var t = new Roo.XTemplate(
39593         '&lt;select name="{name}"&gt;',
39594                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
39595         '&lt;/select&gt;'
39596 );
39597  
39598 // then append, applying the master template values
39599  </code></pre>
39600  *
39601  * Supported features:
39602  *
39603  *  Tags:
39604
39605 <pre><code>
39606       {a_variable} - output encoded.
39607       {a_variable.format:("Y-m-d")} - call a method on the variable
39608       {a_variable:raw} - unencoded output
39609       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
39610       {a_variable:this.method_on_template(...)} - call a method on the template object.
39611  
39612 </code></pre>
39613  *  The tpl tag:
39614 <pre><code>
39615         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
39616         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
39617         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
39618         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
39619   
39620         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
39621         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
39622 </code></pre>
39623  *      
39624  */
39625 Roo.XTemplate = function()
39626 {
39627     Roo.XTemplate.superclass.constructor.apply(this, arguments);
39628     if (this.html) {
39629         this.compile();
39630     }
39631 };
39632
39633
39634 Roo.extend(Roo.XTemplate, Roo.Template, {
39635
39636     /**
39637      * The various sub templates
39638      */
39639     tpls : false,
39640     /**
39641      *
39642      * basic tag replacing syntax
39643      * WORD:WORD()
39644      *
39645      * // you can fake an object call by doing this
39646      *  x.t:(test,tesT) 
39647      * 
39648      */
39649     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
39650
39651     /**
39652      * compile the template
39653      *
39654      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
39655      *
39656      */
39657     compile: function()
39658     {
39659         var s = this.html;
39660      
39661         s = ['<tpl>', s, '</tpl>'].join('');
39662     
39663         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
39664             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
39665             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
39666             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
39667             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
39668             m,
39669             id     = 0,
39670             tpls   = [];
39671     
39672         while(true == !!(m = s.match(re))){
39673             var forMatch   = m[0].match(nameRe),
39674                 ifMatch   = m[0].match(ifRe),
39675                 execMatch   = m[0].match(execRe),
39676                 namedMatch   = m[0].match(namedRe),
39677                 
39678                 exp  = null, 
39679                 fn   = null,
39680                 exec = null,
39681                 name = forMatch && forMatch[1] ? forMatch[1] : '';
39682                 
39683             if (ifMatch) {
39684                 // if - puts fn into test..
39685                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
39686                 if(exp){
39687                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
39688                 }
39689             }
39690             
39691             if (execMatch) {
39692                 // exec - calls a function... returns empty if true is  returned.
39693                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
39694                 if(exp){
39695                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
39696                 }
39697             }
39698             
39699             
39700             if (name) {
39701                 // for = 
39702                 switch(name){
39703                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
39704                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
39705                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
39706                 }
39707             }
39708             var uid = namedMatch ? namedMatch[1] : id;
39709             
39710             
39711             tpls.push({
39712                 id:     namedMatch ? namedMatch[1] : id,
39713                 target: name,
39714                 exec:   exec,
39715                 test:   fn,
39716                 body:   m[1] || ''
39717             });
39718             if (namedMatch) {
39719                 s = s.replace(m[0], '');
39720             } else { 
39721                 s = s.replace(m[0], '{xtpl'+ id + '}');
39722             }
39723             ++id;
39724         }
39725         this.tpls = [];
39726         for(var i = tpls.length-1; i >= 0; --i){
39727             this.compileTpl(tpls[i]);
39728             this.tpls[tpls[i].id] = tpls[i];
39729         }
39730         this.master = tpls[tpls.length-1];
39731         return this;
39732     },
39733     /**
39734      * same as applyTemplate, except it's done to one of the subTemplates
39735      * when using named templates, you can do:
39736      *
39737      * var str = pl.applySubTemplate('your-name', values);
39738      *
39739      * 
39740      * @param {Number} id of the template
39741      * @param {Object} values to apply to template
39742      * @param {Object} parent (normaly the instance of this object)
39743      */
39744     applySubTemplate : function(id, values, parent)
39745     {
39746         
39747         
39748         var t = this.tpls[id];
39749         
39750         
39751         try { 
39752             if(t.test && !t.test.call(this, values, parent)){
39753                 return '';
39754             }
39755         } catch(e) {
39756             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
39757             Roo.log(e.toString());
39758             Roo.log(t.test);
39759             return ''
39760         }
39761         try { 
39762             
39763             if(t.exec && t.exec.call(this, values, parent)){
39764                 return '';
39765             }
39766         } catch(e) {
39767             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
39768             Roo.log(e.toString());
39769             Roo.log(t.exec);
39770             return ''
39771         }
39772         try {
39773             var vs = t.target ? t.target.call(this, values, parent) : values;
39774             parent = t.target ? values : parent;
39775             if(t.target && vs instanceof Array){
39776                 var buf = [];
39777                 for(var i = 0, len = vs.length; i < len; i++){
39778                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
39779                 }
39780                 return buf.join('');
39781             }
39782             return t.compiled.call(this, vs, parent);
39783         } catch (e) {
39784             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
39785             Roo.log(e.toString());
39786             Roo.log(t.compiled);
39787             return '';
39788         }
39789     },
39790
39791     compileTpl : function(tpl)
39792     {
39793         var fm = Roo.util.Format;
39794         var useF = this.disableFormats !== true;
39795         var sep = Roo.isGecko ? "+" : ",";
39796         var undef = function(str) {
39797             Roo.log("Property not found :"  + str);
39798             return '';
39799         };
39800         
39801         var fn = function(m, name, format, args)
39802         {
39803             //Roo.log(arguments);
39804             args = args ? args.replace(/\\'/g,"'") : args;
39805             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
39806             if (typeof(format) == 'undefined') {
39807                 format= 'htmlEncode';
39808             }
39809             if (format == 'raw' ) {
39810                 format = false;
39811             }
39812             
39813             if(name.substr(0, 4) == 'xtpl'){
39814                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
39815             }
39816             
39817             // build an array of options to determine if value is undefined..
39818             
39819             // basically get 'xxxx.yyyy' then do
39820             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
39821             //    (function () { Roo.log("Property not found"); return ''; })() :
39822             //    ......
39823             
39824             var udef_ar = [];
39825             var lookfor = '';
39826             Roo.each(name.split('.'), function(st) {
39827                 lookfor += (lookfor.length ? '.': '') + st;
39828                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
39829             });
39830             
39831             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
39832             
39833             
39834             if(format && useF){
39835                 
39836                 args = args ? ',' + args : "";
39837                  
39838                 if(format.substr(0, 5) != "this."){
39839                     format = "fm." + format + '(';
39840                 }else{
39841                     format = 'this.call("'+ format.substr(5) + '", ';
39842                     args = ", values";
39843                 }
39844                 
39845                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
39846             }
39847              
39848             if (args.length) {
39849                 // called with xxyx.yuu:(test,test)
39850                 // change to ()
39851                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
39852             }
39853             // raw.. - :raw modifier..
39854             return "'"+ sep + udef_st  + name + ")"+sep+"'";
39855             
39856         };
39857         var body;
39858         // branched to use + in gecko and [].join() in others
39859         if(Roo.isGecko){
39860             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
39861                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
39862                     "';};};";
39863         }else{
39864             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
39865             body.push(tpl.body.replace(/(\r\n|\n)/g,
39866                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
39867             body.push("'].join('');};};");
39868             body = body.join('');
39869         }
39870         
39871         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
39872        
39873         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
39874         eval(body);
39875         
39876         return this;
39877     },
39878
39879     applyTemplate : function(values){
39880         return this.master.compiled.call(this, values, {});
39881         //var s = this.subs;
39882     },
39883
39884     apply : function(){
39885         return this.applyTemplate.apply(this, arguments);
39886     }
39887
39888  });
39889
39890 Roo.XTemplate.from = function(el){
39891     el = Roo.getDom(el);
39892     return new Roo.XTemplate(el.value || el.innerHTML);
39893 };