705de4713da1ccb8beb1e9c4189d41e9a7f2eae6
[roojs1] / roojs-bootstrap-debug.js
1 Roo.bootstrap = {};/**
2  * set the version of bootstrap based on the stylesheet...
3  *
4  */
5
6 Roo.bootstrap.version = ( function() {
7     var ret=3;
8     Roo.each(document.styleSheets, function(s) {
9         if ( s.href  && s.href.match(/css-bootstrap4/)) {
10             ret=4;
11         }
12     });
13     if (ret > 3) {
14          Roo.Element.prototype.visibilityMode = Roo.Element.DISPLAY;
15     }
16     return ret;
17 })(); Roo.bootstrap.menu = Roo.bootstrap.menu || {};
18 Roo.bootstrap.nav = {};
19
20 Roo.bootstrap.form = {};Roo.bootstrap.panel = {};Roo.bootstrap.layout = {};
21 Roo.htmleditor = {};
22 Roo.namespace('Roo.bootstrap.form.HtmlEditorToolbar');
23 /*
24  * Based on:
25  * Ext JS Library 1.1.1
26  * Copyright(c) 2006-2007, Ext JS, LLC.
27  *
28  * Originally Released Under LGPL - original licence link has changed is not relivant.
29  *
30  * Fork - LGPL
31  * <script type="text/javascript">
32  */
33
34
35 /**
36  * @class Roo.Shadow
37  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
38  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
39  * functionality that can also provide the same shadow effect, see the {@link Roo.Layer} class.
40  * @constructor
41  * Create a new Shadow
42  * @param {Object} config The config object
43  */
44 Roo.Shadow = function(config){
45     Roo.apply(this, config);
46     if(typeof this.mode != "string"){
47         this.mode = this.defaultMode;
48     }
49     var o = this.offset, a = {h: 0};
50     var rad = Math.floor(this.offset/2);
51     switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
52         case "drop":
53             a.w = 0;
54             a.l = a.t = o;
55             a.t -= 1;
56             if(Roo.isIE){
57                 a.l -= this.offset + rad;
58                 a.t -= this.offset + rad;
59                 a.w -= rad;
60                 a.h -= rad;
61                 a.t += 1;
62             }
63         break;
64         case "sides":
65             a.w = (o*2);
66             a.l = -o;
67             a.t = o-1;
68             if(Roo.isIE){
69                 a.l -= (this.offset - rad);
70                 a.t -= this.offset + rad;
71                 a.l += 1;
72                 a.w -= (this.offset - rad)*2;
73                 a.w -= rad + 1;
74                 a.h -= 1;
75             }
76         break;
77         case "frame":
78             a.w = a.h = (o*2);
79             a.l = a.t = -o;
80             a.t += 1;
81             a.h -= 2;
82             if(Roo.isIE){
83                 a.l -= (this.offset - rad);
84                 a.t -= (this.offset - rad);
85                 a.l += 1;
86                 a.w -= (this.offset + rad + 1);
87                 a.h -= (this.offset + rad);
88                 a.h += 1;
89             }
90         break;
91     };
92
93     this.adjusts = a;
94 };
95
96 Roo.Shadow.prototype = {
97     /**
98      * @cfg {String} mode
99      * The shadow display mode.  Supports the following options:<br />
100      * sides: Shadow displays on both sides and bottom only<br />
101      * frame: Shadow displays equally on all four sides<br />
102      * drop: Traditional bottom-right drop shadow (default)
103      */
104     mode: false,
105     /**
106      * @cfg {String} offset
107      * The number of pixels to offset the shadow from the element (defaults to 4)
108      */
109     offset: 4,
110
111     // private
112     defaultMode: "drop",
113
114     /**
115      * Displays the shadow under the target element
116      * @param {String/HTMLElement/Element} targetEl The id or element under which the shadow should display
117      */
118     show : function(target){
119         target = Roo.get(target);
120         if(!this.el){
121             this.el = Roo.Shadow.Pool.pull();
122             if(this.el.dom.nextSibling != target.dom){
123                 this.el.insertBefore(target);
124             }
125         }
126         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
127         if(Roo.isIE){
128             this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
129         }
130         this.realign(
131             target.getLeft(true),
132             target.getTop(true),
133             target.getWidth(),
134             target.getHeight()
135         );
136         this.el.dom.style.display = "block";
137     },
138
139     /**
140      * Returns true if the shadow is visible, else false
141      */
142     isVisible : function(){
143         return this.el ? true : false;  
144     },
145
146     /**
147      * Direct alignment when values are already available. Show must be called at least once before
148      * calling this method to ensure it is initialized.
149      * @param {Number} left The target element left position
150      * @param {Number} top The target element top position
151      * @param {Number} width The target element width
152      * @param {Number} height The target element height
153      */
154     realign : function(l, t, w, h){
155         if(!this.el){
156             return;
157         }
158         var a = this.adjusts, d = this.el.dom, s = d.style;
159         var iea = 0;
160         s.left = (l+a.l)+"px";
161         s.top = (t+a.t)+"px";
162         var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
163  
164         if(s.width != sws || s.height != shs){
165             s.width = sws;
166             s.height = shs;
167             if(!Roo.isIE){
168                 var cn = d.childNodes;
169                 var sww = Math.max(0, (sw-12))+"px";
170                 cn[0].childNodes[1].style.width = sww;
171                 cn[1].childNodes[1].style.width = sww;
172                 cn[2].childNodes[1].style.width = sww;
173                 cn[1].style.height = Math.max(0, (sh-12))+"px";
174             }
175         }
176     },
177
178     /**
179      * Hides this shadow
180      */
181     hide : function(){
182         if(this.el){
183             this.el.dom.style.display = "none";
184             Roo.Shadow.Pool.push(this.el);
185             delete this.el;
186         }
187     },
188
189     /**
190      * Adjust the z-index of this shadow
191      * @param {Number} zindex The new z-index
192      */
193     setZIndex : function(z){
194         this.zIndex = z;
195         if(this.el){
196             this.el.setStyle("z-index", z);
197         }
198     }
199 };
200
201 // Private utility class that manages the internal Shadow cache
202 Roo.Shadow.Pool = function(){
203     var p = [];
204     var markup = Roo.isIE ?
205                  '<div class="x-ie-shadow"></div>' :
206                  '<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>';
207     return {
208         pull : function(){
209             var sh = p.shift();
210             if(!sh){
211                 sh = Roo.get(Roo.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
212                 sh.autoBoxAdjust = false;
213             }
214             return sh;
215         },
216
217         push : function(sh){
218             p.push(sh);
219         }
220     };
221 }();/*
222  * - LGPL
223  *
224  * base class for bootstrap elements.
225  * 
226  */
227
228 Roo.bootstrap = Roo.bootstrap || {};
229 /**
230  * @class Roo.bootstrap.Component
231  * @extends Roo.Component
232  * @abstract
233  * @children Roo.bootstrap.Component
234  * Bootstrap Component base class
235  * @cfg {String} cls css class
236  * @cfg {String} style any extra css
237  * @cfg {Object} xattr extra attributes to add to 'element' (used by builder to store stuff.)
238  * @cfg {Boolean} can_build_overlaid  True if element can be rebuild from a HTML page
239  * @cfg {string} dataId cutomer id
240  * @cfg {string} name Specifies name attribute
241  * @cfg {string} tooltip  Text for the tooltip
242  * @cfg {string} container_method method to fetch parents container element (used by NavHeaderbar -  getHeaderChildContainer)
243  * @cfg {string|object} visibilityEl (el|parent) What element to use for visibility (@see getVisibilityEl())
244  
245  * @constructor
246  * Do not use directly - it does not do anything..
247  * @param {Object} config The config object
248  */
249
250
251
252 Roo.bootstrap.Component = function(config){
253     Roo.bootstrap.Component.superclass.constructor.call(this, config);
254        
255     this.addEvents({
256         /**
257          * @event childrenrendered
258          * Fires when the children have been rendered..
259          * @param {Roo.bootstrap.Component} this
260          */
261         "childrenrendered" : true
262         
263         
264         
265     });
266     
267     
268 };
269
270 Roo.extend(Roo.bootstrap.Component, Roo.BoxComponent,  {
271     
272     
273     allowDomMove : false, // to stop relocations in parent onRender...
274     
275     cls : false,
276     
277     style : false,
278     
279     autoCreate : false,
280     
281     tooltip : null,
282     /**
283      * Initialize Events for the element
284      */
285     initEvents : function() { },
286     
287     xattr : false,
288     
289     parentId : false,
290     
291     can_build_overlaid : true,
292     
293     container_method : false,
294     
295     dataId : false,
296     
297     name : false,
298     
299     parent: function() {
300         // returns the parent component..
301         return Roo.ComponentMgr.get(this.parentId)
302         
303         
304     },
305     
306     // private
307     onRender : function(ct, position)
308     {
309        // Roo.log("Call onRender: " + this.xtype);
310         
311         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
312         
313         if(this.el){
314             if (this.el.attr('xtype')) {
315                 this.el.attr('xtypex', this.el.attr('xtype'));
316                 this.el.dom.removeAttribute('xtype');
317                 
318                 this.initEvents();
319             }
320             
321             return;
322         }
323         
324          
325         
326         var cfg = Roo.apply({},  this.getAutoCreate());
327         
328         cfg.id = this.id || Roo.id();
329         
330         // fill in the extra attributes 
331         if (this.xattr && typeof(this.xattr) =='object') {
332             for (var i in this.xattr) {
333                 cfg[i] = this.xattr[i];
334             }
335         }
336         
337         if(this.dataId){
338             cfg.dataId = this.dataId;
339         }
340         
341         if (this.cls) {
342             cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
343         }
344         
345         if (this.style) { // fixme needs to support more complex style data.
346             cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
347         }
348         
349         if(this.name){
350             cfg.name = this.name;
351         }
352         
353         this.el = ct.createChild(cfg, position);
354         
355         if (this.tooltip) {
356             this.tooltipEl().attr('tooltip', this.tooltip);
357         }
358         
359         if(this.tabIndex !== undefined){
360             this.el.dom.setAttribute('tabIndex', this.tabIndex);
361         }
362         
363         this.initEvents();
364         
365     },
366     /**
367      * Fetch the element to add children to
368      * @return {Roo.Element} defaults to this.el
369      */
370     getChildContainer : function()
371     {
372         return this.el;
373     },
374     getDocumentBody : function() // used by menus - as they are attached to the body so zIndexes work
375     {
376         return Roo.get(document.body);
377     },
378     
379     /**
380      * Fetch the element to display the tooltip on.
381      * @return {Roo.Element} defaults to this.el
382      */
383     tooltipEl : function()
384     {
385         return this.el;
386     },
387         
388     addxtype  : function(tree,cntr)
389     {
390         var cn = this;
391         
392         cn = Roo.factory(tree);
393         //Roo.log(['addxtype', cn]);
394            
395         cn.parentType = this.xtype; //??
396         cn.parentId = this.id;
397         
398         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
399         if (typeof(cn.container_method) == 'string') {
400             cntr = cn.container_method;
401         }
402         
403         
404         var has_flexy_each =  (typeof(tree['flexy:foreach']) != 'undefined');
405         
406         var has_flexy_if =  (typeof(tree['flexy:if']) != 'undefined');
407         
408         var build_from_html =  Roo.XComponent.build_from_html;
409           
410         var is_body  = (tree.xtype == 'Body') ;
411           
412         var page_has_body = (Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body');
413           
414         var self_cntr_el = Roo.get(this[cntr](false));
415         
416         // do not try and build conditional elements 
417         if ((has_flexy_each || has_flexy_if || this.can_build_overlaid == false ) && build_from_html) {
418             return false;
419         }
420         
421         if (!has_flexy_each || !build_from_html || is_body || !page_has_body) {
422             if(!has_flexy_if || typeof(tree.name) == 'undefined' || !build_from_html || is_body || !page_has_body){
423                 return this.addxtypeChild(tree,cntr, is_body);
424             }
425             
426             var echild =self_cntr_el ? self_cntr_el.child('>*[name=' + tree.name + ']') : false;
427                 
428             if(echild){
429                 return this.addxtypeChild(Roo.apply({}, tree),cntr);
430             }
431             
432             Roo.log('skipping render');
433             return cn;
434             
435         }
436         
437         var ret = false;
438         if (!build_from_html) {
439             return false;
440         }
441         
442         // this i think handles overlaying multiple children of the same type
443         // with the sam eelement.. - which might be buggy..
444         while (true) {
445             var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
446             
447             if (!echild) {
448                 break;
449             }
450             
451             if (echild && echild.attr('xtype').split('.').pop() != cn.xtype) {
452                 break;
453             }
454             
455             ret = this.addxtypeChild(Roo.apply({}, tree),cntr);
456         }
457        
458         return ret;
459     },
460     
461     
462     addxtypeChild : function (tree, cntr, is_body)
463     {
464         Roo.debug && Roo.log('addxtypeChild:' + cntr);
465         var cn = this;
466         cntr = (typeof(cntr) == 'undefined' ) ? 'getChildContainer' : cntr;
467         
468         
469         var has_flexy = (typeof(tree['flexy:if']) != 'undefined') ||
470                     (typeof(tree['flexy:foreach']) != 'undefined');
471           
472     
473         
474         skip_children = false;
475         // render the element if it's not BODY.
476         if (!is_body) {
477             
478             // if parent was disabled, then do not try and create the children..
479             if(!this[cntr](true)){
480                 tree.items = [];
481                 return tree;
482             }
483            
484             cn = Roo.factory(tree);
485            
486             cn.parentType = this.xtype; //??
487             cn.parentId = this.id;
488             
489             var build_from_html =  Roo.XComponent.build_from_html;
490             
491             
492             // does the container contain child eleemnts with 'xtype' attributes.
493             // that match this xtype..
494             // note - when we render we create these as well..
495             // so we should check to see if body has xtype set.
496             if (build_from_html && Roo.get(document.body).attr('xtype') == 'Roo.bootstrap.Body') {
497                
498                 var self_cntr_el = Roo.get(this[cntr](false));
499                 var echild =self_cntr_el ? self_cntr_el.child('>*[xtype]') : false;
500                 if (echild) { 
501                     //Roo.log(Roo.XComponent.build_from_html);
502                     //Roo.log("got echild:");
503                     //Roo.log(echild);
504                 }
505                 // there is a scenario where some of the child elements are flexy:if (and all of the same type)
506                 // and are not displayed -this causes this to use up the wrong element when matching.
507                 // at present the only work around for this is to nest flexy:if elements in another element that is always rendered.
508                 
509                 
510                 if (echild && echild.attr('xtype').split('.').pop() == cn.xtype) {
511                   //  Roo.log("found child for " + this.xtype +": " + echild.attr('xtype') );
512                   
513                   
514                   
515                     cn.el = echild;
516                   //  Roo.log("GOT");
517                     //echild.dom.removeAttribute('xtype');
518                 } else {
519                     Roo.debug && Roo.log("MISSING " + cn.xtype + " on child of " + (this.el ? this.el.attr('xbuilderid') : 'no parent'));
520                     Roo.debug && Roo.log(self_cntr_el);
521                     Roo.debug && Roo.log(echild);
522                     Roo.debug && Roo.log(cn);
523                 }
524             }
525            
526             
527            
528             // if object has flexy:if - then it may or may not be rendered.
529             if (build_from_html && has_flexy && !cn.el &&  cn.can_build_overlaid) {
530                 // skip a flexy if element.
531                 Roo.debug && Roo.log('skipping render');
532                 Roo.debug && Roo.log(tree);
533                 if (!cn.el) {
534                     Roo.debug && Roo.log('skipping all children');
535                     skip_children = true;
536                 }
537                 
538              } else {
539                  
540                 // actually if flexy:foreach is found, we really want to create 
541                 // multiple copies here...
542                 //Roo.log('render');
543                 //Roo.log(this[cntr]());
544                 // some elements do not have render methods.. like the layouts...
545                 /*
546                 if(this[cntr](true) === false){
547                     cn.items = [];
548                     return cn;
549                 }
550                 */
551                 cn.render && cn.render(this[cntr](true));
552                 
553              }
554             // then add the element..
555         }
556          
557         // handle the kids..
558         
559         var nitems = [];
560         /*
561         if (typeof (tree.menu) != 'undefined') {
562             tree.menu.parentType = cn.xtype;
563             tree.menu.triggerEl = cn.el;
564             nitems.push(cn.addxtype(Roo.apply({}, tree.menu)));
565             
566         }
567         */
568         if (!tree.items || !tree.items.length) {
569             cn.items = nitems;
570             //Roo.log(["no children", this]);
571             
572             return cn;
573         }
574          
575         var items = tree.items;
576         delete tree.items;
577         
578         //Roo.log(items.length);
579             // add the items..
580         if (!skip_children) {    
581             for(var i =0;i < items.length;i++) {
582               //  Roo.log(['add child', items[i]]);
583                 nitems.push(cn.addxtype(Roo.apply({}, items[i])));
584             }
585         }
586         
587         cn.items = nitems;
588         
589         //Roo.log("fire childrenrendered");
590         
591         cn.fireEvent('childrenrendered', this);
592         
593         return cn;
594     },
595     
596     /**
597      * Set the element that will be used to show or hide
598      */
599     setVisibilityEl : function(el)
600     {
601         this.visibilityEl = el;
602     },
603     
604      /**
605      * Get the element that will be used to show or hide
606      */
607     getVisibilityEl : function()
608     {
609         if (typeof(this.visibilityEl) == 'object') {
610             return this.visibilityEl;
611         }
612         
613         if (typeof(this.visibilityEl) == 'string') {
614             return this.visibilityEl == 'parent' ? this.parent().getEl() : this.getEl();
615         }
616         
617         return this.getEl();
618     },
619     
620     /**
621      * Show a component - removes 'hidden' class
622      */
623     show : function()
624     {
625         if(!this.getVisibilityEl()){
626             return;
627         }
628          
629         this.getVisibilityEl().removeClass(['hidden','d-none']);
630         
631         this.fireEvent('show', this);
632         
633         
634     },
635     /**
636      * Hide a component - adds 'hidden' class
637      */
638     hide: function()
639     {
640         if(!this.getVisibilityEl()){
641             return;
642         }
643         
644         this.getVisibilityEl().addClass(['hidden','d-none']);
645         
646         this.fireEvent('hide', this);
647         
648     }
649 });
650
651  /*
652  * - LGPL
653  *
654  * element
655  * 
656  */
657
658 /**
659  * @class Roo.bootstrap.Element
660  * @extends Roo.bootstrap.Component
661  * @children Roo.bootstrap.Component
662  * Bootstrap Element class (basically a DIV used to make random stuff )
663  * 
664  * @cfg {String} html contents of the element
665  * @cfg {String} tag tag of the element
666  * @cfg {String} cls class of the element
667  * @cfg {Boolean} preventDefault (true|false) default false
668  * @cfg {Boolean} clickable (true|false) default false
669  * @cfg {String} role default blank - set to button to force cursor pointer
670  
671  * 
672  * @constructor
673  * Create a new Element
674  * @param {Object} config The config object
675  */
676
677 Roo.bootstrap.Element = function(config){
678     Roo.bootstrap.Element.superclass.constructor.call(this, config);
679     
680     this.addEvents({
681         // raw events
682         /**
683          * @event click
684          * When a element is chick
685          * @param {Roo.bootstrap.Element} this
686          * @param {Roo.EventObject} e
687          */
688         "click" : true 
689         
690       
691     });
692 };
693
694 Roo.extend(Roo.bootstrap.Element, Roo.bootstrap.Component,  {
695     
696     tag: 'div',
697     cls: '',
698     html: '',
699     preventDefault: false, 
700     clickable: false,
701     tapedTwice : false,
702     role : false,
703     
704     getAutoCreate : function(){
705         
706         var cfg = {
707             tag: this.tag,
708             // cls: this.cls, double assign in parent class Component.js :: onRender
709             html: this.html
710         };
711         if (this.role !== false) {
712             cfg.role = this.role;
713         }
714         
715         return cfg;
716     },
717     
718     initEvents: function() 
719     {
720         Roo.bootstrap.Element.superclass.initEvents.call(this);
721         
722         if(this.clickable){
723             this.el.on('click', this.onClick, this);
724         }
725         
726         
727     },
728     
729     onClick : function(e)
730     {
731         if(this.preventDefault){
732             e.preventDefault();
733         }
734         
735         this.fireEvent('click', this, e); // why was this double click before?
736     },
737     
738     
739     
740
741     
742     
743     getValue : function()
744     {
745         return this.el.dom.innerHTML;
746     },
747     
748     setValue : function(value)
749     {
750         this.el.dom.innerHTML = value;
751     }
752    
753 });
754
755  
756
757  /*
758  * - LGPL
759  *
760  * dropable area
761  * 
762  */
763
764 /**
765  * @class Roo.bootstrap.DropTarget
766  * @extends Roo.bootstrap.Element
767  * Bootstrap DropTarget class
768  
769  * @cfg {string} name dropable name
770  * 
771  * @constructor
772  * Create a new Dropable Area
773  * @param {Object} config The config object
774  */
775
776 Roo.bootstrap.DropTarget = function(config){
777     Roo.bootstrap.DropTarget.superclass.constructor.call(this, config);
778     
779     this.addEvents({
780         // raw events
781         /**
782          * @event click
783          * When a element is chick
784          * @param {Roo.bootstrap.Element} this
785          * @param {Roo.EventObject} e
786          */
787         "drop" : true
788     });
789 };
790
791 Roo.extend(Roo.bootstrap.DropTarget, Roo.bootstrap.Element,  {
792     
793     
794     getAutoCreate : function(){
795         
796          
797     },
798     
799     initEvents: function() 
800     {
801         Roo.bootstrap.DropTarget.superclass.initEvents.call(this);
802         this.dropZone = new Roo.dd.DropTarget(this.getEl(), {
803             ddGroup: this.name,
804             listeners : {
805                 drop : this.dragDrop.createDelegate(this),
806                 enter : this.dragEnter.createDelegate(this),
807                 out : this.dragOut.createDelegate(this),
808                 over : this.dragOver.createDelegate(this)
809             }
810             
811         });
812         this.dropZone.DDM.useCache = false // so data gets refreshed when we resize stuff
813     },
814     
815     dragDrop : function(source,e,data)
816     {
817         // user has to decide how to impliment this.
818         Roo.log('drop');
819         Roo.log(this);
820         //this.fireEvent('drop', this, source, e ,data);
821         return false;
822     },
823     
824     dragEnter : function(n, dd, e, data)
825     {
826         // probably want to resize the element to match the dropped element..
827         Roo.log("enter");
828         this.originalSize = this.el.getSize();
829         this.el.setSize( n.el.getSize());
830         this.dropZone.DDM.refreshCache(this.name);
831         Roo.log([n, dd, e, data]);
832     },
833     
834     dragOut : function(value)
835     {
836         // resize back to normal
837         Roo.log("out");
838         this.el.setSize(this.originalSize);
839         this.dropZone.resetConstraints();
840     },
841     
842     dragOver : function()
843     {
844         // ??? do nothing?
845     }
846    
847 });
848
849  
850
851  /*
852  * - LGPL
853  *
854  * Body
855  *
856  */
857
858 /**
859  * @class Roo.bootstrap.Body
860  * @extends Roo.bootstrap.Component
861  * @children Roo.bootstrap.Component 
862  * @parent none builder
863  * Bootstrap Body class
864  *
865  * @constructor
866  * Create a new body
867  * @param {Object} config The config object
868  */
869
870 Roo.bootstrap.Body = function(config){
871
872     config = config || {};
873
874     Roo.bootstrap.Body.superclass.constructor.call(this, config);
875     this.el = Roo.get(config.el ? config.el : document.body );
876     if (this.cls && this.cls.length) {
877         Roo.get(document.body).addClass(this.cls);
878     }
879 };
880
881 Roo.extend(Roo.bootstrap.Body, Roo.bootstrap.Component,  {
882
883     is_body : true,// just to make sure it's constructed?
884
885         autoCreate : {
886         cls: 'container'
887     },
888     onRender : function(ct, position)
889     {
890        /* Roo.log("Roo.bootstrap.Body - onRender");
891         if (this.cls && this.cls.length) {
892             Roo.get(document.body).addClass(this.cls);
893         }
894         // style??? xttr???
895         */
896     }
897
898
899
900
901 });
902 /*
903  * - LGPL
904  *
905  * button group
906  * 
907  */
908
909
910 /**
911  * @class Roo.bootstrap.ButtonGroup
912  * @extends Roo.bootstrap.Component
913  * Bootstrap ButtonGroup class
914  * @children Roo.bootstrap.Button Roo.bootstrap.form.Form
915  * 
916  * @cfg {String} size lg | sm | xs (default empty normal)
917  * @cfg {String} align vertical | justified  (default none)
918  * @cfg {String} direction up | down (default down)
919  * @cfg {Boolean} toolbar false | true
920  * @cfg {Boolean} btn true | false
921  * 
922  * 
923  * @constructor
924  * Create a new Input
925  * @param {Object} config The config object
926  */
927
928 Roo.bootstrap.ButtonGroup = function(config){
929     Roo.bootstrap.ButtonGroup.superclass.constructor.call(this, config);
930 };
931
932 Roo.extend(Roo.bootstrap.ButtonGroup, Roo.bootstrap.Component,  {
933     
934     size: '',
935     align: '',
936     direction: '',
937     toolbar: false,
938     btn: true,
939
940     getAutoCreate : function(){
941         var cfg = {
942             cls: 'btn-group',
943             html : null
944         };
945         
946         cfg.html = this.html || cfg.html;
947         
948         if (this.toolbar) {
949             cfg = {
950                 cls: 'btn-toolbar',
951                 html: null
952             };
953             
954             return cfg;
955         }
956         
957         if (['vertical','justified'].indexOf(this.align)!==-1) {
958             cfg.cls = 'btn-group-' + this.align;
959             
960             if (this.align == 'justified') {
961                 console.log(this.items);
962             }
963         }
964         
965         if (['lg','sm','xs'].indexOf(this.size)!==-1) {
966             cfg.cls += ' btn-group-' + this.size;
967         }
968         
969         if (this.direction == 'up') {
970             cfg.cls += ' dropup' ;
971         }
972         
973         return cfg;
974     },
975     /**
976      * Add a button to the group (similar to NavItem API.)
977      */
978     addItem : function(cfg)
979     {
980         var cn = new Roo.bootstrap.Button(cfg);
981         //this.register(cn);
982         cn.parentId = this.id;
983         cn.onRender(this.el, null);
984         return cn;
985     }
986    
987 });
988
989  /*
990  * - LGPL
991  *
992  * button
993  * 
994  */
995
996 /**
997  * @class Roo.bootstrap.Button
998  * @extends Roo.bootstrap.Component
999  * Bootstrap Button class
1000  * @cfg {String} html The button content
1001  * @cfg {String} weight (default|primary|secondary|success|info|warning|danger|link|light|dark) default
1002  * @cfg {String} badge_weight (default|primary|secondary|success|info|warning|danger|link|light|dark) default (same as button)
1003  * @cfg {Boolean} outline default false (except for weight=default which emulates old behaveiour with an outline)
1004  * @cfg {String} size (lg|sm|xs)
1005  * @cfg {String} tag (a|input|submit)
1006  * @cfg {String} href empty or href
1007  * @cfg {Boolean} disabled default false;
1008  * @cfg {Boolean} isClose default false;
1009  * @cfg {String} glyphicon depricated - use fa
1010  * @cfg {String} fa fontawesome icon - eg. 'comment' - without the fa/fas etc..
1011  * @cfg {String} badge text for badge
1012  * @cfg {String} theme (default|glow)  
1013  * @cfg {Boolean} inverse dark themed version
1014  * @cfg {Boolean} toggle is it a slidy toggle button
1015  * @cfg {Boolean} pressed   default null - if the button ahs active state
1016  * @cfg {String} ontext text for on slidy toggle state
1017  * @cfg {String} offtext text for off slidy toggle state
1018  * @cfg {Boolean} preventDefault  default true (stop click event triggering the URL if it's a link.)
1019  * @cfg {Boolean} removeClass remove the standard class..
1020  * @cfg {String} target (_self|_blank|_parent|_top|other) target for a href. 
1021  * @cfg {Boolean} grpup if parent is a btn group - then it turns it into a toogleGroup.
1022  * @cfg {Roo.bootstrap.menu.Menu} menu a Menu 
1023
1024  * @constructor
1025  * Create a new button
1026  * @param {Object} config The config object
1027  */
1028
1029
1030 Roo.bootstrap.Button = function(config){
1031     Roo.bootstrap.Button.superclass.constructor.call(this, config);
1032     
1033     this.addEvents({
1034         // raw events
1035         /**
1036          * @event click
1037          * When a button is pressed
1038          * @param {Roo.bootstrap.Button} btn
1039          * @param {Roo.EventObject} e
1040          */
1041         "click" : true,
1042         /**
1043          * @event dblclick
1044          * When a button is double clicked
1045          * @param {Roo.bootstrap.Button} btn
1046          * @param {Roo.EventObject} e
1047          */
1048         "dblclick" : true,
1049          /**
1050          * @event toggle
1051          * After the button has been toggles
1052          * @param {Roo.bootstrap.Button} btn
1053          * @param {Roo.EventObject} e
1054          * @param {boolean} pressed (also available as button.pressed)
1055          */
1056         "toggle" : true
1057     });
1058 };
1059
1060 Roo.extend(Roo.bootstrap.Button, Roo.bootstrap.Component,  {
1061     html: false,
1062     active: false,
1063     weight: '',
1064     badge_weight: '',
1065     outline : false,
1066     size: '',
1067     tag: 'button',
1068     href: '',
1069     disabled: false,
1070     isClose: false,
1071     glyphicon: '',
1072     fa: '',
1073     badge: '',
1074     theme: 'default',
1075     inverse: false,
1076     
1077     toggle: false,
1078     ontext: 'ON',
1079     offtext: 'OFF',
1080     defaulton: true,
1081     preventDefault: true,
1082     removeClass: false,
1083     name: false,
1084     target: false,
1085     group : false,
1086      
1087     pressed : null,
1088      
1089     
1090     getAutoCreate : function(){
1091         
1092         var cfg = {
1093             tag : 'button',
1094             cls : 'roo-button',
1095             html: ''
1096         };
1097         
1098         if (['a', 'button', 'input', 'submit'].indexOf(this.tag) < 0) {
1099             throw "Invalid value for tag: " + this.tag + ". must be a, button, input or submit.";
1100             this.tag = 'button';
1101         } else {
1102             cfg.tag = this.tag;
1103         }
1104         cfg.html = '<span class="roo-button-text">' + (this.html || cfg.html) + '</span>';
1105         
1106         if (this.toggle == true) {
1107             cfg={
1108                 tag: 'div',
1109                 cls: 'slider-frame roo-button',
1110                 cn: [
1111                     {
1112                         tag: 'span',
1113                         'data-on-text':'ON',
1114                         'data-off-text':'OFF',
1115                         cls: 'slider-button',
1116                         html: this.offtext
1117                     }
1118                 ]
1119             };
1120             // why are we validating the weights?
1121             if (Roo.bootstrap.Button.weights.indexOf(this.weight) > -1) {
1122                 cfg.cls +=  ' ' + this.weight;
1123             }
1124             
1125             return cfg;
1126         }
1127         
1128         if (this.isClose) {
1129             cfg.cls += ' close';
1130             
1131             cfg["aria-hidden"] = true;
1132             
1133             cfg.html = "&times;";
1134             
1135             return cfg;
1136         }
1137              
1138         
1139         if (this.theme==='default') {
1140             cfg.cls = 'btn roo-button';
1141             
1142             //if (this.parentType != 'Navbar') {
1143             this.weight = this.weight.length ?  this.weight : 'default';
1144             //}
1145             if (Roo.bootstrap.Button.weights.indexOf(this.weight) > -1) {
1146                 
1147                 var outline = this.outline || this.weight == 'default' ? 'outline-' : '';
1148                 var weight = this.weight == 'default' ? 'secondary' : this.weight;
1149                 cfg.cls += ' btn-' + outline + weight;
1150                 if (this.weight == 'default') {
1151                     // BC
1152                     cfg.cls += ' btn-' + this.weight;
1153                 }
1154             }
1155         } else if (this.theme==='glow') {
1156             
1157             cfg.tag = 'a';
1158             cfg.cls = 'btn-glow roo-button';
1159             
1160             if (Roo.bootstrap.Button.weights.indexOf(this.weight) > -1) {
1161                 
1162                 cfg.cls += ' ' + this.weight;
1163             }
1164         }
1165    
1166         
1167         if (this.inverse) {
1168             this.cls += ' inverse';
1169         }
1170         
1171         
1172         if (this.active || this.pressed === true) {
1173             cfg.cls += ' active';
1174         }
1175         
1176         if (this.disabled) {
1177             cfg.disabled = 'disabled';
1178         }
1179         
1180         if (this.items) {
1181             Roo.log('changing to ul' );
1182             cfg.tag = 'ul';
1183             this.glyphicon = 'caret';
1184             if (Roo.bootstrap.version == 4) {
1185                 this.fa = 'caret-down';
1186             }
1187             
1188         }
1189         
1190         cfg.cls += this.size.length ? (' btn-' + this.size) : '';
1191          
1192         //gsRoo.log(this.parentType);
1193         if (this.parentType === 'Navbar' && !this.parent().bar) {
1194             Roo.log('changing to li?');
1195             
1196             cfg.tag = 'li';
1197             
1198             cfg.cls = '';
1199             cfg.cn =  [{
1200                 tag : 'a',
1201                 cls : 'roo-button',
1202                 html : this.html,
1203                 href : this.href || '#'
1204             }];
1205             if (this.menu) {
1206                 cfg.cn[0].html = this.html  + ' <span class="caret"></span>';
1207                 cfg.cls += ' dropdown';
1208             }   
1209             
1210             delete cfg.html;
1211             
1212         }
1213         
1214        cfg.cls += this.parentType === 'Navbar' ?  ' navbar-btn' : '';
1215         
1216         if (this.glyphicon) {
1217             cfg.html = ' ' + cfg.html;
1218             
1219             cfg.cn = [
1220                 {
1221                     tag: 'span',
1222                     cls: 'glyphicon glyphicon-' + this.glyphicon
1223                 }
1224             ];
1225         }
1226         if (this.fa) {
1227             cfg.html = ' ' + cfg.html;
1228             
1229             cfg.cn = [
1230                 {
1231                     tag: 'i',
1232                     cls: 'fa fas fa-' + this.fa
1233                 }
1234             ];
1235         }
1236         
1237         if (this.badge) {
1238             cfg.html += ' ';
1239             
1240             cfg.tag = 'a';
1241             
1242 //            cfg.cls='btn roo-button';
1243             
1244             cfg.href=this.href;
1245             
1246             var value = cfg.html;
1247             
1248             if(this.glyphicon){
1249                 value = {
1250                     tag: 'span',
1251                     cls: 'glyphicon glyphicon-' + this.glyphicon,
1252                     html: this.html
1253                 };
1254             }
1255             if(this.fa){
1256                 value = {
1257                     tag: 'i',
1258                     cls: 'fa fas fa-' + this.fa,
1259                     html: this.html
1260                 };
1261             }
1262             
1263             var bw = this.badge_weight.length ? this.badge_weight :
1264                 (this.weight.length ? this.weight : 'secondary');
1265             bw = bw == 'default' ? 'secondary' : bw;
1266             
1267             cfg.cn = [
1268                 value,
1269                 {
1270                     tag: 'span',
1271                     cls: 'badge badge-' + bw,
1272                     html: this.badge
1273                 }
1274             ];
1275             
1276             cfg.html='';
1277         }
1278         
1279         if (this.menu) {
1280             cfg.cls += ' dropdown';
1281             cfg.html = typeof(cfg.html) != 'undefined' ?
1282                     cfg.html + ' <span class="caret"></span>' : '<span class="caret"></span>';
1283         }
1284         
1285         if (cfg.tag !== 'a' && this.href !== '') {
1286             throw "Tag must be a to set href.";
1287         } else if (this.href.length > 0) {
1288             cfg.href = this.href;
1289         }
1290         
1291         if(this.removeClass){
1292             cfg.cls = '';
1293         }
1294         
1295         if(this.target){
1296             cfg.target = this.target;
1297         }
1298         
1299         return cfg;
1300     },
1301     initEvents: function() {
1302        // Roo.log('init events?');
1303 //        Roo.log(this.el.dom);
1304         // add the menu...
1305         
1306         if (typeof (this.menu) != 'undefined') {
1307             this.menu.parentType = this.xtype;
1308             this.menu.triggerEl = this.el;
1309             this.addxtype(Roo.apply({}, this.menu));
1310         }
1311
1312
1313         if (this.el.hasClass('roo-button')) {
1314              this.el.on('click', this.onClick, this);
1315              this.el.on('dblclick', this.onDblClick, this);
1316         } else {
1317              this.el.select('.roo-button').on('click', this.onClick, this);
1318              this.el.select('.roo-button').on('dblclick', this.onDblClick, this);
1319              
1320         }
1321         // why?
1322         if(this.removeClass){
1323             this.el.on('click', this.onClick, this);
1324         }
1325         
1326         if (this.group === true) {
1327              if (this.pressed === false || this.pressed === true) {
1328                 // nothing
1329             } else {
1330                 this.pressed = false;
1331                 this.setActive(this.pressed);
1332             }
1333             
1334         }
1335         
1336         this.el.enableDisplayMode();
1337         
1338     },
1339     onClick : function(e)
1340     {
1341         if (this.disabled) {
1342             return;
1343         }
1344         
1345         Roo.log('button on click ');
1346         if(this.href === '' || this.preventDefault){
1347             e.preventDefault();
1348         }
1349         
1350         if (this.group) {
1351             if (this.pressed) {
1352                 // do nothing -
1353                 return;
1354             }
1355             this.setActive(true);
1356             var pi = this.parent().items;
1357             for (var i = 0;i < pi.length;i++) {
1358                 if (this == pi[i]) {
1359                     continue;
1360                 }
1361                 if (pi[i].el.hasClass('roo-button')) {
1362                     pi[i].setActive(false);
1363                 }
1364             }
1365             this.fireEvent('click', this, e);            
1366             return;
1367         }
1368         
1369         if (this.pressed === true || this.pressed === false) {
1370             this.toggleActive(e);
1371         }
1372         
1373         
1374         this.fireEvent('click', this, e);
1375     },
1376     onDblClick: function(e)
1377     {
1378         if (this.disabled) {
1379             return;
1380         }
1381         if(this.preventDefault){
1382             e.preventDefault();
1383         }
1384         this.fireEvent('dblclick', this, e);
1385     },
1386     /**
1387      * Enables this button
1388      */
1389     enable : function()
1390     {
1391         this.disabled = false;
1392         this.el.removeClass('disabled');
1393         this.el.dom.removeAttribute("disabled");
1394     },
1395     
1396     /**
1397      * Disable this button
1398      */
1399     disable : function()
1400     {
1401         this.disabled = true;
1402         this.el.addClass('disabled');
1403         this.el.attr("disabled", "disabled")
1404     },
1405      /**
1406      * sets the active state on/off, 
1407      * @param {Boolean} state (optional) Force a particular state
1408      */
1409     setActive : function(v) {
1410         
1411         this.el[v ? 'addClass' : 'removeClass']('active');
1412         this.pressed = v;
1413     },
1414      /**
1415      * toggles the current active state 
1416      */
1417     toggleActive : function(e)
1418     {
1419         this.setActive(!this.pressed); // this modifies pressed...
1420         this.fireEvent('toggle', this, e, this.pressed);
1421     },
1422      /**
1423      * get the current active state
1424      * @return {boolean} true if it's active
1425      */
1426     isActive : function()
1427     {
1428         return this.el.hasClass('active');
1429     },
1430     /**
1431      * set the text of the first selected button
1432      */
1433     setText : function(str)
1434     {
1435         this.el.select('.roo-button-text',true).first().dom.innerHTML = str;
1436     },
1437     /**
1438      * get the text of the first selected button
1439      */
1440     getText : function()
1441     {
1442         return this.el.select('.roo-button-text',true).first().dom.innerHTML;
1443     },
1444     
1445     setWeight : function(str)
1446     {
1447         this.el.removeClass(Roo.bootstrap.Button.weights.map(function(w) { return 'btn-' + w; } ) );
1448         this.el.removeClass(Roo.bootstrap.Button.weights.map(function(w) { return 'btn-outline-' + w; } ) );
1449         this.weight = str;
1450         var outline = this.outline ? 'outline-' : '';
1451         if (str == 'default') {
1452             this.el.addClass('btn-default btn-outline-secondary');        
1453             return;
1454         }
1455         this.el.addClass('btn-' + outline + str);        
1456     }
1457     
1458     
1459 });
1460 // fixme - this is probably generic bootstrap - should go in some kind of enum file.. - like sizes.
1461
1462 Roo.bootstrap.Button.weights = [
1463     'default',
1464     'secondary' ,
1465     'primary',
1466     'success',
1467     'info',
1468     'warning',
1469     'danger',
1470     'link',
1471     'light',
1472     'dark'              
1473    
1474 ];/*
1475  * - LGPL
1476  *
1477  * column
1478  * 
1479  */
1480
1481 /**
1482  * @class Roo.bootstrap.Column
1483  * @extends Roo.bootstrap.Component
1484  * @children Roo.bootstrap.Component
1485  * Bootstrap Column class
1486  * @cfg {Number} xs colspan out of 12 for mobile-sized screens or 0 for hidden
1487  * @cfg {Number} sm colspan out of 12 for tablet-sized screens or 0 for hidden
1488  * @cfg {Number} md colspan out of 12 for computer-sized screens or 0 for hidden
1489  * @cfg {Number} lg colspan out of 12 for large computer-sized screens or 0 for hidden
1490  * @cfg {Number} xsoff colspan offset out of 12 for mobile-sized screens or 0 for hidden
1491  * @cfg {Number} smoff colspan offset out of 12 for tablet-sized screens or 0 for hidden
1492  * @cfg {Number} mdoff colspan offset out of 12 for computer-sized screens or 0 for hidden
1493  * @cfg {Number} lgoff colspan offset out of 12 for large computer-sized screens or 0 for hidden
1494  *
1495  * 
1496  * @cfg {Boolean} hidden (true|false) hide the element
1497  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
1498  * @cfg {String} fa (ban|check|...) font awesome icon
1499  * @cfg {Number} fasize (1|2|....) font awsome size
1500
1501  * @cfg {String} icon (info-sign|check|...) glyphicon name
1502
1503  * @cfg {String} html content of column.
1504  * 
1505  * @constructor
1506  * Create a new Column
1507  * @param {Object} config The config object
1508  */
1509
1510 Roo.bootstrap.Column = function(config){
1511     Roo.bootstrap.Column.superclass.constructor.call(this, config);
1512 };
1513
1514 Roo.extend(Roo.bootstrap.Column, Roo.bootstrap.Component,  {
1515     
1516     xs: false,
1517     sm: false,
1518     md: false,
1519     lg: false,
1520     xsoff: false,
1521     smoff: false,
1522     mdoff: false,
1523     lgoff: false,
1524     html: '',
1525     offset: 0,
1526     alert: false,
1527     fa: false,
1528     icon : false,
1529     hidden : false,
1530     fasize : 1,
1531     
1532     getAutoCreate : function(){
1533         var cfg = Roo.apply({}, Roo.bootstrap.Column.superclass.getAutoCreate.call(this));
1534         
1535         cfg = {
1536             tag: 'div',
1537             cls: 'column'
1538         };
1539         
1540         var settings=this;
1541         var sizes =   ['xs','sm','md','lg'];
1542         sizes.map(function(size ,ix){
1543             //Roo.log( size + ':' + settings[size]);
1544             
1545             if (settings[size+'off'] !== false) {
1546                 cfg.cls += ' col-' + size + '-offset-' + settings[size+'off'] ;
1547             }
1548             
1549             if (settings[size] === false) {
1550                 return;
1551             }
1552             
1553             if (!settings[size]) { // 0 = hidden
1554                 cfg.cls += ' hidden-' + size + ' hidden-' + size + '-down';
1555                 // bootsrap4
1556                 for (var i = ix; i > -1; i--) {
1557                     cfg.cls +=  ' d-' + sizes[i] + '-none'; 
1558                 }
1559                 
1560                 
1561                 return;
1562             }
1563             cfg.cls += ' col-' + size + '-' + settings[size] + (
1564                 size == 'xs' ? (' col-' + settings[size] ) : '' // bs4 col-{num} replaces col-xs
1565             );
1566             
1567         });
1568         
1569         if (this.hidden) {
1570             cfg.cls += ' hidden';
1571         }
1572         
1573         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
1574             cfg.cls +=' alert alert-' + this.alert;
1575         }
1576         
1577         
1578         if (this.html.length) {
1579             cfg.html = this.html;
1580         }
1581         if (this.fa) {
1582             var fasize = '';
1583             if (this.fasize > 1) {
1584                 fasize = ' fa-' + this.fasize + 'x';
1585             }
1586             cfg.html = '<i class="fa fa-'+this.fa + fasize + '"></i>' + (cfg.html || '');
1587             
1588             
1589         }
1590         if (this.icon) {
1591             cfg.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' +  (cfg.html || '');
1592         }
1593         
1594         return cfg;
1595     }
1596    
1597 });
1598
1599  
1600
1601  /*
1602  * - LGPL
1603  *
1604  * page container.
1605  * 
1606  */
1607
1608
1609 /**
1610  * @class Roo.bootstrap.Container
1611  * @extends Roo.bootstrap.Component
1612  * @children Roo.bootstrap.Component
1613  * @parent builder
1614  * Bootstrap Container class
1615  * @cfg {Boolean} jumbotron is it a jumbotron element
1616  * @cfg {String} html content of element
1617  * @cfg {String} well (lg|sm|md) a well, large, small or medium.
1618  * @cfg {String} panel (default|primary|success|info|warning|danger) render as panel  - type - primary/success.....
1619  * @cfg {String} header content of header (for panel)
1620  * @cfg {String} footer content of footer (for panel)
1621  * @cfg {String} sticky (footer|wrap|push) block to use as footer or body- needs css-bootstrap/sticky-footer.css
1622  * @cfg {String} tag (header|aside|section) type of HTML tag.
1623  * @cfg {String} alert (success|info|warning|danger) type alert (changes background / border...)
1624  * @cfg {String} fa font awesome icon
1625  * @cfg {String} icon (info-sign|check|...) glyphicon name
1626  * @cfg {Boolean} hidden (true|false) hide the element
1627  * @cfg {Boolean} expandable (true|false) default false
1628  * @cfg {Boolean} expanded (true|false) default true
1629  * @cfg {String} rheader contet on the right of header
1630  * @cfg {Boolean} clickable (true|false) default false
1631
1632  *     
1633  * @constructor
1634  * Create a new Container
1635  * @param {Object} config The config object
1636  */
1637
1638 Roo.bootstrap.Container = function(config){
1639     Roo.bootstrap.Container.superclass.constructor.call(this, config);
1640     
1641     this.addEvents({
1642         // raw events
1643          /**
1644          * @event expand
1645          * After the panel has been expand
1646          * 
1647          * @param {Roo.bootstrap.Container} this
1648          */
1649         "expand" : true,
1650         /**
1651          * @event collapse
1652          * After the panel has been collapsed
1653          * 
1654          * @param {Roo.bootstrap.Container} this
1655          */
1656         "collapse" : true,
1657         /**
1658          * @event click
1659          * When a element is chick
1660          * @param {Roo.bootstrap.Container} this
1661          * @param {Roo.EventObject} e
1662          */
1663         "click" : true
1664     });
1665 };
1666
1667 Roo.extend(Roo.bootstrap.Container, Roo.bootstrap.Component,  {
1668     
1669     jumbotron : false,
1670     well: '',
1671     panel : '',
1672     header: '',
1673     footer : '',
1674     sticky: '',
1675     tag : false,
1676     alert : false,
1677     fa: false,
1678     icon : false,
1679     expandable : false,
1680     rheader : '',
1681     expanded : true,
1682     clickable: false,
1683   
1684      
1685     getChildContainer : function() {
1686         
1687         if(!this.el){
1688             return false;
1689         }
1690         
1691         if (this.panel.length) {
1692             return this.el.select('.panel-body',true).first();
1693         }
1694         
1695         return this.el;
1696     },
1697     
1698     
1699     getAutoCreate : function(){
1700         
1701         var cfg = {
1702             tag : this.tag || 'div',
1703             html : '',
1704             cls : ''
1705         };
1706         if (this.jumbotron) {
1707             cfg.cls = 'jumbotron';
1708         }
1709         
1710         
1711         
1712         // - this is applied by the parent..
1713         //if (this.cls) {
1714         //    cfg.cls = this.cls + '';
1715         //}
1716         
1717         if (this.sticky.length) {
1718             
1719             var bd = Roo.get(document.body);
1720             if (!bd.hasClass('bootstrap-sticky')) {
1721                 bd.addClass('bootstrap-sticky');
1722                 Roo.select('html',true).setStyle('height', '100%');
1723             }
1724              
1725             cfg.cls += 'bootstrap-sticky-' + this.sticky;
1726         }
1727         
1728         
1729         if (this.well.length) {
1730             switch (this.well) {
1731                 case 'lg':
1732                 case 'sm':
1733                     cfg.cls +=' well well-' +this.well;
1734                     break;
1735                 default:
1736                     cfg.cls +=' well';
1737                     break;
1738             }
1739         }
1740         
1741         if (this.hidden) {
1742             cfg.cls += ' hidden';
1743         }
1744         
1745         
1746         if (this.alert && ["success","info","warning", "danger"].indexOf(this.alert) > -1) {
1747             cfg.cls +=' alert alert-' + this.alert;
1748         }
1749         
1750         var body = cfg;
1751         
1752         if (this.panel.length) {
1753             cfg.cls += ' panel panel-' + this.panel;
1754             cfg.cn = [];
1755             if (this.header.length) {
1756                 
1757                 var h = [];
1758                 
1759                 if(this.expandable){
1760                     
1761                     cfg.cls = cfg.cls + ' expandable';
1762                     
1763                     h.push({
1764                         tag: 'i',
1765                         cls: (this.expanded ? 'fa fa-minus' : 'fa fa-plus') 
1766                     });
1767                     
1768                 }
1769                 
1770                 h.push(
1771                     {
1772                         tag: 'span',
1773                         cls : 'panel-title',
1774                         html : (this.expandable ? '&nbsp;' : '') + this.header
1775                     },
1776                     {
1777                         tag: 'span',
1778                         cls: 'panel-header-right',
1779                         html: this.rheader
1780                     }
1781                 );
1782                 
1783                 cfg.cn.push({
1784                     cls : 'panel-heading',
1785                     style : this.expandable ? 'cursor: pointer' : '',
1786                     cn : h
1787                 });
1788                 
1789             }
1790             
1791             body = false;
1792             cfg.cn.push({
1793                 cls : 'panel-body' + (this.expanded ? '' : ' hide'),
1794                 html : this.html
1795             });
1796             
1797             
1798             if (this.footer.length) {
1799                 cfg.cn.push({
1800                     cls : 'panel-footer',
1801                     html : this.footer
1802                     
1803                 });
1804             }
1805             
1806         }
1807         
1808         if (body) {
1809             body.html = this.html || cfg.html;
1810             // prefix with the icons..
1811             if (this.fa) {
1812                 body.html = '<i class="fa fa-'+this.fa + '"></i>' + body.html ;
1813             }
1814             if (this.icon) {
1815                 body.html = '<i class="glyphicon glyphicon-'+this.icon + '"></i>' + body.html ;
1816             }
1817             
1818             
1819         }
1820         if ((!this.cls || !this.cls.length) && (!cfg.cls || !cfg.cls.length)) {
1821             cfg.cls =  'container';
1822         }
1823         
1824         return cfg;
1825     },
1826     
1827     initEvents: function() 
1828     {
1829         if(this.expandable){
1830             var headerEl = this.headerEl();
1831         
1832             if(headerEl){
1833                 headerEl.on('click', this.onToggleClick, this);
1834             }
1835         }
1836         
1837         if(this.clickable){
1838             this.el.on('click', this.onClick, this);
1839         }
1840         
1841     },
1842     
1843     onToggleClick : function()
1844     {
1845         var headerEl = this.headerEl();
1846         
1847         if(!headerEl){
1848             return;
1849         }
1850         
1851         if(this.expanded){
1852             this.collapse();
1853             return;
1854         }
1855         
1856         this.expand();
1857     },
1858     
1859     expand : function()
1860     {
1861         if(this.fireEvent('expand', this)) {
1862             
1863             this.expanded = true;
1864             
1865             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).show();
1866             
1867             this.el.select('.panel-body',true).first().removeClass('hide');
1868             
1869             var toggleEl = this.toggleEl();
1870
1871             if(!toggleEl){
1872                 return;
1873             }
1874
1875             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-minus']);
1876         }
1877         
1878     },
1879     
1880     collapse : function()
1881     {
1882         if(this.fireEvent('collapse', this)) {
1883             
1884             this.expanded = false;
1885             
1886             //this.el.select('.panel-body',true).first().setVisibilityMode(Roo.Element.DISPLAY).hide();
1887             this.el.select('.panel-body',true).first().addClass('hide');
1888         
1889             var toggleEl = this.toggleEl();
1890
1891             if(!toggleEl){
1892                 return;
1893             }
1894
1895             toggleEl.removeClass(['fa-minus', 'fa-plus']).addClass(['fa-plus']);
1896         }
1897     },
1898     
1899     toggleEl : function()
1900     {
1901         if(!this.el || !this.panel.length || !this.header.length || !this.expandable){
1902             return;
1903         }
1904         
1905         return this.el.select('.panel-heading .fa',true).first();
1906     },
1907     
1908     headerEl : function()
1909     {
1910         if(!this.el || !this.panel.length || !this.header.length){
1911             return;
1912         }
1913         
1914         return this.el.select('.panel-heading',true).first()
1915     },
1916     
1917     bodyEl : function()
1918     {
1919         if(!this.el || !this.panel.length){
1920             return;
1921         }
1922         
1923         return this.el.select('.panel-body',true).first()
1924     },
1925     
1926     titleEl : function()
1927     {
1928         if(!this.el || !this.panel.length || !this.header.length){
1929             return;
1930         }
1931         
1932         return this.el.select('.panel-title',true).first();
1933     },
1934     
1935     setTitle : function(v)
1936     {
1937         var titleEl = this.titleEl();
1938         
1939         if(!titleEl){
1940             return;
1941         }
1942         
1943         titleEl.dom.innerHTML = v;
1944     },
1945     
1946     getTitle : function()
1947     {
1948         
1949         var titleEl = this.titleEl();
1950         
1951         if(!titleEl){
1952             return '';
1953         }
1954         
1955         return titleEl.dom.innerHTML;
1956     },
1957     
1958     setRightTitle : function(v)
1959     {
1960         var t = this.el.select('.panel-header-right',true).first();
1961         
1962         if(!t){
1963             return;
1964         }
1965         
1966         t.dom.innerHTML = v;
1967     },
1968     
1969     onClick : function(e)
1970     {
1971         e.preventDefault();
1972         
1973         this.fireEvent('click', this, e);
1974     }
1975 });
1976
1977  /**
1978  * @class Roo.bootstrap.Card
1979  * @extends Roo.bootstrap.Component
1980  * @children Roo.bootstrap.Component
1981  * @licence LGPL
1982  * Bootstrap Card class - note this has children as CardHeader/ImageTop/Footer.. - which should really be listed properties?
1983  *
1984  *
1985  * possible... may not be implemented..
1986  * @cfg {String} header_image  src url of image.
1987  * @cfg {String|Object} header
1988  * @cfg {Number} header_size (0|1|2|3|4|5) H1 or H2 etc.. 0 indicates default
1989  * @cfg {Number} header_weight  (primary|secondary|success|info|warning|danger|light|dark)
1990  * 
1991  * @cfg {String} title
1992  * @cfg {String} subtitle
1993  * @cfg {String|Boolean} html -- html contents - or just use children.. use false to hide it..
1994  * @cfg {String} footer
1995  
1996  * @cfg {String} weight (primary|warning|info|danger|secondary|success|light|dark)
1997  * 
1998  * @cfg {String} margin (0|1|2|3|4|5|auto)
1999  * @cfg {String} margin_top (0|1|2|3|4|5|auto)
2000  * @cfg {String} margin_bottom (0|1|2|3|4|5|auto)
2001  * @cfg {String} margin_left (0|1|2|3|4|5|auto)
2002  * @cfg {String} margin_right (0|1|2|3|4|5|auto)
2003  * @cfg {String} margin_x (0|1|2|3|4|5|auto)
2004  * @cfg {String} margin_y (0|1|2|3|4|5|auto)
2005  *
2006  * @cfg {String} padding (0|1|2|3|4|5)
2007  * @cfg {String} padding_top (0|1|2|3|4|5)next_to_card
2008  * @cfg {String} padding_bottom (0|1|2|3|4|5)
2009  * @cfg {String} padding_left (0|1|2|3|4|5)
2010  * @cfg {String} padding_right (0|1|2|3|4|5)
2011  * @cfg {String} padding_x (0|1|2|3|4|5)
2012  * @cfg {String} padding_y (0|1|2|3|4|5)
2013  *
2014  * @cfg {String} display (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
2015  * @cfg {String} display_xs (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
2016  * @cfg {String} display_sm (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
2017  * @cfg {String} display_lg (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
2018  * @cfg {String} display_xl (none|inline|inline-block|block|table|table-cell|table-row|flex|inline-flex)
2019  
2020  * @config {Boolean} dragable  if this card can be dragged.
2021  * @config {String} drag_group  group for drag
2022  * @config {Boolean} dropable  if this card can recieve other cards being dropped onto it..
2023  * @config {String} drop_group  group for drag
2024  * 
2025  * @config {Boolean} collapsable can the body be collapsed.
2026  * @config {Boolean} collapsed is the body collapsed when rendered...
2027  * @config {Boolean} rotateable can the body be rotated by clicking on it..
2028  * @config {Boolean} rotated is the body rotated when rendered...
2029  * 
2030  * @constructor
2031  * Create a new Container
2032  * @param {Object} config The config object
2033  */
2034
2035 Roo.bootstrap.Card = function(config){
2036     Roo.bootstrap.Card.superclass.constructor.call(this, config);
2037     
2038     this.addEvents({
2039          // raw events
2040         /**
2041          * @event drop
2042          * When a element a card is dropped
2043          * @param {Roo.bootstrap.Card} this
2044          *
2045          * 
2046          * @param {Roo.bootstrap.Card} move_card the card being dropped?
2047          * @param {String} position 'above' or 'below'
2048          * @param {Roo.bootstrap.Card} next_to_card What card position is relative to of 'false' for empty list.
2049         
2050          */
2051         'drop' : true,
2052          /**
2053          * @event rotate
2054          * When a element a card is rotate
2055          * @param {Roo.bootstrap.Card} this
2056          * @param {Roo.Element} n the node being dropped?
2057          * @param {Boolean} rotate status
2058          */
2059         'rotate' : true,
2060         /**
2061          * @event cardover
2062          * When a card element is dragged over ready to drop (return false to block dropable)
2063          * @param {Roo.bootstrap.Card} this
2064          * @param {Object} data from dragdrop 
2065          */
2066          'cardover' : true
2067          
2068     });
2069 };
2070
2071
2072 Roo.extend(Roo.bootstrap.Card, Roo.bootstrap.Component,  {
2073     
2074     
2075     weight : '',
2076     
2077     margin: '', /// may be better in component?
2078     margin_top: '', 
2079     margin_bottom: '', 
2080     margin_left: '',
2081     margin_right: '',
2082     margin_x: '',
2083     margin_y: '',
2084     
2085     padding : '',
2086     padding_top: '', 
2087     padding_bottom: '', 
2088     padding_left: '',
2089     padding_right: '',
2090     padding_x: '',
2091     padding_y: '',
2092     
2093     display: '', 
2094     display_xs: '', 
2095     display_sm: '', 
2096     display_lg: '',
2097     display_xl: '',
2098  
2099     header_image  : '',
2100     header : '',
2101     header_size : 0,
2102     title : '',
2103     subtitle : '',
2104     html : '',
2105     footer: '',
2106
2107     collapsable : false,
2108     collapsed : false,
2109     rotateable : false,
2110     rotated : false,
2111     
2112     dragable : false,
2113     drag_group : false,
2114     dropable : false,
2115     drop_group : false,
2116     childContainer : false,
2117     dropEl : false, /// the dom placeholde element that indicates drop location.
2118     containerEl: false, // body container
2119     bodyEl: false, // card-body
2120     headerContainerEl : false, //
2121     headerEl : false,
2122     header_imageEl : false,
2123     
2124     
2125     layoutCls : function()
2126     {
2127         var cls = '';
2128         var t = this;
2129         Roo.log(this.margin_bottom.length);
2130         ['', 'top', 'bottom', 'left', 'right', 'x', 'y' ].forEach(function(v) {
2131             // in theory these can do margin_top : ml-xs-3 ??? but we don't support that yet
2132             
2133             if (('' + t['margin' + (v.length ? '_' : '') + v]).length) {
2134                 cls += ' m' +  (v.length ? v[0]  : '') + '-' +  t['margin' + (v.length ? '_' : '') + v];
2135             }
2136             if (('' + t['padding' + (v.length ? '_' : '') + v]).length) {
2137                 cls += ' p' +  (v.length ? v[0]  : '') + '-' +  t['padding' + (v.length ? '_' : '') + v];
2138             }
2139         });
2140         
2141         ['', 'xs', 'sm', 'lg', 'xl'].forEach(function(v) {
2142             if (('' + t['display' + (v.length ? '_' : '') + v]).length) {
2143                 cls += ' d' +  (v.length ? '-' : '') + v + '-' + t['display' + (v.length ? '_' : '') + v]
2144             }
2145         });
2146         
2147         // more generic support?
2148         if (this.hidden) {
2149             cls += ' d-none';
2150         }
2151         
2152         return cls;
2153     },
2154  
2155        // Roo.log("Call onRender: " + this.xtype);
2156         /*  We are looking at something like this.
2157 <div class="card">
2158     <img src="..." class="card-img-top" alt="...">
2159     <div class="card-body">
2160         <h5 class="card-title">Card title</h5>
2161          <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
2162
2163         >> this bit is really the body...
2164         <div> << we will ad dthis in hopefully it will not break shit.
2165         
2166         ** card text does not actually have any styling...
2167         
2168             <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
2169         
2170         </div> <<
2171           <a href="#" class="card-link">Card link</a>
2172           
2173     </div>
2174     <div class="card-footer">
2175         <small class="text-muted">Last updated 3 mins ago</small>
2176     </div>
2177 </div>
2178          */
2179     getAutoCreate : function(){
2180         
2181         var cfg = {
2182             tag : 'div',
2183             cls : 'card',
2184             cn : [ ]
2185         };
2186         
2187         if (this.weight.length && this.weight != 'light') {
2188             cfg.cls += ' text-white';
2189         } else {
2190             cfg.cls += ' text-dark'; // need as it's nested..
2191         }
2192         if (this.weight.length) {
2193             cfg.cls += ' bg-' + this.weight;
2194         }
2195         
2196         cfg.cls += ' ' + this.layoutCls(); 
2197         
2198         var hdr = false;
2199         var hdr_ctr = false;
2200         if (this.header.length) {
2201             hdr = {
2202                 tag : this.header_size > 0 ? 'h' + this.header_size : 'div',
2203                 cls : 'card-header ' + (this.header_weight ? 'bg-' + this.header_weight : ''),
2204                 cn : []
2205             };
2206             cfg.cn.push(hdr);
2207             hdr_ctr = hdr;
2208         } else {
2209             hdr = {
2210                 tag : 'div',
2211                 cls : 'card-header d-none ' + (this.header_weight ? 'bg-' + this.header_weight : ''),
2212                 cn : []
2213             };
2214             cfg.cn.push(hdr);
2215             hdr_ctr = hdr;
2216         }
2217         if (this.collapsable) {
2218             hdr_ctr = {
2219             tag : 'a',
2220             cls : 'd-block user-select-none',
2221             cn: [
2222                     {
2223                         tag: 'i',
2224                         cls : 'roo-collapse-toggle fa fa-chevron-down float-right ' + (this.collapsed ? 'collapsed' : '')
2225                     }
2226                    
2227                 ]
2228             };
2229             hdr.cn.push(hdr_ctr);
2230         }
2231         
2232         hdr_ctr.cn.push(        {
2233             tag: 'span',
2234             cls: 'roo-card-header-ctr' + ( this.header.length ? '' : ' d-none'),
2235             html : this.header
2236         });
2237         
2238         
2239         if (this.header_image.length) {
2240             cfg.cn.push({
2241                 tag : 'img',
2242                 cls : 'card-img-top',
2243                 src: this.header_image // escape?
2244             });
2245         } else {
2246             cfg.cn.push({
2247                     tag : 'div',
2248                     cls : 'card-img-top d-none' 
2249                 });
2250         }
2251             
2252         var body = {
2253             tag : 'div',
2254             cls : 'card-body' + (this.html === false  ? ' d-none' : ''),
2255             cn : []
2256         };
2257         var obody = body;
2258         if (this.collapsable || this.rotateable) {
2259             obody = {
2260                 tag: 'div',
2261                 cls : 'roo-collapsable collapse ' + (this.collapsed || this.rotated ? '' : 'show'),
2262                 cn : [  body ]
2263             };
2264         }
2265         
2266         cfg.cn.push(obody);
2267         
2268         if (this.title.length) {
2269             body.cn.push({
2270                 tag : 'div',
2271                 cls : 'card-title',
2272                 src: this.title // escape?
2273             });
2274         }  
2275         
2276         if (this.subtitle.length) {
2277             body.cn.push({
2278                 tag : 'div',
2279                 cls : 'card-title',
2280                 src: this.subtitle // escape?
2281             });
2282         }
2283         
2284         body.cn.push({
2285             tag : 'div',
2286             cls : 'roo-card-body-ctr'
2287         });
2288         
2289         if (this.html.length) {
2290             body.cn.push({
2291                 tag: 'div',
2292                 html : this.html
2293             });
2294         }
2295         // fixme ? handle objects?
2296         
2297         if (this.footer.length) {
2298            
2299             cfg.cn.push({
2300                 cls : 'card-footer ' + (this.rotated ? 'd-none' : ''),
2301                 html : this.footer
2302             });
2303             
2304         } else {
2305             cfg.cn.push({cls : 'card-footer d-none'});
2306         }
2307         
2308         // footer...
2309         
2310         return cfg;
2311     },
2312     
2313     
2314     getCardHeader : function()
2315     {
2316         var  ret = this.el.select('.card-header',true).first();
2317         if (ret.hasClass('d-none')) {
2318             ret.removeClass('d-none');
2319         }
2320         
2321         return ret;
2322     },
2323     getCardFooter : function()
2324     {
2325         var  ret = this.el.select('.card-footer',true).first();
2326         if (ret.hasClass('d-none')) {
2327             ret.removeClass('d-none');
2328         }
2329         
2330         return ret;
2331     },
2332     getCardImageTop : function()
2333     {
2334         var  ret = this.header_imageEl;
2335         if (ret.hasClass('d-none')) {
2336             ret.removeClass('d-none');
2337         }
2338             
2339         return ret;
2340     },
2341     
2342     getChildContainer : function()
2343     {
2344         
2345         if(!this.el){
2346             return false;
2347         }
2348         return this.el.select('.roo-card-body-ctr',true).first();    
2349     },
2350     
2351     initEvents: function() 
2352     {
2353         this.bodyEl = this.el.select('.card-body',true).first(); 
2354         this.containerEl = this.getChildContainer();
2355         if(this.dragable){
2356             this.dragZone = new Roo.dd.DragZone(this.getEl(), {
2357                     containerScroll: true,
2358                     ddGroup: this.drag_group || 'default_card_drag_group'
2359             });
2360             this.dragZone.getDragData = this.getDragData.createDelegate(this);
2361         }
2362         if (this.dropable) {
2363             this.dropZone = new Roo.dd.DropZone(this.el.select('.card-body',true).first() , {
2364                 containerScroll: true,
2365                 ddGroup: this.drop_group || 'default_card_drag_group'
2366             });
2367             this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
2368             this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
2369             this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
2370             this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
2371             this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
2372         }
2373         
2374         if (this.collapsable) {
2375             this.el.select('.card-header',true).on('click', this.onToggleCollapse, this);
2376         }
2377         if (this.rotateable) {
2378             this.el.select('.card-header',true).on('click', this.onToggleRotate, this);
2379         }
2380         this.collapsableEl = this.el.select('.roo-collapsable',true).first();
2381          
2382         this.footerEl = this.el.select('.card-footer',true).first();
2383         this.collapsableToggleEl = this.el.select('.roo-collapse-toggle',true).first();
2384         this.headerContainerEl = this.el.select('.roo-card-header-ctr',true).first();
2385         this.headerEl = this.el.select('.card-header',true).first();
2386         
2387         if (this.rotated) {
2388             this.el.addClass('roo-card-rotated');
2389             this.fireEvent('rotate', this, true);
2390         }
2391         this.header_imageEl = this.el.select('.card-img-top',true).first(); 
2392         this.header_imageEl.on('load', this.onHeaderImageLoad, this );
2393         
2394     },
2395     getDragData : function(e)
2396     {
2397         var target = this.getEl();
2398         if (target) {
2399             //this.handleSelection(e);
2400             
2401             var dragData = {
2402                 source: this,
2403                 copy: false,
2404                 nodes: this.getEl(),
2405                 records: []
2406             };
2407             
2408             
2409             dragData.ddel = target.dom ;    // the div element
2410             Roo.log(target.getWidth( ));
2411             dragData.ddel.style.width = target.getWidth() + 'px';
2412             
2413             return dragData;
2414         }
2415         return false;
2416     },
2417     /**
2418     *    Part of the Roo.dd.DropZone interface. If no target node is found, the
2419     *    whole Element becomes the target, and this causes the drop gesture to append.
2420     *
2421     *    Returns an object:
2422     *     {
2423            
2424            position : 'below' or 'above'
2425            card  : relateive to card OBJECT (or true for no cards listed)
2426            items_n : relative to nth item in list
2427            card_n : relative to  nth card in list
2428     }
2429     *
2430     *    
2431     */
2432     getTargetFromEvent : function(e, dragged_card_el)
2433     {
2434         var target = e.getTarget();
2435         while ((target !== null) && (target.parentNode != this.containerEl.dom)) {
2436             target = target.parentNode;
2437         }
2438         
2439         var ret = {
2440             position: '',
2441             cards : [],
2442             card_n : -1,
2443             items_n : -1,
2444             card : false 
2445         };
2446         
2447         //Roo.log([ 'target' , target ? target.id : '--nothing--']);
2448         // see if target is one of the 'cards'...
2449         
2450         
2451         //Roo.log(this.items.length);
2452         var pos = false;
2453         
2454         var last_card_n = 0;
2455         var cards_len  = 0;
2456         for (var i = 0;i< this.items.length;i++) {
2457             
2458             if (!this.items[i].el.hasClass('card')) {
2459                  continue;
2460             }
2461             pos = this.getDropPoint(e, this.items[i].el.dom);
2462             
2463             cards_len = ret.cards.length;
2464             //Roo.log(this.items[i].el.dom.id);
2465             ret.cards.push(this.items[i]);
2466             last_card_n  = i;
2467             if (ret.card_n < 0 && pos == 'above') {
2468                 ret.position = cards_len > 0 ? 'below' : pos;
2469                 ret.items_n = i > 0 ? i - 1 : 0;
2470                 ret.card_n  = cards_len  > 0 ? cards_len - 1 : 0;
2471                 ret.card = ret.cards[ret.card_n];
2472             }
2473         }
2474         if (!ret.cards.length) {
2475             ret.card = true;
2476             ret.position = 'below';
2477             ret.items_n;
2478             return ret;
2479         }
2480         // could not find a card.. stick it at the end..
2481         if (ret.card_n < 0) {
2482             ret.card_n = last_card_n;
2483             ret.card = ret.cards[last_card_n];
2484             ret.items_n = this.items.indexOf(ret.cards[last_card_n]);
2485             ret.position = 'below';
2486         }
2487         
2488         if (this.items[ret.items_n].el == dragged_card_el) {
2489             return false;
2490         }
2491         
2492         if (ret.position == 'below') {
2493             var card_after = ret.card_n+1 == ret.cards.length ? false : ret.cards[ret.card_n+1];
2494             
2495             if (card_after  && card_after.el == dragged_card_el) {
2496                 return false;
2497             }
2498             return ret;
2499         }
2500         
2501         // its's after ..
2502         var card_before = ret.card_n > 0 ? ret.cards[ret.card_n-1] : false;
2503         
2504         if (card_before  && card_before.el == dragged_card_el) {
2505             return false;
2506         }
2507         
2508         return ret;
2509     },
2510     
2511     onNodeEnter : function(n, dd, e, data){
2512         return false;
2513     },
2514     onNodeOver : function(n, dd, e, data)
2515     {
2516        
2517         var target_info = this.getTargetFromEvent(e,data.source.el);
2518         if (target_info === false) {
2519             this.dropPlaceHolder('hide');
2520             return false;
2521         }
2522         Roo.log(['getTargetFromEvent', target_info ]);
2523         
2524         
2525         if (this.fireEvent('cardover', this, [ data ]) === false) {
2526             return false;
2527         }
2528         
2529         this.dropPlaceHolder('show', target_info,data);
2530         
2531         return false; 
2532     },
2533     onNodeOut : function(n, dd, e, data){
2534         this.dropPlaceHolder('hide');
2535      
2536     },
2537     onNodeDrop : function(n, dd, e, data)
2538     {
2539         
2540         // call drop - return false if
2541         
2542         // this could actually fail - if the Network drops..
2543         // we will ignore this at present..- client should probably reload
2544         // the whole set of cards if stuff like that fails.
2545         
2546         
2547         var info = this.getTargetFromEvent(e,data.source.el);
2548         if (info === false) {
2549             return false;
2550         }
2551         this.dropPlaceHolder('hide');
2552   
2553           
2554     
2555         this.acceptCard(data.source, info.position, info.card, info.items_n);
2556         return true;
2557          
2558     },
2559     firstChildCard : function()
2560     {
2561         for (var i = 0;i< this.items.length;i++) {
2562             
2563             if (!this.items[i].el.hasClass('card')) {
2564                  continue;
2565             }
2566             return this.items[i];
2567         }
2568         return this.items.length ? this.items[this.items.length-1] : false; // don't try and put stuff after the cards...
2569     },
2570     /**
2571      * accept card
2572      *
2573      * -        card.acceptCard(move_card, info.position, info.card, info.items_n);
2574      */
2575     acceptCard : function(move_card,  position, next_to_card )
2576     {
2577         if (this.fireEvent("drop", this, move_card, position, next_to_card) === false) {
2578             return false;
2579         }
2580         
2581         var to_items_n = next_to_card ? this.items.indexOf(next_to_card) : 0;
2582         
2583         move_card.parent().removeCard(move_card);
2584         
2585         
2586         var dom = move_card.el.dom;
2587         dom.style.width = ''; // clear with - which is set by drag.
2588         
2589         if (next_to_card !== false && next_to_card !== true && next_to_card.el.dom.parentNode) {
2590             var cardel = next_to_card.el.dom;
2591             
2592             if (position == 'above' ) {
2593                 cardel.parentNode.insertBefore(dom, cardel);
2594             } else if (cardel.nextSibling) {
2595                 cardel.parentNode.insertBefore(dom,cardel.nextSibling);
2596             } else {
2597                 cardel.parentNode.append(dom);
2598             }
2599         } else {
2600             // card container???
2601             this.containerEl.dom.append(dom);
2602         }
2603         
2604         //FIXME HANDLE card = true 
2605         
2606         // add this to the correct place in items.
2607         
2608         // remove Card from items.
2609         
2610        
2611         if (this.items.length) {
2612             var nitems = [];
2613             //Roo.log([info.items_n, info.position, this.items.length]);
2614             for (var i =0; i < this.items.length; i++) {
2615                 if (i == to_items_n && position == 'above') {
2616                     nitems.push(move_card);
2617                 }
2618                 nitems.push(this.items[i]);
2619                 if (i == to_items_n && position == 'below') {
2620                     nitems.push(move_card);
2621                 }
2622             }
2623             this.items = nitems;
2624             Roo.log(this.items);
2625         } else {
2626             this.items.push(move_card);
2627         }
2628         
2629         move_card.parentId = this.id;
2630         
2631         return true;
2632         
2633         
2634     },
2635     removeCard : function(c)
2636     {
2637         this.items = this.items.filter(function(e) { return e != c });
2638  
2639         var dom = c.el.dom;
2640         dom.parentNode.removeChild(dom);
2641         dom.style.width = ''; // clear with - which is set by drag.
2642         c.parentId = false;
2643         
2644     },
2645     
2646     /**    Decide whether to drop above or below a View node. */
2647     getDropPoint : function(e, n, dd)
2648     {
2649         if (dd) {
2650              return false;
2651         }
2652         if (n == this.containerEl.dom) {
2653             return "above";
2654         }
2655         var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
2656         var c = t + (b - t) / 2;
2657         var y = Roo.lib.Event.getPageY(e);
2658         if(y <= c) {
2659             return "above";
2660         }else{
2661             return "below";
2662         }
2663     },
2664     onToggleCollapse : function(e)
2665         {
2666         if (this.collapsed) {
2667             this.el.select('.roo-collapse-toggle').removeClass('collapsed');
2668             this.collapsableEl.addClass('show');
2669             this.collapsed = false;
2670             return;
2671         }
2672         this.el.select('.roo-collapse-toggle').addClass('collapsed');
2673         this.collapsableEl.removeClass('show');
2674         this.collapsed = true;
2675         
2676     
2677     },
2678     
2679     onToggleRotate : function(e)
2680     {
2681         this.collapsableEl.removeClass('show');
2682         this.footerEl.removeClass('d-none');
2683         this.el.removeClass('roo-card-rotated');
2684         this.el.removeClass('d-none');
2685         if (this.rotated) {
2686             
2687             this.collapsableEl.addClass('show');
2688             this.rotated = false;
2689             this.fireEvent('rotate', this, this.rotated);
2690             return;
2691         }
2692         this.el.addClass('roo-card-rotated');
2693         this.footerEl.addClass('d-none');
2694         this.el.select('.roo-collapsable').removeClass('show');
2695         
2696         this.rotated = true;
2697         this.fireEvent('rotate', this, this.rotated);
2698     
2699     },
2700     
2701     dropPlaceHolder: function (action, info, data)
2702     {
2703         if (this.dropEl === false) {
2704             this.dropEl = Roo.DomHelper.append(this.containerEl, {
2705             cls : 'd-none'
2706             },true);
2707         }
2708         this.dropEl.removeClass(['d-none', 'd-block']);        
2709         if (action == 'hide') {
2710             
2711             this.dropEl.addClass('d-none');
2712             return;
2713         }
2714         // FIXME - info.card == true!!!
2715         this.dropEl.dom.parentNode.removeChild(this.dropEl.dom);
2716         
2717         if (info.card !== true) {
2718             var cardel = info.card.el.dom;
2719             
2720             if (info.position == 'above') {
2721                 cardel.parentNode.insertBefore(this.dropEl.dom, cardel);
2722             } else if (cardel.nextSibling) {
2723                 cardel.parentNode.insertBefore(this.dropEl.dom,cardel.nextSibling);
2724             } else {
2725                 cardel.parentNode.append(this.dropEl.dom);
2726             }
2727         } else {
2728             // card container???
2729             this.containerEl.dom.append(this.dropEl.dom);
2730         }
2731         
2732         this.dropEl.addClass('d-block roo-card-dropzone');
2733         
2734         this.dropEl.setHeight( Roo.get(data.ddel).getHeight() );
2735         
2736         
2737     
2738     
2739     
2740     },
2741     setHeaderText: function(html)
2742     {
2743         this.header = html;
2744         if (this.headerContainerEl) {
2745             this.headerContainerEl.dom.innerHTML = html;
2746         }
2747     },
2748     onHeaderImageLoad : function(ev, he)
2749     {
2750         if (!this.header_image_fit_square) {
2751             return;
2752         }
2753         
2754         var hw = he.naturalHeight / he.naturalWidth;
2755         // wide image = < 0
2756         // tall image = > 1
2757         //var w = he.dom.naturalWidth;
2758         var ww = he.width;
2759         he.style.left =  0;
2760         he.style.position =  'relative';
2761         if (hw > 1) {
2762             var nw = (ww * (1/hw));
2763             Roo.get(he).setSize( ww * (1/hw),  ww);
2764             he.style.left =  ((ww - nw)/ 2) + 'px';
2765             he.style.position =  'relative';
2766         }
2767
2768     }
2769
2770     
2771 });
2772
2773 /*
2774  * - LGPL
2775  *
2776  * Card header - holder for the card header elements.
2777  * 
2778  */
2779
2780 /**
2781  * @class Roo.bootstrap.CardHeader
2782  * @extends Roo.bootstrap.Element
2783  * @parent Roo.bootstrap.Card
2784  * @children Roo.bootstrap.Component
2785  * Bootstrap CardHeader class
2786  * @constructor
2787  * Create a new Card Header - that you can embed children into
2788  * @param {Object} config The config object
2789  */
2790
2791 Roo.bootstrap.CardHeader = function(config){
2792     Roo.bootstrap.CardHeader.superclass.constructor.call(this, config);
2793 };
2794
2795 Roo.extend(Roo.bootstrap.CardHeader, Roo.bootstrap.Element,  {
2796     
2797     
2798     container_method : 'getCardHeader' 
2799     
2800      
2801     
2802     
2803    
2804 });
2805
2806  
2807
2808  /*
2809  * - LGPL
2810  *
2811  * Card footer - holder for the card footer elements.
2812  * 
2813  */
2814
2815 /**
2816  * @class Roo.bootstrap.CardFooter
2817  * @extends Roo.bootstrap.Element
2818  * @parent Roo.bootstrap.Card
2819  * @children Roo.bootstrap.Component
2820  * Bootstrap CardFooter class
2821  * 
2822  * @constructor
2823  * Create a new Card Footer - that you can embed children into
2824  * @param {Object} config The config object
2825  */
2826
2827 Roo.bootstrap.CardFooter = function(config){
2828     Roo.bootstrap.CardFooter.superclass.constructor.call(this, config);
2829 };
2830
2831 Roo.extend(Roo.bootstrap.CardFooter, Roo.bootstrap.Element,  {
2832     
2833     
2834     container_method : 'getCardFooter' 
2835     
2836      
2837     
2838     
2839    
2840 });
2841
2842  
2843
2844  /*
2845  * - LGPL
2846  *
2847  * Card header - holder for the card header elements.
2848  * 
2849  */
2850
2851 /**
2852  * @class Roo.bootstrap.CardImageTop
2853  * @extends Roo.bootstrap.Element
2854  * @parent Roo.bootstrap.Card
2855  * @children Roo.bootstrap.Component
2856  * Bootstrap CardImageTop class
2857  * 
2858  * @constructor
2859  * Create a new Card Image Top container
2860  * @param {Object} config The config object
2861  */
2862
2863 Roo.bootstrap.CardImageTop = function(config){
2864     Roo.bootstrap.CardImageTop.superclass.constructor.call(this, config);
2865 };
2866
2867 Roo.extend(Roo.bootstrap.CardImageTop, Roo.bootstrap.Element,  {
2868     
2869    
2870     container_method : 'getCardImageTop' 
2871     
2872      
2873     
2874    
2875 });
2876
2877  
2878
2879  
2880 /*
2881 * Licence: LGPL
2882 */
2883
2884 /**
2885  * @class Roo.bootstrap.ButtonUploader
2886  * @extends Roo.bootstrap.Button
2887  * Bootstrap Button Uploader class - it's a button which when you add files to it
2888  *
2889  * 
2890  * @cfg {Number} errorTimeout default 3000
2891  * @cfg {Array}  images  an array of ?? Img objects ??? when loading existing files..
2892  * @cfg {Array}  html The button text.
2893  * @cfg {Boolean}  multiple (default true) Should the upload allow multiple files to be uploaded.
2894  *
2895  * @constructor
2896  * Create a new CardUploader
2897  * @param {Object} config The config object
2898  */
2899
2900 Roo.bootstrap.ButtonUploader = function(config){
2901     
2902  
2903     
2904     Roo.bootstrap.ButtonUploader.superclass.constructor.call(this, config);
2905     
2906      
2907      this.addEvents({
2908          // raw events
2909         /**
2910          * @event beforeselect
2911          * When button is pressed, before show upload files dialog is shown
2912          * @param {Roo.bootstrap.UploaderButton} this
2913          *
2914          */
2915         'beforeselect' : true,
2916          /**
2917          * @event fired when files have been selected, 
2918          * When a the download link is clicked
2919          * @param {Roo.bootstrap.UploaderButton} this
2920          * @param {Array} Array of files that have been uploaded
2921          */
2922         'uploaded' : true
2923         
2924     });
2925 };
2926  
2927 Roo.extend(Roo.bootstrap.ButtonUploader, Roo.bootstrap.Button,  {
2928     
2929      
2930     errorTimeout : 3000,
2931      
2932     images : false,
2933    
2934     fileCollection : false,
2935     allowBlank : true,
2936     
2937     multiple : true,
2938     
2939     getAutoCreate : function()
2940     {
2941        
2942         
2943         return  {
2944             cls :'div' ,
2945             cn : [
2946                 Roo.bootstrap.Button.prototype.getAutoCreate.call(this) 
2947             ]
2948         };
2949            
2950          
2951     },
2952      
2953    
2954     initEvents : function()
2955     {
2956         
2957         Roo.bootstrap.Button.prototype.initEvents.call(this);
2958         
2959         
2960         
2961         
2962         
2963         this.urlAPI = (window.createObjectURL && window) || 
2964                                 (window.URL && URL.revokeObjectURL && URL) || 
2965                                 (window.webkitURL && webkitURL);
2966                         
2967         var im = {
2968             tag: 'input',
2969             type : 'file',
2970             cls : 'd-none  roo-card-upload-selector' 
2971           
2972         };
2973         if (this.multiple) {
2974             im.multiple = 'multiple';
2975         }
2976         this.selectorEl = Roo.get(document.body).createChild(im); // so it does not capture click event for navitem.
2977        
2978         //this.selectorEl = this.el.select('.roo-card-upload-selector', true).first();
2979         
2980         this.selectorEl.on('change', this.onFileSelected, this);
2981          
2982          
2983        
2984     },
2985     
2986    
2987     onClick : function(e)
2988     {
2989         e.preventDefault();
2990         
2991         if ( this.fireEvent('beforeselect', this) === false) {
2992             return;
2993         }
2994          
2995         this.selectorEl.dom.click();
2996          
2997     },
2998     
2999     onFileSelected : function(e)
3000     {
3001         e.preventDefault();
3002         
3003         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
3004             return;
3005         }
3006         var files = Array.prototype.slice.call(this.selectorEl.dom.files);
3007         this.selectorEl.dom.value  = '';// hopefully reset..
3008         
3009         this.fireEvent('uploaded', this,  files );
3010         
3011     },
3012     
3013        
3014    
3015     
3016     /**
3017      * addCard - add an Attachment to the uploader
3018      * @param data - the data about the image to upload
3019      *
3020      * {
3021           id : 123
3022           title : "Title of file",
3023           is_uploaded : false,
3024           src : "http://.....",
3025           srcfile : { the File upload object },
3026           mimetype : file.type,
3027           preview : false,
3028           is_deleted : 0
3029           .. any other data...
3030         }
3031      *
3032      * 
3033     */
3034      
3035     reset: function()
3036     {
3037          
3038          this.selectorEl
3039     } 
3040     
3041     
3042     
3043     
3044 });
3045  /*
3046  * - LGPL
3047  *
3048  * image
3049  * 
3050  */
3051
3052
3053 /**
3054  * @class Roo.bootstrap.Img
3055  * @extends Roo.bootstrap.Component
3056  * Bootstrap Img class
3057  * @cfg {Boolean} imgResponsive false | true
3058  * @cfg {String} border rounded | circle | thumbnail
3059  * @cfg {String} src image source
3060  * @cfg {String} alt image alternative text
3061  * @cfg {String} href a tag href
3062  * @cfg {String} target (_self|_blank|_parent|_top)target for a href.
3063  * @cfg {String} xsUrl xs image source
3064  * @cfg {String} smUrl sm image source
3065  * @cfg {String} mdUrl md image source
3066  * @cfg {String} lgUrl lg image source
3067  * @cfg {Boolean} backgroundContain (use style background and contain image in content)
3068  * 
3069  * @constructor
3070  * Create a new Input
3071  * @param {Object} config The config object
3072  */
3073
3074 Roo.bootstrap.Img = function(config){
3075     Roo.bootstrap.Img.superclass.constructor.call(this, config);
3076     
3077     this.addEvents({
3078         // img events
3079         /**
3080          * @event click
3081          * The img click event for the img.
3082          * @param {Roo.EventObject} e
3083          */
3084         "click" : true,
3085         /**
3086          * @event load
3087          * The when any image loads
3088          * @param {Roo.EventObject} e
3089          */
3090         "load" : true
3091     });
3092 };
3093
3094 Roo.extend(Roo.bootstrap.Img, Roo.bootstrap.Component,  {
3095     
3096     imgResponsive: true,
3097     border: '',
3098     src: 'about:blank',
3099     href: false,
3100     target: false,
3101     xsUrl: '',
3102     smUrl: '',
3103     mdUrl: '',
3104     lgUrl: '',
3105     backgroundContain : false,
3106
3107     getAutoCreate : function()
3108     {   
3109         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
3110             return this.createSingleImg();
3111         }
3112         
3113         var cfg = {
3114             tag: 'div',
3115             cls: 'roo-image-responsive-group',
3116             cn: []
3117         };
3118         var _this = this;
3119         
3120         Roo.each(['xs', 'sm', 'md', 'lg'], function(size){
3121             
3122             if(!_this[size + 'Url']){
3123                 return;
3124             }
3125             
3126             var img = {
3127                 tag: 'img',
3128                 cls: (_this.imgResponsive) ? 'img-responsive' : '',
3129                 html: _this.html || cfg.html,
3130                 src: _this[size + 'Url']
3131             };
3132             
3133             img.cls += ' roo-image-responsive-' + size;
3134             
3135             var s = ['xs', 'sm', 'md', 'lg'];
3136             
3137             s.splice(s.indexOf(size), 1);
3138             
3139             Roo.each(s, function(ss){
3140                 img.cls += ' hidden-' + ss;
3141             });
3142             
3143             if (['rounded','circle','thumbnail'].indexOf(_this.border)>-1) {
3144                 cfg.cls += ' img-' + _this.border;
3145             }
3146             
3147             if(_this.alt){
3148                 cfg.alt = _this.alt;
3149             }
3150             
3151             if(_this.href){
3152                 var a = {
3153                     tag: 'a',
3154                     href: _this.href,
3155                     cn: [
3156                         img
3157                     ]
3158                 };
3159
3160                 if(this.target){
3161                     a.target = _this.target;
3162                 }
3163             }
3164             
3165             cfg.cn.push((_this.href) ? a : img);
3166             
3167         });
3168         
3169         return cfg;
3170     },
3171     
3172     createSingleImg : function()
3173     {
3174         var cfg = {
3175             tag: 'img',
3176             cls: (this.imgResponsive) ? 'img-responsive' : '',
3177             html : null,
3178             src : Roo.BLANK_IMAGE_URL  // just incase src get's set to undefined?!?
3179         };
3180         
3181         if (this.backgroundContain) {
3182             cfg.cls += ' background-contain';
3183         }
3184         
3185         cfg.html = this.html || cfg.html;
3186         
3187         if (this.backgroundContain) {
3188             cfg.style="background-image: url(" + this.src + ')';
3189         } else {
3190             cfg.src = this.src || cfg.src;
3191         }
3192         
3193         if (['rounded','circle','thumbnail'].indexOf(this.border)>-1) {
3194             cfg.cls += ' img-' + this.border;
3195         }
3196         
3197         if(this.alt){
3198             cfg.alt = this.alt;
3199         }
3200         
3201         if(this.href){
3202             var a = {
3203                 tag: 'a',
3204                 href: this.href,
3205                 cn: [
3206                     cfg
3207                 ]
3208             };
3209             
3210             if(this.target){
3211                 a.target = this.target;
3212             }
3213             
3214         }
3215         
3216         return (this.href) ? a : cfg;
3217     },
3218     
3219     initEvents: function() 
3220     {
3221         if(!this.href){
3222             this.el.on('click', this.onClick, this);
3223         }
3224         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
3225             this.el.on('load', this.onImageLoad, this);
3226         } else {
3227             // not sure if this works.. not tested
3228             this.el.select('img', true).on('load', this.onImageLoad, this);
3229         }
3230         
3231     },
3232     
3233     onClick : function(e)
3234     {
3235         Roo.log('img onclick');
3236         this.fireEvent('click', this, e);
3237     },
3238     onImageLoad: function(e)
3239     {
3240         Roo.log('img load');
3241         this.fireEvent('load', this, e);
3242     },
3243     
3244     /**
3245      * Sets the url of the image - used to update it
3246      * @param {String} url the url of the image
3247      */
3248     
3249     setSrc : function(url)
3250     {
3251         this.src =  url;
3252         
3253         if(this.src || (!this.xsUrl && !this.smUrl && !this.mdUrl && !this.lgUrl)){
3254             if (this.backgroundContain) {
3255                 this.el.dom.style.backgroundImage =  'url(' + url + ')';
3256             } else {
3257                 this.el.dom.src =  url;
3258             }
3259             return;
3260         }
3261         
3262         this.el.select('img', true).first().dom.src =  url;
3263     }
3264     
3265     
3266    
3267 });
3268
3269  /*
3270  * - LGPL
3271  *
3272  * image
3273  * 
3274  */
3275
3276
3277 /**
3278  * @class Roo.bootstrap.Link
3279  * @extends Roo.bootstrap.Component
3280  * @children Roo.bootstrap.Component
3281  * Bootstrap Link Class (eg. '<a href>')
3282  
3283  * @cfg {String} alt image alternative text
3284  * @cfg {String} href a tag href
3285  * @cfg {String} target (_self|_blank|_parent|_top) target for a href.
3286  * @cfg {String} html the content of the link.
3287  * @cfg {String} anchor name for the anchor link
3288  * @cfg {String} fa - favicon
3289
3290  * @cfg {Boolean} preventDefault (true | false) default false
3291
3292  * 
3293  * @constructor
3294  * Create a new Input
3295  * @param {Object} config The config object
3296  */
3297
3298 Roo.bootstrap.Link = function(config){
3299     Roo.bootstrap.Link.superclass.constructor.call(this, config);
3300     
3301     this.addEvents({
3302         // img events
3303         /**
3304          * @event click
3305          * The img click event for the img.
3306          * @param {Roo.EventObject} e
3307          */
3308         "click" : true
3309     });
3310 };
3311
3312 Roo.extend(Roo.bootstrap.Link, Roo.bootstrap.Component,  {
3313     
3314     href: false,
3315     target: false,
3316     preventDefault: false,
3317     anchor : false,
3318     alt : false,
3319     fa: false,
3320
3321
3322     getAutoCreate : function()
3323     {
3324         var html = this.html || '';
3325         
3326         if (this.fa !== false) {
3327             html = '<i class="fa fa-' + this.fa + '"></i>';
3328         }
3329         var cfg = {
3330             tag: 'a'
3331         };
3332         // anchor's do not require html/href...
3333         if (this.anchor === false) {
3334             cfg.html = html;
3335             cfg.href = this.href || '#';
3336         } else {
3337             cfg.name = this.anchor;
3338             if (this.html !== false || this.fa !== false) {
3339                 cfg.html = html;
3340             }
3341             if (this.href !== false) {
3342                 cfg.href = this.href;
3343             }
3344         }
3345         
3346         if(this.alt !== false){
3347             cfg.alt = this.alt;
3348         }
3349         
3350         
3351         if(this.target !== false) {
3352             cfg.target = this.target;
3353         }
3354         
3355         return cfg;
3356     },
3357     
3358     initEvents: function() {
3359         
3360         if(!this.href || this.preventDefault){
3361             this.el.on('click', this.onClick, this);
3362         }
3363     },
3364     
3365     onClick : function(e)
3366     {
3367         if(this.preventDefault){
3368             e.preventDefault();
3369         }
3370         //Roo.log('img onclick');
3371         this.fireEvent('click', this, e);
3372     }
3373    
3374 });
3375
3376  /*
3377  * - LGPL
3378  *
3379  * header
3380  * 
3381  */
3382
3383 /**
3384  * @class Roo.bootstrap.Header
3385  * @extends Roo.bootstrap.Component
3386  * @children Roo.bootstrap.Component
3387  * Bootstrap Header class
3388  *
3389  * 
3390  * @cfg {String} html content of header
3391  * @cfg {Number} level (1|2|3|4|5|6) default 1
3392  * 
3393  * @constructor
3394  * Create a new Header
3395  * @param {Object} config The config object
3396  */
3397
3398
3399 Roo.bootstrap.Header  = function(config){
3400     Roo.bootstrap.Header.superclass.constructor.call(this, config);
3401 };
3402
3403 Roo.extend(Roo.bootstrap.Header, Roo.bootstrap.Component,  {
3404     
3405     //href : false,
3406     html : false,
3407     level : 1,
3408     
3409     
3410     
3411     getAutoCreate : function(){
3412         
3413         
3414         
3415         var cfg = {
3416             tag: 'h' + (1 *this.level),
3417             html: this.html || ''
3418         } ;
3419         
3420         return cfg;
3421     }
3422    
3423 });
3424
3425  
3426
3427  /**
3428  * @class Roo.bootstrap.MenuMgr
3429  * @licence LGPL
3430  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
3431  * @static
3432  */
3433 Roo.bootstrap.menu.Manager = function(){
3434    var menus, active, groups = {}, attached = false, lastShow = new Date();
3435
3436    // private - called when first menu is created
3437    function init(){
3438        menus = {};
3439        active = new Roo.util.MixedCollection();
3440        Roo.get(document).addKeyListener(27, function(){
3441            if(active.length > 0){
3442                hideAll();
3443            }
3444        });
3445    }
3446
3447    // private
3448    function hideAll(){
3449        if(active && active.length > 0){
3450            var c = active.clone();
3451            c.each(function(m){
3452                m.hide();
3453            });
3454        }
3455    }
3456
3457    // private
3458    function onHide(m){
3459        active.remove(m);
3460        if(active.length < 1){
3461            Roo.get(document).un("mouseup", onMouseDown);
3462             
3463            attached = false;
3464        }
3465    }
3466
3467    // private
3468    function onShow(m){
3469        var last = active.last();
3470        lastShow = new Date();
3471        active.add(m);
3472        if(!attached){
3473           Roo.get(document).on("mouseup", onMouseDown);
3474            
3475            attached = true;
3476        }
3477        if(m.parentMenu){
3478           //m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
3479           m.parentMenu.activeChild = m;
3480        }else if(last && last.isVisible()){
3481           //m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
3482        }
3483    }
3484
3485    // private
3486    function onBeforeHide(m){
3487        if(m.activeChild){
3488            m.activeChild.hide();
3489        }
3490        if(m.autoHideTimer){
3491            clearTimeout(m.autoHideTimer);
3492            delete m.autoHideTimer;
3493        }
3494    }
3495
3496    // private
3497    function onBeforeShow(m){
3498        var pm = m.parentMenu;
3499        if(!pm && !m.allowOtherMenus){
3500            hideAll();
3501        }else if(pm && pm.activeChild && active != m){
3502            pm.activeChild.hide();
3503        }
3504    }
3505
3506    // private this should really trigger on mouseup..
3507    function onMouseDown(e){
3508         Roo.log("on Mouse Up");
3509         
3510         if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".dropdown-menu") && !e.getTarget('.user-menu')){
3511             Roo.log("MenuManager hideAll");
3512             hideAll();
3513             e.stopEvent();
3514         }
3515         
3516         
3517    }
3518
3519    // private
3520    function onBeforeCheck(mi, state){
3521        if(state){
3522            var g = groups[mi.group];
3523            for(var i = 0, l = g.length; i < l; i++){
3524                if(g[i] != mi){
3525                    g[i].setChecked(false);
3526                }
3527            }
3528        }
3529    }
3530
3531    return {
3532
3533        /**
3534         * Hides all menus that are currently visible
3535         */
3536        hideAll : function(){
3537             hideAll();  
3538        },
3539
3540        // private
3541        register : function(menu){
3542            if(!menus){
3543                init();
3544            }
3545            menus[menu.id] = menu;
3546            menu.on("beforehide", onBeforeHide);
3547            menu.on("hide", onHide);
3548            menu.on("beforeshow", onBeforeShow);
3549            menu.on("show", onShow);
3550            var g = menu.group;
3551            if(g && menu.events["checkchange"]){
3552                if(!groups[g]){
3553                    groups[g] = [];
3554                }
3555                groups[g].push(menu);
3556                menu.on("checkchange", onCheck);
3557            }
3558        },
3559
3560         /**
3561          * Returns a {@link Roo.menu.Menu} object
3562          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
3563          * be used to generate and return a new Menu instance.
3564          */
3565        get : function(menu){
3566            if(typeof menu == "string"){ // menu id
3567                return menus[menu];
3568            }else if(menu.events){  // menu instance
3569                return menu;
3570            }
3571            /*else if(typeof menu.length == 'number'){ // array of menu items?
3572                return new Roo.bootstrap.Menu({items:menu});
3573            }else{ // otherwise, must be a config
3574                return new Roo.bootstrap.Menu(menu);
3575            }
3576            */
3577            return false;
3578        },
3579
3580        // private
3581        unregister : function(menu){
3582            delete menus[menu.id];
3583            menu.un("beforehide", onBeforeHide);
3584            menu.un("hide", onHide);
3585            menu.un("beforeshow", onBeforeShow);
3586            menu.un("show", onShow);
3587            var g = menu.group;
3588            if(g && menu.events["checkchange"]){
3589                groups[g].remove(menu);
3590                menu.un("checkchange", onCheck);
3591            }
3592        },
3593
3594        // private
3595        registerCheckable : function(menuItem){
3596            var g = menuItem.group;
3597            if(g){
3598                if(!groups[g]){
3599                    groups[g] = [];
3600                }
3601                groups[g].push(menuItem);
3602                menuItem.on("beforecheckchange", onBeforeCheck);
3603            }
3604        },
3605
3606        // private
3607        unregisterCheckable : function(menuItem){
3608            var g = menuItem.group;
3609            if(g){
3610                groups[g].remove(menuItem);
3611                menuItem.un("beforecheckchange", onBeforeCheck);
3612            }
3613        }
3614    };
3615 }(); 
3616 /**
3617  * @class Roo.bootstrap.menu.Menu
3618  * @extends Roo.bootstrap.Component
3619  * @licence LGPL
3620  * @children Roo.bootstrap.menu.Item Roo.bootstrap.menu.Separator
3621  * @parent none
3622  * Bootstrap Menu class - container for MenuItems - normally has to be added to a object that supports the menu property
3623  * 
3624  * @cfg {String} type (dropdown|treeview|submenu) type of menu
3625  * @cfg {bool} hidden  if the menu should be hidden when rendered.
3626  * @cfg {bool} stopEvent (true|false)  Stop event after trigger press (default true)
3627  * @cfg {bool} isLink (true|false)  the menu has link disable auto expand and collaspe (default false)
3628 * @cfg {bool} hideTrigger (true|false)  default false - hide the carret for trigger.
3629 * @cfg {String} align  default tl-bl? == below  - how the menu should be aligned. 
3630  
3631  * @constructor
3632  * Create a new Menu
3633  * @param {Object} config The config objectQ
3634  */
3635
3636
3637 Roo.bootstrap.menu.Menu = function(config){
3638     
3639     if (config.type == 'treeview') {
3640         // normally menu's are drawn attached to the document to handle layering etc..
3641         // however treeview (used by the docs menu is drawn into the parent element)
3642         this.container_method = 'getChildContainer'; 
3643     }
3644     
3645     Roo.bootstrap.menu.Menu.superclass.constructor.call(this, config);
3646     if (this.registerMenu && this.type != 'treeview')  {
3647         Roo.bootstrap.menu.Manager.register(this);
3648     }
3649     
3650     
3651     this.addEvents({
3652         /**
3653          * @event beforeshow
3654          * Fires before this menu is displayed (return false to block)
3655          * @param {Roo.menu.Menu} this
3656          */
3657         beforeshow : true,
3658         /**
3659          * @event beforehide
3660          * Fires before this menu is hidden (return false to block)
3661          * @param {Roo.menu.Menu} this
3662          */
3663         beforehide : true,
3664         /**
3665          * @event show
3666          * Fires after this menu is displayed
3667          * @param {Roo.menu.Menu} this
3668          */
3669         show : true,
3670         /**
3671          * @event hide
3672          * Fires after this menu is hidden
3673          * @param {Roo.menu.Menu} this
3674          */
3675         hide : true,
3676         /**
3677          * @event click
3678          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
3679          * @param {Roo.menu.Menu} this
3680          * @param {Roo.menu.Item} menuItem The menu item that was clicked
3681          * @param {Roo.EventObject} e
3682          */
3683         click : true,
3684         /**
3685          * @event mouseover
3686          * Fires when the mouse is hovering over this menu
3687          * @param {Roo.menu.Menu} this
3688          * @param {Roo.EventObject} e
3689          * @param {Roo.menu.Item} menuItem The menu item that was clicked
3690          */
3691         mouseover : true,
3692         /**
3693          * @event mouseout
3694          * Fires when the mouse exits this menu
3695          * @param {Roo.menu.Menu} this
3696          * @param {Roo.EventObject} e
3697          * @param {Roo.menu.Item} menuItem The menu item that was clicked
3698          */
3699         mouseout : true,
3700         /**
3701          * @event itemclick
3702          * Fires when a menu item contained in this menu is clicked
3703          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
3704          * @param {Roo.EventObject} e
3705          */
3706         itemclick: true
3707     });
3708     this.menuitems = new Roo.util.MixedCollection(false, function(o) { return o.el.id; });
3709 };
3710
3711 Roo.extend(Roo.bootstrap.menu.Menu, Roo.bootstrap.Component,  {
3712     
3713    /// html : false,
3714    
3715     triggerEl : false,  // is this set by component builder? -- it should really be fetched from parent()???
3716     type: false,
3717     /**
3718      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
3719      */
3720     registerMenu : true,
3721     
3722     menuItems :false, // stores the menu items..
3723     
3724     hidden:true,
3725         
3726     parentMenu : false,
3727     
3728     stopEvent : true,
3729     
3730     isLink : false,
3731     
3732     container_method : 'getDocumentBody', // so the menu is rendered on the body and zIndex works.
3733     
3734     hideTrigger : false,
3735     
3736     align : 'tl-bl?',
3737     
3738     
3739     getChildContainer : function() {
3740         return this.el;  
3741     },
3742     
3743     getAutoCreate : function(){
3744          
3745         //if (['right'].indexOf(this.align)!==-1) {
3746         //    cfg.cn[1].cls += ' pull-right'
3747         //}
3748          
3749         var cfg = {
3750             tag : 'ul',
3751             cls : 'dropdown-menu shadow' ,
3752             style : 'z-index:1000'
3753             
3754         };
3755         
3756         if (this.type === 'submenu') {
3757             cfg.cls = 'submenu active';
3758         }
3759         if (this.type === 'treeview') {
3760             cfg.cls = 'treeview-menu';
3761         }
3762         
3763         return cfg;
3764     },
3765     initEvents : function() {
3766         
3767        // Roo.log("ADD event");
3768        // Roo.log(this.triggerEl.dom);
3769         if (this.triggerEl) {
3770             
3771             this.triggerEl.on('click', this.onTriggerClick, this);
3772             
3773             this.triggerEl.on(Roo.isTouch ? 'touchstart' : 'mouseup', this.onTriggerPress, this);
3774             
3775             if (!this.hideTrigger) {
3776                 if (this.triggerEl.hasClass('nav-item') && this.triggerEl.select('.nav-link',true).length) {
3777                     // dropdown toggle on the 'a' in BS4?
3778                     this.triggerEl.select('.nav-link',true).first().addClass('dropdown-toggle');
3779                 } else {
3780                     this.triggerEl.addClass('dropdown-toggle');
3781                 }
3782             }
3783         }
3784         
3785         if (Roo.isTouch) {
3786             this.el.on('touchstart'  , this.onTouch, this);
3787         }
3788         this.el.on('click' , this.onClick, this);
3789
3790         this.el.on("mouseover", this.onMouseOver, this);
3791         this.el.on("mouseout", this.onMouseOut, this);
3792         
3793     },
3794     
3795     findTargetItem : function(e)
3796     {
3797         var t = e.getTarget(".dropdown-menu-item", this.el,  true);
3798         if(!t){
3799             return false;
3800         }
3801         //Roo.log(t);         Roo.log(t.id);
3802         if(t && t.id){
3803             //Roo.log(this.menuitems);
3804             return this.menuitems.get(t.id);
3805             
3806             //return this.items.get(t.menuItemId);
3807         }
3808         
3809         return false;
3810     },
3811     
3812     onTouch : function(e) 
3813     {
3814         Roo.log("menu.onTouch");
3815         //e.stopEvent(); this make the user popdown broken
3816         this.onClick(e);
3817     },
3818     
3819     onClick : function(e)
3820     {
3821         Roo.log("menu.onClick");
3822         
3823         var t = this.findTargetItem(e);
3824         if(!t || t.isContainer){
3825             return;
3826         }
3827         Roo.log(e);
3828         /*
3829         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
3830             if(t == this.activeItem && t.shouldDeactivate(e)){
3831                 this.activeItem.deactivate();
3832                 delete this.activeItem;
3833                 return;
3834             }
3835             if(t.canActivate){
3836                 this.setActiveItem(t, true);
3837             }
3838             return;
3839             
3840             
3841         }
3842         */
3843        
3844         Roo.log('pass click event');
3845         
3846         t.onClick(e);
3847         
3848         this.fireEvent("click", this, t, e);
3849         
3850         var _this = this;
3851         
3852         if(!t.href.length || t.href == '#'){
3853             (function() { _this.hide(); }).defer(100);
3854         }
3855         
3856     },
3857     
3858     onMouseOver : function(e){
3859         var t  = this.findTargetItem(e);
3860         //Roo.log(t);
3861         //if(t){
3862         //    if(t.canActivate && !t.disabled){
3863         //        this.setActiveItem(t, true);
3864         //    }
3865         //}
3866         
3867         this.fireEvent("mouseover", this, e, t);
3868     },
3869     isVisible : function(){
3870         return !this.hidden;
3871     },
3872     onMouseOut : function(e){
3873         var t  = this.findTargetItem(e);
3874         
3875         //if(t ){
3876         //    if(t == this.activeItem && t.shouldDeactivate(e)){
3877         //        this.activeItem.deactivate();
3878         //        delete this.activeItem;
3879         //    }
3880         //}
3881         this.fireEvent("mouseout", this, e, t);
3882     },
3883     
3884     
3885     /**
3886      * Displays this menu relative to another element
3887      * @param {String/HTMLElement/Roo.Element} element The element to align to
3888      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
3889      * the element (defaults to this.defaultAlign)
3890      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
3891      */
3892     show : function(el, pos, parentMenu)
3893     {
3894         if (false === this.fireEvent("beforeshow", this)) {
3895             Roo.log("show canceled");
3896             return;
3897         }
3898         this.parentMenu = parentMenu;
3899         if(!this.el){
3900             this.render();
3901         }
3902         this.el.addClass('show'); // show otherwise we do not know how big we are..
3903          
3904         var xy = this.el.getAlignToXY(el, pos);
3905         
3906         // bl-tl << left align  below
3907         // tl-bl << left align 
3908         
3909         if(this.el.getWidth() + xy[0] >= Roo.lib.Dom.getViewWidth()){
3910             // if it goes to far to the right.. -> align left.
3911             xy = this.el.getAlignToXY(el, this.align.replace('/l/g', 'r'))
3912         }
3913         if(xy[0] < 0){
3914             // was left align - go right?
3915             xy = this.el.getAlignToXY(el, this.align.replace('/r/g', 'l'))
3916         }
3917         
3918         // goes down the bottom
3919         if(this.el.getHeight() + xy[1] >= Roo.lib.Dom.getViewHeight() ||
3920            xy[1]  < 0 ){
3921             var a = this.align.replace('?', '').split('-');
3922             xy = this.el.getAlignToXY(el, a[1]  + '-' + a[0] + '?')
3923             
3924         }
3925         
3926         this.showAt(  xy , parentMenu, false);
3927     },
3928      /**
3929      * Displays this menu at a specific xy position
3930      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
3931      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
3932      */
3933     showAt : function(xy, parentMenu, /* private: */_e){
3934         this.parentMenu = parentMenu;
3935         if(!this.el){
3936             this.render();
3937         }
3938         if(_e !== false){
3939             this.fireEvent("beforeshow", this);
3940             //xy = this.el.adjustForConstraints(xy);
3941         }
3942         
3943         //this.el.show();
3944         this.hideMenuItems();
3945         this.hidden = false;
3946         if (this.triggerEl) {
3947             this.triggerEl.addClass('open');
3948         }
3949         
3950         this.el.addClass('show');
3951         
3952         
3953         
3954         // reassign x when hitting right
3955         
3956         // reassign y when hitting bottom
3957         
3958         // but the list may align on trigger left or trigger top... should it be a properity?
3959         
3960         if(this.el.getStyle('top') != 'auto' && this.el.getStyle('top').slice(-1) != "%"){
3961             this.el.setXY(xy);
3962         }
3963         
3964         this.focus();
3965         this.fireEvent("show", this);
3966     },
3967     
3968     focus : function(){
3969         return;
3970         if(!this.hidden){
3971             this.doFocus.defer(50, this);
3972         }
3973     },
3974
3975     doFocus : function(){
3976         if(!this.hidden){
3977             this.focusEl.focus();
3978         }
3979     },
3980
3981     /**
3982      * Hides this menu and optionally all parent menus
3983      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
3984      */
3985     hide : function(deep)
3986     {
3987         if (false === this.fireEvent("beforehide", this)) {
3988             Roo.log("hide canceled");
3989             return;
3990         }
3991         this.hideMenuItems();
3992         if(this.el && this.isVisible()){
3993            
3994             if(this.activeItem){
3995                 this.activeItem.deactivate();
3996                 this.activeItem = null;
3997             }
3998             if (this.triggerEl) {
3999                 this.triggerEl.removeClass('open');
4000             }
4001             
4002             this.el.removeClass('show');
4003             this.hidden = true;
4004             this.fireEvent("hide", this);
4005         }
4006         if(deep === true && this.parentMenu){
4007             this.parentMenu.hide(true);
4008         }
4009     },
4010     
4011     onTriggerClick : function(e)
4012     {
4013         Roo.log('trigger click');
4014         
4015         var target = e.getTarget();
4016         
4017         Roo.log(target.nodeName.toLowerCase());
4018         
4019         if(target.nodeName.toLowerCase() === 'i'){
4020             e.preventDefault();
4021         }
4022         
4023     },
4024     
4025     onTriggerPress  : function(e)
4026     {
4027         Roo.log('trigger press');
4028         //Roo.log(e.getTarget());
4029        // Roo.log(this.triggerEl.dom);
4030        
4031         // trigger only occurs on normal menu's -- if it's a treeview or dropdown... do not hide/show..
4032         var pel = Roo.get(e.getTarget());
4033         if (pel.findParent('.dropdown-menu') || pel.findParent('.treeview-menu') ) {
4034             Roo.log('is treeview or dropdown?');
4035             return;
4036         }
4037         
4038         if(e.getTarget().nodeName.toLowerCase() !== 'i' && this.isLink){
4039             return;
4040         }
4041         
4042         if (this.isVisible()) {
4043             Roo.log('hide');
4044             this.hide();
4045         } else {
4046             Roo.log('show');
4047             
4048             this.show(this.triggerEl, this.align, false);
4049         }
4050         
4051         if(this.stopEvent || e.getTarget().nodeName.toLowerCase() === 'i'){
4052             e.stopEvent();
4053         }
4054         
4055     },
4056        
4057     
4058     hideMenuItems : function()
4059     {
4060         Roo.log("hide Menu Items");
4061         if (!this.el) { 
4062             return;
4063         }
4064         
4065         this.el.select('.open',true).each(function(aa) {
4066             
4067             aa.removeClass('open');
4068          
4069         });
4070     },
4071     addxtypeChild : function (tree, cntr) {
4072         var comp= Roo.bootstrap.menu.Menu.superclass.addxtypeChild.call(this, tree, cntr);
4073           
4074         this.menuitems.add(comp);
4075         return comp;
4076
4077     },
4078     getEl : function()
4079     {
4080         Roo.log(this.el);
4081         return this.el;
4082     },
4083     
4084     clear : function()
4085     {
4086         this.getEl().dom.innerHTML = '';
4087         this.menuitems.clear();
4088     }
4089 });
4090
4091  
4092  /**
4093  * @class Roo.bootstrap.menu.Item
4094  * @extends Roo.bootstrap.Component
4095  * @children  Roo.bootstrap.Button Roo.bootstrap.ButtonUploader Roo.bootstrap.Row Roo.bootstrap.Column Roo.bootstrap.Container
4096  * @parent Roo.bootstrap.menu.Menu
4097  * @licence LGPL
4098  * Bootstrap MenuItem class
4099  * 
4100  * @cfg {String} html the menu label
4101  * @cfg {String} href the link
4102  * @cfg {Boolean} preventDefault do not trigger A href on clicks (default false).
4103  * @cfg {Boolean} isContainer is it a container - just returns a drop down item..
4104  * @cfg {Boolean} active  used on sidebars to highlight active itesm
4105  * @cfg {String} fa favicon to show on left of menu item.
4106  * @cfg {Roo.bootsrap.Menu} menu the child menu.
4107  * 
4108  * 
4109  * @constructor
4110  * Create a new MenuItem
4111  * @param {Object} config The config object
4112  */
4113
4114
4115 Roo.bootstrap.menu.Item = function(config){
4116     Roo.bootstrap.menu.Item.superclass.constructor.call(this, config);
4117     this.addEvents({
4118         // raw events
4119         /**
4120          * @event click
4121          * The raw click event for the entire grid.
4122          * @param {Roo.bootstrap.menu.Item} this
4123          * @param {Roo.EventObject} e
4124          */
4125         "click" : true
4126     });
4127 };
4128
4129 Roo.extend(Roo.bootstrap.menu.Item, Roo.bootstrap.Component,  {
4130     
4131     href : false,
4132     html : false,
4133     preventDefault: false,
4134     isContainer : false,
4135     active : false,
4136     fa: false,
4137     
4138     getAutoCreate : function(){
4139         
4140         if(this.isContainer){
4141             return {
4142                 tag: 'li',
4143                 cls: 'dropdown-menu-item '
4144             };
4145         }
4146         var ctag = {
4147             tag: 'span',
4148             html: 'Link'
4149         };
4150         
4151         var anc = {
4152             tag : 'a',
4153             cls : 'dropdown-item',
4154             href : '#',
4155             cn : [  ]
4156         };
4157         
4158         if (this.fa !== false) {
4159             anc.cn.push({
4160                 tag : 'i',
4161                 cls : 'fa fa-' + this.fa
4162             });
4163         }
4164         
4165         anc.cn.push(ctag);
4166         
4167         
4168         var cfg= {
4169             tag: 'li',
4170             cls: 'dropdown-menu-item',
4171             cn: [ anc ]
4172         };
4173         if (this.parent().type == 'treeview') {
4174             cfg.cls = 'treeview-menu';
4175         }
4176         if (this.active) {
4177             cfg.cls += ' active';
4178         }
4179         
4180         
4181         
4182         anc.href = this.href || cfg.cn[0].href ;
4183         ctag.html = this.html || cfg.cn[0].html ;
4184         return cfg;
4185     },
4186     
4187     initEvents: function()
4188     {
4189         if (this.parent().type == 'treeview') {
4190             this.el.select('a').on('click', this.onClick, this);
4191         }
4192         
4193         if (this.menu) {
4194             this.menu.parentType = this.xtype;
4195             this.menu.triggerEl = this.el;
4196             this.menu = this.addxtype(Roo.apply({}, this.menu));
4197         }
4198         
4199     },
4200     onClick : function(e)
4201     {
4202         //Roo.log('item on click ');
4203         
4204         if(this.href === false || this.preventDefault){
4205             e.preventDefault();
4206         }
4207         //this.parent().hideMenuItems();
4208         
4209         this.fireEvent('click', this, e);
4210     },
4211     getEl : function()
4212     {
4213         return this.el;
4214     } 
4215 });
4216
4217  
4218
4219  
4220
4221   
4222 /**
4223  * @class Roo.bootstrap.menu.Separator
4224  * @extends Roo.bootstrap.Component
4225  * @licence LGPL
4226  * @parent Roo.bootstrap.menu.Menu
4227  * Bootstrap Separator class
4228  * 
4229  * @constructor
4230  * Create a new Separator
4231  * @param {Object} config The config object
4232  */
4233
4234
4235 Roo.bootstrap.menu.Separator = function(config){
4236     Roo.bootstrap.menu.Separator.superclass.constructor.call(this, config);
4237 };
4238
4239 Roo.extend(Roo.bootstrap.menu.Separator, Roo.bootstrap.Component,  {
4240     
4241     getAutoCreate : function(){
4242         var cfg = {
4243             tag : 'li',
4244             cls: 'dropdown-divider divider'
4245         };
4246         
4247         return cfg;
4248     }
4249    
4250 });
4251
4252  
4253
4254  
4255 /*
4256 * Licence: LGPL
4257 */
4258
4259 /**
4260  * @class Roo.bootstrap.Modal
4261  * @extends Roo.bootstrap.Component
4262  * @parent none builder
4263  * @children Roo.bootstrap.Component
4264  * Bootstrap Modal class
4265  * @cfg {String} title Title of dialog
4266  * @cfg {String} html - the body of the dialog (for simple ones) - you can also use template..
4267  * @cfg {Roo.Template} tmpl - a template with variables. to use it, add a handler in show:method  adn
4268  * @cfg {Boolean} specificTitle default false
4269  * @cfg {Roo.bootstrap.Button} buttons[] Array of buttons or standard button set..
4270  * @cfg {String} buttonPosition (left|right|center) default right (DEPRICATED) - use mr-auto on buttons to put them on the left
4271  * @cfg {Boolean} animate default true
4272  * @cfg {Boolean} allow_close default true
4273  * @cfg {Boolean} fitwindow default false
4274  * @cfg {Boolean} bodyOverflow should the body element have overflow auto added default false
4275  * @cfg {Number} width fixed width - usefull for chrome extension only really.
4276  * @cfg {Number} height fixed height - usefull for chrome extension only really.
4277  * @cfg {String} size (sm|lg|xl) default empty
4278  * @cfg {Number} max_width set the max width of modal
4279  * @cfg {Boolean} editableTitle can the title be edited
4280
4281  *
4282  *
4283  * @constructor
4284  * Create a new Modal Dialog
4285  * @param {Object} config The config object
4286  */
4287
4288 Roo.bootstrap.Modal = function(config){
4289     Roo.bootstrap.Modal.superclass.constructor.call(this, config);
4290     this.addEvents({
4291         // raw events
4292         /**
4293          * @event btnclick
4294          * The raw btnclick event for the button
4295          * @param {Roo.EventObject} e
4296          */
4297         "btnclick" : true,
4298         /**
4299          * @event resize
4300          * Fire when dialog resize
4301          * @param {Roo.bootstrap.Modal} this
4302          * @param {Roo.EventObject} e
4303          */
4304         "resize" : true,
4305         /**
4306          * @event titlechanged
4307          * Fire when the editable title has been changed
4308          * @param {Roo.bootstrap.Modal} this
4309          * @param {Roo.EventObject} value
4310          */
4311         "titlechanged" : true 
4312         
4313     });
4314     this.buttons = this.buttons || [];
4315
4316     if (this.tmpl) {
4317         this.tmpl = Roo.factory(this.tmpl);
4318     }
4319
4320 };
4321
4322 Roo.extend(Roo.bootstrap.Modal, Roo.bootstrap.Component,  {
4323
4324     title : 'test dialog',
4325
4326     buttons : false,
4327
4328     // set on load...
4329
4330     html: false,
4331
4332     tmp: false,
4333
4334     specificTitle: false,
4335
4336     buttonPosition: 'right',
4337
4338     allow_close : true,
4339
4340     animate : true,
4341
4342     fitwindow: false,
4343     
4344      // private
4345     dialogEl: false,
4346     bodyEl:  false,
4347     footerEl:  false,
4348     titleEl:  false,
4349     closeEl:  false,
4350
4351     size: '',
4352     
4353     max_width: 0,
4354     
4355     max_height: 0,
4356     
4357     fit_content: false,
4358     editableTitle  : false,
4359
4360     onRender : function(ct, position)
4361     {
4362         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
4363
4364         if(!this.el){
4365             var cfg = Roo.apply({},  this.getAutoCreate());
4366             cfg.id = Roo.id();
4367             //if(!cfg.name){
4368             //    cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
4369             //}
4370             //if (!cfg.name.length) {
4371             //    delete cfg.name;
4372            // }
4373             if (this.cls) {
4374                 cfg.cls += ' ' + this.cls;
4375             }
4376             if (this.style) {
4377                 cfg.style = this.style;
4378             }
4379             this.el = Roo.get(document.body).createChild(cfg, position);
4380         }
4381         //var type = this.el.dom.type;
4382
4383
4384         if(this.tabIndex !== undefined){
4385             this.el.dom.setAttribute('tabIndex', this.tabIndex);
4386         }
4387
4388         this.dialogEl = this.el.select('.modal-dialog',true).first();
4389         this.bodyEl = this.el.select('.modal-body',true).first();
4390         this.closeEl = this.el.select('.modal-header .close', true).first();
4391         this.headerEl = this.el.select('.modal-header',true).first();
4392         this.titleEl = this.el.select('.modal-title',true).first();
4393         this.footerEl = this.el.select('.modal-footer',true).first();
4394
4395         this.maskEl = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
4396         
4397         //this.el.addClass("x-dlg-modal");
4398
4399         if (this.buttons.length) {
4400             Roo.each(this.buttons, function(bb) {
4401                 var b = Roo.apply({}, bb);
4402                 b.xns = b.xns || Roo.bootstrap;
4403                 b.xtype = b.xtype || 'Button';
4404                 if (typeof(b.listeners) == 'undefined') {
4405                     b.listeners = { click : this.onButtonClick.createDelegate(this)  };
4406                 }
4407
4408                 var btn = Roo.factory(b);
4409
4410                 btn.render(this.getButtonContainer());
4411
4412             },this);
4413         }
4414         // render the children.
4415         var nitems = [];
4416
4417         if(typeof(this.items) != 'undefined'){
4418             var items = this.items;
4419             delete this.items;
4420
4421             for(var i =0;i < items.length;i++) {
4422                 // we force children not to montor widnow resize  - as we do that for them.
4423                 items[i].monitorWindowResize = false;
4424                 nitems.push(this.addxtype(Roo.apply({}, items[i])));
4425             }
4426         }
4427
4428         this.items = nitems;
4429
4430         // where are these used - they used to be body/close/footer
4431
4432
4433         this.initEvents();
4434         //this.el.addClass([this.fieldClass, this.cls]);
4435
4436     },
4437
4438     getAutoCreate : function()
4439     {
4440         // we will default to modal-body-overflow - might need to remove or make optional later.
4441         var bdy = {
4442                 cls : 'modal-body ' + (this.bodyOverflow ? 'overflow-auto' : ''), 
4443                 html : this.html || ''
4444         };
4445
4446         var title = {
4447             tag: 'h5',
4448             cls : 'modal-title',
4449             html : this.title
4450         };
4451
4452         if(this.specificTitle){ // WTF is this?
4453             title = this.title;
4454         }
4455
4456         var header = [];
4457         if (this.allow_close && Roo.bootstrap.version == 3) {
4458             header.push({
4459                 tag: 'button',
4460                 cls : 'close',
4461                 html : '&times'
4462             });
4463         }
4464
4465         header.push(title);
4466
4467         if (this.editableTitle) {
4468             header.push({
4469                 cls: 'form-control roo-editable-title d-none',
4470                 tag: 'input',
4471                 type: 'text'
4472             });
4473         }
4474         
4475         if (this.allow_close && Roo.bootstrap.version == 4) {
4476             header.push({
4477                 tag: 'button',
4478                 cls : 'close',
4479                 html : '&times'
4480             });
4481         }
4482         
4483         var size = '';
4484
4485         if(this.size.length){
4486             size = 'modal-' + this.size;
4487         }
4488         
4489         var footer = Roo.bootstrap.version == 3 ?
4490             {
4491                 cls : 'modal-footer',
4492                 cn : [
4493                     {
4494                         tag: 'div',
4495                         cls: 'btn-' + this.buttonPosition
4496                     }
4497                 ]
4498
4499             } :
4500             {  // BS4 uses mr-auto on left buttons....
4501                 cls : 'modal-footer'
4502             };
4503
4504             
4505
4506         
4507         
4508         var modal = {
4509             cls: "modal",
4510              cn : [
4511                 {
4512                     cls: "modal-dialog " + size,
4513                     cn : [
4514                         {
4515                             cls : "modal-content",
4516                             cn : [
4517                                 {
4518                                     cls : 'modal-header',
4519                                     cn : header
4520                                 },
4521                                 bdy,
4522                                 footer
4523                             ]
4524
4525                         }
4526                     ]
4527
4528                 }
4529             ]
4530         };
4531
4532         if(this.animate){
4533             modal.cls += ' fade';
4534         }
4535
4536         return modal;
4537
4538     },
4539     getChildContainer : function() {
4540
4541          return this.bodyEl;
4542
4543     },
4544     getButtonContainer : function() {
4545         
4546          return Roo.bootstrap.version == 4 ?
4547             this.el.select('.modal-footer',true).first()
4548             : this.el.select('.modal-footer div',true).first();
4549
4550     },
4551     
4552     closeClick : function()
4553     {
4554         this.hide();
4555     },
4556     
4557     initEvents : function()
4558     {
4559         if (this.allow_close) {
4560             this.closeEl.on('click', this.closeClick, this);
4561         }
4562         Roo.EventManager.onWindowResize(this.resize, this, true);
4563         if (this.editableTitle) {
4564             this.headerEditEl =  this.headerEl.select('.form-control',true).first();
4565             this.headerEl.on('click', function() { this.toggleHeaderInput(true) } , this);
4566             this.headerEditEl.on('keyup', function(e) {
4567                     if([  e.RETURN , e.TAB , e.ESC ].indexOf(e.keyCode) > -1) {
4568                         this.toggleHeaderInput(false)
4569                     }
4570                 }, this);
4571             this.headerEditEl.on('blur', function(e) {
4572                 this.toggleHeaderInput(false)
4573             },this);
4574         }
4575
4576     },
4577   
4578
4579     resize : function()
4580     {
4581         this.maskEl.setSize(
4582             Roo.lib.Dom.getViewWidth(true),
4583             Roo.lib.Dom.getViewHeight(true)
4584         );
4585         
4586         if (this.fitwindow) {
4587             
4588            this.dialogEl.setStyle( { 'max-width' : '100%' });
4589             this.setSize(
4590                 this.width || Roo.lib.Dom.getViewportWidth(true) - 30,
4591                 this.height || Roo.lib.Dom.getViewportHeight(true) // catering margin-top 30 margin-bottom 30
4592             );
4593             return;
4594         }
4595         
4596         if(this.max_width !== 0) {
4597             
4598             var w = Math.min(this.max_width, Roo.lib.Dom.getViewportWidth(true) - 30);
4599             
4600             if(this.height) {
4601                 this.setSize(w, this.height);
4602                 return;
4603             }
4604             
4605             if(this.max_height) {
4606                 this.setSize(w,Math.min(
4607                     this.max_height,
4608                     Roo.lib.Dom.getViewportHeight(true) - 60
4609                 ));
4610                 
4611                 return;
4612             }
4613             
4614             if(!this.fit_content) {
4615                 this.setSize(w, Roo.lib.Dom.getViewportHeight(true) - 60);
4616                 return;
4617             }
4618             
4619             this.setSize(w, Math.min(
4620                 60 +
4621                 this.headerEl.getHeight() + 
4622                 this.footerEl.getHeight() + 
4623                 this.getChildHeight(this.bodyEl.dom.childNodes),
4624                 Roo.lib.Dom.getViewportHeight(true) - 60)
4625             );
4626         }
4627         
4628     },
4629
4630     setSize : function(w,h)
4631     {
4632         if (!w && !h) {
4633             return;
4634         }
4635         
4636         this.resizeTo(w,h);
4637         // any layout/border etc.. resize..
4638         (function () {
4639             this.items.forEach( function(e) {
4640                 e.layout ? e.layout() : false;
4641
4642             });
4643         }).defer(100,this);
4644         
4645     },
4646
4647     show : function() {
4648
4649         if (!this.rendered) {
4650             this.render();
4651         }
4652         this.toggleHeaderInput(false);
4653         //this.el.setStyle('display', 'block');
4654         this.el.removeClass('hideing');
4655         this.el.dom.style.display='block';
4656         
4657         Roo.get(document.body).addClass('modal-open');
4658  
4659         if(this.animate){  // element has 'fade'  - so stuff happens after .3s ?- not sure why the delay?
4660             
4661             (function(){
4662                 this.el.addClass('show');
4663                 this.el.addClass('in');
4664             }).defer(50, this);
4665         }else{
4666             this.el.addClass('show');
4667             this.el.addClass('in');
4668         }
4669
4670         // not sure how we can show data in here..
4671         //if (this.tmpl) {
4672         //    this.getChildContainer().dom.innerHTML = this.tmpl.applyTemplate(this);
4673         //}
4674
4675         Roo.get(document.body).addClass("x-body-masked");
4676         
4677         this.maskEl.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
4678         this.maskEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
4679         this.maskEl.dom.style.display = 'block';
4680         this.maskEl.addClass('show');
4681         
4682         
4683         this.resize();
4684         
4685         this.fireEvent('show', this);
4686
4687         // set zindex here - otherwise it appears to be ignored...
4688         this.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
4689         
4690         
4691         // this is for children that are... layout.Border 
4692         (function () {
4693             this.items.forEach( function(e) {
4694                 e.layout ? e.layout() : false;
4695
4696             });
4697         }).defer(100,this);
4698
4699     },
4700     hide : function()
4701     {
4702         if(this.fireEvent("beforehide", this) !== false){
4703             
4704             this.maskEl.removeClass('show');
4705             
4706             this.maskEl.dom.style.display = '';
4707             Roo.get(document.body).removeClass("x-body-masked");
4708             this.el.removeClass('in');
4709             this.el.select('.modal-dialog', true).first().setStyle('transform','');
4710
4711             if(this.animate){ // why
4712                 this.el.addClass('hideing');
4713                 this.el.removeClass('show');
4714                 (function(){
4715                     if (!this.el.hasClass('hideing')) {
4716                         return; // it's been shown again...
4717                     }
4718                     
4719                     this.el.dom.style.display='';
4720
4721                     Roo.get(document.body).removeClass('modal-open');
4722                     this.el.removeClass('hideing');
4723                 }).defer(150,this);
4724                 
4725             }else{
4726                 this.el.removeClass('show');
4727                 this.el.dom.style.display='';
4728                 Roo.get(document.body).removeClass('modal-open');
4729
4730             }
4731             this.fireEvent('hide', this);
4732         }
4733     },
4734     isVisible : function()
4735     {
4736         
4737         return this.el.hasClass('show') && !this.el.hasClass('hideing');
4738         
4739     },
4740
4741     addButton : function(str, cb)
4742     {
4743
4744
4745         var b = Roo.apply({}, { html : str } );
4746         b.xns = b.xns || Roo.bootstrap;
4747         b.xtype = b.xtype || 'Button';
4748         if (typeof(b.listeners) == 'undefined') {
4749             b.listeners = { click : cb.createDelegate(this)  };
4750         }
4751
4752         var btn = Roo.factory(b);
4753
4754         btn.render(this.getButtonContainer());
4755
4756         return btn;
4757
4758     },
4759
4760     setDefaultButton : function(btn)
4761     {
4762         //this.el.select('.modal-footer').()
4763     },
4764
4765     resizeTo: function(w,h)
4766     {
4767         this.dialogEl.setWidth(w);
4768         
4769         var diff = this.headerEl.getHeight() + this.footerEl.getHeight() + 60; // dialog margin-bottom: 30  
4770
4771         this.bodyEl.setHeight(h - diff);
4772         
4773         this.fireEvent('resize', this);
4774     },
4775     
4776     setContentSize  : function(w, h)
4777     {
4778
4779     },
4780     onButtonClick: function(btn,e)
4781     {
4782         //Roo.log([a,b,c]);
4783         this.fireEvent('btnclick', btn.name, e);
4784     },
4785      /**
4786      * Set the title of the Dialog
4787      * @param {String} str new Title
4788      */
4789     setTitle: function(str) {
4790         this.titleEl.dom.innerHTML = str;
4791         this.title = str;
4792     },
4793     /**
4794      * Set the body of the Dialog
4795      * @param {String} str new Title
4796      */
4797     setBody: function(str) {
4798         this.bodyEl.dom.innerHTML = str;
4799     },
4800     /**
4801      * Set the body of the Dialog using the template
4802      * @param {Obj} data - apply this data to the template and replace the body contents.
4803      */
4804     applyBody: function(obj)
4805     {
4806         if (!this.tmpl) {
4807             Roo.log("Error - using apply Body without a template");
4808             //code
4809         }
4810         this.tmpl.overwrite(this.bodyEl, obj);
4811     },
4812     
4813     getChildHeight : function(child_nodes)
4814     {
4815         if(
4816             !child_nodes ||
4817             child_nodes.length == 0
4818         ) {
4819             return 0;
4820         }
4821         
4822         var child_height = 0;
4823         
4824         for(var i = 0; i < child_nodes.length; i++) {
4825             
4826             /*
4827             * for modal with tabs...
4828             if(child_nodes[i].classList.contains('roo-layout-panel')) {
4829                 
4830                 var layout_childs = child_nodes[i].childNodes;
4831                 
4832                 for(var j = 0; j < layout_childs.length; j++) {
4833                     
4834                     if(layout_childs[j].classList.contains('roo-layout-panel-body')) {
4835                         
4836                         var layout_body_childs = layout_childs[j].childNodes;
4837                         
4838                         for(var k = 0; k < layout_body_childs.length; k++) {
4839                             
4840                             if(layout_body_childs[k].classList.contains('navbar')) {
4841                                 child_height += layout_body_childs[k].offsetHeight;
4842                                 continue;
4843                             }
4844                             
4845                             if(layout_body_childs[k].classList.contains('roo-layout-tabs-body')) {
4846                                 
4847                                 var layout_body_tab_childs = layout_body_childs[k].childNodes;
4848                                 
4849                                 for(var m = 0; m < layout_body_tab_childs.length; m++) {
4850                                     
4851                                     if(layout_body_tab_childs[m].classList.contains('roo-layout-active-content')) {
4852                                         child_height += this.getChildHeight(layout_body_tab_childs[m].childNodes);
4853                                         continue;
4854                                     }
4855                                     
4856                                 }
4857                                 
4858                             }
4859                             
4860                         }
4861                     }
4862                 }
4863                 continue;
4864             }
4865             */
4866             
4867             child_height += child_nodes[i].offsetHeight;
4868             // Roo.log(child_nodes[i].offsetHeight);
4869         }
4870         
4871         return child_height;
4872     },
4873     toggleHeaderInput : function(is_edit)
4874     {
4875         if (!this.editableTitle) {
4876             return; // not editable.
4877         }
4878         if (is_edit && this.is_header_editing) {
4879             return; // already editing..
4880         }
4881         if (is_edit) {
4882     
4883             this.headerEditEl.dom.value = this.title;
4884             this.headerEditEl.removeClass('d-none');
4885             this.headerEditEl.dom.focus();
4886             this.titleEl.addClass('d-none');
4887             
4888             this.is_header_editing = true;
4889             return
4890         }
4891         // flip back to not editing.
4892         this.title = this.headerEditEl.dom.value;
4893         this.headerEditEl.addClass('d-none');
4894         this.titleEl.removeClass('d-none');
4895         this.titleEl.dom.innerHTML = String.format('{0}', this.title);
4896         this.is_header_editing = false;
4897         this.fireEvent('titlechanged', this, this.title);
4898     
4899             
4900         
4901     }
4902
4903 });
4904
4905
4906 Roo.apply(Roo.bootstrap.Modal,  {
4907     /**
4908          * Button config that displays a single OK button
4909          * @type Object
4910          */
4911         OK :  [{
4912             name : 'ok',
4913             weight : 'primary',
4914             html : 'OK'
4915         }],
4916         /**
4917          * Button config that displays Yes and No buttons
4918          * @type Object
4919          */
4920         YESNO : [
4921             {
4922                 name  : 'no',
4923                 html : 'No'
4924             },
4925             {
4926                 name  :'yes',
4927                 weight : 'primary',
4928                 html : 'Yes'
4929             }
4930         ],
4931
4932         /**
4933          * Button config that displays OK and Cancel buttons
4934          * @type Object
4935          */
4936         OKCANCEL : [
4937             {
4938                name : 'cancel',
4939                 html : 'Cancel'
4940             },
4941             {
4942                 name : 'ok',
4943                 weight : 'primary',
4944                 html : 'OK'
4945             }
4946         ],
4947         /**
4948          * Button config that displays Yes, No and Cancel buttons
4949          * @type Object
4950          */
4951         YESNOCANCEL : [
4952             {
4953                 name : 'yes',
4954                 weight : 'primary',
4955                 html : 'Yes'
4956             },
4957             {
4958                 name : 'no',
4959                 html : 'No'
4960             },
4961             {
4962                 name : 'cancel',
4963                 html : 'Cancel'
4964             }
4965         ],
4966         
4967         zIndex : 10001
4968 });
4969
4970 /*
4971  * - LGPL
4972  *
4973  * messagebox - can be used as a replace
4974  * 
4975  */
4976 /**
4977  * @class Roo.MessageBox
4978  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
4979  * Example usage:
4980  *<pre><code>
4981 // Basic alert:
4982 Roo.Msg.alert('Status', 'Changes saved successfully.');
4983
4984 // Prompt for user data:
4985 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
4986     if (btn == 'ok'){
4987         // process text value...
4988     }
4989 });
4990
4991 // Show a dialog using config options:
4992 Roo.Msg.show({
4993    title:'Save Changes?',
4994    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
4995    buttons: Roo.Msg.YESNOCANCEL,
4996    fn: processResult,
4997    animEl: 'elId'
4998 });
4999 </code></pre>
5000  * @static
5001  */
5002 Roo.bootstrap.MessageBox = function(){
5003     var dlg, opt, mask, waitTimer;
5004     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
5005     var buttons, activeTextEl, bwidth;
5006
5007     
5008     // private
5009     var handleButton = function(button){
5010         dlg.hide();
5011         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
5012     };
5013
5014     // private
5015     var handleHide = function(){
5016         if(opt && opt.cls){
5017             dlg.el.removeClass(opt.cls);
5018         }
5019         //if(waitTimer){
5020         //    Roo.TaskMgr.stop(waitTimer);
5021         //    waitTimer = null;
5022         //}
5023     };
5024
5025     // private
5026     var updateButtons = function(b){
5027         var width = 0;
5028         if(!b){
5029             buttons["ok"].hide();
5030             buttons["cancel"].hide();
5031             buttons["yes"].hide();
5032             buttons["no"].hide();
5033             dlg.footerEl.hide();
5034             
5035             return width;
5036         }
5037         dlg.footerEl.show();
5038         for(var k in buttons){
5039             if(typeof buttons[k] != "function"){
5040                 if(b[k]){
5041                     buttons[k].show();
5042                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.bootstrap.MessageBox.buttonText[k]);
5043                     width += buttons[k].el.getWidth()+15;
5044                 }else{
5045                     buttons[k].hide();
5046                 }
5047             }
5048         }
5049         return width;
5050     };
5051
5052     // private
5053     var handleEsc = function(d, k, e){
5054         if(opt && opt.closable !== false){
5055             dlg.hide();
5056         }
5057         if(e){
5058             e.stopEvent();
5059         }
5060     };
5061
5062     return {
5063         /**
5064          * Returns a reference to the underlying {@link Roo.BasicDialog} element
5065          * @return {Roo.BasicDialog} The BasicDialog element
5066          */
5067         getDialog : function(){
5068            if(!dlg){
5069                 dlg = new Roo.bootstrap.Modal( {
5070                     //draggable: true,
5071                     //resizable:false,
5072                     //constraintoviewport:false,
5073                     //fixedcenter:true,
5074                     //collapsible : false,
5075                     //shim:true,
5076                     //modal: true,
5077                 //    width: 'auto',
5078                   //  height:100,
5079                     //buttonAlign:"center",
5080                     closeClick : function(){
5081                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
5082                             handleButton("no");
5083                         }else{
5084                             handleButton("cancel");
5085                         }
5086                     }
5087                 });
5088                 dlg.render();
5089                 dlg.on("hide", handleHide);
5090                 mask = dlg.mask;
5091                 //dlg.addKeyListener(27, handleEsc);
5092                 buttons = {};
5093                 this.buttons = buttons;
5094                 var bt = this.buttonText;
5095                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
5096                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
5097                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
5098                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
5099                 //Roo.log(buttons);
5100                 bodyEl = dlg.bodyEl.createChild({
5101
5102                     html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" />' +
5103                         '<textarea class="roo-mb-textarea"></textarea>' +
5104                         '<div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar">&#160;</div></div></div>'
5105                 });
5106                 msgEl = bodyEl.dom.firstChild;
5107                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
5108                 textboxEl.enableDisplayMode();
5109                 textboxEl.addKeyListener([10,13], function(){
5110                     if(dlg.isVisible() && opt && opt.buttons){
5111                         if(opt.buttons.ok){
5112                             handleButton("ok");
5113                         }else if(opt.buttons.yes){
5114                             handleButton("yes");
5115                         }
5116                     }
5117                 });
5118                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
5119                 textareaEl.enableDisplayMode();
5120                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
5121                 progressEl.enableDisplayMode();
5122                 
5123                 // This is supposed to be the progessElement.. but I think it's controlling the height of everything..
5124                 var pf = progressEl.dom.firstChild;
5125                 if (pf) {
5126                     pp = Roo.get(pf.firstChild);
5127                     pp.setHeight(pf.offsetHeight);
5128                 }
5129                 
5130             }
5131             return dlg;
5132         },
5133
5134         /**
5135          * Updates the message box body text
5136          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
5137          * the XHTML-compliant non-breaking space character '&amp;#160;')
5138          * @return {Roo.MessageBox} This message box
5139          */
5140         updateText : function(text)
5141         {
5142             if(!dlg.isVisible() && !opt.width){
5143                 dlg.dialogEl.setStyle({ 'max-width' : this.maxWidth});
5144                 // dlg.resizeTo(this.maxWidth, 100); // forcing the height breaks long alerts()
5145             }
5146             msgEl.innerHTML = text || '&#160;';
5147       
5148             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
5149             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
5150             var w = Math.max(
5151                     Math.min(opt.width || cw , this.maxWidth), 
5152                     Math.max(opt.minWidth || this.minWidth, bwidth)
5153             );
5154             if(opt.prompt){
5155                 activeTextEl.setWidth(w);
5156             }
5157             if(dlg.isVisible()){
5158                 dlg.fixedcenter = false;
5159             }
5160             // to big, make it scroll. = But as usual stupid IE does not support
5161             // !important..
5162             
5163             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
5164                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
5165                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
5166             } else {
5167                 bodyEl.dom.style.height = '';
5168                 bodyEl.dom.style.overflowY = '';
5169             }
5170             if (cw > w) {
5171                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
5172             } else {
5173                 bodyEl.dom.style.overflowX = '';
5174             }
5175             
5176             dlg.setContentSize(w, bodyEl.getHeight());
5177             if(dlg.isVisible()){
5178                 dlg.fixedcenter = true;
5179             }
5180             return this;
5181         },
5182
5183         /**
5184          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
5185          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
5186          * @param {Number} value Any number between 0 and 1 (e.g., .5)
5187          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
5188          * @return {Roo.MessageBox} This message box
5189          */
5190         updateProgress : function(value, text){
5191             if(text){
5192                 this.updateText(text);
5193             }
5194             
5195             if (pp) { // weird bug on my firefox - for some reason this is not defined
5196                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
5197                 pp.setHeight(Math.floor(progressEl.dom.firstChild.offsetHeight));
5198             }
5199             return this;
5200         },        
5201
5202         /**
5203          * Returns true if the message box is currently displayed
5204          * @return {Boolean} True if the message box is visible, else false
5205          */
5206         isVisible : function(){
5207             return dlg && dlg.isVisible();  
5208         },
5209
5210         /**
5211          * Hides the message box if it is displayed
5212          */
5213         hide : function(){
5214             if(this.isVisible()){
5215                 dlg.hide();
5216             }  
5217         },
5218
5219         /**
5220          * Displays a new message box, or reinitializes an existing message box, based on the config options
5221          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
5222          * The following config object properties are supported:
5223          * <pre>
5224 Property    Type             Description
5225 ----------  ---------------  ------------------------------------------------------------------------------------
5226 animEl            String/Element   An id or Element from which the message box should animate as it opens and
5227                                    closes (defaults to undefined)
5228 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
5229                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
5230 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
5231                                    progress and wait dialogs will ignore this property and always hide the
5232                                    close button as they can only be closed programmatically.
5233 cls               String           A custom CSS class to apply to the message box element
5234 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
5235                                    displayed (defaults to 75)
5236 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
5237                                    function will be btn (the name of the button that was clicked, if applicable,
5238                                    e.g. "ok"), and text (the value of the active text field, if applicable).
5239                                    Progress and wait dialogs will ignore this option since they do not respond to
5240                                    user actions and can only be closed programmatically, so any required function
5241                                    should be called by the same code after it closes the dialog.
5242 icon              String           A CSS class that provides a background image to be used as an icon for
5243                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
5244 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
5245 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
5246 modal             Boolean          False to allow user interaction with the page while the message box is
5247                                    displayed (defaults to true)
5248 msg               String           A string that will replace the existing message box body text (defaults
5249                                    to the XHTML-compliant non-breaking space character '&#160;')
5250 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
5251 progress          Boolean          True to display a progress bar (defaults to false)
5252 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
5253 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
5254 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
5255 title             String           The title text
5256 value             String           The string value to set into the active textbox element if displayed
5257 wait              Boolean          True to display a progress bar (defaults to false)
5258 width             Number           The width of the dialog in pixels
5259 </pre>
5260          *
5261          * Example usage:
5262          * <pre><code>
5263 Roo.Msg.show({
5264    title: 'Address',
5265    msg: 'Please enter your address:',
5266    width: 300,
5267    buttons: Roo.MessageBox.OKCANCEL,
5268    multiline: true,
5269    fn: saveAddress,
5270    animEl: 'addAddressBtn'
5271 });
5272 </code></pre>
5273          * @param {Object} config Configuration options
5274          * @return {Roo.MessageBox} This message box
5275          */
5276         show : function(options)
5277         {
5278             
5279             // this causes nightmares if you show one dialog after another
5280             // especially on callbacks..
5281              
5282             if(this.isVisible()){
5283                 
5284                 this.hide();
5285                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
5286                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
5287                 Roo.log("New Dialog Message:" +  options.msg )
5288                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
5289                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
5290                 
5291             }
5292             var d = this.getDialog();
5293             opt = options;
5294             d.setTitle(opt.title || "&#160;");
5295             d.closeEl.setDisplayed(opt.closable !== false);
5296             activeTextEl = textboxEl;
5297             opt.prompt = opt.prompt || (opt.multiline ? true : false);
5298             if(opt.prompt){
5299                 if(opt.multiline){
5300                     textboxEl.hide();
5301                     textareaEl.show();
5302                     textareaEl.setHeight(typeof opt.multiline == "number" ?
5303                         opt.multiline : this.defaultTextHeight);
5304                     activeTextEl = textareaEl;
5305                 }else{
5306                     textboxEl.show();
5307                     textareaEl.hide();
5308                 }
5309             }else{
5310                 textboxEl.hide();
5311                 textareaEl.hide();
5312             }
5313             progressEl.setDisplayed(opt.progress === true);
5314             if (opt.progress) {
5315                 d.animate = false; // do not animate progress, as it may not have finished animating before we close it..
5316             }
5317             this.updateProgress(0);
5318             activeTextEl.dom.value = opt.value || "";
5319             if(opt.prompt){
5320                 dlg.setDefaultButton(activeTextEl);
5321             }else{
5322                 var bs = opt.buttons;
5323                 var db = null;
5324                 if(bs && bs.ok){
5325                     db = buttons["ok"];
5326                 }else if(bs && bs.yes){
5327                     db = buttons["yes"];
5328                 }
5329                 dlg.setDefaultButton(db);
5330             }
5331             bwidth = updateButtons(opt.buttons);
5332             this.updateText(opt.msg);
5333             if(opt.cls){
5334                 d.el.addClass(opt.cls);
5335             }
5336             d.proxyDrag = opt.proxyDrag === true;
5337             d.modal = opt.modal !== false;
5338             d.mask = opt.modal !== false ? mask : false;
5339             if(!d.isVisible()){
5340                 // force it to the end of the z-index stack so it gets a cursor in FF
5341                 document.body.appendChild(dlg.el.dom);
5342                 d.animateTarget = null;
5343                 d.show(options.animEl);
5344             }
5345             return this;
5346         },
5347
5348         /**
5349          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
5350          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
5351          * and closing the message box when the process is complete.
5352          * @param {String} title The title bar text
5353          * @param {String} msg The message box body text
5354          * @return {Roo.MessageBox} This message box
5355          */
5356         progress : function(title, msg){
5357             this.show({
5358                 title : title,
5359                 msg : msg,
5360                 buttons: false,
5361                 progress:true,
5362                 closable:false,
5363                 minWidth: this.minProgressWidth,
5364                 modal : true
5365             });
5366             return this;
5367         },
5368
5369         /**
5370          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
5371          * If a callback function is passed it will be called after the user clicks the button, and the
5372          * id of the button that was clicked will be passed as the only parameter to the callback
5373          * (could also be the top-right close button).
5374          * @param {String} title The title bar text
5375          * @param {String} msg The message box body text
5376          * @param {Function} fn (optional) The callback function invoked after the message box is closed
5377          * @param {Object} scope (optional) The scope of the callback function
5378          * @return {Roo.MessageBox} This message box
5379          */
5380         alert : function(title, msg, fn, scope)
5381         {
5382             this.show({
5383                 title : title,
5384                 msg : msg,
5385                 buttons: this.OK,
5386                 fn: fn,
5387                 closable : false,
5388                 scope : scope,
5389                 modal : true
5390             });
5391             return this;
5392         },
5393
5394         /**
5395          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
5396          * interaction while waiting for a long-running process to complete that does not have defined intervals.
5397          * You are responsible for closing the message box when the process is complete.
5398          * @param {String} msg The message box body text
5399          * @param {String} title (optional) The title bar text
5400          * @return {Roo.MessageBox} This message box
5401          */
5402         wait : function(msg, title){
5403             this.show({
5404                 title : title,
5405                 msg : msg,
5406                 buttons: false,
5407                 closable:false,
5408                 progress:true,
5409                 modal:true,
5410                 width:300,
5411                 wait:true
5412             });
5413             waitTimer = Roo.TaskMgr.start({
5414                 run: function(i){
5415                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
5416                 },
5417                 interval: 1000
5418             });
5419             return this;
5420         },
5421
5422         /**
5423          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
5424          * If a callback function is passed it will be called after the user clicks either button, and the id of the
5425          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
5426          * @param {String} title The title bar text
5427          * @param {String} msg The message box body text
5428          * @param {Function} fn (optional) The callback function invoked after the message box is closed
5429          * @param {Object} scope (optional) The scope of the callback function
5430          * @return {Roo.MessageBox} This message box
5431          */
5432         confirm : function(title, msg, fn, scope){
5433             this.show({
5434                 title : title,
5435                 msg : msg,
5436                 buttons: this.YESNO,
5437                 fn: fn,
5438                 scope : scope,
5439                 modal : true
5440             });
5441             return this;
5442         },
5443
5444         /**
5445          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
5446          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
5447          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
5448          * (could also be the top-right close button) and the text that was entered will be passed as the two
5449          * parameters to the callback.
5450          * @param {String} title The title bar text
5451          * @param {String} msg The message box body text
5452          * @param {Function} fn (optional) The callback function invoked after the message box is closed
5453          * @param {Object} scope (optional) The scope of the callback function
5454          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
5455          * property, or the height in pixels to create the textbox (defaults to false / single-line)
5456          * @return {Roo.MessageBox} This message box
5457          */
5458         prompt : function(title, msg, fn, scope, multiline){
5459             this.show({
5460                 title : title,
5461                 msg : msg,
5462                 buttons: this.OKCANCEL,
5463                 fn: fn,
5464                 minWidth:250,
5465                 scope : scope,
5466                 prompt:true,
5467                 multiline: multiline,
5468                 modal : true
5469             });
5470             return this;
5471         },
5472
5473         /**
5474          * Button config that displays a single OK button
5475          * @type Object
5476          */
5477         OK : {ok:true},
5478         /**
5479          * Button config that displays Yes and No buttons
5480          * @type Object
5481          */
5482         YESNO : {yes:true, no:true},
5483         /**
5484          * Button config that displays OK and Cancel buttons
5485          * @type Object
5486          */
5487         OKCANCEL : {ok:true, cancel:true},
5488         /**
5489          * Button config that displays Yes, No and Cancel buttons
5490          * @type Object
5491          */
5492         YESNOCANCEL : {yes:true, no:true, cancel:true},
5493
5494         /**
5495          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
5496          * @type Number
5497          */
5498         defaultTextHeight : 75,
5499         /**
5500          * The maximum width in pixels of the message box (defaults to 600)
5501          * @type Number
5502          */
5503         maxWidth : 600,
5504         /**
5505          * The minimum width in pixels of the message box (defaults to 100)
5506          * @type Number
5507          */
5508         minWidth : 100,
5509         /**
5510          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
5511          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
5512          * @type Number
5513          */
5514         minProgressWidth : 250,
5515         /**
5516          * An object containing the default button text strings that can be overriden for localized language support.
5517          * Supported properties are: ok, cancel, yes and no.
5518          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
5519          * @type Object
5520          */
5521         buttonText : {
5522             ok : "OK",
5523             cancel : "Cancel",
5524             yes : "Yes",
5525             no : "No"
5526         }
5527     };
5528 }();
5529
5530 /**
5531  * Shorthand for {@link Roo.MessageBox}
5532  */
5533 Roo.MessageBox = Roo.MessageBox || Roo.bootstrap.MessageBox;
5534 Roo.Msg = Roo.Msg || Roo.MessageBox;
5535 /*
5536  * - LGPL
5537  *
5538  * navbar
5539  * 
5540  */
5541
5542 /**
5543  * @class Roo.bootstrap.nav.Bar
5544  * @extends Roo.bootstrap.Component
5545  * @abstract
5546  * Bootstrap Navbar class
5547
5548  * @constructor
5549  * Create a new Navbar
5550  * @param {Object} config The config object
5551  */
5552
5553
5554 Roo.bootstrap.nav.Bar = function(config){
5555     Roo.bootstrap.nav.Bar.superclass.constructor.call(this, config);
5556     this.addEvents({
5557         // raw events
5558         /**
5559          * @event beforetoggle
5560          * Fire before toggle the menu
5561          * @param {Roo.EventObject} e
5562          */
5563         "beforetoggle" : true
5564     });
5565 };
5566
5567 Roo.extend(Roo.bootstrap.nav.Bar, Roo.bootstrap.Component,  {
5568     
5569     
5570    
5571     // private
5572     navItems : false,
5573     loadMask : false,
5574     
5575     
5576     getAutoCreate : function(){
5577         
5578         
5579         throw { message : "nav bar is now a abstract base class - use NavSimplebar / NavHeaderbar / NavSidebar etc..."};
5580         
5581     },
5582     
5583     initEvents :function ()
5584     {
5585         //Roo.log(this.el.select('.navbar-toggle',true));
5586         this.el.select('.navbar-toggle',true).on('click', this.onToggle , this);
5587         
5588         var mark = {
5589             tag: "div",
5590             cls:"x-dlg-mask"
5591         };
5592         
5593         this.maskEl = Roo.DomHelper.append(this.el, mark, true);
5594         
5595         var size = this.el.getSize();
5596         this.maskEl.setSize(size.width, size.height);
5597         this.maskEl.enableDisplayMode("block");
5598         this.maskEl.hide();
5599         
5600         if(this.loadMask){
5601             this.maskEl.show();
5602         }
5603     },
5604     
5605     
5606     getChildContainer : function()
5607     {
5608         if (this.el && this.el.select('.collapse').getCount()) {
5609             return this.el.select('.collapse',true).first();
5610         }
5611         
5612         return this.el;
5613     },
5614     
5615     mask : function()
5616     {
5617         this.maskEl.show();
5618     },
5619     
5620     unmask : function()
5621     {
5622         this.maskEl.hide();
5623     },
5624     onToggle : function()
5625     {
5626         
5627         if(this.fireEvent('beforetoggle', this) === false){
5628             return;
5629         }
5630         var ce = this.el.select('.navbar-collapse',true).first();
5631       
5632         if (!ce.hasClass('show')) {
5633            this.expand();
5634         } else {
5635             this.collapse();
5636         }
5637         
5638         
5639     
5640     },
5641     /**
5642      * Expand the navbar pulldown 
5643      */
5644     expand : function ()
5645     {
5646        
5647         var ce = this.el.select('.navbar-collapse',true).first();
5648         if (ce.hasClass('collapsing')) {
5649             return;
5650         }
5651         ce.dom.style.height = '';
5652                // show it...
5653         ce.addClass('in'); // old...
5654         ce.removeClass('collapse');
5655         ce.addClass('show');
5656         var h = ce.getHeight();
5657         Roo.log(h);
5658         ce.removeClass('show');
5659         // at this point we should be able to see it..
5660         ce.addClass('collapsing');
5661         
5662         ce.setHeight(0); // resize it ...
5663         ce.on('transitionend', function() {
5664             //Roo.log('done transition');
5665             ce.removeClass('collapsing');
5666             ce.addClass('show');
5667             ce.removeClass('collapse');
5668
5669             ce.dom.style.height = '';
5670         }, this, { single: true} );
5671         ce.setHeight(h);
5672         ce.dom.scrollTop = 0;
5673     },
5674     /**
5675      * Collapse the navbar pulldown 
5676      */
5677     collapse : function()
5678     {
5679          var ce = this.el.select('.navbar-collapse',true).first();
5680        
5681         if (ce.hasClass('collapsing') || ce.hasClass('collapse') ) {
5682             // it's collapsed or collapsing..
5683             return;
5684         }
5685         ce.removeClass('in'); // old...
5686         ce.setHeight(ce.getHeight());
5687         ce.removeClass('show');
5688         ce.addClass('collapsing');
5689         
5690         ce.on('transitionend', function() {
5691             ce.dom.style.height = '';
5692             ce.removeClass('collapsing');
5693             ce.addClass('collapse');
5694         }, this, { single: true} );
5695         ce.setHeight(0);
5696     }
5697     
5698     
5699     
5700 });
5701
5702
5703
5704  
5705
5706  /*
5707  * - LGPL
5708  *
5709  * navbar
5710  * 
5711  */
5712
5713 /**
5714  * @class Roo.bootstrap.nav.Simplebar
5715  * @extends Roo.bootstrap.nav.Bar
5716  * @children Roo.bootstrap.nav.Group Roo.bootstrap.Container Roo.bootstrap.form.Form Roo.bootstrap.Row Roo.bootstrap.Column Roo.bootstrap.Link
5717  * Bootstrap Sidebar class
5718  *
5719  * @cfg {Boolean} inverse is inverted color
5720  * 
5721  * @cfg {String} type (nav | pills | tabs)
5722  * @cfg {Boolean} arrangement stacked | justified
5723  * @cfg {String} align (left | right) alignment
5724  * 
5725  * @cfg {Boolean} main (true|false) main nav bar? default false
5726  * @cfg {Boolean} loadMask (true|false) loadMask on the bar
5727  * 
5728  * @cfg {String} tag (header|footer|nav|div) default is nav 
5729
5730  * @cfg {String} weight (light|primary|secondary|success|danger|warning|info|dark|white) default is light.
5731  * 
5732  * 
5733  * @constructor
5734  * Create a new Sidebar
5735  * @param {Object} config The config object
5736  */
5737
5738
5739 Roo.bootstrap.nav.Simplebar = function(config){
5740     Roo.bootstrap.nav.Simplebar.superclass.constructor.call(this, config);
5741 };
5742
5743 Roo.extend(Roo.bootstrap.nav.Simplebar, Roo.bootstrap.nav.Bar,  {
5744     
5745     inverse: false,
5746     
5747     type: false,
5748     arrangement: '',
5749     align : false,
5750     
5751     weight : 'light',
5752     
5753     main : false,
5754     
5755     
5756     tag : false,
5757     
5758     
5759     getAutoCreate : function(){
5760         
5761         
5762         var cfg = {
5763             tag : this.tag || 'div',
5764             cls : 'navbar roo-navbar-simple' //navbar-expand-lg ??
5765         };
5766         if (['light','white'].indexOf(this.weight) > -1) {
5767             cfg.cls += ['light','white'].indexOf(this.weight) > -1 ? ' navbar-light' : ' navbar-dark';
5768         }
5769         cfg.cls += ' bg-' + this.weight;
5770         
5771         if (this.inverse) {
5772             cfg.cls += ' navbar-inverse';
5773             
5774         }
5775         
5776         // i'm not actually sure these are really used - normally we add a navGroup to a navbar
5777         
5778         if (Roo.bootstrap.version == 4 && this.xtype == 'NavSimplebar') {
5779             return cfg;
5780         }
5781         
5782         
5783     
5784         
5785         cfg.cn = [
5786             {
5787                 cls: 'nav nav-' + this.xtype,
5788                 tag : 'ul'
5789             }
5790         ];
5791         
5792          
5793         this.type = this.type || 'nav';
5794         if (['tabs','pills'].indexOf(this.type) != -1) {
5795             cfg.cn[0].cls += ' nav-' + this.type
5796         
5797         
5798         } else {
5799             if (this.type!=='nav') {
5800                 Roo.log('nav type must be nav/tabs/pills')
5801             }
5802             cfg.cn[0].cls += ' navbar-nav'
5803         }
5804         
5805         
5806         
5807         
5808         if (['stacked','justified'].indexOf(this.arrangement) != -1) {
5809             cfg.cn[0].cls += ' nav-' + this.arrangement;
5810         }
5811         
5812         
5813         if (this.align === 'right') {
5814             cfg.cn[0].cls += ' navbar-right';
5815         }
5816         
5817         
5818         
5819         
5820         return cfg;
5821     
5822         
5823     }
5824     
5825     
5826     
5827 });
5828
5829
5830
5831  
5832
5833  
5834        /*
5835  * - LGPL
5836  *
5837  * navbar
5838  * navbar-fixed-top
5839  * navbar-expand-md  fixed-top 
5840  */
5841
5842 /**
5843  * @class Roo.bootstrap.nav.Headerbar
5844  * @extends Roo.bootstrap.nav.Simplebar
5845  * @children Roo.bootstrap.nav.Group Roo.bootstrap.Container Roo.bootstrap.form.Form Roo.bootstrap.Row Roo.bootstrap.Column Roo.bootstrap.Link
5846  * Bootstrap Sidebar class
5847  *
5848  * @cfg {String} brand what is brand
5849  * @cfg {String} position (fixed-top|fixed-bottom|static-top) position
5850  * @cfg {String} brand_href href of the brand
5851  * @cfg {Boolean} srButton generate the (screen reader / mobile) sr-only button   default true
5852  * @cfg {Boolean} autohide a top nav bar header that hides on scroll.
5853  * @cfg {Boolean} desktopCenter should the header be centered on desktop using a container class
5854  * @cfg {Roo.bootstrap.Row} mobilerow - a row to display on mobile only..
5855  * 
5856  * @constructor
5857  * Create a new Sidebar
5858  * @param {Object} config The config object
5859  */
5860
5861
5862 Roo.bootstrap.nav.Headerbar = function(config){
5863     Roo.bootstrap.nav.Headerbar.superclass.constructor.call(this, config);
5864       
5865 };
5866
5867 Roo.extend(Roo.bootstrap.nav.Headerbar, Roo.bootstrap.nav.Simplebar,  {
5868     
5869     position: '',
5870     brand: '',
5871     brand_href: false,
5872     srButton : true,
5873     autohide : false,
5874     desktopCenter : false,
5875    
5876     
5877     getAutoCreate : function(){
5878         
5879         var   cfg = {
5880             tag: this.nav || 'nav',
5881             cls: 'navbar navbar-expand-md',
5882             role: 'navigation',
5883             cn: []
5884         };
5885         
5886         var cn = cfg.cn;
5887         if (this.desktopCenter) {
5888             cn.push({cls : 'container', cn : []});
5889             cn = cn[0].cn;
5890         }
5891         
5892         if(this.srButton){
5893             var btn = {
5894                 tag: 'button',
5895                 type: 'button',
5896                 cls: 'navbar-toggle navbar-toggler',
5897                 'data-toggle': 'collapse',
5898                 cn: [
5899                     {
5900                         tag: 'span',
5901                         cls: 'sr-only',
5902                         html: 'Toggle navigation'
5903                     },
5904                     {
5905                         tag: 'span',
5906                         cls: 'icon-bar navbar-toggler-icon'
5907                     },
5908                     {
5909                         tag: 'span',
5910                         cls: 'icon-bar'
5911                     },
5912                     {
5913                         tag: 'span',
5914                         cls: 'icon-bar'
5915                     }
5916                 ]
5917             };
5918             
5919             cn.push( Roo.bootstrap.version == 4 ? btn : {
5920                 tag: 'div',
5921                 cls: 'navbar-header',
5922                 cn: [
5923                     btn
5924                 ]
5925             });
5926         }
5927         
5928         cn.push({
5929             tag: 'div',
5930             cls: Roo.bootstrap.version == 4  ? 'nav flex-row roo-navbar-collapse collapse navbar-collapse' : 'collapse navbar-collapse roo-navbar-collapse',
5931             cn : []
5932         });
5933         
5934         cfg.cls += this.inverse ? ' navbar-inverse navbar-dark bg-dark' : ' navbar-default';
5935         
5936         if (['light','white'].indexOf(this.weight) > -1) {
5937             cfg.cls += ['light','white'].indexOf(this.weight) > -1 ? ' navbar-light' : ' navbar-dark';
5938         }
5939         cfg.cls += ' bg-' + this.weight;
5940         
5941         
5942         if (['fixed-top','fixed-bottom','static-top'].indexOf(this.position)>-1) {
5943             cfg.cls += ' navbar-' + this.position + ' ' + this.position ;
5944             
5945             // tag can override this..
5946             
5947             cfg.tag = this.tag || (this.position  == 'fixed-bottom' ? 'footer' : 'header');
5948         }
5949         
5950         if (this.brand !== '') {
5951             var cp =  Roo.bootstrap.version == 4 ? cn : cn[0].cn;
5952             cp.unshift({ // changed from push ?? BS4 needs it at the start? - does this break or exsiting?
5953                 tag: 'a',
5954                 href: this.brand_href ? this.brand_href : '#',
5955                 cls: 'navbar-brand',
5956                 cn: [
5957                 this.brand
5958                 ]
5959             });
5960         }
5961         
5962         if(this.main){
5963             cfg.cls += ' main-nav';
5964         }
5965         
5966         
5967         return cfg;
5968
5969         
5970     },
5971     getHeaderChildContainer : function()
5972     {
5973         if (this.srButton && this.el.select('.navbar-header').getCount()) {
5974             return this.el.select('.navbar-header',true).first();
5975         }
5976         
5977         return this.getChildContainer();
5978     },
5979     
5980     getChildContainer : function()
5981     {
5982          
5983         return this.el.select('.roo-navbar-collapse',true).first();
5984          
5985         
5986     },
5987     
5988     initEvents : function()
5989     {
5990         Roo.bootstrap.nav.Headerbar.superclass.initEvents.call(this);
5991         
5992         if (this.autohide) {
5993             
5994             var prevScroll = 0;
5995             var ft = this.el;
5996             
5997             Roo.get(document).on('scroll',function(e) {
5998                 var ns = Roo.get(document).getScroll().top;
5999                 var os = prevScroll;
6000                 prevScroll = ns;
6001                 
6002                 if(ns > os){
6003                     ft.removeClass('slideDown');
6004                     ft.addClass('slideUp');
6005                     return;
6006                 }
6007                 ft.removeClass('slideUp');
6008                 ft.addClass('slideDown');
6009                  
6010               
6011           },this);
6012         }
6013     }    
6014     
6015 });
6016
6017
6018
6019  
6020
6021  /*
6022  * - LGPL
6023  *
6024  * navbar
6025  * 
6026  */
6027
6028 /**
6029  * @class Roo.bootstrap.nav.Sidebar
6030  * @extends Roo.bootstrap.nav.Bar
6031  * @children Roo.bootstrap.nav.Group Roo.bootstrap.Container Roo.bootstrap.form.Form Roo.bootstrap.Row Roo.bootstrap.Column Roo.bootstrap.Link
6032  * Bootstrap Sidebar class
6033  * 
6034  * @constructor
6035  * Create a new Sidebar
6036  * @param {Object} config The config object
6037  */
6038
6039
6040 Roo.bootstrap.nav.Sidebar = function(config){
6041     Roo.bootstrap.nav.Sidebar.superclass.constructor.call(this, config);
6042 };
6043
6044 Roo.extend(Roo.bootstrap.nav.Sidebar, Roo.bootstrap.nav.Bar,  {
6045     
6046     sidebar : true, // used by Navbar Item and NavbarGroup at present...
6047     
6048     getAutoCreate : function(){
6049         
6050         
6051         return  {
6052             tag: 'div',
6053             cls: 'sidebar sidebar-nav'
6054         };
6055     
6056         
6057     }
6058     
6059     
6060     
6061 });
6062
6063
6064
6065  
6066
6067  /*
6068  * - LGPL
6069  *
6070  * nav group
6071  * 
6072  */
6073
6074 /**
6075  * @class Roo.bootstrap.nav.Group
6076  * @extends Roo.bootstrap.Component
6077  * @children Roo.bootstrap.nav.Item
6078  * Bootstrap NavGroup class
6079  * @cfg {String} align (left|right)
6080  * @cfg {Boolean} inverse
6081  * @cfg {String} type (nav|pills|tab) default nav
6082  * @cfg {String} navId - reference Id for navbar.
6083  * @cfg {Boolean} pilltype default true (turn to off to disable active toggle)
6084  * 
6085  * @constructor
6086  * Create a new nav group
6087  * @param {Object} config The config object
6088  */
6089
6090 Roo.bootstrap.nav.Group = function(config){
6091     Roo.bootstrap.nav.Group.superclass.constructor.call(this, config);
6092     this.navItems = [];
6093    
6094     Roo.bootstrap.nav.Group.register(this);
6095      this.addEvents({
6096         /**
6097              * @event changed
6098              * Fires when the active item changes
6099              * @param {Roo.bootstrap.nav.Group} this
6100              * @param {Roo.bootstrap.Navbar.Item} selected The item selected
6101              * @param {Roo.bootstrap.Navbar.Item} prev The previously selected item 
6102          */
6103         'changed': true
6104      });
6105     
6106 };
6107
6108 Roo.extend(Roo.bootstrap.nav.Group, Roo.bootstrap.Component,  {
6109     
6110     align: '',
6111     inverse: false,
6112     form: false,
6113     type: 'nav',
6114     navId : '',
6115     // private
6116     pilltype : true,
6117     
6118     navItems : false, 
6119     
6120     getAutoCreate : function()
6121     {
6122         var cfg = Roo.apply({}, Roo.bootstrap.nav.Group.superclass.getAutoCreate.call(this));
6123         
6124         cfg = {
6125             tag : 'ul',
6126             cls: 'nav' 
6127         };
6128         if (Roo.bootstrap.version == 4) {
6129             if (['tabs','pills'].indexOf(this.type) != -1) {
6130                 cfg.cls += ' nav-' + this.type; 
6131             } else {
6132                 // trying to remove so header bar can right align top?
6133                 if (this.parent() && this.parent().xtype != 'NavHeaderbar') {
6134                     // do not use on header bar... 
6135                     cfg.cls += ' navbar-nav';
6136                 }
6137             }
6138             
6139         } else {
6140             if (['tabs','pills'].indexOf(this.type) != -1) {
6141                 cfg.cls += ' nav-' + this.type
6142             } else {
6143                 if (this.type !== 'nav') {
6144                     Roo.log('nav type must be nav/tabs/pills')
6145                 }
6146                 cfg.cls += ' navbar-nav'
6147             }
6148         }
6149         
6150         if (this.parent() && this.parent().sidebar) {
6151             cfg = {
6152                 tag: 'ul',
6153                 cls: 'dashboard-menu sidebar-menu'
6154             };
6155             
6156             return cfg;
6157         }
6158         
6159         if (this.form === true) {
6160             cfg = {
6161                 tag: 'form',
6162                 cls: 'navbar-form form-inline'
6163             };
6164             //nav navbar-right ml-md-auto
6165             if (this.align === 'right') {
6166                 cfg.cls += ' navbar-right ml-md-auto';
6167             } else {
6168                 cfg.cls += ' navbar-left';
6169             }
6170         }
6171         
6172         if (this.align === 'right') {
6173             cfg.cls += ' navbar-right ml-md-auto';
6174         } else {
6175             cfg.cls += ' mr-auto';
6176         }
6177         
6178         if (this.inverse) {
6179             cfg.cls += ' navbar-inverse';
6180             
6181         }
6182         
6183         
6184         return cfg;
6185     },
6186     /**
6187     * sets the active Navigation item
6188     * @param {Roo.bootstrap.nav.Item} the new current navitem
6189     */
6190     setActiveItem : function(item)
6191     {
6192         var prev = false;
6193         Roo.each(this.navItems, function(v){
6194             if (v == item) {
6195                 return ;
6196             }
6197             if (v.isActive()) {
6198                 v.setActive(false, true);
6199                 prev = v;
6200                 
6201             }
6202             
6203         });
6204
6205         item.setActive(true, true);
6206         this.fireEvent('changed', this, item, prev);
6207         
6208         
6209     },
6210     /**
6211     * gets the active Navigation item
6212     * @return {Roo.bootstrap.nav.Item} the current navitem
6213     */
6214     getActive : function()
6215     {
6216         
6217         var prev = false;
6218         Roo.each(this.navItems, function(v){
6219             
6220             if (v.isActive()) {
6221                 prev = v;
6222                 
6223             }
6224             
6225         });
6226         return prev;
6227     },
6228     
6229     indexOfNav : function()
6230     {
6231         
6232         var prev = false;
6233         Roo.each(this.navItems, function(v,i){
6234             
6235             if (v.isActive()) {
6236                 prev = i;
6237                 
6238             }
6239             
6240         });
6241         return prev;
6242     },
6243     /**
6244     * adds a Navigation item
6245     * @param {Roo.bootstrap.nav.Item} the navitem to add
6246     */
6247     addItem : function(cfg)
6248     {
6249         if (this.form && Roo.bootstrap.version == 4) {
6250             cfg.tag = 'div';
6251         }
6252         var cn = new Roo.bootstrap.nav.Item(cfg);
6253         this.register(cn);
6254         cn.parentId = this.id;
6255         cn.onRender(this.el, null);
6256         return cn;
6257     },
6258     /**
6259     * register a Navigation item
6260     * @param {Roo.bootstrap.nav.Item} the navitem to add
6261     */
6262     register : function(item)
6263     {
6264         this.navItems.push( item);
6265         item.navId = this.navId;
6266     
6267     },
6268     
6269     /**
6270     * clear all the Navigation item
6271     */
6272    
6273     clearAll : function()
6274     {
6275         this.navItems = [];
6276         this.el.dom.innerHTML = '';
6277     },
6278     
6279     getNavItem: function(tabId)
6280     {
6281         var ret = false;
6282         Roo.each(this.navItems, function(e) {
6283             if (e.tabId == tabId) {
6284                ret =  e;
6285                return false;
6286             }
6287             return true;
6288             
6289         });
6290         return ret;
6291     },
6292     
6293     setActiveNext : function()
6294     {
6295         var i = this.indexOfNav(this.getActive());
6296         if (i > this.navItems.length) {
6297             return;
6298         }
6299         this.setActiveItem(this.navItems[i+1]);
6300     },
6301     setActivePrev : function()
6302     {
6303         var i = this.indexOfNav(this.getActive());
6304         if (i  < 1) {
6305             return;
6306         }
6307         this.setActiveItem(this.navItems[i-1]);
6308     },
6309     clearWasActive : function(except) {
6310         Roo.each(this.navItems, function(e) {
6311             if (e.tabId != except.tabId && e.was_active) {
6312                e.was_active = false;
6313                return false;
6314             }
6315             return true;
6316             
6317         });
6318     },
6319     getWasActive : function ()
6320     {
6321         var r = false;
6322         Roo.each(this.navItems, function(e) {
6323             if (e.was_active) {
6324                r = e;
6325                return false;
6326             }
6327             return true;
6328             
6329         });
6330         return r;
6331     }
6332     
6333     
6334 });
6335
6336  
6337 Roo.apply(Roo.bootstrap.nav.Group, {
6338     
6339     groups: {},
6340      /**
6341     * register a Navigation Group
6342     * @param {Roo.bootstrap.nav.Group} the navgroup to add
6343     */
6344     register : function(navgrp)
6345     {
6346         this.groups[navgrp.navId] = navgrp;
6347         
6348     },
6349     /**
6350     * fetch a Navigation Group based on the navigation ID
6351     * @param {string} the navgroup to add
6352     * @returns {Roo.bootstrap.nav.Group} the navgroup 
6353     */
6354     get: function(navId) {
6355         if (typeof(this.groups[navId]) == 'undefined') {
6356             return false;
6357             //this.register(new Roo.bootstrap.nav.Group({ navId : navId }));
6358         }
6359         return this.groups[navId] ;
6360     }
6361     
6362     
6363     
6364 });
6365
6366  /**
6367  * @class Roo.bootstrap.nav.Item
6368  * @extends Roo.bootstrap.Component
6369  * @children Roo.bootstrap.Container Roo.bootstrap.Button
6370  * @parent Roo.bootstrap.nav.Group
6371  * @licence LGPL
6372  * Bootstrap Navbar.NavItem class
6373  * 
6374  * @cfg {String} href  link to
6375  * @cfg {String} button_weight (default|primary|secondary|success|info|warning|danger|link|light|dark) default none
6376  * @cfg {Boolean} button_outline show and outlined button
6377  * @cfg {String} html content of button
6378  * @cfg {String} badge text inside badge
6379  * @cfg {String} badgecls (bg-green|bg-red|bg-yellow)the extra classes for the badge
6380  * @cfg {String} glyphicon DEPRICATED - use fa
6381  * @cfg {String} icon DEPRICATED - use fa
6382  * @cfg {String} fa - Fontawsome icon name (can add stuff to it like fa-2x)
6383  * @cfg {Boolean} active Is item active
6384  * @cfg {Boolean} disabled Is item disabled
6385  * @cfg {String} linkcls  Link Class
6386  * @cfg {Boolean} preventDefault (true | false) default false
6387  * @cfg {String} tabId the tab that this item activates.
6388  * @cfg {String} tagtype (a|span) render as a href or span?
6389  * @cfg {Boolean} animateRef (true|false) link to element default false  
6390  * @cfg {Roo.bootstrap.menu.Menu} menu a Menu 
6391   
6392  * @constructor
6393  * Create a new Navbar Item
6394  * @param {Object} config The config object
6395  */
6396 Roo.bootstrap.nav.Item = function(config){
6397     Roo.bootstrap.nav.Item.superclass.constructor.call(this, config);
6398     this.addEvents({
6399         // raw events
6400         /**
6401          * @event click
6402          * The raw click event for the entire grid.
6403          * @param {Roo.EventObject} e
6404          */
6405         "click" : true,
6406          /**
6407             * @event changed
6408             * Fires when the active item active state changes
6409             * @param {Roo.bootstrap.nav.Item} this
6410             * @param {boolean} state the new state
6411              
6412          */
6413         'changed': true,
6414         /**
6415             * @event scrollto
6416             * Fires when scroll to element
6417             * @param {Roo.bootstrap.nav.Item} this
6418             * @param {Object} options
6419             * @param {Roo.EventObject} e
6420              
6421          */
6422         'scrollto': true
6423     });
6424    
6425 };
6426
6427 Roo.extend(Roo.bootstrap.nav.Item, Roo.bootstrap.Component,  {
6428     
6429     href: false,
6430     html: '',
6431     badge: '',
6432     icon: false,
6433     fa : false,
6434     glyphicon: false,
6435     active: false,
6436     preventDefault : false,
6437     tabId : false,
6438     tagtype : 'a',
6439     tag: 'li',
6440     disabled : false,
6441     animateRef : false,
6442     was_active : false,
6443     button_weight : '',
6444     button_outline : false,
6445     linkcls : '',
6446     navLink: false,
6447     
6448     getAutoCreate : function(){
6449          
6450         var cfg = {
6451             tag: this.tag,
6452             cls: 'nav-item'
6453         };
6454         
6455         cfg.cls =  typeof(cfg.cls) == 'undefined'  ? '' : cfg.cls;
6456         
6457         if (this.active) {
6458             cfg.cls +=  ' active' ;
6459         }
6460         if (this.disabled) {
6461             cfg.cls += ' disabled';
6462         }
6463         
6464         // BS4 only?
6465         if (this.button_weight.length) {
6466             cfg.tag = this.href ? 'a' : 'button';
6467             cfg.html = this.html || '';
6468             cfg.cls += ' btn btn' + (this.button_outline ? '-outline' : '') + '-' + this.button_weight;
6469             if (this.href) {
6470                 cfg.href = this.href;
6471             }
6472             if (this.fa) {
6473                 cfg.html = '<i class="fa fas fa-'+this.fa+'"></i> <span class="nav-html">' + this.html + '</span>';
6474             } else {
6475                 cfg.cls += " nav-html";
6476             }
6477             
6478             // menu .. should add dropdown-menu class - so no need for carat..
6479             
6480             if (this.badge !== '') {
6481                  
6482                 cfg.html += ' <span class="badge badge-secondary">' + this.badge + '</span>';
6483             }
6484             return cfg;
6485         }
6486         
6487         if (this.href || this.html || this.glyphicon || this.icon || this.fa) {
6488             cfg.cn = [
6489                 {
6490                     tag: this.tagtype,
6491                     href : this.href || "#",
6492                     html: this.html || '',
6493                     cls : ''
6494                 }
6495             ];
6496             if (this.tagtype == 'a') {
6497                 cfg.cn[0].cls = 'nav-link' +  (this.active ?  ' active'  : '') + ' ' + this.linkcls;
6498         
6499             }
6500             if (this.icon) {
6501                 cfg.cn[0].html = '<i class="'+this.icon+'"></i> <span class="nav-html">' + cfg.cn[0].html + '</span>';
6502             } else  if (this.fa) {
6503                 cfg.cn[0].html = '<i class="fa fas fa-'+this.fa+'"></i> <span class="nav-html">' + cfg.cn[0].html + '</span>';
6504             } else if(this.glyphicon) {
6505                 cfg.cn[0].html = '<span class="glyphicon glyphicon-' + this.glyphicon + '"></span> '  + cfg.cn[0].html;
6506             } else {
6507                 cfg.cn[0].cls += " nav-html";
6508             }
6509             
6510             if (this.menu) {
6511                 cfg.cn[0].html += " <span class='caret'></span>";
6512              
6513             }
6514             
6515             if (this.badge !== '') {
6516                 cfg.cn[0].html += ' <span class="badge badge-secondary">' + this.badge + '</span>';
6517             }
6518         }
6519         
6520         
6521         
6522         return cfg;
6523     },
6524     onRender : function(ct, position)
6525     {
6526        // Roo.log("Call onRender: " + this.xtype);
6527         if (Roo.bootstrap.version == 4 && ct.dom.type != 'ul') {
6528             this.tag = 'div';
6529         }
6530         
6531         var ret = Roo.bootstrap.nav.Item.superclass.onRender.call(this, ct, position);
6532         this.navLink = this.el.select('.nav-link',true).first();
6533         this.htmlEl = this.el.hasClass('nav-html') ? this.el : this.el.select('.nav-html',true).first();
6534         return ret;
6535     },
6536       
6537     
6538     initEvents: function() 
6539     {
6540         if (typeof (this.menu) != 'undefined') {
6541             this.menu.parentType = this.xtype;
6542             this.menu.triggerEl = this.el;
6543             this.menu = this.addxtype(Roo.apply({}, this.menu));
6544         }
6545         
6546         this.el.on('click', this.onClick, this);
6547         
6548         //if(this.tagtype == 'span'){
6549         //    this.el.select('span',true).on('click', this.onClick, this);
6550         //}
6551        
6552         // at this point parent should be available..
6553         this.parent().register(this);
6554     },
6555     
6556     onClick : function(e)
6557     {
6558         if (e.getTarget('.dropdown-menu-item')) {
6559             // did you click on a menu itemm.... - then don't trigger onclick..
6560             return;
6561         }
6562         
6563         if(
6564                 this.preventDefault ||
6565                                 this.href === false ||
6566                 this.href === '#' 
6567         ){
6568             //Roo.log("NavItem - prevent Default?");
6569             e.preventDefault();
6570         }
6571         
6572         if (this.disabled) {
6573             return;
6574         }
6575         
6576         var tg = Roo.bootstrap.TabGroup.get(this.navId);
6577         if (tg && tg.transition) {
6578             Roo.log("waiting for the transitionend");
6579             return;
6580         }
6581         
6582         
6583         
6584         //Roo.log("fire event clicked");
6585         if(this.fireEvent('click', this, e) === false){
6586             return;
6587         };
6588         
6589         if(this.tagtype == 'span'){
6590             return;
6591         }
6592         
6593         //Roo.log(this.href);
6594         var ael = this.el.select('a',true).first();
6595         //Roo.log(ael);
6596         
6597         if(ael && this.animateRef && this.href.indexOf('#') > -1){
6598             //Roo.log(["test:",ael.dom.href.split("#")[0], document.location.toString().split("#")[0]]);
6599             if (ael.dom.href.split("#")[0] != document.location.toString().split("#")[0]) {
6600                 return; // ignore... - it's a 'hash' to another page.
6601             }
6602             Roo.log("NavItem - prevent Default?");
6603             e.preventDefault();
6604             this.scrollToElement(e);
6605         }
6606         
6607         
6608         var p =  this.parent();
6609    
6610         if (['tabs','pills'].indexOf(p.type)!==-1 && p.pilltype) {
6611             if (typeof(p.setActiveItem) !== 'undefined') {
6612                 p.setActiveItem(this);
6613             }
6614         }
6615         
6616         // if parent is a navbarheader....- and link is probably a '#' page ref.. then remove the expanded menu.
6617         if (p.parentType == 'NavHeaderbar' && !this.menu) {
6618             // remove the collapsed menu expand...
6619             p.parent().el.select('.roo-navbar-collapse',true).removeClass('in');  
6620         }
6621     },
6622     
6623     isActive: function () {
6624         return this.active
6625     },
6626     setActive : function(state, fire, is_was_active)
6627     {
6628         if (this.active && !state && this.navId) {
6629             this.was_active = true;
6630             var nv = Roo.bootstrap.nav.Group.get(this.navId);
6631             if (nv) {
6632                 nv.clearWasActive(this);
6633             }
6634             
6635         }
6636         this.active = state;
6637         
6638         if (!state ) {
6639             this.el.removeClass('active');
6640             this.navLink ? this.navLink.removeClass('active') : false;
6641         } else if (!this.el.hasClass('active')) {
6642             
6643             this.el.addClass('active');
6644             if (Roo.bootstrap.version == 4 && this.navLink ) {
6645                 this.navLink.addClass('active');
6646             }
6647             
6648         }
6649         if (fire) {
6650             this.fireEvent('changed', this, state);
6651         }
6652         
6653         // show a panel if it's registered and related..
6654         
6655         if (!this.navId || !this.tabId || !state || is_was_active) {
6656             return;
6657         }
6658         
6659         var tg = Roo.bootstrap.TabGroup.get(this.navId);
6660         if (!tg) {
6661             return;
6662         }
6663         var pan = tg.getPanelByName(this.tabId);
6664         if (!pan) {
6665             return;
6666         }
6667         // if we can not flip to new panel - go back to old nav highlight..
6668         if (false == tg.showPanel(pan)) {
6669             var nv = Roo.bootstrap.nav.Group.get(this.navId);
6670             if (nv) {
6671                 var onav = nv.getWasActive();
6672                 if (onav) {
6673                     onav.setActive(true, false, true);
6674                 }
6675             }
6676             
6677         }
6678         
6679         
6680         
6681     },
6682      // this should not be here...
6683     setDisabled : function(state)
6684     {
6685         this.disabled = state;
6686         if (!state ) {
6687             this.el.removeClass('disabled');
6688         } else if (!this.el.hasClass('disabled')) {
6689             this.el.addClass('disabled');
6690         }
6691         
6692     },
6693     
6694     /**
6695      * Fetch the element to display the tooltip on.
6696      * @return {Roo.Element} defaults to this.el
6697      */
6698     tooltipEl : function()
6699     {
6700         return this.el; //this.tagtype  == 'a' ? this.el  : this.el.select('' + this.tagtype + '', true).first();
6701     },
6702     
6703     scrollToElement : function(e)
6704     {
6705         var c = document.body;
6706         
6707         /*
6708          * Firefox / IE places the overflow at the html level, unless specifically styled to behave differently.
6709          */
6710         if(Roo.isFirefox || Roo.isIE || Roo.isIE11){
6711             c = document.documentElement;
6712         }
6713         
6714         var target = Roo.get(c).select('a[name=' + this.href.split('#')[1] +']', true).first();
6715         
6716         if(!target){
6717             return;
6718         }
6719
6720         var o = target.calcOffsetsTo(c);
6721         
6722         var options = {
6723             target : target,
6724             value : o[1]
6725         };
6726         
6727         this.fireEvent('scrollto', this, options, e);
6728         
6729         Roo.get(c).scrollTo('top', options.value, true);
6730         
6731         return;
6732     },
6733     /**
6734      * Set the HTML (text content) of the item
6735      * @param {string} html  content for the nav item
6736      */
6737     setHtml : function(html)
6738     {
6739         this.html = html;
6740         this.htmlEl.dom.innerHTML = html;
6741         
6742     } 
6743 });
6744  
6745
6746  /*
6747  * - LGPL
6748  *
6749  * sidebar item
6750  *
6751  *  li
6752  *    <span> icon </span>
6753  *    <span> text </span>
6754  *    <span>badge </span>
6755  */
6756
6757 /**
6758  * @class Roo.bootstrap.nav.SidebarItem
6759  * @extends Roo.bootstrap.nav.Item
6760  * Bootstrap Navbar.NavSidebarItem class
6761  * 
6762  * {String} badgeWeight (default|primary|success|info|warning|danger)the extra classes for the badge
6763  * {Boolean} open is the menu open
6764  * {Boolean} buttonView use button as the tigger el rather that a (default false)
6765  * {String} buttonWeight (default|primary|success|info|warning|danger)the extra classes for the button
6766  * {String} buttonSize (sm|md|lg)the extra classes for the button
6767  * {Boolean} showArrow show arrow next to the text (default true)
6768  * @constructor
6769  * Create a new Navbar Button
6770  * @param {Object} config The config object
6771  */
6772 Roo.bootstrap.nav.SidebarItem = function(config){
6773     Roo.bootstrap.nav.SidebarItem.superclass.constructor.call(this, config);
6774     this.addEvents({
6775         // raw events
6776         /**
6777          * @event click
6778          * The raw click event for the entire grid.
6779          * @param {Roo.EventObject} e
6780          */
6781         "click" : true,
6782          /**
6783             * @event changed
6784             * Fires when the active item active state changes
6785             * @param {Roo.bootstrap.nav.SidebarItem} this
6786             * @param {boolean} state the new state
6787              
6788          */
6789         'changed': true
6790     });
6791    
6792 };
6793
6794 Roo.extend(Roo.bootstrap.nav.SidebarItem, Roo.bootstrap.nav.Item,  {
6795     
6796     badgeWeight : 'default',
6797     
6798     open: false,
6799     
6800     buttonView : false,
6801     
6802     buttonWeight : 'default',
6803     
6804     buttonSize : 'md',
6805     
6806     showArrow : true,
6807     
6808     getAutoCreate : function(){
6809         
6810         
6811         var a = {
6812                 tag: 'a',
6813                 href : this.href || '#',
6814                 cls: '',
6815                 html : '',
6816                 cn : []
6817         };
6818         
6819         if(this.buttonView){
6820             a = {
6821                 tag: 'button',
6822                 href : this.href || '#',
6823                 cls: 'btn btn-' + this.buttonWeight + ' btn-' + this.buttonSize + 'roo-button-dropdown-toggle',
6824                 html : this.html,
6825                 cn : []
6826             };
6827         }
6828         
6829         var cfg = {
6830             tag: 'li',
6831             cls: '',
6832             cn: [ a ]
6833         };
6834         
6835         if (this.active) {
6836             cfg.cls += ' active';
6837         }
6838         
6839         if (this.disabled) {
6840             cfg.cls += ' disabled';
6841         }
6842         if (this.open) {
6843             cfg.cls += ' open x-open';
6844         }
6845         // left icon..
6846         if (this.glyphicon || this.icon) {
6847             var c = this.glyphicon  ? ('glyphicon glyphicon-'+this.glyphicon)  : this.icon;
6848             a.cn.push({ tag : 'i', cls : c }) ;
6849         }
6850         
6851         if(!this.buttonView){
6852             var span = {
6853                 tag: 'span',
6854                 html : this.html || ''
6855             };
6856
6857             a.cn.push(span);
6858             
6859         }
6860         
6861         if (this.badge !== '') {
6862             a.cn.push({ tag: 'span',  cls : 'badge pull-right badge-' + this.badgeWeight, html: this.badge }); 
6863         }
6864         
6865         if (this.menu) {
6866             
6867             if(this.showArrow){
6868                 a.cn.push({ tag : 'i', cls : 'glyphicon glyphicon-chevron-down pull-right'});
6869             }
6870             
6871             a.cls += ' dropdown-toggle treeview' ;
6872         }
6873         
6874         return cfg;
6875     },
6876     
6877     initEvents : function()
6878     { 
6879         if (typeof (this.menu) != 'undefined') {
6880             this.menu.parentType = this.xtype;
6881             this.menu.triggerEl = this.el;
6882             this.menu = this.addxtype(Roo.apply({}, this.menu));
6883         }
6884         
6885         this.el.on('click', this.onClick, this);
6886         
6887         if(this.badge !== ''){
6888             this.badgeEl = this.el.select('.badge', true).first().setVisibilityMode(Roo.Element.DISPLAY);
6889         }
6890         
6891     },
6892     
6893     onClick : function(e)
6894     {
6895         if(this.disabled){
6896             e.preventDefault();
6897             return;
6898         }
6899         
6900         if(this.preventDefault){
6901             e.preventDefault();
6902         }
6903         
6904         this.fireEvent('click', this, e);
6905     },
6906     
6907     disable : function()
6908     {
6909         this.setDisabled(true);
6910     },
6911     
6912     enable : function()
6913     {
6914         this.setDisabled(false);
6915     },
6916     
6917     setDisabled : function(state)
6918     {
6919         if(this.disabled == state){
6920             return;
6921         }
6922         
6923         this.disabled = state;
6924         
6925         if (state) {
6926             this.el.addClass('disabled');
6927             return;
6928         }
6929         
6930         this.el.removeClass('disabled');
6931         
6932         return;
6933     },
6934     
6935     setActive : function(state)
6936     {
6937         if(this.active == state){
6938             return;
6939         }
6940         
6941         this.active = state;
6942         
6943         if (state) {
6944             this.el.addClass('active');
6945             return;
6946         }
6947         
6948         this.el.removeClass('active');
6949         
6950         return;
6951     },
6952     
6953     isActive: function () 
6954     {
6955         return this.active;
6956     },
6957     
6958     setBadge : function(str)
6959     {
6960         if(!this.badgeEl){
6961             return;
6962         }
6963         
6964         this.badgeEl.dom.innerHTML = str;
6965     }
6966     
6967    
6968      
6969  
6970 });
6971  
6972
6973  /*
6974  * - LGPL
6975  *
6976  * nav progress bar
6977  * 
6978  */
6979
6980 /**
6981  * @class Roo.bootstrap.nav.ProgressBar
6982  * @extends Roo.bootstrap.Component
6983  * @children Roo.bootstrap.nav.ProgressBarItem
6984  * Bootstrap NavProgressBar class
6985  * 
6986  * @constructor
6987  * Create a new nav progress bar - a bar indicating step along a process
6988  * @param {Object} config The config object
6989  */
6990
6991 Roo.bootstrap.nav.ProgressBar = function(config){
6992     Roo.bootstrap.nav.ProgressBar.superclass.constructor.call(this, config);
6993
6994     this.bullets = this.bullets || [];
6995    
6996 //    Roo.bootstrap.nav.ProgressBar.register(this);
6997      this.addEvents({
6998         /**
6999              * @event changed
7000              * Fires when the active item changes
7001              * @param {Roo.bootstrap.nav.ProgressBar} this
7002              * @param {Roo.bootstrap.nav.ProgressItem} selected The item selected
7003              * @param {Roo.bootstrap.nav.ProgressItem} prev The previously selected item 
7004          */
7005         'changed': true
7006      });
7007     
7008 };
7009
7010 Roo.extend(Roo.bootstrap.nav.ProgressBar, Roo.bootstrap.Component,  {
7011     /**
7012      * @cfg {Roo.bootstrap.nav.ProgressItem} NavProgressBar:bullets[]
7013      * Bullets for the Nav Progress bar for the toolbar
7014      */
7015     bullets : [],
7016     barItems : [],
7017     
7018     getAutoCreate : function()
7019     {
7020         var cfg = Roo.apply({}, Roo.bootstrap.nav.ProgressBar.superclass.getAutoCreate.call(this));
7021         
7022         cfg = {
7023             tag : 'div',
7024             cls : 'roo-navigation-bar-group',
7025             cn : [
7026                 {
7027                     tag : 'div',
7028                     cls : 'roo-navigation-top-bar'
7029                 },
7030                 {
7031                     tag : 'div',
7032                     cls : 'roo-navigation-bullets-bar',
7033                     cn : [
7034                         {
7035                             tag : 'ul',
7036                             cls : 'roo-navigation-bar'
7037                         }
7038                     ]
7039                 },
7040                 
7041                 {
7042                     tag : 'div',
7043                     cls : 'roo-navigation-bottom-bar'
7044                 }
7045             ]
7046             
7047         };
7048         
7049         return cfg;
7050         
7051     },
7052     
7053     initEvents: function() 
7054     {
7055         
7056     },
7057     
7058     onRender : function(ct, position) 
7059     {
7060         Roo.bootstrap.nav.ProgressBar.superclass.onRender.call(this, ct, position);
7061         
7062         if(this.bullets.length){
7063             Roo.each(this.bullets, function(b){
7064                this.addItem(b);
7065             }, this);
7066         }
7067         
7068         this.format();
7069         
7070     },
7071     
7072     addItem : function(cfg)
7073     {
7074         var item = new Roo.bootstrap.nav.ProgressItem(cfg);
7075         
7076         item.parentId = this.id;
7077         item.render(this.el.select('.roo-navigation-bar', true).first(), null);
7078         
7079         if(cfg.html){
7080             var top = new Roo.bootstrap.Element({
7081                 tag : 'div',
7082                 cls : 'roo-navigation-bar-text'
7083             });
7084             
7085             var bottom = new Roo.bootstrap.Element({
7086                 tag : 'div',
7087                 cls : 'roo-navigation-bar-text'
7088             });
7089             
7090             top.onRender(this.el.select('.roo-navigation-top-bar', true).first(), null);
7091             bottom.onRender(this.el.select('.roo-navigation-bottom-bar', true).first(), null);
7092             
7093             var topText = new Roo.bootstrap.Element({
7094                 tag : 'span',
7095                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? cfg.html : ''
7096             });
7097             
7098             var bottomText = new Roo.bootstrap.Element({
7099                 tag : 'span',
7100                 html : (typeof(cfg.position) != 'undefined' && cfg.position == 'top') ? '' : cfg.html
7101             });
7102             
7103             topText.onRender(top.el, null);
7104             bottomText.onRender(bottom.el, null);
7105             
7106             item.topEl = top;
7107             item.bottomEl = bottom;
7108         }
7109         
7110         this.barItems.push(item);
7111         
7112         return item;
7113     },
7114     
7115     getActive : function()
7116     {
7117         var active = false;
7118         
7119         Roo.each(this.barItems, function(v){
7120             
7121             if (!v.isActive()) {
7122                 return;
7123             }
7124             
7125             active = v;
7126             return false;
7127             
7128         });
7129         
7130         return active;
7131     },
7132     
7133     setActiveItem : function(item)
7134     {
7135         var prev = false;
7136         
7137         Roo.each(this.barItems, function(v){
7138             if (v.rid == item.rid) {
7139                 return ;
7140             }
7141             
7142             if (v.isActive()) {
7143                 v.setActive(false);
7144                 prev = v;
7145             }
7146         });
7147
7148         item.setActive(true);
7149         
7150         this.fireEvent('changed', this, item, prev);
7151     },
7152     
7153     getBarItem: function(rid)
7154     {
7155         var ret = false;
7156         
7157         Roo.each(this.barItems, function(e) {
7158             if (e.rid != rid) {
7159                 return;
7160             }
7161             
7162             ret =  e;
7163             return false;
7164         });
7165         
7166         return ret;
7167     },
7168     
7169     indexOfItem : function(item)
7170     {
7171         var index = false;
7172         
7173         Roo.each(this.barItems, function(v, i){
7174             
7175             if (v.rid != item.rid) {
7176                 return;
7177             }
7178             
7179             index = i;
7180             return false
7181         });
7182         
7183         return index;
7184     },
7185     
7186     setActiveNext : function()
7187     {
7188         var i = this.indexOfItem(this.getActive());
7189         
7190         if (i > this.barItems.length) {
7191             return;
7192         }
7193         
7194         this.setActiveItem(this.barItems[i+1]);
7195     },
7196     
7197     setActivePrev : function()
7198     {
7199         var i = this.indexOfItem(this.getActive());
7200         
7201         if (i  < 1) {
7202             return;
7203         }
7204         
7205         this.setActiveItem(this.barItems[i-1]);
7206     },
7207     
7208     format : function()
7209     {
7210         if(!this.barItems.length){
7211             return;
7212         }
7213      
7214         var width = 100 / this.barItems.length;
7215         
7216         Roo.each(this.barItems, function(i){
7217             i.el.setStyle('width', width + '%');
7218             i.topEl.el.setStyle('width', width + '%');
7219             i.bottomEl.el.setStyle('width', width + '%');
7220         }, this);
7221         
7222     }
7223     
7224 });
7225 /*
7226  * - LGPL
7227  *
7228  * Nav Progress Item
7229  * 
7230  */
7231
7232 /**
7233  * @class Roo.bootstrap.nav.ProgressBarItem
7234  * @extends Roo.bootstrap.Component
7235  * Bootstrap NavProgressBarItem class
7236  * @cfg {String} rid the reference id
7237  * @cfg {Boolean} active (true|false) Is item active default false
7238  * @cfg {Boolean} disabled (true|false) Is item active default false
7239  * @cfg {String} html
7240  * @cfg {String} position (top|bottom) text position default bottom
7241  * @cfg {String} icon show icon instead of number
7242  * 
7243  * @constructor
7244  * Create a new NavProgressBarItem
7245  * @param {Object} config The config object
7246  */
7247 Roo.bootstrap.nav.ProgressBarItem = function(config){
7248     Roo.bootstrap.nav.ProgressBarItem.superclass.constructor.call(this, config);
7249     this.addEvents({
7250         // raw events
7251         /**
7252          * @event click
7253          * The raw click event for the entire grid.
7254          * @param {Roo.bootstrap.nav.ProgressBarItem} this
7255          * @param {Roo.EventObject} e
7256          */
7257         "click" : true
7258     });
7259    
7260 };
7261
7262 Roo.extend(Roo.bootstrap.nav.ProgressBarItem, Roo.bootstrap.Component,  {
7263     
7264     rid : '',
7265     active : false,
7266     disabled : false,
7267     html : '',
7268     position : 'bottom',
7269     icon : false,
7270     
7271     getAutoCreate : function()
7272     {
7273         var iconCls = 'roo-navigation-bar-item-icon';
7274         
7275         iconCls += ((this.icon) ? (' ' + this.icon) : (' step-number')) ;
7276         
7277         var cfg = {
7278             tag: 'li',
7279             cls: 'roo-navigation-bar-item',
7280             cn : [
7281                 {
7282                     tag : 'i',
7283                     cls : iconCls
7284                 }
7285             ]
7286         };
7287         
7288         if(this.active){
7289             cfg.cls += ' active';
7290         }
7291         if(this.disabled){
7292             cfg.cls += ' disabled';
7293         }
7294         
7295         return cfg;
7296     },
7297     
7298     disable : function()
7299     {
7300         this.setDisabled(true);
7301     },
7302     
7303     enable : function()
7304     {
7305         this.setDisabled(false);
7306     },
7307     
7308     initEvents: function() 
7309     {
7310         this.iconEl = this.el.select('.roo-navigation-bar-item-icon', true).first();
7311         
7312         this.iconEl.on('click', this.onClick, this);
7313     },
7314     
7315     onClick : function(e)
7316     {
7317         e.preventDefault();
7318         
7319         if(this.disabled){
7320             return;
7321         }
7322         
7323         if(this.fireEvent('click', this, e) === false){
7324             return;
7325         };
7326         
7327         this.parent().setActiveItem(this);
7328     },
7329     
7330     isActive: function () 
7331     {
7332         return this.active;
7333     },
7334     
7335     setActive : function(state)
7336     {
7337         if(this.active == state){
7338             return;
7339         }
7340         
7341         this.active = state;
7342         
7343         if (state) {
7344             this.el.addClass('active');
7345             return;
7346         }
7347         
7348         this.el.removeClass('active');
7349         
7350         return;
7351     },
7352     
7353     setDisabled : function(state)
7354     {
7355         if(this.disabled == state){
7356             return;
7357         }
7358         
7359         this.disabled = state;
7360         
7361         if (state) {
7362             this.el.addClass('disabled');
7363             return;
7364         }
7365         
7366         this.el.removeClass('disabled');
7367     },
7368     
7369     tooltipEl : function()
7370     {
7371         return this.el.select('.roo-navigation-bar-item-icon', true).first();;
7372     }
7373 });
7374  
7375
7376  /*
7377  * - LGPL
7378  *
7379  *  Breadcrumb Nav
7380  * 
7381  */
7382 Roo.namespace('Roo.bootstrap.breadcrumb');
7383
7384
7385 /**
7386  * @class Roo.bootstrap.breadcrumb.Nav
7387  * @extends Roo.bootstrap.Component
7388  * Bootstrap Breadcrumb Nav Class
7389  *  
7390  * @children Roo.bootstrap.breadcrumb.Item
7391  * 
7392  * @constructor
7393  * Create a new breadcrumb.Nav
7394  * @param {Object} config The config object
7395  */
7396
7397
7398 Roo.bootstrap.breadcrumb.Nav = function(config){
7399     Roo.bootstrap.breadcrumb.Nav.superclass.constructor.call(this, config);
7400     
7401     
7402 };
7403
7404 Roo.extend(Roo.bootstrap.breadcrumb.Nav, Roo.bootstrap.Component,  {
7405     
7406     getAutoCreate : function()
7407     {
7408
7409         var cfg = {
7410             tag: 'nav',
7411             cn : [
7412                 {
7413                     tag : 'ol',
7414                     cls : 'breadcrumb'
7415                 }
7416             ]
7417             
7418         };
7419           
7420         return cfg;
7421     },
7422     
7423     initEvents: function()
7424     {
7425         this.olEl = this.el.select('ol',true).first();    
7426     },
7427     getChildContainer : function()
7428     {
7429         return this.olEl;  
7430     }
7431     
7432 });
7433
7434  /*
7435  * - LGPL
7436  *
7437  *  Breadcrumb Item
7438  * 
7439  */
7440
7441
7442 /**
7443  * @class Roo.bootstrap.breadcrumb.Nav
7444  * @extends Roo.bootstrap.Component
7445  * @children Roo.bootstrap.Component
7446  * @parent Roo.bootstrap.breadcrumb.Nav
7447  * Bootstrap Breadcrumb Nav Class
7448  *  
7449  * 
7450  * @cfg {String} html the content of the link.
7451  * @cfg {String} href where it links to if '#' is used the link will be handled by onClick.
7452  * @cfg {Boolean} active is it active
7453
7454  * 
7455  * @constructor
7456  * Create a new breadcrumb.Nav
7457  * @param {Object} config The config object
7458  */
7459
7460 Roo.bootstrap.breadcrumb.Item = function(config){
7461     Roo.bootstrap.breadcrumb.Item.superclass.constructor.call(this, config);
7462     this.addEvents({
7463         // img events
7464         /**
7465          * @event click
7466          * The img click event for the img.
7467          * @param {Roo.EventObject} e
7468          */
7469         "click" : true
7470     });
7471     
7472 };
7473
7474 Roo.extend(Roo.bootstrap.breadcrumb.Item, Roo.bootstrap.Component,  {
7475     
7476     href: false,
7477     html : '',
7478     
7479     getAutoCreate : function()
7480     {
7481
7482         var cfg = {
7483             tag: 'li',
7484             cls : 'breadcrumb-item' + (this.active ? ' active' : '')
7485         };
7486         if (this.href !== false) {
7487             cfg.cn = [{
7488                 tag : 'a',
7489                 href : this.href,
7490                 html : this.html
7491             }];
7492         } else {
7493             cfg.html = this.html;
7494         }
7495         
7496         return cfg;
7497     },
7498     
7499     initEvents: function()
7500     {
7501         if (this.href) {
7502             this.el.select('a', true).first().on('click',this.onClick, this)
7503         }
7504         
7505     },
7506     onClick : function(e)
7507     {
7508         e.preventDefault();
7509         this.fireEvent('click',this,  e);
7510     }
7511     
7512 });
7513
7514  /*
7515  * - LGPL
7516  *
7517  * row
7518  * 
7519  */
7520
7521 /**
7522  * @class Roo.bootstrap.Row
7523  * @extends Roo.bootstrap.Component
7524  * @children Roo.bootstrap.Component
7525  * Bootstrap Row class (contains columns...)
7526  * 
7527  * @constructor
7528  * Create a new Row
7529  * @param {Object} config The config object
7530  */
7531
7532 Roo.bootstrap.Row = function(config){
7533     Roo.bootstrap.Row.superclass.constructor.call(this, config);
7534 };
7535
7536 Roo.extend(Roo.bootstrap.Row, Roo.bootstrap.Component,  {
7537     
7538     getAutoCreate : function(){
7539        return {
7540             cls: 'row clearfix'
7541        };
7542     }
7543     
7544     
7545 });
7546
7547  
7548
7549  /*
7550  * - LGPL
7551  *
7552  * pagination
7553  * 
7554  */
7555
7556 /**
7557  * @class Roo.bootstrap.Pagination
7558  * @extends Roo.bootstrap.Component
7559  * @children Roo.bootstrap.Pagination
7560  * Bootstrap Pagination class
7561  * 
7562  * @cfg {String} size (xs|sm|md|lg|xl)
7563  * @cfg {Boolean} inverse 
7564  * 
7565  * @constructor
7566  * Create a new Pagination
7567  * @param {Object} config The config object
7568  */
7569
7570 Roo.bootstrap.Pagination = function(config){
7571     Roo.bootstrap.Pagination.superclass.constructor.call(this, config);
7572 };
7573
7574 Roo.extend(Roo.bootstrap.Pagination, Roo.bootstrap.Component,  {
7575     
7576     cls: false,
7577     size: false,
7578     inverse: false,
7579     
7580     getAutoCreate : function(){
7581         var cfg = {
7582             tag: 'ul',
7583                 cls: 'pagination'
7584         };
7585         if (this.inverse) {
7586             cfg.cls += ' inverse';
7587         }
7588         if (this.html) {
7589             cfg.html=this.html;
7590         }
7591         if (this.cls) {
7592             cfg.cls += " " + this.cls;
7593         }
7594         return cfg;
7595     }
7596    
7597 });
7598
7599  
7600
7601  /*
7602  * - LGPL
7603  *
7604  * Pagination item
7605  * 
7606  */
7607
7608
7609 /**
7610  * @class Roo.bootstrap.PaginationItem
7611  * @extends Roo.bootstrap.Component
7612  * Bootstrap PaginationItem class
7613  * @cfg {String} html text
7614  * @cfg {String} href the link
7615  * @cfg {Boolean} preventDefault (true | false) default true
7616  * @cfg {Boolean} active (true | false) default false
7617  * @cfg {Boolean} disabled default false
7618  * 
7619  * 
7620  * @constructor
7621  * Create a new PaginationItem
7622  * @param {Object} config The config object
7623  */
7624
7625
7626 Roo.bootstrap.PaginationItem = function(config){
7627     Roo.bootstrap.PaginationItem.superclass.constructor.call(this, config);
7628     this.addEvents({
7629         // raw events
7630         /**
7631          * @event click
7632          * The raw click event for the entire grid.
7633          * @param {Roo.EventObject} e
7634          */
7635         "click" : true
7636     });
7637 };
7638
7639 Roo.extend(Roo.bootstrap.PaginationItem, Roo.bootstrap.Component,  {
7640     
7641     href : false,
7642     html : false,
7643     preventDefault: true,
7644     active : false,
7645     cls : false,
7646     disabled: false,
7647     
7648     getAutoCreate : function(){
7649         var cfg= {
7650             tag: 'li',
7651             cn: [
7652                 {
7653                     tag : 'a',
7654                     href : this.href ? this.href : '#',
7655                     html : this.html ? this.html : ''
7656                 }
7657             ]
7658         };
7659         
7660         if(this.cls){
7661             cfg.cls = this.cls;
7662         }
7663         
7664         if(this.disabled){
7665             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' disabled' : 'disabled';
7666         }
7667         
7668         if(this.active){
7669             cfg.cls = typeof(cfg.cls) !== 'undefined' ? cfg.cls + ' active' : 'active';
7670         }
7671         
7672         return cfg;
7673     },
7674     
7675     initEvents: function() {
7676         
7677         this.el.on('click', this.onClick, this);
7678         
7679     },
7680     onClick : function(e)
7681     {
7682         Roo.log('PaginationItem on click ');
7683         if(this.preventDefault){
7684             e.preventDefault();
7685         }
7686         
7687         if(this.disabled){
7688             return;
7689         }
7690         
7691         this.fireEvent('click', this, e);
7692     }
7693    
7694 });
7695
7696  
7697
7698  /*
7699  * - LGPL
7700  *
7701  * slider
7702  * 
7703  */
7704
7705
7706 /**
7707  * @class Roo.bootstrap.Slider
7708  * @extends Roo.bootstrap.Component
7709  * Bootstrap Slider class
7710  *    
7711  * @constructor
7712  * Create a new Slider
7713  * @param {Object} config The config object
7714  */
7715
7716 Roo.bootstrap.Slider = function(config){
7717     Roo.bootstrap.Slider.superclass.constructor.call(this, config);
7718 };
7719
7720 Roo.extend(Roo.bootstrap.Slider, Roo.bootstrap.Component,  {
7721     
7722     getAutoCreate : function(){
7723         
7724         var cfg = {
7725             tag: 'div',
7726             cls: 'slider slider-sample1 vertical-handler ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all',
7727             cn: [
7728                 {
7729                     tag: 'a',
7730                     cls: 'ui-slider-handle ui-state-default ui-corner-all'
7731                 }
7732             ]
7733         };
7734         
7735         return cfg;
7736     }
7737    
7738 });
7739
7740  /*
7741  * Based on:
7742  * Ext JS Library 1.1.1
7743  * Copyright(c) 2006-2007, Ext JS, LLC.
7744  *
7745  * Originally Released Under LGPL - original licence link has changed is not relivant.
7746  *
7747  * Fork - LGPL
7748  * <script type="text/javascript">
7749  */
7750  /**
7751  * @extends Roo.dd.DDProxy
7752  * @class Roo.grid.SplitDragZone
7753  * Support for Column Header resizing
7754  * @constructor
7755  * @param {Object} config
7756  */
7757 // private
7758 // This is a support class used internally by the Grid components
7759 Roo.grid.SplitDragZone = function(grid, hd, hd2){
7760     this.grid = grid;
7761     this.view = grid.getView();
7762     this.proxy = this.view.resizeProxy;
7763     Roo.grid.SplitDragZone.superclass.constructor.call(
7764         this,
7765         hd, // ID
7766         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
7767         {  // CONFIG
7768             dragElId : Roo.id(this.proxy.dom),
7769             resizeFrame:false
7770         }
7771     );
7772     
7773     this.setHandleElId(Roo.id(hd));
7774     if (hd2 !== false) {
7775         this.setOuterHandleElId(Roo.id(hd2));
7776     }
7777     
7778     this.scroll = false;
7779 };
7780 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
7781     fly: Roo.Element.fly,
7782
7783     b4StartDrag : function(x, y){
7784         this.view.headersDisabled = true;
7785         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
7786                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
7787         );
7788         this.proxy.setHeight(h);
7789         
7790         // for old system colWidth really stored the actual width?
7791         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
7792         // which in reality did not work.. - it worked only for fixed sizes
7793         // for resizable we need to use actual sizes.
7794         var w = this.cm.getColumnWidth(this.cellIndex);
7795         if (!this.view.mainWrap) {
7796             // bootstrap.
7797             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
7798         }
7799         
7800         
7801         
7802         // this was w-this.grid.minColumnWidth;
7803         // doesnt really make sense? - w = thie curren width or the rendered one?
7804         var minw = Math.max(w-this.grid.minColumnWidth, 0);
7805         this.resetConstraints();
7806         this.setXConstraint(minw, 1000);
7807         this.setYConstraint(0, 0);
7808         this.minX = x - minw;
7809         this.maxX = x + 1000;
7810         this.startPos = x;
7811         if (!this.view.mainWrap) { // this is Bootstrap code..
7812             this.getDragEl().style.display='block';
7813         }
7814         
7815         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
7816     },
7817
7818
7819     handleMouseDown : function(e){
7820         ev = Roo.EventObject.setEvent(e);
7821         var t = this.fly(ev.getTarget());
7822         if(t.hasClass("x-grid-split")){
7823             this.cellIndex = this.view.getCellIndex(t.dom);
7824             this.split = t.dom;
7825             this.cm = this.grid.colModel;
7826             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
7827                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
7828             }
7829         }
7830     },
7831
7832     endDrag : function(e){
7833         this.view.headersDisabled = false;
7834         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
7835         var diff = endX - this.startPos;
7836         // 
7837         var w = this.cm.getColumnWidth(this.cellIndex);
7838         if (!this.view.mainWrap) {
7839             w = 0;
7840         }
7841         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
7842     },
7843
7844     autoOffset : function(){
7845         this.setDelta(0,0);
7846     }
7847 });/*
7848  * Based on:
7849  * Ext JS Library 1.1.1
7850  * Copyright(c) 2006-2007, Ext JS, LLC.
7851  *
7852  * Originally Released Under LGPL - original licence link has changed is not relivant.
7853  *
7854  * Fork - LGPL
7855  * <script type="text/javascript">
7856  */
7857
7858 /**
7859  * @class Roo.grid.AbstractSelectionModel
7860  * @extends Roo.util.Observable
7861  * @abstract
7862  * Abstract base class for grid SelectionModels.  It provides the interface that should be
7863  * implemented by descendant classes.  This class should not be directly instantiated.
7864  * @constructor
7865  */
7866 Roo.grid.AbstractSelectionModel = function(){
7867     this.locked = false;
7868     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
7869 };
7870
7871 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
7872     /** @ignore Called by the grid automatically. Do not call directly. */
7873     init : function(grid){
7874         this.grid = grid;
7875         this.initEvents();
7876     },
7877
7878     /**
7879      * Locks the selections.
7880      */
7881     lock : function(){
7882         this.locked = true;
7883     },
7884
7885     /**
7886      * Unlocks the selections.
7887      */
7888     unlock : function(){
7889         this.locked = false;
7890     },
7891
7892     /**
7893      * Returns true if the selections are locked.
7894      * @return {Boolean}
7895      */
7896     isLocked : function(){
7897         return this.locked;
7898     }
7899 });/*
7900  * Based on:
7901  * Ext JS Library 1.1.1
7902  * Copyright(c) 2006-2007, Ext JS, LLC.
7903  *
7904  * Originally Released Under LGPL - original licence link has changed is not relivant.
7905  *
7906  * Fork - LGPL
7907  * <script type="text/javascript">
7908  */
7909 /**
7910  * @extends Roo.grid.AbstractSelectionModel
7911  * @class Roo.grid.RowSelectionModel
7912  * The default SelectionModel used by {@link Roo.grid.Grid}.
7913  * It supports multiple selections and keyboard selection/navigation. 
7914  * @constructor
7915  * @param {Object} config
7916  */
7917 Roo.grid.RowSelectionModel = function(config){
7918     Roo.apply(this, config);
7919     this.selections = new Roo.util.MixedCollection(false, function(o){
7920         return o.id;
7921     });
7922
7923     this.last = false;
7924     this.lastActive = false;
7925
7926     this.addEvents({
7927         /**
7928         * @event selectionchange
7929         * Fires when the selection changes
7930         * @param {SelectionModel} this
7931         */
7932        "selectionchange" : true,
7933        /**
7934         * @event afterselectionchange
7935         * Fires after the selection changes (eg. by key press or clicking)
7936         * @param {SelectionModel} this
7937         */
7938        "afterselectionchange" : true,
7939        /**
7940         * @event beforerowselect
7941         * Fires when a row is selected being selected, return false to cancel.
7942         * @param {SelectionModel} this
7943         * @param {Number} rowIndex The selected index
7944         * @param {Boolean} keepExisting False if other selections will be cleared
7945         */
7946        "beforerowselect" : true,
7947        /**
7948         * @event rowselect
7949         * Fires when a row is selected.
7950         * @param {SelectionModel} this
7951         * @param {Number} rowIndex The selected index
7952         * @param {Roo.data.Record} r The record
7953         */
7954        "rowselect" : true,
7955        /**
7956         * @event rowdeselect
7957         * Fires when a row is deselected.
7958         * @param {SelectionModel} this
7959         * @param {Number} rowIndex The selected index
7960         */
7961         "rowdeselect" : true
7962     });
7963     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
7964     this.locked = false;
7965 };
7966
7967 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
7968     /**
7969      * @cfg {Boolean} singleSelect
7970      * True to allow selection of only one row at a time (defaults to false)
7971      */
7972     singleSelect : false,
7973
7974     // private
7975     initEvents : function(){
7976
7977         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
7978             this.grid.on("mousedown", this.handleMouseDown, this);
7979         }else{ // allow click to work like normal
7980             this.grid.on("rowclick", this.handleDragableRowClick, this);
7981         }
7982         // bootstrap does not have a view..
7983         var view = this.grid.view ? this.grid.view : this.grid;
7984         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
7985             "up" : function(e){
7986                 if(!e.shiftKey){
7987                     this.selectPrevious(e.shiftKey);
7988                 }else if(this.last !== false && this.lastActive !== false){
7989                     var last = this.last;
7990                     this.selectRange(this.last,  this.lastActive-1);
7991                     view.focusRow(this.lastActive);
7992                     if(last !== false){
7993                         this.last = last;
7994                     }
7995                 }else{
7996                     this.selectFirstRow();
7997                 }
7998                 this.fireEvent("afterselectionchange", this);
7999             },
8000             "down" : function(e){
8001                 if(!e.shiftKey){
8002                     this.selectNext(e.shiftKey);
8003                 }else if(this.last !== false && this.lastActive !== false){
8004                     var last = this.last;
8005                     this.selectRange(this.last,  this.lastActive+1);
8006                     view.focusRow(this.lastActive);
8007                     if(last !== false){
8008                         this.last = last;
8009                     }
8010                 }else{
8011                     this.selectFirstRow();
8012                 }
8013                 this.fireEvent("afterselectionchange", this);
8014             },
8015             scope: this
8016         });
8017
8018          
8019         view.on("refresh", this.onRefresh, this);
8020         view.on("rowupdated", this.onRowUpdated, this);
8021         view.on("rowremoved", this.onRemove, this);
8022     },
8023
8024     // private
8025     onRefresh : function(){
8026         var ds = this.grid.ds, i, v = this.grid.view;
8027         var s = this.selections;
8028         s.each(function(r){
8029             if((i = ds.indexOfId(r.id)) != -1){
8030                 v.onRowSelect(i);
8031                 s.add(ds.getAt(i)); // updating the selection relate data
8032             }else{
8033                 s.remove(r);
8034             }
8035         });
8036     },
8037
8038     // private
8039     onRemove : function(v, index, r){
8040         this.selections.remove(r);
8041     },
8042
8043     // private
8044     onRowUpdated : function(v, index, r){
8045         if(this.isSelected(r)){
8046             v.onRowSelect(index);
8047         }
8048     },
8049
8050     /**
8051      * Select records.
8052      * @param {Array} records The records to select
8053      * @param {Boolean} keepExisting (optional) True to keep existing selections
8054      */
8055     selectRecords : function(records, keepExisting){
8056         if(!keepExisting){
8057             this.clearSelections();
8058         }
8059         var ds = this.grid.ds;
8060         for(var i = 0, len = records.length; i < len; i++){
8061             this.selectRow(ds.indexOf(records[i]), true);
8062         }
8063     },
8064
8065     /**
8066      * Gets the number of selected rows.
8067      * @return {Number}
8068      */
8069     getCount : function(){
8070         return this.selections.length;
8071     },
8072
8073     /**
8074      * Selects the first row in the grid.
8075      */
8076     selectFirstRow : function(){
8077         this.selectRow(0);
8078     },
8079
8080     /**
8081      * Select the last row.
8082      * @param {Boolean} keepExisting (optional) True to keep existing selections
8083      */
8084     selectLastRow : function(keepExisting){
8085         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
8086     },
8087
8088     /**
8089      * Selects the row immediately following the last selected row.
8090      * @param {Boolean} keepExisting (optional) True to keep existing selections
8091      */
8092     selectNext : function(keepExisting){
8093         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
8094             this.selectRow(this.last+1, keepExisting);
8095             var view = this.grid.view ? this.grid.view : this.grid;
8096             view.focusRow(this.last);
8097         }
8098     },
8099
8100     /**
8101      * Selects the row that precedes the last selected row.
8102      * @param {Boolean} keepExisting (optional) True to keep existing selections
8103      */
8104     selectPrevious : function(keepExisting){
8105         if(this.last){
8106             this.selectRow(this.last-1, keepExisting);
8107             var view = this.grid.view ? this.grid.view : this.grid;
8108             view.focusRow(this.last);
8109         }
8110     },
8111
8112     /**
8113      * Returns the selected records
8114      * @return {Array} Array of selected records
8115      */
8116     getSelections : function(){
8117         return [].concat(this.selections.items);
8118     },
8119
8120     /**
8121      * Returns the first selected record.
8122      * @return {Record}
8123      */
8124     getSelected : function(){
8125         return this.selections.itemAt(0);
8126     },
8127
8128
8129     /**
8130      * Clears all selections.
8131      */
8132     clearSelections : function(fast){
8133         if(this.locked) {
8134             return;
8135         }
8136         if(fast !== true){
8137             var ds = this.grid.ds;
8138             var s = this.selections;
8139             s.each(function(r){
8140                 this.deselectRow(ds.indexOfId(r.id));
8141             }, this);
8142             s.clear();
8143         }else{
8144             this.selections.clear();
8145         }
8146         this.last = false;
8147     },
8148
8149
8150     /**
8151      * Selects all rows.
8152      */
8153     selectAll : function(){
8154         if(this.locked) {
8155             return;
8156         }
8157         this.selections.clear();
8158         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
8159             this.selectRow(i, true);
8160         }
8161     },
8162
8163     /**
8164      * Returns True if there is a selection.
8165      * @return {Boolean}
8166      */
8167     hasSelection : function(){
8168         return this.selections.length > 0;
8169     },
8170
8171     /**
8172      * Returns True if the specified row is selected.
8173      * @param {Number/Record} record The record or index of the record to check
8174      * @return {Boolean}
8175      */
8176     isSelected : function(index){
8177         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
8178         return (r && this.selections.key(r.id) ? true : false);
8179     },
8180
8181     /**
8182      * Returns True if the specified record id is selected.
8183      * @param {String} id The id of record to check
8184      * @return {Boolean}
8185      */
8186     isIdSelected : function(id){
8187         return (this.selections.key(id) ? true : false);
8188     },
8189
8190     // private
8191     handleMouseDown : function(e, t)
8192     {
8193         var view = this.grid.view ? this.grid.view : this.grid;
8194         var rowIndex;
8195         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
8196             return;
8197         };
8198         if(e.shiftKey && this.last !== false){
8199             var last = this.last;
8200             this.selectRange(last, rowIndex, e.ctrlKey);
8201             this.last = last; // reset the last
8202             view.focusRow(rowIndex);
8203         }else{
8204             var isSelected = this.isSelected(rowIndex);
8205             if(e.button !== 0 && isSelected){
8206                 view.focusRow(rowIndex);
8207             }else if(e.ctrlKey && isSelected){
8208                 this.deselectRow(rowIndex);
8209             }else if(!isSelected){
8210                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
8211                 view.focusRow(rowIndex);
8212             }
8213         }
8214         this.fireEvent("afterselectionchange", this);
8215     },
8216     // private
8217     handleDragableRowClick :  function(grid, rowIndex, e) 
8218     {
8219         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
8220             this.selectRow(rowIndex, false);
8221             var view = this.grid.view ? this.grid.view : this.grid;
8222             view.focusRow(rowIndex);
8223              this.fireEvent("afterselectionchange", this);
8224         }
8225     },
8226     
8227     /**
8228      * Selects multiple rows.
8229      * @param {Array} rows Array of the indexes of the row to select
8230      * @param {Boolean} keepExisting (optional) True to keep existing selections
8231      */
8232     selectRows : function(rows, keepExisting){
8233         if(!keepExisting){
8234             this.clearSelections();
8235         }
8236         for(var i = 0, len = rows.length; i < len; i++){
8237             this.selectRow(rows[i], true);
8238         }
8239     },
8240
8241     /**
8242      * Selects a range of rows. All rows in between startRow and endRow are also selected.
8243      * @param {Number} startRow The index of the first row in the range
8244      * @param {Number} endRow The index of the last row in the range
8245      * @param {Boolean} keepExisting (optional) True to retain existing selections
8246      */
8247     selectRange : function(startRow, endRow, keepExisting){
8248         if(this.locked) {
8249             return;
8250         }
8251         if(!keepExisting){
8252             this.clearSelections();
8253         }
8254         if(startRow <= endRow){
8255             for(var i = startRow; i <= endRow; i++){
8256                 this.selectRow(i, true);
8257             }
8258         }else{
8259             for(var i = startRow; i >= endRow; i--){
8260                 this.selectRow(i, true);
8261             }
8262         }
8263     },
8264
8265     /**
8266      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
8267      * @param {Number} startRow The index of the first row in the range
8268      * @param {Number} endRow The index of the last row in the range
8269      */
8270     deselectRange : function(startRow, endRow, preventViewNotify){
8271         if(this.locked) {
8272             return;
8273         }
8274         for(var i = startRow; i <= endRow; i++){
8275             this.deselectRow(i, preventViewNotify);
8276         }
8277     },
8278
8279     /**
8280      * Selects a row.
8281      * @param {Number} row The index of the row to select
8282      * @param {Boolean} keepExisting (optional) True to keep existing selections
8283      */
8284     selectRow : function(index, keepExisting, preventViewNotify){
8285         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
8286             return;
8287         }
8288         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
8289             if(!keepExisting || this.singleSelect){
8290                 this.clearSelections();
8291             }
8292             var r = this.grid.ds.getAt(index);
8293             this.selections.add(r);
8294             this.last = this.lastActive = index;
8295             if(!preventViewNotify){
8296                 var view = this.grid.view ? this.grid.view : this.grid;
8297                 view.onRowSelect(index);
8298             }
8299             this.fireEvent("rowselect", this, index, r);
8300             this.fireEvent("selectionchange", this);
8301         }
8302     },
8303
8304     /**
8305      * Deselects a row.
8306      * @param {Number} row The index of the row to deselect
8307      */
8308     deselectRow : function(index, preventViewNotify){
8309         if(this.locked) {
8310             return;
8311         }
8312         if(this.last == index){
8313             this.last = false;
8314         }
8315         if(this.lastActive == index){
8316             this.lastActive = false;
8317         }
8318         var r = this.grid.ds.getAt(index);
8319         this.selections.remove(r);
8320         if(!preventViewNotify){
8321             var view = this.grid.view ? this.grid.view : this.grid;
8322             view.onRowDeselect(index);
8323         }
8324         this.fireEvent("rowdeselect", this, index);
8325         this.fireEvent("selectionchange", this);
8326     },
8327
8328     // private
8329     restoreLast : function(){
8330         if(this._last){
8331             this.last = this._last;
8332         }
8333     },
8334
8335     // private
8336     acceptsNav : function(row, col, cm){
8337         return !cm.isHidden(col) && cm.isCellEditable(col, row);
8338     },
8339
8340     // private
8341     onEditorKey : function(field, e){
8342         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
8343         if(k == e.TAB){
8344             e.stopEvent();
8345             ed.completeEdit();
8346             if(e.shiftKey){
8347                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
8348             }else{
8349                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
8350             }
8351         }else if(k == e.ENTER && !e.ctrlKey){
8352             e.stopEvent();
8353             ed.completeEdit();
8354             if(e.shiftKey){
8355                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
8356             }else{
8357                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
8358             }
8359         }else if(k == e.ESC){
8360             ed.cancelEdit();
8361         }
8362         if(newCell){
8363             g.startEditing(newCell[0], newCell[1]);
8364         }
8365     }
8366 });/*
8367  * Based on:
8368  * Ext JS Library 1.1.1
8369  * Copyright(c) 2006-2007, Ext JS, LLC.
8370  *
8371  * Originally Released Under LGPL - original licence link has changed is not relivant.
8372  *
8373  * Fork - LGPL
8374  * <script type="text/javascript">
8375  */
8376  
8377
8378 /**
8379  * @class Roo.grid.ColumnModel
8380  * @extends Roo.util.Observable
8381  * This is the default implementation of a ColumnModel used by the Grid. It defines
8382  * the columns in the grid.
8383  * <br>Usage:<br>
8384  <pre><code>
8385  var colModel = new Roo.grid.ColumnModel([
8386         {header: "Ticker", width: 60, sortable: true, locked: true},
8387         {header: "Company Name", width: 150, sortable: true},
8388         {header: "Market Cap.", width: 100, sortable: true},
8389         {header: "$ Sales", width: 100, sortable: true, renderer: money},
8390         {header: "Employees", width: 100, sortable: true, resizable: false}
8391  ]);
8392  </code></pre>
8393  * <p>
8394  
8395  * The config options listed for this class are options which may appear in each
8396  * individual column definition.
8397  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
8398  * @constructor
8399  * @param {Object} config An Array of column config objects. See this class's
8400  * config objects for details.
8401 */
8402 Roo.grid.ColumnModel = function(config){
8403         /**
8404      * The config passed into the constructor
8405      */
8406     this.config = []; //config;
8407     this.lookup = {};
8408
8409     // if no id, create one
8410     // if the column does not have a dataIndex mapping,
8411     // map it to the order it is in the config
8412     for(var i = 0, len = config.length; i < len; i++){
8413         this.addColumn(config[i]);
8414         
8415     }
8416
8417     /**
8418      * The width of columns which have no width specified (defaults to 100)
8419      * @type Number
8420      */
8421     this.defaultWidth = 100;
8422
8423     /**
8424      * Default sortable of columns which have no sortable specified (defaults to false)
8425      * @type Boolean
8426      */
8427     this.defaultSortable = false;
8428
8429     this.addEvents({
8430         /**
8431              * @event widthchange
8432              * Fires when the width of a column changes.
8433              * @param {ColumnModel} this
8434              * @param {Number} columnIndex The column index
8435              * @param {Number} newWidth The new width
8436              */
8437             "widthchange": true,
8438         /**
8439              * @event headerchange
8440              * Fires when the text of a header changes.
8441              * @param {ColumnModel} this
8442              * @param {Number} columnIndex The column index
8443              * @param {Number} newText The new header text
8444              */
8445             "headerchange": true,
8446         /**
8447              * @event hiddenchange
8448              * Fires when a column is hidden or "unhidden".
8449              * @param {ColumnModel} this
8450              * @param {Number} columnIndex The column index
8451              * @param {Boolean} hidden true if hidden, false otherwise
8452              */
8453             "hiddenchange": true,
8454             /**
8455          * @event columnmoved
8456          * Fires when a column is moved.
8457          * @param {ColumnModel} this
8458          * @param {Number} oldIndex
8459          * @param {Number} newIndex
8460          */
8461         "columnmoved" : true,
8462         /**
8463          * @event columlockchange
8464          * Fires when a column's locked state is changed
8465          * @param {ColumnModel} this
8466          * @param {Number} colIndex
8467          * @param {Boolean} locked true if locked
8468          */
8469         "columnlockchange" : true
8470     });
8471     Roo.grid.ColumnModel.superclass.constructor.call(this);
8472 };
8473 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
8474     /**
8475      * @cfg {String} header [required] The header text to display in the Grid view.
8476      */
8477         /**
8478      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
8479      */
8480         /**
8481      * @cfg {String} smHeader Header at Bootsrap Small width
8482      */
8483         /**
8484      * @cfg {String} mdHeader Header at Bootsrap Medium width
8485      */
8486         /**
8487      * @cfg {String} lgHeader Header at Bootsrap Large width
8488      */
8489         /**
8490      * @cfg {String} xlHeader Header at Bootsrap extra Large width
8491      */
8492     /**
8493      * @cfg {String} dataIndex  The name of the field in the grid's {@link Roo.data.Store}'s
8494      * {@link Roo.data.Record} definition from which to draw the column's value. If not
8495      * specified, the column's index is used as an index into the Record's data Array.
8496      */
8497     /**
8498      * @cfg {Number} width  The initial width in pixels of the column. Using this
8499      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
8500      */
8501     /**
8502      * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
8503      * Defaults to the value of the {@link #defaultSortable} property.
8504      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
8505      */
8506     /**
8507      * @cfg {Boolean} locked  True to lock the column in place while scrolling the Grid.  Defaults to false.
8508      */
8509     /**
8510      * @cfg {Boolean} fixed  True if the column width cannot be changed.  Defaults to false.
8511      */
8512     /**
8513      * @cfg {Boolean} resizable  False to disable column resizing. Defaults to true.
8514      */
8515     /**
8516      * @cfg {Boolean} hidden  True to hide the column. Defaults to false.
8517      */
8518     /**
8519      * @cfg {Function} renderer A function used to generate HTML markup for a cell
8520      * given the cell's data value. See {@link #setRenderer}. If not specified, the
8521      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
8522      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
8523      */
8524        /**
8525      * @cfg {Roo.grid.GridEditor} editor  For grid editors - returns the grid editor 
8526      */
8527     /**
8528      * @cfg {String} align (left|right) Set the CSS text-align property of the column.  Defaults to undefined (left).
8529      */
8530     /**
8531      * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined (middle)
8532      */
8533     /**
8534      * @cfg {String} cursor ( auto|default|none|context-menu|help|pointer|progress|wait|cell|crosshair|text|vertical-text|alias|copy|move|no-drop|not-allowed|e-resize|n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|ew-resize|ns-resize|nesw-resize|nwse-resize|col-resize|row-resize|all-scroll|zoom-in|zoom-out|grab|grabbing)
8535      */
8536     /**
8537      * @cfg {String} tooltip mouse over tooltip text
8538      */
8539     /**
8540      * @cfg {Number} xs  can be '0' for hidden at this size (number less than 12)
8541      */
8542     /**
8543      * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
8544      */
8545     /**
8546      * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
8547      */
8548     /**
8549      * @cfg {Number} lg   can be '0' for hidden at this size (number less than 12)
8550      */
8551         /**
8552      * @cfg {Number} xl   can be '0' for hidden at this size (number less than 12)
8553      */
8554     /**
8555      * Returns the id of the column at the specified index.
8556      * @param {Number} index The column index
8557      * @return {String} the id
8558      */
8559     getColumnId : function(index){
8560         return this.config[index].id;
8561     },
8562
8563     /**
8564      * Returns the column for a specified id.
8565      * @param {String} id The column id
8566      * @return {Object} the column
8567      */
8568     getColumnById : function(id){
8569         return this.lookup[id];
8570     },
8571
8572     
8573     /**
8574      * Returns the column Object for a specified dataIndex.
8575      * @param {String} dataIndex The column dataIndex
8576      * @return {Object|Boolean} the column or false if not found
8577      */
8578     getColumnByDataIndex: function(dataIndex){
8579         var index = this.findColumnIndex(dataIndex);
8580         return index > -1 ? this.config[index] : false;
8581     },
8582     
8583     /**
8584      * Returns the index for a specified column id.
8585      * @param {String} id The column id
8586      * @return {Number} the index, or -1 if not found
8587      */
8588     getIndexById : function(id){
8589         for(var i = 0, len = this.config.length; i < len; i++){
8590             if(this.config[i].id == id){
8591                 return i;
8592             }
8593         }
8594         return -1;
8595     },
8596     
8597     /**
8598      * Returns the index for a specified column dataIndex.
8599      * @param {String} dataIndex The column dataIndex
8600      * @return {Number} the index, or -1 if not found
8601      */
8602     
8603     findColumnIndex : function(dataIndex){
8604         for(var i = 0, len = this.config.length; i < len; i++){
8605             if(this.config[i].dataIndex == dataIndex){
8606                 return i;
8607             }
8608         }
8609         return -1;
8610     },
8611     
8612     
8613     moveColumn : function(oldIndex, newIndex){
8614         var c = this.config[oldIndex];
8615         this.config.splice(oldIndex, 1);
8616         this.config.splice(newIndex, 0, c);
8617         this.dataMap = null;
8618         this.fireEvent("columnmoved", this, oldIndex, newIndex);
8619     },
8620
8621     isLocked : function(colIndex){
8622         return this.config[colIndex].locked === true;
8623     },
8624
8625     setLocked : function(colIndex, value, suppressEvent){
8626         if(this.isLocked(colIndex) == value){
8627             return;
8628         }
8629         this.config[colIndex].locked = value;
8630         if(!suppressEvent){
8631             this.fireEvent("columnlockchange", this, colIndex, value);
8632         }
8633     },
8634
8635     getTotalLockedWidth : function(){
8636         var totalWidth = 0;
8637         for(var i = 0; i < this.config.length; i++){
8638             if(this.isLocked(i) && !this.isHidden(i)){
8639                 this.totalWidth += this.getColumnWidth(i);
8640             }
8641         }
8642         return totalWidth;
8643     },
8644
8645     getLockedCount : function(){
8646         for(var i = 0, len = this.config.length; i < len; i++){
8647             if(!this.isLocked(i)){
8648                 return i;
8649             }
8650         }
8651         
8652         return this.config.length;
8653     },
8654
8655     /**
8656      * Returns the number of columns.
8657      * @return {Number}
8658      */
8659     getColumnCount : function(visibleOnly){
8660         if(visibleOnly === true){
8661             var c = 0;
8662             for(var i = 0, len = this.config.length; i < len; i++){
8663                 if(!this.isHidden(i)){
8664                     c++;
8665                 }
8666             }
8667             return c;
8668         }
8669         return this.config.length;
8670     },
8671
8672     /**
8673      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
8674      * @param {Function} fn
8675      * @param {Object} scope (optional)
8676      * @return {Array} result
8677      */
8678     getColumnsBy : function(fn, scope){
8679         var r = [];
8680         for(var i = 0, len = this.config.length; i < len; i++){
8681             var c = this.config[i];
8682             if(fn.call(scope||this, c, i) === true){
8683                 r[r.length] = c;
8684             }
8685         }
8686         return r;
8687     },
8688
8689     /**
8690      * Returns true if the specified column is sortable.
8691      * @param {Number} col The column index
8692      * @return {Boolean}
8693      */
8694     isSortable : function(col){
8695         if(typeof this.config[col].sortable == "undefined"){
8696             return this.defaultSortable;
8697         }
8698         return this.config[col].sortable;
8699     },
8700
8701     /**
8702      * Returns the rendering (formatting) function defined for the column.
8703      * @param {Number} col The column index.
8704      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
8705      */
8706     getRenderer : function(col){
8707         if(!this.config[col].renderer){
8708             return Roo.grid.ColumnModel.defaultRenderer;
8709         }
8710         return this.config[col].renderer;
8711     },
8712
8713     /**
8714      * Sets the rendering (formatting) function for a column.
8715      * @param {Number} col The column index
8716      * @param {Function} fn The function to use to process the cell's raw data
8717      * to return HTML markup for the grid view. The render function is called with
8718      * the following parameters:<ul>
8719      * <li>Data value.</li>
8720      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
8721      * <li>css A CSS style string to apply to the table cell.</li>
8722      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
8723      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
8724      * <li>Row index</li>
8725      * <li>Column index</li>
8726      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
8727      */
8728     setRenderer : function(col, fn){
8729         this.config[col].renderer = fn;
8730     },
8731
8732     /**
8733      * Returns the width for the specified column.
8734      * @param {Number} col The column index
8735      * @param (optional) {String} gridSize bootstrap width size.
8736      * @return {Number}
8737      */
8738     getColumnWidth : function(col, gridSize)
8739         {
8740                 var cfg = this.config[col];
8741                 
8742                 if (typeof(gridSize) == 'undefined') {
8743                         return cfg.width * 1 || this.defaultWidth;
8744                 }
8745                 if (gridSize === false) { // if we set it..
8746                         return cfg.width || false;
8747                 }
8748                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
8749                 
8750                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
8751                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
8752                                 continue;
8753                         }
8754                         return cfg[ sizes[i] ];
8755                 }
8756                 return 1;
8757                 
8758     },
8759
8760     /**
8761      * Sets the width for a column.
8762      * @param {Number} col The column index
8763      * @param {Number} width The new width
8764      */
8765     setColumnWidth : function(col, width, suppressEvent){
8766         this.config[col].width = width;
8767         this.totalWidth = null;
8768         if(!suppressEvent){
8769              this.fireEvent("widthchange", this, col, width);
8770         }
8771     },
8772
8773     /**
8774      * Returns the total width of all columns.
8775      * @param {Boolean} includeHidden True to include hidden column widths
8776      * @return {Number}
8777      */
8778     getTotalWidth : function(includeHidden){
8779         if(!this.totalWidth){
8780             this.totalWidth = 0;
8781             for(var i = 0, len = this.config.length; i < len; i++){
8782                 if(includeHidden || !this.isHidden(i)){
8783                     this.totalWidth += this.getColumnWidth(i);
8784                 }
8785             }
8786         }
8787         return this.totalWidth;
8788     },
8789
8790     /**
8791      * Returns the header for the specified column.
8792      * @param {Number} col The column index
8793      * @return {String}
8794      */
8795     getColumnHeader : function(col){
8796         return this.config[col].header;
8797     },
8798
8799     /**
8800      * Sets the header for a column.
8801      * @param {Number} col The column index
8802      * @param {String} header The new header
8803      */
8804     setColumnHeader : function(col, header){
8805         this.config[col].header = header;
8806         this.fireEvent("headerchange", this, col, header);
8807     },
8808
8809     /**
8810      * Returns the tooltip for the specified column.
8811      * @param {Number} col The column index
8812      * @return {String}
8813      */
8814     getColumnTooltip : function(col){
8815             return this.config[col].tooltip;
8816     },
8817     /**
8818      * Sets the tooltip for a column.
8819      * @param {Number} col The column index
8820      * @param {String} tooltip The new tooltip
8821      */
8822     setColumnTooltip : function(col, tooltip){
8823             this.config[col].tooltip = tooltip;
8824     },
8825
8826     /**
8827      * Returns the dataIndex for the specified column.
8828      * @param {Number} col The column index
8829      * @return {Number}
8830      */
8831     getDataIndex : function(col){
8832         return this.config[col].dataIndex;
8833     },
8834
8835     /**
8836      * Sets the dataIndex for a column.
8837      * @param {Number} col The column index
8838      * @param {Number} dataIndex The new dataIndex
8839      */
8840     setDataIndex : function(col, dataIndex){
8841         this.config[col].dataIndex = dataIndex;
8842     },
8843
8844     
8845     
8846     /**
8847      * Returns true if the cell is editable.
8848      * @param {Number} colIndex The column index
8849      * @param {Number} rowIndex The row index - this is nto actually used..?
8850      * @return {Boolean}
8851      */
8852     isCellEditable : function(colIndex, rowIndex){
8853         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
8854     },
8855
8856     /**
8857      * Returns the editor defined for the cell/column.
8858      * return false or null to disable editing.
8859      * @param {Number} colIndex The column index
8860      * @param {Number} rowIndex The row index
8861      * @return {Object}
8862      */
8863     getCellEditor : function(colIndex, rowIndex){
8864         return this.config[colIndex].editor;
8865     },
8866
8867     /**
8868      * Sets if a column is editable.
8869      * @param {Number} col The column index
8870      * @param {Boolean} editable True if the column is editable
8871      */
8872     setEditable : function(col, editable){
8873         this.config[col].editable = editable;
8874     },
8875
8876
8877     /**
8878      * Returns true if the column is hidden.
8879      * @param {Number} colIndex The column index
8880      * @return {Boolean}
8881      */
8882     isHidden : function(colIndex){
8883         return this.config[colIndex].hidden;
8884     },
8885
8886
8887     /**
8888      * Returns true if the column width cannot be changed
8889      */
8890     isFixed : function(colIndex){
8891         return this.config[colIndex].fixed;
8892     },
8893
8894     /**
8895      * Returns true if the column can be resized
8896      * @return {Boolean}
8897      */
8898     isResizable : function(colIndex){
8899         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
8900     },
8901     /**
8902      * Sets if a column is hidden.
8903      * @param {Number} colIndex The column index
8904      * @param {Boolean} hidden True if the column is hidden
8905      */
8906     setHidden : function(colIndex, hidden){
8907         this.config[colIndex].hidden = hidden;
8908         this.totalWidth = null;
8909         this.fireEvent("hiddenchange", this, colIndex, hidden);
8910     },
8911
8912     /**
8913      * Sets the editor for a column.
8914      * @param {Number} col The column index
8915      * @param {Object} editor The editor object
8916      */
8917     setEditor : function(col, editor){
8918         this.config[col].editor = editor;
8919     },
8920     /**
8921      * Add a column (experimental...) - defaults to adding to the end..
8922      * @param {Object} config 
8923     */
8924     addColumn : function(c)
8925     {
8926     
8927         var i = this.config.length;
8928         this.config[i] = c;
8929         
8930         if(typeof c.dataIndex == "undefined"){
8931             c.dataIndex = i;
8932         }
8933         if(typeof c.renderer == "string"){
8934             c.renderer = Roo.util.Format[c.renderer];
8935         }
8936         if(typeof c.id == "undefined"){
8937             c.id = Roo.id();
8938         }
8939         if(c.editor && c.editor.xtype){
8940             c.editor  = Roo.factory(c.editor, Roo.grid);
8941         }
8942         if(c.editor && c.editor.isFormField){
8943             c.editor = new Roo.grid.GridEditor(c.editor);
8944         }
8945         this.lookup[c.id] = c;
8946     }
8947     
8948 });
8949
8950 Roo.grid.ColumnModel.defaultRenderer = function(value)
8951 {
8952     if(typeof value == "object") {
8953         return value;
8954     }
8955         if(typeof value == "string" && value.length < 1){
8956             return "&#160;";
8957         }
8958     
8959         return String.format("{0}", value);
8960 };
8961
8962 // Alias for backwards compatibility
8963 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
8964 /*
8965  * Based on:
8966  * Ext JS Library 1.1.1
8967  * Copyright(c) 2006-2007, Ext JS, LLC.
8968  *
8969  * Originally Released Under LGPL - original licence link has changed is not relivant.
8970  *
8971  * Fork - LGPL
8972  * <script type="text/javascript">
8973  */
8974  
8975 /**
8976  * @class Roo.LoadMask
8977  * A simple utility class for generically masking elements while loading data.  If the element being masked has
8978  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
8979  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
8980  * element's UpdateManager load indicator and will be destroyed after the initial load.
8981  * @constructor
8982  * Create a new LoadMask
8983  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
8984  * @param {Object} config The config object
8985  */
8986 Roo.LoadMask = function(el, config){
8987     this.el = Roo.get(el);
8988     Roo.apply(this, config);
8989     if(this.store){
8990         this.store.on('beforeload', this.onBeforeLoad, this);
8991         this.store.on('load', this.onLoad, this);
8992         this.store.on('loadexception', this.onLoadException, this);
8993         this.removeMask = false;
8994     }else{
8995         var um = this.el.getUpdateManager();
8996         um.showLoadIndicator = false; // disable the default indicator
8997         um.on('beforeupdate', this.onBeforeLoad, this);
8998         um.on('update', this.onLoad, this);
8999         um.on('failure', this.onLoad, this);
9000         this.removeMask = true;
9001     }
9002 };
9003
9004 Roo.LoadMask.prototype = {
9005     /**
9006      * @cfg {Boolean} removeMask
9007      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
9008      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
9009      */
9010     removeMask : false,
9011     /**
9012      * @cfg {String} msg
9013      * The text to display in a centered loading message box (defaults to 'Loading...')
9014      */
9015     msg : 'Loading...',
9016     /**
9017      * @cfg {String} msgCls
9018      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
9019      */
9020     msgCls : 'x-mask-loading',
9021
9022     /**
9023      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
9024      * @type Boolean
9025      */
9026     disabled: false,
9027
9028     /**
9029      * Disables the mask to prevent it from being displayed
9030      */
9031     disable : function(){
9032        this.disabled = true;
9033     },
9034
9035     /**
9036      * Enables the mask so that it can be displayed
9037      */
9038     enable : function(){
9039         this.disabled = false;
9040     },
9041     
9042     onLoadException : function()
9043     {
9044         Roo.log(arguments);
9045         
9046         if (typeof(arguments[3]) != 'undefined') {
9047             Roo.MessageBox.alert("Error loading",arguments[3]);
9048         } 
9049         /*
9050         try {
9051             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
9052                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
9053             }   
9054         } catch(e) {
9055             
9056         }
9057         */
9058     
9059         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
9060     },
9061     // private
9062     onLoad : function()
9063     {
9064         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
9065     },
9066
9067     // private
9068     onBeforeLoad : function(){
9069         if(!this.disabled){
9070             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
9071         }
9072     },
9073
9074     // private
9075     destroy : function(){
9076         if(this.store){
9077             this.store.un('beforeload', this.onBeforeLoad, this);
9078             this.store.un('load', this.onLoad, this);
9079             this.store.un('loadexception', this.onLoadException, this);
9080         }else{
9081             var um = this.el.getUpdateManager();
9082             um.un('beforeupdate', this.onBeforeLoad, this);
9083             um.un('update', this.onLoad, this);
9084             um.un('failure', this.onLoad, this);
9085         }
9086     }
9087 };/**
9088  * @class Roo.bootstrap.Table
9089  * @licence LGBL
9090  * @extends Roo.bootstrap.Component
9091  * @children Roo.bootstrap.TableBody
9092  * Bootstrap Table class.  This class represents the primary interface of a component based grid control.
9093  * Similar to Roo.grid.Grid
9094  * <pre><code>
9095  var table = Roo.factory({
9096     xtype : 'Table',
9097     xns : Roo.bootstrap,
9098     autoSizeColumns: true,
9099     
9100     
9101     store : {
9102         xtype : 'Store',
9103         xns : Roo.data,
9104         remoteSort : true,
9105         sortInfo : { direction : 'ASC', field: 'name' },
9106         proxy : {
9107            xtype : 'HttpProxy',
9108            xns : Roo.data,
9109            method : 'GET',
9110            url : 'https://example.com/some.data.url.json'
9111         },
9112         reader : {
9113            xtype : 'JsonReader',
9114            xns : Roo.data,
9115            fields : [ 'id', 'name', whatever' ],
9116            id : 'id',
9117            root : 'data'
9118         }
9119     },
9120     cm : [
9121         {
9122             xtype : 'ColumnModel',
9123             xns : Roo.grid,
9124             align : 'center',
9125             cursor : 'pointer',
9126             dataIndex : 'is_in_group',
9127             header : "Name",
9128             sortable : true,
9129             renderer : function(v, x , r) {  
9130             
9131                 return String.format("{0}", v)
9132             }
9133             width : 3
9134         } // more columns..
9135     ],
9136     selModel : {
9137         xtype : 'RowSelectionModel',
9138         xns : Roo.bootstrap.Table
9139         // you can add listeners to catch selection change here....
9140     }
9141      
9142
9143  });
9144  // set any options
9145  grid.render(Roo.get("some-div"));
9146 </code></pre>
9147
9148 Currently the Table  uses multiple headers to try and handle XL / Medium etc... styling
9149
9150
9151
9152  *
9153  * @cfg {Roo.grid.AbstractSelectionModel} sm The selection model to use (cell selection is not supported yet)
9154  * @cfg {Roo.data.Store} store The data store to use
9155  * @cfg {Roo.grid.ColumnModel} cm[] A column for the grid.
9156  * 
9157  * @cfg {String} cls table class
9158  *
9159  *
9160  * @cfg {string} empty_results  Text to display for no results 
9161  * @cfg {boolean} striped Should the rows be alternative striped
9162  * @cfg {boolean} bordered Add borders to the table
9163  * @cfg {boolean} hover Add hover highlighting
9164  * @cfg {boolean} condensed Format condensed
9165  * @cfg {boolean} responsive default false - if this is on, columns are rendered with col-xs-4 etc. classes, otherwise columns will be sized by CSS,
9166  *                also adds table-responsive (see bootstrap docs for details)
9167  * @cfg {Boolean} loadMask (true|false) default false
9168  * @cfg {Boolean} footerShow (true|false) generate tfoot, default true
9169  * @cfg {Boolean} footerRow (true|false) generate tfoot with columns of values, default false
9170  * @cfg {Boolean} headerShow (true|false) generate thead, default true
9171  * @cfg {Boolean} rowSelection (true|false) default false
9172  * @cfg {Boolean} cellSelection (true|false) default false
9173  * @cfg {Boolean} scrollBody (true|false) default false - body scrolled / fixed header (with resizable columns)
9174  * @cfg {Roo.bootstrap.PagingToolbar} footer  a paging toolbar
9175  * @cfg {Boolean} lazyLoad  auto load data while scrolling to the end (default false)
9176  * @cfg {Boolean} auto_hide_footer  auto hide footer if only one page (default false)
9177  * @cfg {Boolean} enableColumnResize default true if columns can be resized = needs scrollBody to be set to work (drag/drop)
9178  * @cfg {Boolean} disableAutoSize disable autoSize() and initCSS()
9179  *
9180  * 
9181  * @cfg {Number} minColumnWidth default 50 pixels minimum column width 
9182  * 
9183  * @constructor
9184  * Create a new Table
9185  * @param {Object} config The config object
9186  */
9187
9188 Roo.bootstrap.Table = function(config)
9189 {
9190     Roo.bootstrap.Table.superclass.constructor.call(this, config);
9191      
9192     // BC...
9193     this.rowSelection = (typeof(config.rowSelection) != 'undefined') ? config.rowSelection : this.rowSelection;
9194     this.cellSelection = (typeof(config.cellSelection) != 'undefined') ? config.cellSelection : this.cellSelection;
9195     this.headerShow = (typeof(config.thead) != 'undefined') ? config.thead : this.headerShow;
9196     this.footerShow = (typeof(config.tfoot) != 'undefined') ? config.tfoot : this.footerShow;
9197     
9198     this.view = this; // compat with grid.
9199     
9200     this.sm = this.sm || {xtype: 'RowSelectionModel'};
9201     if (this.sm) {
9202         this.sm.grid = this;
9203         this.selModel = Roo.factory(this.sm, Roo.grid);
9204         this.sm = this.selModel;
9205         this.sm.xmodule = this.xmodule || false;
9206     }
9207     
9208     if (this.cm && typeof(this.cm.config) == 'undefined') {
9209         this.colModel = new Roo.grid.ColumnModel(this.cm);
9210         this.cm = this.colModel;
9211         this.cm.xmodule = this.xmodule || false;
9212     }
9213     if (this.store) {
9214         this.store= Roo.factory(this.store, Roo.data);
9215         this.ds = this.store;
9216         this.ds.xmodule = this.xmodule || false;
9217          
9218     }
9219     if (this.footer && this.store) {
9220         this.footer.dataSource = this.ds;
9221         this.footer = Roo.factory(this.footer);
9222     }
9223     
9224     /** @private */
9225     this.addEvents({
9226         /**
9227          * @event cellclick
9228          * Fires when a cell is clicked
9229          * @param {Roo.bootstrap.Table} this
9230          * @param {Roo.Element} el
9231          * @param {Number} rowIndex
9232          * @param {Number} columnIndex
9233          * @param {Roo.EventObject} e
9234          */
9235         "cellclick" : true,
9236         /**
9237          * @event celldblclick
9238          * Fires when a cell is double clicked
9239          * @param {Roo.bootstrap.Table} this
9240          * @param {Roo.Element} el
9241          * @param {Number} rowIndex
9242          * @param {Number} columnIndex
9243          * @param {Roo.EventObject} e
9244          */
9245         "celldblclick" : true,
9246         /**
9247          * @event rowclick
9248          * Fires when a row is clicked
9249          * @param {Roo.bootstrap.Table} this
9250          * @param {Roo.Element} el
9251          * @param {Number} rowIndex
9252          * @param {Roo.EventObject} e
9253          */
9254         "rowclick" : true,
9255         /**
9256          * @event rowdblclick
9257          * Fires when a row is double clicked
9258          * @param {Roo.bootstrap.Table} this
9259          * @param {Roo.Element} el
9260          * @param {Number} rowIndex
9261          * @param {Roo.EventObject} e
9262          */
9263         "rowdblclick" : true,
9264         /**
9265          * @event mouseover
9266          * Fires when a mouseover occur
9267          * @param {Roo.bootstrap.Table} this
9268          * @param {Roo.Element} el
9269          * @param {Number} rowIndex
9270          * @param {Number} columnIndex
9271          * @param {Roo.EventObject} e
9272          */
9273         "mouseover" : true,
9274         /**
9275          * @event mouseout
9276          * Fires when a mouseout occur
9277          * @param {Roo.bootstrap.Table} this
9278          * @param {Roo.Element} el
9279          * @param {Number} rowIndex
9280          * @param {Number} columnIndex
9281          * @param {Roo.EventObject} e
9282          */
9283         "mouseout" : true,
9284         /**
9285          * @event rowclass
9286          * Fires when a row is rendered, so you can change add a style to it.
9287          * @param {Roo.bootstrap.Table} this
9288          * @param {Object} rowcfg   contains record  rowIndex colIndex and rowClass - set rowClass to add a style.
9289          */
9290         'rowclass' : true,
9291           /**
9292          * @event rowsrendered
9293          * Fires when all the  rows have been rendered
9294          * @param {Roo.bootstrap.Table} this
9295          */
9296         'rowsrendered' : true,
9297         /**
9298          * @event contextmenu
9299          * The raw contextmenu event for the entire grid.
9300          * @param {Roo.EventObject} e
9301          */
9302         "contextmenu" : true,
9303         /**
9304          * @event rowcontextmenu
9305          * Fires when a row is right clicked
9306          * @param {Roo.bootstrap.Table} this
9307          * @param {Number} rowIndex
9308          * @param {Roo.EventObject} e
9309          */
9310         "rowcontextmenu" : true,
9311         /**
9312          * @event cellcontextmenu
9313          * Fires when a cell is right clicked
9314          * @param {Roo.bootstrap.Table} this
9315          * @param {Number} rowIndex
9316          * @param {Number} cellIndex
9317          * @param {Roo.EventObject} e
9318          */
9319          "cellcontextmenu" : true,
9320          /**
9321          * @event headercontextmenu
9322          * Fires when a header is right clicked
9323          * @param {Roo.bootstrap.Table} this
9324          * @param {Number} columnIndex
9325          * @param {Roo.EventObject} e
9326          */
9327         "headercontextmenu" : true,
9328         /**
9329          * @event mousedown
9330          * The raw mousedown event for the entire grid.
9331          * @param {Roo.EventObject} e
9332          */
9333         "mousedown" : true
9334         
9335     });
9336 };
9337
9338 Roo.extend(Roo.bootstrap.Table, Roo.bootstrap.Component,  {
9339     
9340     cls: false,
9341     
9342     empty_results : '',
9343     striped : false,
9344     scrollBody : false,
9345     bordered: false,
9346     hover:  false,
9347     condensed : false,
9348     responsive : false,
9349     sm : false,
9350     cm : false,
9351     store : false,
9352     loadMask : false,
9353     footerShow : true,
9354     footerRow : false,
9355     headerShow : true,
9356     enableColumnResize: true,
9357     disableAutoSize: false,
9358   
9359     rowSelection : false,
9360     cellSelection : false,
9361     layout : false,
9362
9363     minColumnWidth : 50,
9364     
9365     // Roo.Element - the tbody
9366     bodyEl: false,  // <tbody> Roo.Element - thead element    
9367     headEl: false,  // <thead> Roo.Element - thead element
9368     resizeProxy : false, // proxy element for dragging?
9369
9370
9371     
9372     container: false, // used by gridpanel...
9373     
9374     lazyLoad : false,
9375     
9376     CSS : Roo.util.CSS,
9377     
9378     auto_hide_footer : false,
9379     
9380     view: false, // actually points to this..
9381     
9382     getAutoCreate : function()
9383     {
9384         var cfg = Roo.apply({}, Roo.bootstrap.Table.superclass.getAutoCreate.call(this));
9385         
9386         cfg = {
9387             tag: 'table',
9388             cls : 'table', 
9389             cn : []
9390         };
9391         // this get's auto added by panel.Grid
9392         if (this.scrollBody) {
9393             cfg.cls += ' table-body-fixed';
9394         }    
9395         if (this.striped) {
9396             cfg.cls += ' table-striped';
9397         }
9398         
9399         if (this.hover) {
9400             cfg.cls += ' table-hover';
9401         }
9402         if (this.bordered) {
9403             cfg.cls += ' table-bordered';
9404         }
9405         if (this.condensed) {
9406             cfg.cls += ' table-condensed';
9407         }
9408         
9409         if (this.responsive) {
9410             cfg.cls += ' table-responsive';
9411         }
9412         
9413         if (this.cls) {
9414             cfg.cls+=  ' ' +this.cls;
9415         }
9416         
9417         
9418         
9419         if (this.layout) {
9420             cfg.style = (typeof(cfg.style) == 'undefined') ? ('table-layout:' + this.layout + ';') : (cfg.style + ('table-layout:' + this.layout + ';'));
9421         }
9422         
9423         if(this.store || this.cm){
9424             if(this.headerShow){
9425                 cfg.cn.push(this.renderHeader());
9426             }
9427             
9428             cfg.cn.push(this.renderBody());
9429             
9430             if(this.footerShow || this.footerRow){
9431                 cfg.cn.push(this.renderFooter());
9432             }
9433
9434             // where does this come from?
9435             //cfg.cls+=  ' TableGrid';
9436         }
9437         
9438         return { cn : [ cfg ] };
9439     },
9440     
9441     initEvents : function()
9442     {   
9443         if(!this.store || !this.cm){
9444             return;
9445         }
9446         if (this.selModel) {
9447             this.selModel.initEvents();
9448         }
9449         
9450         
9451         //Roo.log('initEvents with ds!!!!');
9452         
9453         this.bodyEl = this.el.select('tbody', true).first();
9454         this.headEl = this.el.select('thead', true).first();
9455         this.mainFoot = this.el.select('tfoot', true).first();
9456         
9457         
9458         
9459         
9460         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
9461             e.on('click', this.sort, this);
9462         }, this);
9463         
9464         
9465         // why is this done????? = it breaks dialogs??
9466         //this.parent().el.setStyle('position', 'relative');
9467         
9468         
9469         if (this.footer) {
9470             this.footer.parentId = this.id;
9471             this.footer.onRender(this.el.select('tfoot tr td').first(), null);
9472             
9473             if(this.lazyLoad){
9474                 this.el.select('tfoot tr td').first().addClass('hide');
9475             }
9476         } 
9477         
9478         if(this.loadMask) {
9479             this.maskEl = new Roo.LoadMask(this.el, { store : this.ds, msgCls: 'roo-el-mask-msg' });
9480         }
9481         
9482         this.store.on('load', this.onLoad, this);
9483         this.store.on('beforeload', this.onBeforeLoad, this);
9484         this.store.on('update', this.onUpdate, this);
9485         this.store.on('add', this.onAdd, this);
9486         this.store.on("clear", this.clear, this);
9487         
9488         this.el.on("contextmenu", this.onContextMenu, this);
9489         
9490         
9491         this.cm.on("headerchange", this.onHeaderChange, this);
9492         this.cm.on("hiddenchange", this.onHiddenChange, this, arguments);
9493
9494  //?? does bodyEl get replaced on render?
9495         this.bodyEl.on("click", this.onClick, this);
9496         this.bodyEl.on("dblclick", this.onDblClick, this);        
9497         this.bodyEl.on('scroll', this.onBodyScroll, this);
9498
9499         // guessing mainbody will work - this relays usually caught by selmodel at present.
9500         this.relayEvents(this.bodyEl, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
9501   
9502   
9503         this.resizeProxy = Roo.get(document.body).createChild({ cls:"x-grid-resize-proxy", html: '&#160;' });
9504         
9505   
9506         if(this.headEl && this.enableColumnResize !== false && Roo.grid.SplitDragZone){
9507             new Roo.grid.SplitDragZone(this, this.headEl.dom, false); // not sure what 'lockedHd is for this implementation..)
9508         }
9509         
9510         this.initCSS();
9511     },
9512     // Compatibility with grid - we implement all the view features at present.
9513     getView : function()
9514     {
9515         return this;
9516     },
9517     
9518     initCSS : function()
9519     {
9520         if(this.disableAutoSize) {
9521             return;
9522         }
9523         
9524         var cm = this.cm, styles = [];
9525         this.CSS.removeStyleSheet(this.id + '-cssrules');
9526         var headHeight = this.headEl ? this.headEl.dom.clientHeight : 0;
9527         // we can honour xs/sm/md/xl  as widths...
9528         // we first have to decide what widht we are currently at...
9529         var sz = Roo.getGridSize();
9530         
9531         var total = 0;
9532         var last = -1;
9533         var cols = []; // visable cols.
9534         var total_abs = 0;
9535         for(var i = 0, len = cm.getColumnCount(); i < len; i++) {
9536             var w = cm.getColumnWidth(i, false);
9537             if(cm.isHidden(i)){
9538                 cols.push( { rel : false, abs : 0 });
9539                 continue;
9540             }
9541             if (w !== false) {
9542                 cols.push( { rel : false, abs : w });
9543                 total_abs += w;
9544                 last = i; // not really..
9545                 continue;
9546             }
9547             var w = cm.getColumnWidth(i, sz);
9548             if (w > 0) {
9549                 last = i
9550             }
9551             total += w;
9552             cols.push( { rel : w, abs : false });
9553         }
9554         
9555         var avail = this.bodyEl.dom.clientWidth - total_abs;
9556         
9557         var unitWidth = Math.floor(avail / total);
9558         var rem = avail - (unitWidth * total);
9559         
9560         var hidden, width, pos = 0 , splithide , left;
9561         for(var i = 0, len = cm.getColumnCount(); i < len; i++) {
9562             
9563             hidden = 'display:none;';
9564             left = '';
9565             width  = 'width:0px;';
9566             splithide = '';
9567             if(!cm.isHidden(i)){
9568                 hidden = '';
9569                 
9570                 
9571                 // we can honour xs/sm/md/xl ?
9572                 var w = cols[i].rel == false ? cols[i].abs : (cols[i].rel * unitWidth);
9573                 if (w===0) {
9574                     hidden = 'display:none;';
9575                 }
9576                 // width should return a small number...
9577                 if (i == last) {
9578                     w+=rem; // add the remaining with..
9579                 }
9580                 pos += w;
9581                 left = "left:" + (pos -4) + "px;";
9582                 width = "width:" + w+ "px;";
9583                 
9584             }
9585             if (this.responsive) {
9586                 width = '';
9587                 left = '';
9588                 hidden = cm.isHidden(i) ? 'display:none;' : '';
9589                 splithide = 'display: none;';
9590             }
9591             
9592             styles.push( '#' , this.id , ' .x-col-' , i, " {", cm.config[i].css, width, hidden, "}\n" );
9593             if (this.headEl) {
9594                 if (i == last) {
9595                     splithide = 'display:none;';
9596                 }
9597                 
9598                 styles.push('#' , this.id , ' .x-hcol-' , i, " { ", width, hidden," }\n",
9599                             '#' , this.id , ' .x-grid-split-' , i, " { ", left, splithide, 'height:', (headHeight - 4), "px;}\n",
9600                             // this is the popover version..
9601                             '.popover-inner #' , this.id , ' .x-grid-split-' , i, " { ", left, splithide, 'height:', 100, "%;}\n"
9602                 );
9603             }
9604             
9605         }
9606         //Roo.log(styles.join(''));
9607         this.CSS.createStyleSheet( styles.join(''), this.id + '-cssrules');
9608         
9609     },
9610     
9611     
9612     
9613     onContextMenu : function(e, t)
9614     {
9615         this.processEvent("contextmenu", e);
9616     },
9617     
9618     processEvent : function(name, e)
9619     {
9620         if (name != 'touchstart' ) {
9621             this.fireEvent(name, e);    
9622         }
9623         
9624         var t = e.getTarget();
9625         
9626         var cell = Roo.get(t);
9627         
9628         if(!cell){
9629             return;
9630         }
9631         
9632         if(cell.findParent('tfoot', false, true)){
9633             return;
9634         }
9635         
9636         if(cell.findParent('thead', false, true)){
9637             
9638             if(e.getTarget().nodeName.toLowerCase() != 'th'){
9639                 cell = Roo.get(t).findParent('th', false, true);
9640                 if (!cell) {
9641                     Roo.log("failed to find th in thead?");
9642                     Roo.log(e.getTarget());
9643                     return;
9644                 }
9645             }
9646             
9647             var cellIndex = cell.dom.cellIndex;
9648             
9649             var ename = name == 'touchstart' ? 'click' : name;
9650             this.fireEvent("header" + ename, this, cellIndex, e);
9651             
9652             return;
9653         }
9654         
9655         if(e.getTarget().nodeName.toLowerCase() != 'td'){
9656             cell = Roo.get(t).findParent('td', false, true);
9657             if (!cell) {
9658                 Roo.log("failed to find th in tbody?");
9659                 Roo.log(e.getTarget());
9660                 return;
9661             }
9662         }
9663         
9664         var row = cell.findParent('tr', false, true);
9665         var cellIndex = cell.dom.cellIndex;
9666         var rowIndex = row.dom.rowIndex - 1;
9667         
9668         if(row !== false){
9669             
9670             this.fireEvent("row" + name, this, rowIndex, e);
9671             
9672             if(cell !== false){
9673             
9674                 this.fireEvent("cell" + name, this, rowIndex, cellIndex, e);
9675             }
9676         }
9677         
9678     },
9679     
9680     onMouseover : function(e, el)
9681     {
9682         var cell = Roo.get(el);
9683         
9684         if(!cell){
9685             return;
9686         }
9687         
9688         if(e.getTarget().nodeName.toLowerCase() != 'td'){
9689             cell = cell.findParent('td', false, true);
9690         }
9691         
9692         var row = cell.findParent('tr', false, true);
9693         var cellIndex = cell.dom.cellIndex;
9694         var rowIndex = row.dom.rowIndex - 1; // start from 0
9695         
9696         this.fireEvent('mouseover', this, cell, rowIndex, cellIndex, e);
9697         
9698     },
9699     
9700     onMouseout : function(e, el)
9701     {
9702         var cell = Roo.get(el);
9703         
9704         if(!cell){
9705             return;
9706         }
9707         
9708         if(e.getTarget().nodeName.toLowerCase() != 'td'){
9709             cell = cell.findParent('td', false, true);
9710         }
9711         
9712         var row = cell.findParent('tr', false, true);
9713         var cellIndex = cell.dom.cellIndex;
9714         var rowIndex = row.dom.rowIndex - 1; // start from 0
9715         
9716         this.fireEvent('mouseout', this, cell, rowIndex, cellIndex, e);
9717         
9718     },
9719     
9720     onClick : function(e, el)
9721     {
9722         var cell = Roo.get(el);
9723         
9724         if(!cell || (!this.cellSelection && !this.rowSelection)){
9725             return;
9726         }
9727         
9728         if(e.getTarget().nodeName.toLowerCase() != 'td'){
9729             cell = cell.findParent('td', false, true);
9730         }
9731         
9732         if(!cell || typeof(cell) == 'undefined'){
9733             return;
9734         }
9735         
9736         var row = cell.findParent('tr', false, true);
9737         
9738         if(!row || typeof(row) == 'undefined'){
9739             return;
9740         }
9741         
9742         var cellIndex = cell.dom.cellIndex;
9743         var rowIndex = this.getRowIndex(row);
9744         
9745         // why??? - should these not be based on SelectionModel?
9746         //if(this.cellSelection){
9747             this.fireEvent('cellclick', this, cell, rowIndex, cellIndex, e);
9748         //}
9749         
9750         //if(this.rowSelection){
9751             this.fireEvent('rowclick', this, row, rowIndex, e);
9752         //}
9753          
9754     },
9755         
9756     onDblClick : function(e,el)
9757     {
9758         var cell = Roo.get(el);
9759         
9760         if(!cell || (!this.cellSelection && !this.rowSelection)){
9761             return;
9762         }
9763         
9764         if(e.getTarget().nodeName.toLowerCase() != 'td'){
9765             cell = cell.findParent('td', false, true);
9766         }
9767         
9768         if(!cell || typeof(cell) == 'undefined'){
9769             return;
9770         }
9771         
9772         var row = cell.findParent('tr', false, true);
9773         
9774         if(!row || typeof(row) == 'undefined'){
9775             return;
9776         }
9777         
9778         var cellIndex = cell.dom.cellIndex;
9779         var rowIndex = this.getRowIndex(row);
9780         
9781         if(this.cellSelection){
9782             this.fireEvent('celldblclick', this, cell, rowIndex, cellIndex, e);
9783         }
9784         
9785         if(this.rowSelection){
9786             this.fireEvent('rowdblclick', this, row, rowIndex, e);
9787         }
9788     },
9789     findRowIndex : function(el)
9790     {
9791         var cell = Roo.get(el);
9792         if(!cell) {
9793             return false;
9794         }
9795         var row = cell.findParent('tr', false, true);
9796         
9797         if(!row || typeof(row) == 'undefined'){
9798             return false;
9799         }
9800         return this.getRowIndex(row);
9801     },
9802     sort : function(e,el)
9803     {
9804         var col = Roo.get(el);
9805         
9806         if(!col.hasClass('sortable')){
9807             return;
9808         }
9809         
9810         var sort = col.attr('sort');
9811         var dir = 'ASC';
9812         
9813         if(col.select('i', true).first().hasClass('fa-arrow-up')){
9814             dir = 'DESC';
9815         }
9816         
9817         this.store.sortInfo = {field : sort, direction : dir};
9818         
9819         if (this.footer) {
9820             Roo.log("calling footer first");
9821             this.footer.onClick('first');
9822         } else {
9823         
9824             this.store.load({ params : { start : 0 } });
9825         }
9826     },
9827     
9828     renderHeader : function()
9829     {
9830         var header = {
9831             tag: 'thead',
9832             cn : []
9833         };
9834         
9835         var cm = this.cm;
9836         this.totalWidth = 0;
9837         
9838         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
9839             
9840             var config = cm.config[i];
9841             
9842             var c = {
9843                 tag: 'th',
9844                 cls : 'x-hcol-' + i,
9845                 style : '',
9846                 
9847                 html: cm.getColumnHeader(i)
9848             };
9849             
9850             var tooltip = cm.getColumnTooltip(i);
9851             if (tooltip) {
9852                 c.tooltip = tooltip;
9853             }
9854             
9855             
9856             var hh = '';
9857             
9858             if(typeof(config.sortable) != 'undefined' && config.sortable){
9859                 c.cls += ' sortable';
9860                 c.html = '<i class="fa"></i>' + c.html;
9861             }
9862             
9863             // could use BS4 hidden-..-down 
9864             
9865             if(typeof(config.lgHeader) != 'undefined'){
9866                 hh += '<span class="hidden-xs hidden-sm hidden-md ">' + config.lgHeader + '</span>';
9867             }
9868             
9869             if(typeof(config.mdHeader) != 'undefined'){
9870                 hh += '<span class="hidden-xs hidden-sm hidden-lg">' + config.mdHeader + '</span>';
9871             }
9872             
9873             if(typeof(config.smHeader) != 'undefined'){
9874                 hh += '<span class="hidden-xs hidden-md hidden-lg">' + config.smHeader + '</span>';
9875             }
9876             
9877             if(typeof(config.xsHeader) != 'undefined'){
9878                 hh += '<span class="hidden-sm hidden-md hidden-lg">' + config.xsHeader + '</span>';
9879             }
9880             
9881             if(hh.length){
9882                 c.html = hh;
9883             }
9884             
9885             if(typeof(config.tooltip) != 'undefined'){
9886                 c.tooltip = config.tooltip;
9887             }
9888             
9889             if(typeof(config.colspan) != 'undefined'){
9890                 c.colspan = config.colspan;
9891             }
9892             
9893             // hidden is handled by CSS now
9894             
9895             if(typeof(config.dataIndex) != 'undefined'){
9896                 c.sort = config.dataIndex;
9897             }
9898             
9899            
9900             
9901             if(typeof(config.align) != 'undefined' && config.align.length){
9902                 c.style += ' text-align:' + config.align + ';';
9903             }
9904             
9905             /* width is done in CSS
9906              *if(typeof(config.width) != 'undefined'){
9907                 c.style += ' width:' + config.width + 'px;';
9908                 this.totalWidth += config.width;
9909             } else {
9910                 this.totalWidth += 100; // assume minimum of 100 per column?
9911             }
9912             */
9913             
9914             if(typeof(config.cls) != 'undefined'){
9915                 c.cls = (typeof(c.cls) == 'undefined') ? config.cls : (c.cls + ' ' + config.cls);
9916             }
9917             // this is the bit that doesnt reall work at all...
9918             
9919             if (this.responsive) {
9920                  
9921             
9922                 ['xs','sm','md','lg'].map(function(size){
9923                     
9924                     if(typeof(config[size]) == 'undefined'){
9925                         return;
9926                     }
9927                      
9928                     if (!config[size]) { // 0 = hidden
9929                         // BS 4 '0' is treated as hide that column and below.
9930                         c.cls += ' hidden-' + size + ' hidden' + size + '-down';
9931                         return;
9932                     }
9933                     
9934                     c.cls += ' col-' + size + '-' + config[size] + (
9935                         size == 'xs' ? (' col-' + config[size] ) : '' // bs4 col-{num} replaces col-xs
9936                     );
9937                     
9938                     
9939                 });
9940             }
9941             // at the end?
9942             
9943             c.html +=' <span class="x-grid-split x-grid-split-' + i + '"></span>';
9944             
9945             
9946             
9947             
9948             header.cn.push(c)
9949         }
9950         
9951         return header;
9952     },
9953     
9954     renderBody : function()
9955     {
9956         var body = {
9957             tag: 'tbody',
9958             cn : [
9959                 {
9960                     tag: 'tr',
9961                     cn : [
9962                         {
9963                             tag : 'td',
9964                             colspan :  this.cm.getColumnCount()
9965                         }
9966                     ]
9967                 }
9968             ]
9969         };
9970         
9971         return body;
9972     },
9973     
9974     renderFooter : function()
9975     {
9976         var footer = {
9977             tag: 'tfoot',
9978             cn : [
9979                 {
9980                     tag: 'tr',
9981                     cn : [
9982                         {
9983                             tag : 'td',
9984                             colspan :  this.cm.getColumnCount()
9985                         }
9986                     ]
9987                 }
9988             ]
9989         };
9990         
9991         return footer;
9992     },
9993     
9994     onLoad : function()
9995     {
9996 //        Roo.log('ds onload');
9997         this.clear();
9998         
9999         var _this = this;
10000         var cm = this.cm;
10001         var ds = this.store;
10002         
10003         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
10004             e.select('i', true).removeClass(['fa-arrow-up', 'fa-arrow-down']);
10005             if (_this.store.sortInfo) {
10006                     
10007                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'ASC'){
10008                     e.select('i', true).addClass(['fa-arrow-up']);
10009                 }
10010                 
10011                 if(e.hasClass('sortable') && e.attr('sort') == _this.store.sortInfo.field && _this.store.sortInfo.direction.toUpperCase() == 'DESC'){
10012                     e.select('i', true).addClass(['fa-arrow-down']);
10013                 }
10014             }
10015         });
10016         
10017         var tbody =  this.bodyEl;
10018               
10019         if(ds.getCount() > 0){
10020             ds.data.each(function(d,rowIndex){
10021                 var row =  this.renderRow(cm, ds, rowIndex);
10022                 
10023                 tbody.createChild(row);
10024                 
10025                 var _this = this;
10026                 
10027                 if(row.cellObjects.length){
10028                     Roo.each(row.cellObjects, function(r){
10029                         _this.renderCellObject(r);
10030                     })
10031                 }
10032                 
10033             }, this);
10034         } else if (this.empty_results.length) {
10035             this.el.mask(this.empty_results, 'no-spinner');
10036         }
10037         
10038         var tfoot = this.el.select('tfoot', true).first();
10039         
10040         if(this.footerShow && !this.footerRow && this.auto_hide_footer && this.mainFoot){
10041             
10042             this.mainFoot.setVisibilityMode(Roo.Element.DISPLAY).hide();
10043             
10044             var total = this.ds.getTotalCount();
10045             
10046             if(this.footer.pageSize < total){
10047                 this.mainFoot.show();
10048             }
10049         }
10050
10051         if(!this.footerShow && this.footerRow) {
10052
10053             var tr = {
10054                 tag : 'tr',
10055                 cn : []
10056             };
10057
10058             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
10059                 var footer = typeof(cm.config[i].footer) == "function" ? cm.config[i].footer(ds, cm.config[i]) : cm.config[i].footer;
10060                 var td = {
10061                     tag: 'td',
10062                     cls : ' x-fcol-' + i,
10063                     html: footer
10064                 };
10065
10066                 tr.cn.push(td);
10067                 
10068             }
10069             
10070             tfoot.dom.innerHTML = '';
10071
10072             tfoot.createChild(tr);
10073         }
10074         
10075         Roo.each(this.el.select('tbody td', true).elements, function(e){
10076             e.on('mouseover', _this.onMouseover, _this);
10077         });
10078         
10079         Roo.each(this.el.select('tbody td', true).elements, function(e){
10080             e.on('mouseout', _this.onMouseout, _this);
10081         });
10082         this.fireEvent('rowsrendered', this);
10083         
10084         this.autoSize();
10085         
10086         this.initCSS(); /// resize cols
10087
10088         
10089     },
10090     
10091     
10092     onUpdate : function(ds,record)
10093     {
10094         this.refreshRow(record);
10095         this.autoSize();
10096     },
10097     
10098     onRemove : function(ds, record, index, isUpdate){
10099         if(isUpdate !== true){
10100             this.fireEvent("beforerowremoved", this, index, record);
10101         }
10102         var bt = this.bodyEl.dom;
10103         
10104         var rows = this.el.select('tbody > tr', true).elements;
10105         
10106         if(typeof(rows[index]) != 'undefined'){
10107             bt.removeChild(rows[index].dom);
10108         }
10109         
10110 //        if(bt.rows[index]){
10111 //            bt.removeChild(bt.rows[index]);
10112 //        }
10113         
10114         if(isUpdate !== true){
10115             //this.stripeRows(index);
10116             //this.syncRowHeights(index, index);
10117             //this.layout();
10118             this.fireEvent("rowremoved", this, index, record);
10119         }
10120     },
10121     
10122     onAdd : function(ds, records, rowIndex)
10123     {
10124         //Roo.log('on Add called');
10125         // - note this does not handle multiple adding very well..
10126         var bt = this.bodyEl.dom;
10127         for (var i =0 ; i < records.length;i++) {
10128             //Roo.log('call insert row Add called on ' + rowIndex + ':' + i);
10129             //Roo.log(records[i]);
10130             //Roo.log(this.store.getAt(rowIndex+i));
10131             this.insertRow(this.store, rowIndex + i, false);
10132             return;
10133         }
10134         
10135     },
10136     
10137     
10138     refreshRow : function(record){
10139         var ds = this.store, index;
10140         if(typeof record == 'number'){
10141             index = record;
10142             record = ds.getAt(index);
10143         }else{
10144             index = ds.indexOf(record);
10145             if (index < 0) {
10146                 return; // should not happen - but seems to 
10147             }
10148         }
10149         this.insertRow(ds, index, true);
10150         this.autoSize();
10151         this.onRemove(ds, record, index+1, true);
10152         this.autoSize();
10153         //this.syncRowHeights(index, index);
10154         //this.layout();
10155         this.fireEvent("rowupdated", this, index, record);
10156     },
10157     // private - called by RowSelection
10158     onRowSelect : function(rowIndex){
10159         var row = this.getRowDom(rowIndex);
10160         row.addClass(['bg-info','info']);
10161     },
10162     // private - called by RowSelection
10163     onRowDeselect : function(rowIndex)
10164     {
10165         if (rowIndex < 0) {
10166             return;
10167         }
10168         var row = this.getRowDom(rowIndex);
10169         row.removeClass(['bg-info','info']);
10170     },
10171       /**
10172      * Focuses the specified row.
10173      * @param {Number} row The row index
10174      */
10175     focusRow : function(row)
10176     {
10177         //Roo.log('GridView.focusRow');
10178         var x = this.bodyEl.dom.scrollLeft;
10179         this.focusCell(row, 0, false);
10180         this.bodyEl.dom.scrollLeft = x;
10181
10182     },
10183      /**
10184      * Focuses the specified cell.
10185      * @param {Number} row The row index
10186      * @param {Number} col The column index
10187      * @param {Boolean} hscroll false to disable horizontal scrolling
10188      */
10189     focusCell : function(row, col, hscroll)
10190     {
10191         //Roo.log('GridView.focusCell');
10192         var el = this.ensureVisible(row, col, hscroll);
10193         // not sure what focusEL achives = it's a <a> pos relative 
10194         //this.focusEl.alignTo(el, "tl-tl");
10195         //if(Roo.isGecko){
10196         //    this.focusEl.focus();
10197         //}else{
10198         //    this.focusEl.focus.defer(1, this.focusEl);
10199         //}
10200     },
10201     
10202      /**
10203      * Scrolls the specified cell into view
10204      * @param {Number} row The row index
10205      * @param {Number} col The column index
10206      * @param {Boolean} hscroll false to disable horizontal scrolling
10207      */
10208     ensureVisible : function(row, col, hscroll)
10209     {
10210         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
10211         //return null; //disable for testing.
10212         if(typeof row != "number"){
10213             row = row.rowIndex;
10214         }
10215         if(row < 0 && row >= this.ds.getCount()){
10216             return  null;
10217         }
10218         col = (col !== undefined ? col : 0);
10219         var cm = this.cm;
10220         while(cm.isHidden(col)){
10221             col++;
10222         }
10223
10224         var el = this.getCellDom(row, col);
10225         if(!el){
10226             return null;
10227         }
10228         var c = this.bodyEl.dom;
10229
10230         var ctop = parseInt(el.offsetTop, 10);
10231         var cleft = parseInt(el.offsetLeft, 10);
10232         var cbot = ctop + el.offsetHeight;
10233         var cright = cleft + el.offsetWidth;
10234
10235         //var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
10236         var ch = 0; //?? header is not withing the area?
10237         var stop = parseInt(c.scrollTop, 10);
10238         var sleft = parseInt(c.scrollLeft, 10);
10239         var sbot = stop + ch;
10240         var sright = sleft + c.clientWidth;
10241         /*
10242         Roo.log('GridView.ensureVisible:' +
10243                 ' ctop:' + ctop +
10244                 ' c.clientHeight:' + c.clientHeight +
10245                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
10246                 ' stop:' + stop +
10247                 ' cbot:' + cbot +
10248                 ' sbot:' + sbot +
10249                 ' ch:' + ch  
10250                 );
10251         */
10252         if(ctop < stop){
10253             c.scrollTop = ctop;
10254             //Roo.log("set scrolltop to ctop DISABLE?");
10255         }else if(cbot > sbot){
10256             //Roo.log("set scrolltop to cbot-ch");
10257             c.scrollTop = cbot-ch;
10258         }
10259
10260         if(hscroll !== false){
10261             if(cleft < sleft){
10262                 c.scrollLeft = cleft;
10263             }else if(cright > sright){
10264                 c.scrollLeft = cright-c.clientWidth;
10265             }
10266         }
10267
10268         return el;
10269     },
10270     
10271     
10272     insertRow : function(dm, rowIndex, isUpdate){
10273         
10274         if(!isUpdate){
10275             this.fireEvent("beforerowsinserted", this, rowIndex);
10276         }
10277             //var s = this.getScrollState();
10278         var row = this.renderRow(this.cm, this.store, rowIndex);
10279         // insert before rowIndex..
10280         var e = this.bodyEl.createChild(row,this.getRowDom(rowIndex));
10281         
10282         var _this = this;
10283                 
10284         if(row.cellObjects.length){
10285             Roo.each(row.cellObjects, function(r){
10286                 _this.renderCellObject(r);
10287             })
10288         }
10289             
10290         if(!isUpdate){
10291             this.fireEvent("rowsinserted", this, rowIndex);
10292             //this.syncRowHeights(firstRow, lastRow);
10293             //this.stripeRows(firstRow);
10294             //this.layout();
10295         }
10296         
10297     },
10298     
10299     
10300     getRowDom : function(rowIndex)
10301     {
10302         var rows = this.el.select('tbody > tr', true).elements;
10303         
10304         return (typeof(rows[rowIndex]) == 'undefined') ? false : rows[rowIndex];
10305         
10306     },
10307     getCellDom : function(rowIndex, colIndex)
10308     {
10309         var row = this.getRowDom(rowIndex);
10310         if (row === false) {
10311             return false;
10312         }
10313         var cols = row.select('td', true).elements;
10314         return (typeof(cols[colIndex]) == 'undefined') ? false : cols[colIndex];
10315         
10316     },
10317     
10318     // returns the object tree for a tr..
10319   
10320     
10321     renderRow : function(cm, ds, rowIndex) 
10322     {
10323         var d = ds.getAt(rowIndex);
10324         
10325         var row = {
10326             tag : 'tr',
10327             cls : 'x-row-' + rowIndex,
10328             cn : []
10329         };
10330             
10331         var cellObjects = [];
10332         
10333         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
10334             var config = cm.config[i];
10335             
10336             var renderer = cm.getRenderer(i);
10337             var value = '';
10338             var id = false;
10339             
10340             if(typeof(renderer) !== 'undefined'){
10341                 value = renderer.call(config, d.data[cm.getDataIndex(i)], false, d);
10342             }
10343             // if object are returned, then they are expected to be Roo.bootstrap.Component instances
10344             // and are rendered into the cells after the row is rendered - using the id for the element.
10345             
10346             if(typeof(value) === 'object'){
10347                 id = Roo.id();
10348                 cellObjects.push({
10349                     container : id,
10350                     cfg : value 
10351                 })
10352             }
10353             
10354             var rowcfg = {
10355                 record: d,
10356                 rowIndex : rowIndex,
10357                 colIndex : i,
10358                 rowClass : ''
10359             };
10360
10361             this.fireEvent('rowclass', this, rowcfg);
10362             
10363             var td = {
10364                 tag: 'td',
10365                 // this might end up displaying HTML?
10366                 // this is too messy... - better to only do it on columsn you know are going to be too long
10367                 //tooltip : (typeof(value) === 'object') ? '' : value,
10368                 cls : rowcfg.rowClass + ' x-col-' + i,
10369                 style: '',
10370                 html: (typeof(value) === 'object') ? '' : value
10371             };
10372             
10373             if (id) {
10374                 td.id = id;
10375             }
10376             
10377             if(typeof(config.colspan) != 'undefined'){
10378                 td.colspan = config.colspan;
10379             }
10380             
10381             
10382             
10383             if(typeof(config.align) != 'undefined' && config.align.length){
10384                 td.style += ' text-align:' + config.align + ';';
10385             }
10386             if(typeof(config.valign) != 'undefined' && config.valign.length){
10387                 td.style += ' vertical-align:' + config.valign + ';';
10388             }
10389             /*
10390             if(typeof(config.width) != 'undefined'){
10391                 td.style += ' width:' +  config.width + 'px;';
10392             }
10393             */
10394             
10395             if(typeof(config.cursor) != 'undefined'){
10396                 td.style += ' cursor:' +  config.cursor + ';';
10397             }
10398             
10399             if(typeof(config.cls) != 'undefined'){
10400                 td.cls = (typeof(td.cls) == 'undefined') ? config.cls : (td.cls + ' ' + config.cls);
10401             }
10402             if (this.responsive) {
10403                 ['xs','sm','md','lg'].map(function(size){
10404                     
10405                     if(typeof(config[size]) == 'undefined'){
10406                         return;
10407                     }
10408                     
10409                     
10410                       
10411                     if (!config[size]) { // 0 = hidden
10412                         // BS 4 '0' is treated as hide that column and below.
10413                         td.cls += ' hidden-' + size + ' hidden' + size + '-down';
10414                         return;
10415                     }
10416                     
10417                     td.cls += ' col-' + size + '-' + config[size] + (
10418                         size == 'xs' ? (' col-' +   config[size] ) : '' // bs4 col-{num} replaces col-xs
10419                     );
10420                      
10421     
10422                 });
10423             }
10424             row.cn.push(td);
10425            
10426         }
10427         
10428         row.cellObjects = cellObjects;
10429         
10430         return row;
10431           
10432     },
10433     
10434     
10435     
10436     onBeforeLoad : function()
10437     {
10438         this.el.unmask(); // if needed.
10439     },
10440      /**
10441      * Remove all rows
10442      */
10443     clear : function()
10444     {
10445         this.el.select('tbody', true).first().dom.innerHTML = '';
10446     },
10447     /**
10448      * Show or hide a row.
10449      * @param {Number} rowIndex to show or hide
10450      * @param {Boolean} state hide
10451      */
10452     setRowVisibility : function(rowIndex, state)
10453     {
10454         var bt = this.bodyEl.dom;
10455         
10456         var rows = this.el.select('tbody > tr', true).elements;
10457         
10458         if(typeof(rows[rowIndex]) == 'undefined'){
10459             return;
10460         }
10461         rows[rowIndex][ state ? 'removeClass' : 'addClass']('d-none');
10462         
10463     },
10464     
10465     
10466     getSelectionModel : function(){
10467         if(!this.selModel){
10468             this.selModel = new Roo.bootstrap.Table.RowSelectionModel({grid: this});
10469         }
10470         return this.selModel;
10471     },
10472     /*
10473      * Render the Roo.bootstrap object from renderder
10474      */
10475     renderCellObject : function(r)
10476     {
10477         var _this = this;
10478         
10479         r.cfg.parentId = (typeof(r.container) == 'string') ? r.container : r.container.id;
10480         
10481         var t = r.cfg.render(r.container);
10482         
10483         if(r.cfg.cn){
10484             Roo.each(r.cfg.cn, function(c){
10485                 var child = {
10486                     container: t.getChildContainer(),
10487                     cfg: c
10488                 };
10489                 _this.renderCellObject(child);
10490             })
10491         }
10492     },
10493     /**
10494      * get the Row Index from a dom element.
10495      * @param {Roo.Element} row The row to look for
10496      * @returns {Number} the row
10497      */
10498     getRowIndex : function(row)
10499     {
10500         var rowIndex = -1;
10501         
10502         Roo.each(this.el.select('tbody > tr', true).elements, function(el, index){
10503             if(el != row){
10504                 return;
10505             }
10506             
10507             rowIndex = index;
10508         });
10509         
10510         return rowIndex;
10511     },
10512     /**
10513      * get the header TH element for columnIndex
10514      * @param {Number} columnIndex
10515      * @returns {Roo.Element}
10516      */
10517     getHeaderIndex: function(colIndex)
10518     {
10519         var cols = this.headEl.select('th', true).elements;
10520         return cols[colIndex]; 
10521     },
10522     /**
10523      * get the Column Index from a dom element. (using regex on x-hcol-{colid})
10524      * @param {domElement} cell to look for
10525      * @returns {Number} the column
10526      */
10527     getCellIndex : function(cell)
10528     {
10529         var id = String(cell.className).match(Roo.bootstrap.Table.cellRE);
10530         if(id){
10531             return parseInt(id[1], 10);
10532         }
10533         return 0;
10534     },
10535      /**
10536      * Returns the grid's underlying element = used by panel.Grid
10537      * @return {Element} The element
10538      */
10539     getGridEl : function(){
10540         return this.el;
10541     },
10542      /**
10543      * Forces a resize - used by panel.Grid
10544      * @return {Element} The element
10545      */
10546     autoSize : function()
10547     {
10548         if(this.disableAutoSize) {
10549             return;
10550         }
10551         //var ctr = Roo.get(this.container.dom.parentElement);
10552         var ctr = Roo.get(this.el.dom);
10553         
10554         var thd = this.getGridEl().select('thead',true).first();
10555         var tbd = this.getGridEl().select('tbody', true).first();
10556         var tfd = this.getGridEl().select('tfoot', true).first();
10557         
10558         var cw = ctr.getWidth();
10559         this.getGridEl().select('tfoot tr, tfoot  td',true).setWidth(cw);
10560         
10561         if (tbd) {
10562             
10563             tbd.setWidth(ctr.getWidth());
10564             // if the body has a max height - and then scrolls - we should perhaps set up the height here
10565             // this needs fixing for various usage - currently only hydra job advers I think..
10566             //tdb.setHeight(
10567             //        ctr.getHeight() - ((thd ? thd.getHeight() : 0) + (tfd ? tfd.getHeight() : 0))
10568             //); 
10569             var barsize = (tbd.dom.offsetWidth - tbd.dom.clientWidth);
10570             cw -= barsize;
10571         }
10572         cw = Math.max(cw, this.totalWidth);
10573         this.getGridEl().select('tbody tr',true).setWidth(cw);
10574         this.initCSS();
10575         
10576         // resize 'expandable coloumn?
10577         
10578         return; // we doe not have a view in this design..
10579         
10580     },
10581     onBodyScroll: function()
10582     {
10583         //Roo.log("body scrolled');" + this.bodyEl.dom.scrollLeft);
10584         if(this.headEl){
10585             this.headEl.setStyle({
10586                 'position' : 'relative',
10587                 'left': (-1* this.bodyEl.dom.scrollLeft) + 'px'
10588             });
10589         }
10590         
10591         if(this.lazyLoad){
10592             
10593             var scrollHeight = this.bodyEl.dom.scrollHeight;
10594             
10595             var scrollTop = Math.ceil(this.bodyEl.getScroll().top);
10596             
10597             var height = this.bodyEl.getHeight();
10598             
10599             if(scrollHeight - height == scrollTop) {
10600                 
10601                 var total = this.ds.getTotalCount();
10602                 
10603                 if(this.footer.cursor + this.footer.pageSize < total){
10604                     
10605                     this.footer.ds.load({
10606                         params : {
10607                             start : this.footer.cursor + this.footer.pageSize,
10608                             limit : this.footer.pageSize
10609                         },
10610                         add : true
10611                     });
10612                 }
10613             }
10614             
10615         }
10616     },
10617     onColumnSplitterMoved : function(i, diff)
10618     {
10619         this.userResized = true;
10620         
10621         var cm = this.colModel;
10622         
10623         var w = this.getHeaderIndex(i).getWidth() + diff;
10624         
10625         
10626         cm.setColumnWidth(i, w, true);
10627         this.initCSS();
10628         //var cid = cm.getColumnId(i); << not used in this version?
10629        /* Roo.log(['#' + this.id + ' .x-col-' + i, "width", w + "px"]);
10630         
10631         this.CSS.updateRule( '#' + this.id + ' .x-col-' + i, "width", w + "px");
10632         this.CSS.updateRule('#' + this.id + ' .x-hcol-' + i, "width", w + "px");
10633         this.CSS.updateRule('#' + this.id + ' .x-grid-split-' + i, "left", w + "px");
10634 */
10635         //this.updateSplitters();
10636         //this.layout(); << ??
10637         this.fireEvent("columnresize", i, w);
10638     },
10639     onHeaderChange : function()
10640     {
10641         var header = this.renderHeader();
10642         var table = this.el.select('table', true).first();
10643         
10644         this.headEl.remove();
10645         this.headEl = table.createChild(header, this.bodyEl, false);
10646         
10647         Roo.each(this.el.select('thead th.sortable', true).elements, function(e){
10648             e.on('click', this.sort, this);
10649         }, this);
10650         
10651         if(this.enableColumnResize !== false && Roo.grid.SplitDragZone){
10652             new Roo.grid.SplitDragZone(this, this.headEl.dom, false); // not sure what 'lockedHd is for this implementation..)
10653         }
10654         
10655     },
10656     
10657     onHiddenChange : function(colModel, colIndex, hidden)
10658     {
10659         /*
10660         this.cm.setHidden()
10661         var thSelector = '#' + this.id + ' .x-hcol-' + colIndex;
10662         var tdSelector = '#' + this.id + ' .x-col-' + colIndex;
10663         
10664         this.CSS.updateRule(thSelector, "display", "");
10665         this.CSS.updateRule(tdSelector, "display", "");
10666         
10667         if(hidden){
10668             this.CSS.updateRule(thSelector, "display", "none");
10669             this.CSS.updateRule(tdSelector, "display", "none");
10670         }
10671         */
10672         // onload calls initCSS()
10673         this.onHeaderChange();
10674         this.onLoad();
10675     },
10676     
10677     setColumnWidth: function(col_index, width)
10678     {
10679         // width = "md-2 xs-2..."
10680         if(!this.colModel.config[col_index]) {
10681             return;
10682         }
10683         
10684         var w = width.split(" ");
10685         
10686         var rows = this.el.dom.getElementsByClassName("x-col-"+col_index);
10687         
10688         var h_row = this.el.dom.getElementsByClassName("x-hcol-"+col_index);
10689         
10690         
10691         for(var j = 0; j < w.length; j++) {
10692             
10693             if(!w[j]) {
10694                 continue;
10695             }
10696             
10697             var size_cls = w[j].split("-");
10698             
10699             if(!Number.isInteger(size_cls[1] * 1)) {
10700                 continue;
10701             }
10702             
10703             if(!this.colModel.config[col_index][size_cls[0]]) {
10704                 continue;
10705             }
10706             
10707             if(!h_row[0].classList.contains("col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]])) {
10708                 continue;
10709             }
10710             
10711             h_row[0].classList.replace(
10712                 "col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]],
10713                 "col-"+size_cls[0]+"-"+size_cls[1]
10714             );
10715             
10716             for(var i = 0; i < rows.length; i++) {
10717                 
10718                 var size_cls = w[j].split("-");
10719                 
10720                 if(!Number.isInteger(size_cls[1] * 1)) {
10721                     continue;
10722                 }
10723                 
10724                 if(!this.colModel.config[col_index][size_cls[0]]) {
10725                     continue;
10726                 }
10727                 
10728                 if(!rows[i].classList.contains("col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]])) {
10729                     continue;
10730                 }
10731                 
10732                 rows[i].classList.replace(
10733                     "col-"+size_cls[0]+"-"+this.colModel.config[col_index][size_cls[0]],
10734                     "col-"+size_cls[0]+"-"+size_cls[1]
10735                 );
10736             }
10737             
10738             this.colModel.config[col_index][size_cls[0]] = size_cls[1];
10739         }
10740     }
10741 });
10742
10743 // currently only used to find the split on drag.. 
10744 Roo.bootstrap.Table.cellRE = /(?:.*?)x-grid-(?:hd|cell|split)-([\d]+)(?:.*?)/;
10745
10746 /**
10747  * @depricated
10748 */
10749 Roo.bootstrap.Table.AbstractSelectionModel = Roo.grid.AbstractSelectionModel;
10750 Roo.bootstrap.Table.RowSelectionModel = Roo.grid.RowSelectionModel;
10751 /*
10752  * - LGPL
10753  *
10754  * table cell
10755  * 
10756  */
10757
10758 /**
10759  * @class Roo.bootstrap.TableCell
10760  * @extends Roo.bootstrap.Component
10761  * @children Roo.bootstrap.Component
10762  * @parent Roo.bootstrap.TableRow
10763  * Bootstrap TableCell class
10764  * 
10765  * @cfg {String} html cell contain text
10766  * @cfg {String} cls cell class
10767  * @cfg {String} tag cell tag (td|th) default td
10768  * @cfg {String} abbr Specifies an abbreviated version of the content in a cell
10769  * @cfg {String} align Aligns the content in a cell
10770  * @cfg {String} axis Categorizes cells
10771  * @cfg {String} bgcolor Specifies the background color of a cell
10772  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
10773  * @cfg {Number} colspan Specifies the number of columns a cell should span
10774  * @cfg {String} headers Specifies one or more header cells a cell is related to
10775  * @cfg {Number} height Sets the height of a cell
10776  * @cfg {String} nowrap Specifies that the content inside a cell should not wrap
10777  * @cfg {Number} rowspan Sets the number of rows a cell should span
10778  * @cfg {String} scope Defines a way to associate header cells and data cells in a table
10779  * @cfg {String} valign Vertical aligns the content in a cell
10780  * @cfg {Number} width Specifies the width of a cell
10781  * 
10782  * @constructor
10783  * Create a new TableCell
10784  * @param {Object} config The config object
10785  */
10786
10787 Roo.bootstrap.TableCell = function(config){
10788     Roo.bootstrap.TableCell.superclass.constructor.call(this, config);
10789 };
10790
10791 Roo.extend(Roo.bootstrap.TableCell, Roo.bootstrap.Component,  {
10792     
10793     html: false,
10794     cls: false,
10795     tag: false,
10796     abbr: false,
10797     align: false,
10798     axis: false,
10799     bgcolor: false,
10800     charoff: false,
10801     colspan: false,
10802     headers: false,
10803     height: false,
10804     nowrap: false,
10805     rowspan: false,
10806     scope: false,
10807     valign: false,
10808     width: false,
10809     
10810     
10811     getAutoCreate : function(){
10812         var cfg = Roo.apply({}, Roo.bootstrap.TableCell.superclass.getAutoCreate.call(this));
10813         
10814         cfg = {
10815             tag: 'td'
10816         };
10817         
10818         if(this.tag){
10819             cfg.tag = this.tag;
10820         }
10821         
10822         if (this.html) {
10823             cfg.html=this.html
10824         }
10825         if (this.cls) {
10826             cfg.cls=this.cls
10827         }
10828         if (this.abbr) {
10829             cfg.abbr=this.abbr
10830         }
10831         if (this.align) {
10832             cfg.align=this.align
10833         }
10834         if (this.axis) {
10835             cfg.axis=this.axis
10836         }
10837         if (this.bgcolor) {
10838             cfg.bgcolor=this.bgcolor
10839         }
10840         if (this.charoff) {
10841             cfg.charoff=this.charoff
10842         }
10843         if (this.colspan) {
10844             cfg.colspan=this.colspan
10845         }
10846         if (this.headers) {
10847             cfg.headers=this.headers
10848         }
10849         if (this.height) {
10850             cfg.height=this.height
10851         }
10852         if (this.nowrap) {
10853             cfg.nowrap=this.nowrap
10854         }
10855         if (this.rowspan) {
10856             cfg.rowspan=this.rowspan
10857         }
10858         if (this.scope) {
10859             cfg.scope=this.scope
10860         }
10861         if (this.valign) {
10862             cfg.valign=this.valign
10863         }
10864         if (this.width) {
10865             cfg.width=this.width
10866         }
10867         
10868         
10869         return cfg;
10870     }
10871    
10872 });
10873
10874  
10875
10876  /*
10877  * - LGPL
10878  *
10879  * table row
10880  * 
10881  */
10882
10883 /**
10884  * @class Roo.bootstrap.TableRow
10885  * @extends Roo.bootstrap.Component
10886  * @children Roo.bootstrap.TableCell
10887  * @parent Roo.bootstrap.TableBody
10888  * Bootstrap TableRow class
10889  * @cfg {String} cls row class
10890  * @cfg {String} align Aligns the content in a table row
10891  * @cfg {String} bgcolor Specifies a background color for a table row
10892  * @cfg {Number} charoff Sets the number of characters the content will be aligned from the character specified by the char attribute
10893  * @cfg {String} valign Vertical aligns the content in a table row
10894  * 
10895  * @constructor
10896  * Create a new TableRow
10897  * @param {Object} config The config object
10898  */
10899
10900 Roo.bootstrap.TableRow = function(config){
10901     Roo.bootstrap.TableRow.superclass.constructor.call(this, config);
10902 };
10903
10904 Roo.extend(Roo.bootstrap.TableRow, Roo.bootstrap.Component,  {
10905     
10906     cls: false,
10907     align: false,
10908     bgcolor: false,
10909     charoff: false,
10910     valign: false,
10911     
10912     getAutoCreate : function(){
10913         var cfg = Roo.apply({}, Roo.bootstrap.TableRow.superclass.getAutoCreate.call(this));
10914         
10915         cfg = {
10916             tag: 'tr'
10917         };
10918             
10919         if(this.cls){
10920             cfg.cls = this.cls;
10921         }
10922         if(this.align){
10923             cfg.align = this.align;
10924         }
10925         if(this.bgcolor){
10926             cfg.bgcolor = this.bgcolor;
10927         }
10928         if(this.charoff){
10929             cfg.charoff = this.charoff;
10930         }
10931         if(this.valign){
10932             cfg.valign = this.valign;
10933         }
10934         
10935         return cfg;
10936     }
10937    
10938 });
10939
10940  
10941
10942  /*
10943  * - LGPL
10944  *
10945  * table body
10946  * 
10947  */
10948
10949 /**
10950  * @class Roo.bootstrap.TableBody
10951  * @extends Roo.bootstrap.Component
10952  * @children Roo.bootstrap.TableRow
10953  * @parent Roo.bootstrap.Table
10954  * Bootstrap TableBody class
10955  * @cfg {String} cls element class
10956  * @cfg {String} tag element tag (thead|tbody|tfoot) default tbody
10957  * @cfg {String} align Aligns the content inside the element
10958  * @cfg {Number} charoff Sets the number of characters the content inside the element will be aligned from the character specified by the char attribute
10959  * @cfg {String} valign Vertical aligns the content inside the <tbody> element
10960  * 
10961  * @constructor
10962  * Create a new TableBody
10963  * @param {Object} config The config object
10964  */
10965
10966 Roo.bootstrap.TableBody = function(config){
10967     Roo.bootstrap.TableBody.superclass.constructor.call(this, config);
10968 };
10969
10970 Roo.extend(Roo.bootstrap.TableBody, Roo.bootstrap.Component,  {
10971     
10972     cls: false,
10973     tag: false,
10974     align: false,
10975     charoff: false,
10976     valign: false,
10977     
10978     getAutoCreate : function(){
10979         var cfg = Roo.apply({}, Roo.bootstrap.TableBody.superclass.getAutoCreate.call(this));
10980         
10981         cfg = {
10982             tag: 'tbody'
10983         };
10984             
10985         if (this.cls) {
10986             cfg.cls=this.cls
10987         }
10988         if(this.tag){
10989             cfg.tag = this.tag;
10990         }
10991         
10992         if(this.align){
10993             cfg.align = this.align;
10994         }
10995         if(this.charoff){
10996             cfg.charoff = this.charoff;
10997         }
10998         if(this.valign){
10999             cfg.valign = this.valign;
11000         }
11001         
11002         return cfg;
11003     }
11004     
11005     
11006 //    initEvents : function()
11007 //    {
11008 //        
11009 //        if(!this.store){
11010 //            return;
11011 //        }
11012 //        
11013 //        this.store = Roo.factory(this.store, Roo.data);
11014 //        this.store.on('load', this.onLoad, this);
11015 //        
11016 //        this.store.load();
11017 //        
11018 //    },
11019 //    
11020 //    onLoad: function () 
11021 //    {   
11022 //        this.fireEvent('load', this);
11023 //    }
11024 //    
11025 //   
11026 });
11027
11028  
11029
11030  /*
11031  * Based on:
11032  * Ext JS Library 1.1.1
11033  * Copyright(c) 2006-2007, Ext JS, LLC.
11034  *
11035  * Originally Released Under LGPL - original licence link has changed is not relivant.
11036  *
11037  * Fork - LGPL
11038  * <script type="text/javascript">
11039  */
11040
11041 // as we use this in bootstrap.
11042 Roo.namespace('Roo.form');
11043  /**
11044  * @class Roo.form.Action
11045  * Internal Class used to handle form actions
11046  * @constructor
11047  * @param {Roo.form.BasicForm} el The form element or its id
11048  * @param {Object} config Configuration options
11049  */
11050
11051  
11052  
11053 // define the action interface
11054 Roo.form.Action = function(form, options){
11055     this.form = form;
11056     this.options = options || {};
11057 };
11058 /**
11059  * Client Validation Failed
11060  * @const 
11061  */
11062 Roo.form.Action.CLIENT_INVALID = 'client';
11063 /**
11064  * Server Validation Failed
11065  * @const 
11066  */
11067 Roo.form.Action.SERVER_INVALID = 'server';
11068  /**
11069  * Connect to Server Failed
11070  * @const 
11071  */
11072 Roo.form.Action.CONNECT_FAILURE = 'connect';
11073 /**
11074  * Reading Data from Server Failed
11075  * @const 
11076  */
11077 Roo.form.Action.LOAD_FAILURE = 'load';
11078
11079 Roo.form.Action.prototype = {
11080     type : 'default',
11081     failureType : undefined,
11082     response : undefined,
11083     result : undefined,
11084
11085     // interface method
11086     run : function(options){
11087
11088     },
11089
11090     // interface method
11091     success : function(response){
11092
11093     },
11094
11095     // interface method
11096     handleResponse : function(response){
11097
11098     },
11099
11100     // default connection failure
11101     failure : function(response){
11102         
11103         this.response = response;
11104         this.failureType = Roo.form.Action.CONNECT_FAILURE;
11105         this.form.afterAction(this, false);
11106     },
11107
11108     processResponse : function(response){
11109         this.response = response;
11110         if(!response.responseText){
11111             return true;
11112         }
11113         this.result = this.handleResponse(response);
11114         return this.result;
11115     },
11116
11117     // utility functions used internally
11118     getUrl : function(appendParams){
11119         var url = this.options.url || this.form.url || this.form.el.dom.action;
11120         if(appendParams){
11121             var p = this.getParams();
11122             if(p){
11123                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11124             }
11125         }
11126         return url;
11127     },
11128
11129     getMethod : function(){
11130         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
11131     },
11132
11133     getParams : function(){
11134         var bp = this.form.baseParams;
11135         var p = this.options.params;
11136         if(p){
11137             if(typeof p == "object"){
11138                 p = Roo.urlEncode(Roo.applyIf(p, bp));
11139             }else if(typeof p == 'string' && bp){
11140                 p += '&' + Roo.urlEncode(bp);
11141             }
11142         }else if(bp){
11143             p = Roo.urlEncode(bp);
11144         }
11145         return p;
11146     },
11147
11148     createCallback : function(){
11149         return {
11150             success: this.success,
11151             failure: this.failure,
11152             scope: this,
11153             timeout: (this.form.timeout*1000),
11154             upload: this.form.fileUpload ? this.success : undefined
11155         };
11156     }
11157 };
11158
11159 Roo.form.Action.Submit = function(form, options){
11160     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
11161 };
11162
11163 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
11164     type : 'submit',
11165
11166     haveProgress : false,
11167     uploadComplete : false,
11168     
11169     // uploadProgress indicator.
11170     uploadProgress : function()
11171     {
11172         if (!this.form.progressUrl) {
11173             return;
11174         }
11175         
11176         if (!this.haveProgress) {
11177             Roo.MessageBox.progress("Uploading", "Uploading");
11178         }
11179         if (this.uploadComplete) {
11180            Roo.MessageBox.hide();
11181            return;
11182         }
11183         
11184         this.haveProgress = true;
11185    
11186         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
11187         
11188         var c = new Roo.data.Connection();
11189         c.request({
11190             url : this.form.progressUrl,
11191             params: {
11192                 id : uid
11193             },
11194             method: 'GET',
11195             success : function(req){
11196                //console.log(data);
11197                 var rdata = false;
11198                 var edata;
11199                 try  {
11200                    rdata = Roo.decode(req.responseText)
11201                 } catch (e) {
11202                     Roo.log("Invalid data from server..");
11203                     Roo.log(edata);
11204                     return;
11205                 }
11206                 if (!rdata || !rdata.success) {
11207                     Roo.log(rdata);
11208                     Roo.MessageBox.alert(Roo.encode(rdata));
11209                     return;
11210                 }
11211                 var data = rdata.data;
11212                 
11213                 if (this.uploadComplete) {
11214                    Roo.MessageBox.hide();
11215                    return;
11216                 }
11217                    
11218                 if (data){
11219                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
11220                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
11221                     );
11222                 }
11223                 this.uploadProgress.defer(2000,this);
11224             },
11225        
11226             failure: function(data) {
11227                 Roo.log('progress url failed ');
11228                 Roo.log(data);
11229             },
11230             scope : this
11231         });
11232            
11233     },
11234     
11235     
11236     run : function()
11237     {
11238         // run get Values on the form, so it syncs any secondary forms.
11239         this.form.getValues();
11240         
11241         var o = this.options;
11242         var method = this.getMethod();
11243         var isPost = method == 'POST';
11244         if(o.clientValidation === false || this.form.isValid()){
11245             
11246             if (this.form.progressUrl) {
11247                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
11248                     (new Date() * 1) + '' + Math.random());
11249                     
11250             } 
11251             
11252             
11253             Roo.Ajax.request(Roo.apply(this.createCallback(), {
11254                 form:this.form.el.dom,
11255                 url:this.getUrl(!isPost),
11256                 method: method,
11257                 params:isPost ? this.getParams() : null,
11258                 isUpload: this.form.fileUpload,
11259                 formData : this.form.formData
11260             }));
11261             
11262             this.uploadProgress();
11263
11264         }else if (o.clientValidation !== false){ // client validation failed
11265             this.failureType = Roo.form.Action.CLIENT_INVALID;
11266             this.form.afterAction(this, false);
11267         }
11268     },
11269
11270     success : function(response)
11271     {
11272         this.uploadComplete= true;
11273         if (this.haveProgress) {
11274             Roo.MessageBox.hide();
11275         }
11276         
11277         
11278         var result = this.processResponse(response);
11279         if(result === true || result.success){
11280             this.form.afterAction(this, true);
11281             return;
11282         }
11283         if(result.errors){
11284             this.form.markInvalid(result.errors);
11285             this.failureType = Roo.form.Action.SERVER_INVALID;
11286         }
11287         this.form.afterAction(this, false);
11288     },
11289     failure : function(response)
11290     {
11291         this.uploadComplete= true;
11292         if (this.haveProgress) {
11293             Roo.MessageBox.hide();
11294         }
11295         
11296         this.response = response;
11297         this.failureType = Roo.form.Action.CONNECT_FAILURE;
11298         this.form.afterAction(this, false);
11299     },
11300     
11301     handleResponse : function(response){
11302         if(this.form.errorReader){
11303             var rs = this.form.errorReader.read(response);
11304             var errors = [];
11305             if(rs.records){
11306                 for(var i = 0, len = rs.records.length; i < len; i++) {
11307                     var r = rs.records[i];
11308                     errors[i] = r.data;
11309                 }
11310             }
11311             if(errors.length < 1){
11312                 errors = null;
11313             }
11314             return {
11315                 success : rs.success,
11316                 errors : errors
11317             };
11318         }
11319         var ret = false;
11320         try {
11321             var rt = response.responseText;
11322             if (rt.match(/^\<!--\[CDATA\[/)) {
11323                 rt = rt.replace(/^\<!--\[CDATA\[/,'');
11324                 rt = rt.replace(/\]\]--\>$/,'');
11325             }
11326             
11327             ret = Roo.decode(rt);
11328         } catch (e) {
11329             ret = {
11330                 success: false,
11331                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
11332                 errors : []
11333             };
11334         }
11335         return ret;
11336         
11337     }
11338 });
11339
11340
11341 Roo.form.Action.Load = function(form, options){
11342     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
11343     this.reader = this.form.reader;
11344 };
11345
11346 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
11347     type : 'load',
11348
11349     run : function(){
11350         
11351         Roo.Ajax.request(Roo.apply(
11352                 this.createCallback(), {
11353                     method:this.getMethod(),
11354                     url:this.getUrl(false),
11355                     params:this.getParams()
11356         }));
11357     },
11358
11359     success : function(response){
11360         
11361         var result = this.processResponse(response);
11362         if(result === true || !result.success || !result.data){
11363             this.failureType = Roo.form.Action.LOAD_FAILURE;
11364             this.form.afterAction(this, false);
11365             return;
11366         }
11367         this.form.clearInvalid();
11368         this.form.setValues(result.data);
11369         this.form.afterAction(this, true);
11370     },
11371
11372     handleResponse : function(response){
11373         if(this.form.reader){
11374             var rs = this.form.reader.read(response);
11375             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
11376             return {
11377                 success : rs.success,
11378                 data : data
11379             };
11380         }
11381         return Roo.decode(response.responseText);
11382     }
11383 });
11384
11385 Roo.form.Action.ACTION_TYPES = {
11386     'load' : Roo.form.Action.Load,
11387     'submit' : Roo.form.Action.Submit
11388 };/*
11389  * - LGPL
11390  *
11391  * form
11392  *
11393  */
11394
11395 /**
11396  * @class Roo.bootstrap.form.Form
11397  * @extends Roo.bootstrap.Component
11398  * @children Roo.bootstrap.Component
11399  * Bootstrap Form class
11400  * @cfg {String} method  GET | POST (default POST)
11401  * @cfg {String} labelAlign top | left (default top)
11402  * @cfg {String} align left  | right - for navbars
11403  * @cfg {Boolean} loadMask load mask when submit (default true)
11404
11405  *
11406  * @constructor
11407  * Create a new Form
11408  * @param {Object} config The config object
11409  */
11410
11411
11412 Roo.bootstrap.form.Form = function(config){
11413     
11414     Roo.bootstrap.form.Form.superclass.constructor.call(this, config);
11415     
11416     Roo.bootstrap.form.Form.popover.apply();
11417     
11418     this.addEvents({
11419         /**
11420          * @event clientvalidation
11421          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
11422          * @param {Form} this
11423          * @param {Boolean} valid true if the form has passed client-side validation
11424          */
11425         clientvalidation: true,
11426         /**
11427          * @event beforeaction
11428          * Fires before any action is performed. Return false to cancel the action.
11429          * @param {Form} this
11430          * @param {Action} action The action to be performed
11431          */
11432         beforeaction: true,
11433         /**
11434          * @event actionfailed
11435          * Fires when an action fails.
11436          * @param {Form} this
11437          * @param {Action} action The action that failed
11438          */
11439         actionfailed : true,
11440         /**
11441          * @event actioncomplete
11442          * Fires when an action is completed.
11443          * @param {Form} this
11444          * @param {Action} action The action that completed
11445          */
11446         actioncomplete : true
11447     });
11448 };
11449
11450 Roo.extend(Roo.bootstrap.form.Form, Roo.bootstrap.Component,  {
11451
11452      /**
11453      * @cfg {String} method
11454      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
11455      */
11456     method : 'POST',
11457     /**
11458      * @cfg {String} url
11459      * The URL to use for form actions if one isn't supplied in the action options.
11460      */
11461     /**
11462      * @cfg {Boolean} fileUpload
11463      * Set to true if this form is a file upload.
11464      */
11465
11466     /**
11467      * @cfg {Object} baseParams
11468      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
11469      */
11470
11471     /**
11472      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
11473      */
11474     timeout: 30,
11475     /**
11476      * @cfg {Sting} align (left|right) for navbar forms
11477      */
11478     align : 'left',
11479
11480     // private
11481     activeAction : null,
11482
11483     /**
11484      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
11485      * element by passing it or its id or mask the form itself by passing in true.
11486      * @type Mixed
11487      */
11488     waitMsgTarget : false,
11489
11490     loadMask : true,
11491     
11492     /**
11493      * @cfg {Boolean} errorMask (true|false) default false
11494      */
11495     errorMask : false,
11496     
11497     /**
11498      * @cfg {Number} maskOffset Default 100
11499      */
11500     maskOffset : 100,
11501     
11502     /**
11503      * @cfg {Boolean} maskBody
11504      */
11505     maskBody : false,
11506
11507     getAutoCreate : function(){
11508
11509         var cfg = {
11510             tag: 'form',
11511             method : this.method || 'POST',
11512             id : this.id || Roo.id(),
11513             cls : ''
11514         };
11515         if (this.parent().xtype.match(/^Nav/)) {
11516             cfg.cls = 'navbar-form form-inline navbar-' + this.align;
11517
11518         }
11519
11520         if (this.labelAlign == 'left' ) {
11521             cfg.cls += ' form-horizontal';
11522         }
11523
11524
11525         return cfg;
11526     },
11527     initEvents : function()
11528     {
11529         this.el.on('submit', this.onSubmit, this);
11530         // this was added as random key presses on the form where triggering form submit.
11531         this.el.on('keypress', function(e) {
11532             if (e.getCharCode() != 13) {
11533                 return true;
11534             }
11535             // we might need to allow it for textareas.. and some other items.
11536             // check e.getTarget().
11537
11538             if(e.getTarget().nodeName.toLowerCase() === 'textarea'){
11539                 return true;
11540             }
11541
11542             Roo.log("keypress blocked");
11543
11544             e.preventDefault();
11545             return false;
11546         });
11547         
11548     },
11549     // private
11550     onSubmit : function(e){
11551         e.stopEvent();
11552     },
11553
11554      /**
11555      * Returns true if client-side validation on the form is successful.
11556      * @return Boolean
11557      */
11558     isValid : function(){
11559         var items = this.getItems();
11560         var valid = true;
11561         var target = false;
11562         
11563         items.each(function(f){
11564             
11565             if(f.validate()){
11566                 return;
11567             }
11568             
11569             Roo.log('invalid field: ' + f.name);
11570             
11571             valid = false;
11572
11573             if(!target && f.el.isVisible(true)){
11574                 target = f;
11575             }
11576            
11577         });
11578         
11579         if(this.errorMask && !valid){
11580             Roo.bootstrap.form.Form.popover.mask(this, target);
11581         }
11582         
11583         return valid;
11584     },
11585     
11586     /**
11587      * Returns true if any fields in this form have changed since their original load.
11588      * @return Boolean
11589      */
11590     isDirty : function(){
11591         var dirty = false;
11592         var items = this.getItems();
11593         items.each(function(f){
11594            if(f.isDirty()){
11595                dirty = true;
11596                return false;
11597            }
11598            return true;
11599         });
11600         return dirty;
11601     },
11602      /**
11603      * Performs a predefined action (submit or load) or custom actions you define on this form.
11604      * @param {String} actionName The name of the action type
11605      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
11606      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
11607      * accept other config options):
11608      * <pre>
11609 Property          Type             Description
11610 ----------------  ---------------  ----------------------------------------------------------------------------------
11611 url               String           The url for the action (defaults to the form's url)
11612 method            String           The form method to use (defaults to the form's method, or POST if not defined)
11613 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
11614 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
11615                                    validate the form on the client (defaults to false)
11616      * </pre>
11617      * @return {BasicForm} this
11618      */
11619     doAction : function(action, options){
11620         if(typeof action == 'string'){
11621             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
11622         }
11623         if(this.fireEvent('beforeaction', this, action) !== false){
11624             this.beforeAction(action);
11625             action.run.defer(100, action);
11626         }
11627         return this;
11628     },
11629
11630     // private
11631     beforeAction : function(action){
11632         var o = action.options;
11633         
11634         if(this.loadMask){
11635             
11636             if(this.maskBody){
11637                 Roo.get(document.body).mask(o.waitMsg || "Sending", 'x-mask-loading')
11638             } else {
11639                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
11640             }
11641         }
11642         // not really supported yet.. ??
11643
11644         //if(this.waitMsgTarget === true){
11645         //  this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
11646         //}else if(this.waitMsgTarget){
11647         //    this.waitMsgTarget = Roo.get(this.waitMsgTarget);
11648         //    this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
11649         //}else {
11650         //    Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
11651        // }
11652
11653     },
11654
11655     // private
11656     afterAction : function(action, success){
11657         this.activeAction = null;
11658         var o = action.options;
11659
11660         if(this.loadMask){
11661             
11662             if(this.maskBody){
11663                 Roo.get(document.body).unmask();
11664             } else {
11665                 this.el.unmask();
11666             }
11667         }
11668         
11669         //if(this.waitMsgTarget === true){
11670 //            this.el.unmask();
11671         //}else if(this.waitMsgTarget){
11672         //    this.waitMsgTarget.unmask();
11673         //}else{
11674         //    Roo.MessageBox.updateProgress(1);
11675         //    Roo.MessageBox.hide();
11676        // }
11677         //
11678         if(success){
11679             if(o.reset){
11680                 this.reset();
11681             }
11682             Roo.callback(o.success, o.scope, [this, action]);
11683             this.fireEvent('actioncomplete', this, action);
11684
11685         }else{
11686
11687             // failure condition..
11688             // we have a scenario where updates need confirming.
11689             // eg. if a locking scenario exists..
11690             // we look for { errors : { needs_confirm : true }} in the response.
11691             if (
11692                 (typeof(action.result) != 'undefined')  &&
11693                 (typeof(action.result.errors) != 'undefined')  &&
11694                 (typeof(action.result.errors.needs_confirm) != 'undefined')
11695            ){
11696                 var _t = this;
11697                 Roo.log("not supported yet");
11698                  /*
11699
11700                 Roo.MessageBox.confirm(
11701                     "Change requires confirmation",
11702                     action.result.errorMsg,
11703                     function(r) {
11704                         if (r != 'yes') {
11705                             return;
11706                         }
11707                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
11708                     }
11709
11710                 );
11711                 */
11712
11713
11714                 return;
11715             }
11716
11717             Roo.callback(o.failure, o.scope, [this, action]);
11718             // show an error message if no failed handler is set..
11719             if (!this.hasListener('actionfailed')) {
11720                 Roo.log("need to add dialog support");
11721                 /*
11722                 Roo.MessageBox.alert("Error",
11723                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
11724                         action.result.errorMsg :
11725                         "Saving Failed, please check your entries or try again"
11726                 );
11727                 */
11728             }
11729
11730             this.fireEvent('actionfailed', this, action);
11731         }
11732
11733     },
11734     /**
11735      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
11736      * @param {String} id The value to search for
11737      * @return Field
11738      */
11739     findField : function(id){
11740         var items = this.getItems();
11741         var field = items.get(id);
11742         if(!field){
11743              items.each(function(f){
11744                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
11745                     field = f;
11746                     return false;
11747                 }
11748                 return true;
11749             });
11750         }
11751         return field || null;
11752     },
11753      /**
11754      * Mark fields in this form invalid in bulk.
11755      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
11756      * @return {BasicForm} this
11757      */
11758     markInvalid : function(errors){
11759         if(errors instanceof Array){
11760             for(var i = 0, len = errors.length; i < len; i++){
11761                 var fieldError = errors[i];
11762                 var f = this.findField(fieldError.id);
11763                 if(f){
11764                     f.markInvalid(fieldError.msg);
11765                 }
11766             }
11767         }else{
11768             var field, id;
11769             for(id in errors){
11770                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
11771                     field.markInvalid(errors[id]);
11772                 }
11773             }
11774         }
11775         //Roo.each(this.childForms || [], function (f) {
11776         //    f.markInvalid(errors);
11777         //});
11778
11779         return this;
11780     },
11781
11782     /**
11783      * Set values for fields in this form in bulk.
11784      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
11785      * @return {BasicForm} this
11786      */
11787     setValues : function(values){
11788         if(values instanceof Array){ // array of objects
11789             for(var i = 0, len = values.length; i < len; i++){
11790                 var v = values[i];
11791                 var f = this.findField(v.id);
11792                 if(f){
11793                     f.setValue(v.value);
11794                     if(this.trackResetOnLoad){
11795                         f.originalValue = f.getValue();
11796                     }
11797                 }
11798             }
11799         }else{ // object hash
11800             var field, id;
11801             for(id in values){
11802                 if(typeof values[id] != 'function' && (field = this.findField(id))){
11803
11804                     if (field.setFromData &&
11805                         field.valueField &&
11806                         field.displayField &&
11807                         // combos' with local stores can
11808                         // be queried via setValue()
11809                         // to set their value..
11810                         (field.store && !field.store.isLocal)
11811                         ) {
11812                         // it's a combo
11813                         var sd = { };
11814                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
11815                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
11816                         field.setFromData(sd);
11817
11818                     } else if(field.setFromData && (field.store && !field.store.isLocal)) {
11819                         
11820                         field.setFromData(values);
11821                         
11822                     } else {
11823                         field.setValue(values[id]);
11824                     }
11825
11826
11827                     if(this.trackResetOnLoad){
11828                         field.originalValue = field.getValue();
11829                     }
11830                 }
11831             }
11832         }
11833
11834         //Roo.each(this.childForms || [], function (f) {
11835         //    f.setValues(values);
11836         //});
11837
11838         return this;
11839     },
11840
11841     /**
11842      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
11843      * they are returned as an array.
11844      * @param {Boolean} asString
11845      * @return {Object}
11846      */
11847     getValues : function(asString){
11848         //if (this.childForms) {
11849             // copy values from the child forms
11850         //    Roo.each(this.childForms, function (f) {
11851         //        this.setValues(f.getValues());
11852         //    }, this);
11853         //}
11854
11855
11856
11857         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
11858         if(asString === true){
11859             return fs;
11860         }
11861         return Roo.urlDecode(fs);
11862     },
11863
11864     /**
11865      * Returns the fields in this form as an object with key/value pairs.
11866      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
11867      * @return {Object}
11868      */
11869     getFieldValues : function(with_hidden)
11870     {
11871         var items = this.getItems();
11872         var ret = {};
11873         items.each(function(f){
11874             
11875             if (!f.getName()) {
11876                 return;
11877             }
11878             
11879             var v = f.getValue();
11880             
11881             if (f.inputType =='radio') {
11882                 if (typeof(ret[f.getName()]) == 'undefined') {
11883                     ret[f.getName()] = ''; // empty..
11884                 }
11885
11886                 if (!f.el.dom.checked) {
11887                     return;
11888
11889                 }
11890                 v = f.el.dom.value;
11891
11892             }
11893             
11894             if(f.xtype == 'MoneyField'){
11895                 ret[f.currencyName] = f.getCurrency();
11896             }
11897
11898             // not sure if this supported any more..
11899             if ((typeof(v) == 'object') && f.getRawValue) {
11900                 v = f.getRawValue() ; // dates..
11901             }
11902             // combo boxes where name != hiddenName...
11903             if (f.name !== false && f.name != '' && f.name != f.getName()) {
11904                 ret[f.name] = f.getRawValue();
11905             }
11906             ret[f.getName()] = v;
11907         });
11908
11909         return ret;
11910     },
11911
11912     /**
11913      * Clears all invalid messages in this form.
11914      * @return {BasicForm} this
11915      */
11916     clearInvalid : function(){
11917         var items = this.getItems();
11918
11919         items.each(function(f){
11920            f.clearInvalid();
11921         });
11922
11923         return this;
11924     },
11925
11926     /**
11927      * Resets this form.
11928      * @return {BasicForm} this
11929      */
11930     reset : function(){
11931         var items = this.getItems();
11932         items.each(function(f){
11933             f.reset();
11934         });
11935
11936         Roo.each(this.childForms || [], function (f) {
11937             f.reset();
11938         });
11939
11940
11941         return this;
11942     },
11943     
11944     getItems : function()
11945     {
11946         var r=new Roo.util.MixedCollection(false, function(o){
11947             return o.id || (o.id = Roo.id());
11948         });
11949         var iter = function(el) {
11950             if (el.inputEl) {
11951                 r.add(el);
11952             }
11953             if (!el.items) {
11954                 return;
11955             }
11956             Roo.each(el.items,function(e) {
11957                 iter(e);
11958             });
11959         };
11960
11961         iter(this);
11962         return r;
11963     },
11964     
11965     hideFields : function(items)
11966     {
11967         Roo.each(items, function(i){
11968             
11969             var f = this.findField(i);
11970             
11971             if(!f){
11972                 return;
11973             }
11974             
11975             f.hide();
11976             
11977         }, this);
11978     },
11979     
11980     showFields : function(items)
11981     {
11982         Roo.each(items, function(i){
11983             
11984             var f = this.findField(i);
11985             
11986             if(!f){
11987                 return;
11988             }
11989             
11990             f.show();
11991             
11992         }, this);
11993     }
11994
11995 });
11996
11997 Roo.apply(Roo.bootstrap.form.Form, {
11998     
11999     popover : {
12000         
12001         padding : 5,
12002         
12003         isApplied : false,
12004         
12005         isMasked : false,
12006         
12007         form : false,
12008         
12009         target : false,
12010         
12011         toolTip : false,
12012         
12013         intervalID : false,
12014         
12015         maskEl : false,
12016         
12017         apply : function()
12018         {
12019             if(this.isApplied){
12020                 return;
12021             }
12022             
12023             this.maskEl = {
12024                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
12025                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
12026                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
12027                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
12028             };
12029             
12030             this.maskEl.top.enableDisplayMode("block");
12031             this.maskEl.left.enableDisplayMode("block");
12032             this.maskEl.bottom.enableDisplayMode("block");
12033             this.maskEl.right.enableDisplayMode("block");
12034             
12035             this.toolTip = new Roo.bootstrap.Tooltip({
12036                 cls : 'roo-form-error-popover',
12037                 alignment : {
12038                     'left' : ['r-l', [-2,0], 'right'],
12039                     'right' : ['l-r', [2,0], 'left'],
12040                     'bottom' : ['tl-bl', [0,2], 'top'],
12041                     'top' : [ 'bl-tl', [0,-2], 'bottom']
12042                 }
12043             });
12044             
12045             this.toolTip.render(Roo.get(document.body));
12046
12047             this.toolTip.el.enableDisplayMode("block");
12048             
12049             Roo.get(document.body).on('click', function(){
12050                 this.unmask();
12051             }, this);
12052             
12053             Roo.get(document.body).on('touchstart', function(){
12054                 this.unmask();
12055             }, this);
12056             
12057             this.isApplied = true
12058         },
12059         
12060         mask : function(form, target)
12061         {
12062             this.form = form;
12063             
12064             this.target = target;
12065             
12066             if(!this.form.errorMask || !target.el){
12067                 return;
12068             }
12069             
12070             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.modal', 100, true) || Roo.get(document.body);
12071             
12072             Roo.log(scrollable);
12073             
12074             var ot = this.target.el.calcOffsetsTo(scrollable);
12075             
12076             var scrollTo = ot[1] - this.form.maskOffset;
12077             
12078             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
12079             
12080             scrollable.scrollTo('top', scrollTo);
12081             
12082             var box = this.target.el.getBox();
12083             Roo.log(box);
12084             var zIndex = Roo.bootstrap.Modal.zIndex++;
12085
12086             
12087             this.maskEl.top.setStyle('position', 'absolute');
12088             this.maskEl.top.setStyle('z-index', zIndex);
12089             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
12090             this.maskEl.top.setLeft(0);
12091             this.maskEl.top.setTop(0);
12092             this.maskEl.top.show();
12093             
12094             this.maskEl.left.setStyle('position', 'absolute');
12095             this.maskEl.left.setStyle('z-index', zIndex);
12096             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
12097             this.maskEl.left.setLeft(0);
12098             this.maskEl.left.setTop(box.y - this.padding);
12099             this.maskEl.left.show();
12100
12101             this.maskEl.bottom.setStyle('position', 'absolute');
12102             this.maskEl.bottom.setStyle('z-index', zIndex);
12103             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
12104             this.maskEl.bottom.setLeft(0);
12105             this.maskEl.bottom.setTop(box.bottom + this.padding);
12106             this.maskEl.bottom.show();
12107
12108             this.maskEl.right.setStyle('position', 'absolute');
12109             this.maskEl.right.setStyle('z-index', zIndex);
12110             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
12111             this.maskEl.right.setLeft(box.right + this.padding);
12112             this.maskEl.right.setTop(box.y - this.padding);
12113             this.maskEl.right.show();
12114
12115             this.toolTip.bindEl = this.target.el;
12116
12117             this.toolTip.el.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
12118
12119             var tip = this.target.blankText;
12120
12121             if(this.target.getValue() !== '' ) {
12122                 
12123                 if (this.target.invalidText.length) {
12124                     tip = this.target.invalidText;
12125                 } else if (this.target.regexText.length){
12126                     tip = this.target.regexText;
12127                 }
12128             }
12129
12130             this.toolTip.show(tip);
12131
12132             this.intervalID = window.setInterval(function() {
12133                 Roo.bootstrap.form.Form.popover.unmask();
12134             }, 10000);
12135
12136             window.onwheel = function(){ return false;};
12137             
12138             (function(){ this.isMasked = true; }).defer(500, this);
12139             
12140         },
12141         
12142         unmask : function()
12143         {
12144             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
12145                 return;
12146             }
12147             
12148             this.maskEl.top.setStyle('position', 'absolute');
12149             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
12150             this.maskEl.top.hide();
12151
12152             this.maskEl.left.setStyle('position', 'absolute');
12153             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
12154             this.maskEl.left.hide();
12155
12156             this.maskEl.bottom.setStyle('position', 'absolute');
12157             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
12158             this.maskEl.bottom.hide();
12159
12160             this.maskEl.right.setStyle('position', 'absolute');
12161             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
12162             this.maskEl.right.hide();
12163             
12164             this.toolTip.hide();
12165             
12166             this.toolTip.el.hide();
12167             
12168             window.onwheel = function(){ return true;};
12169             
12170             if(this.intervalID){
12171                 window.clearInterval(this.intervalID);
12172                 this.intervalID = false;
12173             }
12174             
12175             this.isMasked = false;
12176             
12177         }
12178         
12179     }
12180     
12181 });
12182
12183 /*
12184  * Based on:
12185  * Ext JS Library 1.1.1
12186  * Copyright(c) 2006-2007, Ext JS, LLC.
12187  *
12188  * Originally Released Under LGPL - original licence link has changed is not relivant.
12189  *
12190  * Fork - LGPL
12191  * <script type="text/javascript">
12192  */
12193 /**
12194  * @class Roo.form.VTypes
12195  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
12196  * @static
12197  */
12198 Roo.form.VTypes = function(){
12199     // closure these in so they are only created once.
12200     var alpha = /^[a-zA-Z_]+$/;
12201     var alphanum = /^[a-zA-Z0-9_]+$/;
12202     var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
12203     var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
12204
12205     // All these messages and functions are configurable
12206     return {
12207         /**
12208          * The function used to validate email addresses
12209          * @param {String} value The email address
12210          */
12211         email : function(v){
12212             return email.test(v);
12213         },
12214         /**
12215          * The error text to display when the email validation function returns false
12216          * @type String
12217          */
12218         emailText : 'This field should be an e-mail address in the format "user@domain.com"',
12219         /**
12220          * The keystroke filter mask to be applied on email input
12221          * @type RegExp
12222          */
12223         emailMask : /[a-z0-9_\.\-@]/i,
12224
12225         /**
12226          * The function used to validate URLs
12227          * @param {String} value The URL
12228          */
12229         url : function(v){
12230             return url.test(v);
12231         },
12232         /**
12233          * The error text to display when the url validation function returns false
12234          * @type String
12235          */
12236         urlText : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
12237         
12238         /**
12239          * The function used to validate alpha values
12240          * @param {String} value The value
12241          */
12242         alpha : function(v){
12243             return alpha.test(v);
12244         },
12245         /**
12246          * The error text to display when the alpha validation function returns false
12247          * @type String
12248          */
12249         alphaText : 'This field should only contain letters and _',
12250         /**
12251          * The keystroke filter mask to be applied on alpha input
12252          * @type RegExp
12253          */
12254         alphaMask : /[a-z_]/i,
12255
12256         /**
12257          * The function used to validate alphanumeric values
12258          * @param {String} value The value
12259          */
12260         alphanum : function(v){
12261             return alphanum.test(v);
12262         },
12263         /**
12264          * The error text to display when the alphanumeric validation function returns false
12265          * @type String
12266          */
12267         alphanumText : 'This field should only contain letters, numbers and _',
12268         /**
12269          * The keystroke filter mask to be applied on alphanumeric input
12270          * @type RegExp
12271          */
12272         alphanumMask : /[a-z0-9_]/i
12273     };
12274 }();/*
12275  * - LGPL
12276  *
12277  * Input
12278  * 
12279  */
12280
12281 /**
12282  * @class Roo.bootstrap.form.Input
12283  * @extends Roo.bootstrap.Component
12284  * Bootstrap Input class
12285  * @cfg {Boolean} disabled is it disabled
12286  * @cfg {String} inputType (button|checkbox|email|file|hidden|image|number|password|radio|range|reset|search|submit|text)  
12287  * @cfg {String} name name of the input
12288  * @cfg {string} fieldLabel - the label associated
12289  * @cfg {string} placeholder - placeholder to put in text.
12290  * @cfg {string} before - input group add on before
12291  * @cfg {string} after - input group add on after
12292  * @cfg {string} size - (lg|sm) or leave empty..
12293  * @cfg {Number} xs colspan out of 12 for mobile-sized screens
12294  * @cfg {Number} sm colspan out of 12 for tablet-sized screens
12295  * @cfg {Number} md colspan out of 12 for computer-sized screens
12296  * @cfg {Number} lg colspan out of 12 for large computer-sized screens
12297  * @cfg {string} value default value of the input
12298  * @cfg {Number} labelWidth set the width of label 
12299  * @cfg {Number} labellg set the width of label (1-12)
12300  * @cfg {Number} labelmd set the width of label (1-12)
12301  * @cfg {Number} labelsm set the width of label (1-12)
12302  * @cfg {Number} labelxs set the width of label (1-12)
12303  * @cfg {String} labelAlign (top|left)
12304  * @cfg {Boolean} readOnly Specifies that the field should be read-only
12305  * @cfg {String} autocomplete - default is new-password see: https://developers.google.com/web/fundamentals/input/form/label-and-name-inputs?hl=en
12306  * @cfg {String} indicatorpos (left|right) default left
12307  * @cfg {String} capture (user|camera) use for file input only. (default empty)
12308  * @cfg {String} accept (image|video|audio) use for file input only. (default empty)
12309  * @cfg {Boolean} preventMark Do not show tick or cross if error/success
12310  * @cfg {Roo.bootstrap.Button} before Button to show before
12311  * @cfg {Roo.bootstrap.Button} afterButton to show before
12312  * @cfg {String} align (left|center|right) Default left
12313  * @cfg {Boolean} forceFeedback (true|false) Default false
12314  * 
12315  * @constructor
12316  * Create a new Input
12317  * @param {Object} config The config object
12318  */
12319
12320 Roo.bootstrap.form.Input = function(config){
12321     
12322     Roo.bootstrap.form.Input.superclass.constructor.call(this, config);
12323     
12324     this.addEvents({
12325         /**
12326          * @event focus
12327          * Fires when this field receives input focus.
12328          * @param {Roo.form.Field} this
12329          */
12330         focus : true,
12331         /**
12332          * @event blur
12333          * Fires when this field loses input focus.
12334          * @param {Roo.form.Field} this
12335          */
12336         blur : true,
12337         /**
12338          * @event specialkey
12339          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
12340          * {@link Roo.EventObject#getKey} to determine which key was pressed.
12341          * @param {Roo.form.Field} this
12342          * @param {Roo.EventObject} e The event object
12343          */
12344         specialkey : true,
12345         /**
12346          * @event change
12347          * Fires just before the field blurs if the field value has changed.
12348          * @param {Roo.form.Field} this
12349          * @param {Mixed} newValue The new value
12350          * @param {Mixed} oldValue The original value
12351          */
12352         change : true,
12353         /**
12354          * @event invalid
12355          * Fires after the field has been marked as invalid.
12356          * @param {Roo.form.Field} this
12357          * @param {String} msg The validation message
12358          */
12359         invalid : true,
12360         /**
12361          * @event valid
12362          * Fires after the field has been validated with no errors.
12363          * @param {Roo.form.Field} this
12364          */
12365         valid : true,
12366          /**
12367          * @event keyup
12368          * Fires after the key up
12369          * @param {Roo.form.Field} this
12370          * @param {Roo.EventObject}  e The event Object
12371          */
12372         keyup : true,
12373         /**
12374          * @event paste
12375          * Fires after the user pastes into input
12376          * @param {Roo.form.Field} this
12377          * @param {Roo.EventObject}  e The event Object
12378          */
12379         paste : true
12380     });
12381 };
12382
12383 Roo.extend(Roo.bootstrap.form.Input, Roo.bootstrap.Component,  {
12384      /**
12385      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
12386       automatic validation (defaults to "keyup").
12387      */
12388     validationEvent : "keyup",
12389      /**
12390      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
12391      */
12392     validateOnBlur : true,
12393     /**
12394      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
12395      */
12396     validationDelay : 250,
12397      /**
12398      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
12399      */
12400     focusClass : "x-form-focus",  // not needed???
12401     
12402        
12403     /**
12404      * @cfg {String} invalidClass DEPRICATED - code uses BS4 - is-valid / is-invalid
12405      */
12406     invalidClass : "has-warning",
12407     
12408     /**
12409      * @cfg {String} validClass DEPRICATED - code uses BS4 - is-valid / is-invalid
12410      */
12411     validClass : "has-success",
12412     
12413     /**
12414      * @cfg {Boolean} hasFeedback (true|false) default true
12415      */
12416     hasFeedback : true,
12417     
12418     /**
12419      * @cfg {String} invalidFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
12420      */
12421     invalidFeedbackClass : "glyphicon-warning-sign",
12422     
12423     /**
12424      * @cfg {String} validFeedbackIcon The CSS class to use when create feedback icon (defaults to "x-form-invalid")
12425      */
12426     validFeedbackClass : "glyphicon-ok",
12427     
12428     /**
12429      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
12430      */
12431     selectOnFocus : false,
12432     
12433      /**
12434      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
12435      */
12436     maskRe : null,
12437        /**
12438      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
12439      */
12440     vtype : null,
12441     
12442       /**
12443      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
12444      */
12445     disableKeyFilter : false,
12446     
12447        /**
12448      * @cfg {Boolean} disabled True to disable the field (defaults to false).
12449      */
12450     disabled : false,
12451      /**
12452      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
12453      */
12454     allowBlank : true,
12455     /**
12456      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
12457      */
12458     blankText : "Please complete this mandatory field",
12459     
12460      /**
12461      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
12462      */
12463     minLength : 0,
12464     /**
12465      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
12466      */
12467     maxLength : Number.MAX_VALUE,
12468     /**
12469      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
12470      */
12471     minLengthText : "The minimum length for this field is {0}",
12472     /**
12473      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
12474      */
12475     maxLengthText : "The maximum length for this field is {0}",
12476   
12477     
12478     /**
12479      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
12480      * If available, this function will be called only after the basic validators all return true, and will be passed the
12481      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
12482      */
12483     validator : null,
12484     /**
12485      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
12486      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
12487      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
12488      */
12489     regex : null,
12490     /**
12491      * @cfg {String} regexText -- Depricated - use Invalid Text
12492      */
12493     regexText : "",
12494     
12495     /**
12496      * @cfg {String} invalidText The error text to display if {@link #validator} test fails during validation (defaults to "")
12497      */
12498     invalidText : "",
12499     
12500     
12501     
12502     autocomplete: false,
12503     
12504     
12505     fieldLabel : '',
12506     inputType : 'text',
12507     
12508     name : false,
12509     placeholder: false,
12510     before : false,
12511     after : false,
12512     size : false,
12513     hasFocus : false,
12514     preventMark: false,
12515     isFormField : true,
12516     value : '',
12517     labelWidth : 2,
12518     labelAlign : false,
12519     readOnly : false,
12520     align : false,
12521     formatedValue : false,
12522     forceFeedback : false,
12523     
12524     indicatorpos : 'left',
12525     
12526     labellg : 0,
12527     labelmd : 0,
12528     labelsm : 0,
12529     labelxs : 0,
12530     
12531     capture : '',
12532     accept : '',
12533     
12534     parentLabelAlign : function()
12535     {
12536         var parent = this;
12537         while (parent.parent()) {
12538             parent = parent.parent();
12539             if (typeof(parent.labelAlign) !='undefined') {
12540                 return parent.labelAlign;
12541             }
12542         }
12543         return 'left';
12544         
12545     },
12546     
12547     getAutoCreate : function()
12548     {
12549         
12550         var id = Roo.id();
12551         
12552         var cfg = {};
12553         
12554         if(this.inputType != 'hidden'){
12555             cfg.cls = 'form-group' //input-group
12556         }
12557         
12558         var input =  {
12559             tag: 'input',
12560             id : id,
12561             type : this.inputType,
12562             value : this.value,
12563             cls : 'form-control',
12564             placeholder : this.placeholder || '',
12565             autocomplete : this.autocomplete || 'new-password'
12566         };
12567         if (this.inputType == 'file') {
12568             input.style = 'overflow:hidden'; // why not in CSS?
12569         }
12570         
12571         if(this.capture.length){
12572             input.capture = this.capture;
12573         }
12574         
12575         if(this.accept.length){
12576             input.accept = this.accept + "/*";
12577         }
12578         
12579         if(this.align){
12580             input.style = (typeof(input.style) == 'undefined') ? ('text-align:' + this.align) : (input.style + 'text-align:' + this.align);
12581         }
12582         
12583         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
12584             input.maxLength = this.maxLength;
12585         }
12586         
12587         if (this.disabled) {
12588             input.disabled=true;
12589         }
12590         
12591         if (this.readOnly) {
12592             input.readonly=true;
12593         }
12594         
12595         if (this.name) {
12596             input.name = this.name;
12597         }
12598         
12599         if (this.size) {
12600             input.cls += ' input-' + this.size;
12601         }
12602         
12603         var settings=this;
12604         ['xs','sm','md','lg'].map(function(size){
12605             if (settings[size]) {
12606                 cfg.cls += ' col-' + size + '-' + settings[size];
12607             }
12608         });
12609         
12610         var inputblock = input;
12611         
12612         var feedback = {
12613             tag: 'span',
12614             cls: 'glyphicon form-control-feedback'
12615         };
12616             
12617         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
12618             
12619             inputblock = {
12620                 cls : 'has-feedback',
12621                 cn :  [
12622                     input,
12623                     feedback
12624                 ] 
12625             };  
12626         }
12627         
12628         if (this.before || this.after) {
12629             
12630             inputblock = {
12631                 cls : 'input-group',
12632                 cn :  [] 
12633             };
12634             
12635             if (this.before && typeof(this.before) == 'string') {
12636                 
12637                 inputblock.cn.push({
12638                     tag :'span',
12639                     cls : 'roo-input-before input-group-addon input-group-prepend input-group-text',
12640                     html : this.before
12641                 });
12642             }
12643             if (this.before && typeof(this.before) == 'object') {
12644                 this.before = Roo.factory(this.before);
12645                 
12646                 inputblock.cn.push({
12647                     tag :'span',
12648                     cls : 'roo-input-before input-group-prepend   input-group-' +
12649                         (this.before.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
12650                 });
12651             }
12652             
12653             inputblock.cn.push(input);
12654             
12655             if (this.after && typeof(this.after) == 'string') {
12656                 inputblock.cn.push({
12657                     tag :'span',
12658                     cls : 'roo-input-after input-group-append input-group-text input-group-addon',
12659                     html : this.after
12660                 });
12661             }
12662             if (this.after && typeof(this.after) == 'object') {
12663                 this.after = Roo.factory(this.after);
12664                 
12665                 inputblock.cn.push({
12666                     tag :'span',
12667                     cls : 'roo-input-after input-group-append  input-group-' +
12668                         (this.after.xtype == 'Button' ? 'btn' : 'addon')  //?? what about checkboxes - that looks like a bit of a hack thought? 
12669                 });
12670             }
12671             
12672             if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
12673                 inputblock.cls += ' has-feedback';
12674                 inputblock.cn.push(feedback);
12675             }
12676         };
12677         
12678         
12679         
12680         cfg = this.getAutoCreateLabel( cfg, inputblock );
12681         
12682        
12683          
12684         
12685         if (this.parentType === 'Navbar' &&  this.parent().bar) {
12686            cfg.cls += ' navbar-form';
12687         }
12688         
12689         if (this.parentType === 'NavGroup' && !(Roo.bootstrap.version == 4 && this.parent().form)) {
12690             // on BS4 we do this only if not form 
12691             cfg.cls += ' navbar-form';
12692             cfg.tag = 'li';
12693         }
12694         
12695         return cfg;
12696         
12697     },
12698     /**
12699      * autocreate the label - also used by textara... ?? and others?
12700      */
12701     getAutoCreateLabel : function( cfg, inputblock )
12702     {
12703         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
12704        
12705         var indicator = {
12706             tag : 'i',
12707             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
12708             tooltip : 'This field is required'
12709         };
12710         if (this.allowBlank ) {
12711             indicator.style = this.allowBlank ? ' display:none' : '';
12712         }
12713         if (align ==='left' && this.fieldLabel.length) {
12714             
12715             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
12716             
12717             cfg.cn = [
12718                 indicator,
12719                 {
12720                     tag: 'label',
12721                     'for' :  id,
12722                     cls : 'control-label col-form-label',
12723                     html : this.fieldLabel
12724
12725                 },
12726                 {
12727                     cls : "", 
12728                     cn: [
12729                         inputblock
12730                     ]
12731                 }
12732             ];
12733             
12734             var labelCfg = cfg.cn[1];
12735             var contentCfg = cfg.cn[2];
12736             
12737             if(this.indicatorpos == 'right'){
12738                 cfg.cn = [
12739                     {
12740                         tag: 'label',
12741                         'for' :  id,
12742                         cls : 'control-label col-form-label',
12743                         cn : [
12744                             {
12745                                 tag : 'span',
12746                                 html : this.fieldLabel
12747                             },
12748                             indicator
12749                         ]
12750                     },
12751                     {
12752                         cls : "",
12753                         cn: [
12754                             inputblock
12755                         ]
12756                     }
12757
12758                 ];
12759                 
12760                 labelCfg = cfg.cn[0];
12761                 contentCfg = cfg.cn[1];
12762             
12763             }
12764             
12765             if(this.labelWidth > 12){
12766                 labelCfg.style = "width: " + this.labelWidth + 'px';
12767             }
12768             
12769             if(this.labelWidth < 13 && this.labelmd == 0){
12770                 this.labellg = this.labellg > 0 ? this.labellg : this.labelWidth;
12771             }
12772             
12773             if(this.labellg > 0){
12774                 labelCfg.cls += ' col-lg-' + this.labellg;
12775                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
12776             }
12777             
12778             if(this.labelmd > 0){
12779                 labelCfg.cls += ' col-md-' + this.labelmd;
12780                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
12781             }
12782             
12783             if(this.labelsm > 0){
12784                 labelCfg.cls += ' col-sm-' + this.labelsm;
12785                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
12786             }
12787             
12788             if(this.labelxs > 0){
12789                 labelCfg.cls += ' col-xs-' + this.labelxs;
12790                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
12791             }
12792             
12793             
12794         } else if ( this.fieldLabel.length) {
12795                 
12796             
12797             
12798             cfg.cn = [
12799                 {
12800                     tag : 'i',
12801                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
12802                     tooltip : 'This field is required',
12803                     style : this.allowBlank ? ' display:none' : '' 
12804                 },
12805                 {
12806                     tag: 'label',
12807                    //cls : 'input-group-addon',
12808                     html : this.fieldLabel
12809
12810                 },
12811
12812                inputblock
12813
12814            ];
12815            
12816            if(this.indicatorpos == 'right'){
12817        
12818                 cfg.cn = [
12819                     {
12820                         tag: 'label',
12821                        //cls : 'input-group-addon',
12822                         html : this.fieldLabel
12823
12824                     },
12825                     {
12826                         tag : 'i',
12827                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
12828                         tooltip : 'This field is required',
12829                         style : this.allowBlank ? ' display:none' : '' 
12830                     },
12831
12832                    inputblock
12833
12834                ];
12835
12836             }
12837
12838         } else {
12839             
12840             cfg.cn = [
12841
12842                     inputblock
12843
12844             ];
12845                 
12846                 
12847         };
12848         return cfg;
12849     },
12850     
12851     
12852     /**
12853      * return the real input element.
12854      */
12855     inputEl: function ()
12856     {
12857         return this.el.select('input.form-control',true).first();
12858     },
12859     
12860     tooltipEl : function()
12861     {
12862         return this.inputEl();
12863     },
12864     
12865     indicatorEl : function()
12866     {
12867         if (Roo.bootstrap.version == 4) {
12868             return false; // not enabled in v4 yet.
12869         }
12870         
12871         var indicator = this.el.select('i.roo-required-indicator',true).first();
12872         
12873         if(!indicator){
12874             return false;
12875         }
12876         
12877         return indicator;
12878         
12879     },
12880     
12881     setDisabled : function(v)
12882     {
12883         var i  = this.inputEl().dom;
12884         if (!v) {
12885             i.removeAttribute('disabled');
12886             return;
12887             
12888         }
12889         i.setAttribute('disabled','true');
12890     },
12891     initEvents : function()
12892     {
12893           
12894         this.inputEl().on("keydown" , this.fireKey,  this);
12895         this.inputEl().on("focus", this.onFocus,  this);
12896         this.inputEl().on("blur", this.onBlur,  this);
12897         
12898         this.inputEl().relayEvent('keyup', this);
12899         this.inputEl().relayEvent('paste', this);
12900         
12901         this.indicator = this.indicatorEl();
12902         
12903         if(this.indicator){
12904             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible'); // changed from invisible??? - 
12905         }
12906  
12907         // reference to original value for reset
12908         this.originalValue = this.getValue();
12909         //Roo.form.TextField.superclass.initEvents.call(this);
12910         if(this.validationEvent == 'keyup'){
12911             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
12912             this.inputEl().on('keyup', this.filterValidation, this);
12913         }
12914         else if(this.validationEvent !== false){
12915             this.inputEl().on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
12916         }
12917         
12918         if(this.selectOnFocus){
12919             this.on("focus", this.preFocus, this);
12920             
12921         }
12922         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
12923             this.inputEl().on("keypress", this.filterKeys, this);
12924         } else {
12925             this.inputEl().relayEvent('keypress', this);
12926         }
12927        /* if(this.grow){
12928             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
12929             this.el.on("click", this.autoSize,  this);
12930         }
12931         */
12932         if(this.inputEl().is('input[type=password]') && Roo.isSafari){
12933             this.inputEl().on('keydown', this.SafariOnKeyDown, this);
12934         }
12935         
12936         if (typeof(this.before) == 'object') {
12937             this.before.render(this.el.select('.roo-input-before',true).first());
12938         }
12939         if (typeof(this.after) == 'object') {
12940             this.after.render(this.el.select('.roo-input-after',true).first());
12941         }
12942         
12943         this.inputEl().on('change', this.onChange, this);
12944         
12945     },
12946     filterValidation : function(e){
12947         if(!e.isNavKeyPress()){
12948             this.validationTask.delay(this.validationDelay);
12949         }
12950     },
12951      /**
12952      * Validates the field value
12953      * @return {Boolean} True if the value is valid, else false
12954      */
12955     validate : function(){
12956         //if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
12957         if(this.disabled || this.validateValue(this.getRawValue())){
12958             this.markValid();
12959             return true;
12960         }
12961         
12962         this.markInvalid();
12963         return false;
12964     },
12965     
12966     
12967     /**
12968      * Validates a value according to the field's validation rules and marks the field as invalid
12969      * if the validation fails
12970      * @param {Mixed} value The value to validate
12971      * @return {Boolean} True if the value is valid, else false
12972      */
12973     validateValue : function(value)
12974     {
12975         if(this.getVisibilityEl().hasClass('hidden')){
12976             return true;
12977         }
12978         
12979         if(value.length < 1)  { // if it's blank
12980             if(this.allowBlank){
12981                 return true;
12982             }
12983             return false;
12984         }
12985         
12986         if(value.length < this.minLength){
12987             return false;
12988         }
12989         if(value.length > this.maxLength){
12990             return false;
12991         }
12992         if(this.vtype){
12993             var vt = Roo.form.VTypes;
12994             if(!vt[this.vtype](value, this)){
12995                 return false;
12996             }
12997         }
12998         if(typeof this.validator == "function"){
12999             var msg = this.validator(value);
13000             if (typeof(msg) == 'string') {
13001                 this.invalidText = msg;
13002             }
13003             if(msg !== true){
13004                 return false;
13005             }
13006         }
13007         
13008         if(this.regex && !this.regex.test(value)){
13009             return false;
13010         }
13011         
13012         return true;
13013     },
13014     
13015      // private
13016     fireKey : function(e){
13017         //Roo.log('field ' + e.getKey());
13018         if(e.isNavKeyPress()){
13019             this.fireEvent("specialkey", this, e);
13020         }
13021     },
13022     focus : function (selectText){
13023         if(this.rendered){
13024             this.inputEl().focus();
13025             if(selectText === true){
13026                 this.inputEl().dom.select();
13027             }
13028         }
13029         return this;
13030     } ,
13031     
13032     onFocus : function(){
13033         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
13034            // this.el.addClass(this.focusClass);
13035         }
13036         if(!this.hasFocus){
13037             this.hasFocus = true;
13038             this.startValue = this.getValue();
13039             this.fireEvent("focus", this);
13040         }
13041     },
13042     
13043     beforeBlur : Roo.emptyFn,
13044
13045     
13046     // private
13047     onBlur : function(){
13048         this.beforeBlur();
13049         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
13050             //this.el.removeClass(this.focusClass);
13051         }
13052         this.hasFocus = false;
13053         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
13054             this.validate();
13055         }
13056         var v = this.getValue();
13057         if(String(v) !== String(this.startValue)){
13058             this.fireEvent('change', this, v, this.startValue);
13059         }
13060         this.fireEvent("blur", this);
13061     },
13062     
13063     onChange : function(e)
13064     {
13065         var v = this.getValue();
13066         if(String(v) !== String(this.startValue)){
13067             this.fireEvent('change', this, v, this.startValue);
13068         }
13069         
13070     },
13071     
13072     /**
13073      * Resets the current field value to the originally loaded value and clears any validation messages
13074      */
13075     reset : function(){
13076         this.setValue(this.originalValue);
13077         this.validate();
13078     },
13079      /**
13080      * Returns the name of the field
13081      * @return {Mixed} name The name field
13082      */
13083     getName: function(){
13084         return this.name;
13085     },
13086      /**
13087      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
13088      * @return {Mixed} value The field value
13089      */
13090     getValue : function(){
13091         
13092         var v = this.inputEl().getValue();
13093         
13094         return v;
13095     },
13096     /**
13097      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
13098      * @return {Mixed} value The field value
13099      */
13100     getRawValue : function(){
13101         var v = this.inputEl().getValue();
13102         
13103         return v;
13104     },
13105     
13106     /**
13107      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
13108      * @param {Mixed} value The value to set
13109      */
13110     setRawValue : function(v){
13111         return this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
13112     },
13113     
13114     selectText : function(start, end){
13115         var v = this.getRawValue();
13116         if(v.length > 0){
13117             start = start === undefined ? 0 : start;
13118             end = end === undefined ? v.length : end;
13119             var d = this.inputEl().dom;
13120             if(d.setSelectionRange){
13121                 d.setSelectionRange(start, end);
13122             }else if(d.createTextRange){
13123                 var range = d.createTextRange();
13124                 range.moveStart("character", start);
13125                 range.moveEnd("character", v.length-end);
13126                 range.select();
13127             }
13128         }
13129     },
13130     
13131     /**
13132      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
13133      * @param {Mixed} value The value to set
13134      */
13135     setValue : function(v){
13136         this.value = v;
13137         if(this.rendered){
13138             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
13139             this.validate();
13140         }
13141     },
13142     
13143     /*
13144     processValue : function(value){
13145         if(this.stripCharsRe){
13146             var newValue = value.replace(this.stripCharsRe, '');
13147             if(newValue !== value){
13148                 this.setRawValue(newValue);
13149                 return newValue;
13150             }
13151         }
13152         return value;
13153     },
13154   */
13155     preFocus : function(){
13156         
13157         if(this.selectOnFocus){
13158             this.inputEl().dom.select();
13159         }
13160     },
13161     filterKeys : function(e){
13162         var k = e.getKey();
13163         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
13164             return;
13165         }
13166         var c = e.getCharCode(), cc = String.fromCharCode(c);
13167         if(Roo.isIE && (e.isSpecialKey() || !cc)){
13168             return;
13169         }
13170         if(!this.maskRe.test(cc)){
13171             e.stopEvent();
13172         }
13173     },
13174      /**
13175      * Clear any invalid styles/messages for this field
13176      */
13177     clearInvalid : function(){
13178         
13179         if(!this.el || this.preventMark){ // not rendered
13180             return;
13181         }
13182         
13183         
13184         this.el.removeClass([this.invalidClass, 'is-invalid']);
13185         
13186         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
13187             
13188             var feedback = this.el.select('.form-control-feedback', true).first();
13189             
13190             if(feedback){
13191                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
13192             }
13193             
13194         }
13195         
13196         if(this.indicator){
13197             this.indicator.removeClass('visible');
13198             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
13199         }
13200         
13201         this.fireEvent('valid', this);
13202     },
13203     
13204      /**
13205      * Mark this field as valid
13206      */
13207     markValid : function()
13208     {
13209         if(!this.el  || this.preventMark){ // not rendered...
13210             return;
13211         }
13212         
13213         this.el.removeClass([this.invalidClass, this.validClass]);
13214         this.inputEl().removeClass(['is-valid', 'is-invalid']);
13215
13216         var feedback = this.el.select('.form-control-feedback', true).first();
13217             
13218         if(feedback){
13219             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13220         }
13221         
13222         if(this.indicator){
13223             this.indicator.removeClass('visible');
13224             this.indicator.addClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
13225         }
13226         
13227         if(this.disabled){
13228             return;
13229         }
13230         
13231            
13232         if(this.allowBlank && !this.getRawValue().length){
13233             return;
13234         }
13235         if (Roo.bootstrap.version == 3) {
13236             this.el.addClass(this.validClass);
13237         } else {
13238             this.inputEl().addClass('is-valid');
13239         }
13240
13241         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
13242             
13243             var feedback = this.el.select('.form-control-feedback', true).first();
13244             
13245             if(feedback){
13246                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13247                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
13248             }
13249             
13250         }
13251         
13252         this.fireEvent('valid', this);
13253     },
13254     
13255      /**
13256      * Mark this field as invalid
13257      * @param {String} msg The validation message
13258      */
13259     markInvalid : function(msg)
13260     {
13261         if(!this.el  || this.preventMark){ // not rendered
13262             return;
13263         }
13264         
13265         this.el.removeClass([this.invalidClass, this.validClass]);
13266         this.inputEl().removeClass(['is-valid', 'is-invalid']);
13267         
13268         var feedback = this.el.select('.form-control-feedback', true).first();
13269             
13270         if(feedback){
13271             this.el.select('.form-control-feedback', true).first().removeClass(
13272                     [this.invalidFeedbackClass, this.validFeedbackClass]);
13273         }
13274
13275         if(this.disabled){
13276             return;
13277         }
13278         
13279         if(this.allowBlank && !this.getRawValue().length){
13280             return;
13281         }
13282         
13283         if(this.indicator){
13284             this.indicator.removeClass(this.indicatorpos == 'right' ? 'hidden' : 'invisible');
13285             this.indicator.addClass('visible');
13286         }
13287         if (Roo.bootstrap.version == 3) {
13288             this.el.addClass(this.invalidClass);
13289         } else {
13290             this.inputEl().addClass('is-invalid');
13291         }
13292         
13293         
13294         
13295         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
13296             
13297             var feedback = this.el.select('.form-control-feedback', true).first();
13298             
13299             if(feedback){
13300                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13301                 
13302                 if(this.getValue().length || this.forceFeedback){
13303                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
13304                 }
13305                 
13306             }
13307             
13308         }
13309         
13310         this.fireEvent('invalid', this, msg);
13311     },
13312     // private
13313     SafariOnKeyDown : function(event)
13314     {
13315         // this is a workaround for a password hang bug on chrome/ webkit.
13316         if (this.inputEl().dom.type != 'password') {
13317             return;
13318         }
13319         
13320         var isSelectAll = false;
13321         
13322         if(this.inputEl().dom.selectionEnd > 0){
13323             isSelectAll = (this.inputEl().dom.selectionEnd - this.inputEl().dom.selectionStart - this.getValue().length == 0) ? true : false;
13324         }
13325         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
13326             event.preventDefault();
13327             this.setValue('');
13328             return;
13329         }
13330         
13331         if(isSelectAll  && event.getCharCode() > 31 && !event.ctrlKey) { // not backspace and delete key (or ctrl-v)
13332             
13333             event.preventDefault();
13334             // this is very hacky as keydown always get's upper case.
13335             //
13336             var cc = String.fromCharCode(event.getCharCode());
13337             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
13338             
13339         }
13340     },
13341     adjustWidth : function(tag, w){
13342         tag = tag.toLowerCase();
13343         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
13344             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
13345                 if(tag == 'input'){
13346                     return w + 2;
13347                 }
13348                 if(tag == 'textarea'){
13349                     return w-2;
13350                 }
13351             }else if(Roo.isOpera){
13352                 if(tag == 'input'){
13353                     return w + 2;
13354                 }
13355                 if(tag == 'textarea'){
13356                     return w-2;
13357                 }
13358             }
13359         }
13360         return w;
13361     },
13362     
13363     setFieldLabel : function(v)
13364     {
13365         if(!this.rendered){
13366             return;
13367         }
13368         
13369         if(this.indicatorEl()){
13370             var ar = this.el.select('label > span',true);
13371             
13372             if (ar.elements.length) {
13373                 this.el.select('label > span',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
13374                 this.fieldLabel = v;
13375                 return;
13376             }
13377             
13378             var br = this.el.select('label',true);
13379             
13380             if(br.elements.length) {
13381                 this.el.select('label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
13382                 this.fieldLabel = v;
13383                 return;
13384             }
13385             
13386             Roo.log('Cannot Found any of label > span || label in input');
13387             return;
13388         }
13389         
13390         this.el.select('label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
13391         this.fieldLabel = v;
13392         
13393         
13394     }
13395 });
13396
13397  
13398 /*
13399  * - LGPL
13400  *
13401  * Input
13402  * 
13403  */
13404
13405 /**
13406  * @class Roo.bootstrap.form.TextArea
13407  * @extends Roo.bootstrap.form.Input
13408  * Bootstrap TextArea class
13409  * @cfg {Number} cols Specifies the visible width of a text area
13410  * @cfg {Number} rows Specifies the visible number of lines in a text area
13411  * @cfg {string} wrap (soft|hard)Specifies how the text in a text area is to be wrapped when submitted in a form
13412  * @cfg {string} resize (none|both|horizontal|vertical|inherit|initial)
13413  * @cfg {string} html text
13414  * 
13415  * @constructor
13416  * Create a new TextArea
13417  * @param {Object} config The config object
13418  */
13419
13420 Roo.bootstrap.form.TextArea = function(config){
13421     Roo.bootstrap.form.TextArea.superclass.constructor.call(this, config);
13422    
13423 };
13424
13425 Roo.extend(Roo.bootstrap.form.TextArea, Roo.bootstrap.form.Input,  {
13426      
13427     cols : false,
13428     rows : 5,
13429     readOnly : false,
13430     warp : 'soft',
13431     resize : false,
13432     value: false,
13433     html: false,
13434     
13435     getAutoCreate : function(){
13436         
13437         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
13438         
13439         var id = Roo.id();
13440         
13441         var cfg = {};
13442         
13443         if(this.inputType != 'hidden'){
13444             cfg.cls = 'form-group' //input-group
13445         }
13446         
13447         var input =  {
13448             tag: 'textarea',
13449             id : id,
13450             warp : this.warp,
13451             rows : this.rows,
13452             value : this.value || '',
13453             html: this.html || '',
13454             cls : 'form-control',
13455             placeholder : this.placeholder || '' 
13456             
13457         };
13458         
13459         if(this.maxLength && this.maxLength != Number.MAX_VALUE){
13460             input.maxLength = this.maxLength;
13461         }
13462         
13463         if(this.resize){
13464             input.style = (typeof(input.style) == 'undefined') ? 'resize:' + this.resize : input.style + 'resize:' + this.resize;
13465         }
13466         
13467         if(this.cols){
13468             input.cols = this.cols;
13469         }
13470         
13471         if (this.readOnly) {
13472             input.readonly = true;
13473         }
13474         
13475         if (this.name) {
13476             input.name = this.name;
13477         }
13478         
13479         if (this.size) {
13480             input.cls = (typeof(input.cls) == 'undefined') ? 'input-' + this.size : input.cls + ' input-' + this.size;
13481         }
13482         
13483         var settings=this;
13484         ['xs','sm','md','lg'].map(function(size){
13485             if (settings[size]) {
13486                 cfg.cls += ' col-' + size + '-' + settings[size];
13487             }
13488         });
13489         
13490         var inputblock = input;
13491         
13492         if(this.hasFeedback && !this.allowBlank){
13493             
13494             var feedback = {
13495                 tag: 'span',
13496                 cls: 'glyphicon form-control-feedback'
13497             };
13498
13499             inputblock = {
13500                 cls : 'has-feedback',
13501                 cn :  [
13502                     input,
13503                     feedback
13504                 ] 
13505             };  
13506         }
13507         
13508         
13509         if (this.before || this.after) {
13510             
13511             inputblock = {
13512                 cls : 'input-group',
13513                 cn :  [] 
13514             };
13515             if (this.before) {
13516                 inputblock.cn.push({
13517                     tag :'span',
13518                     cls : 'input-group-addon',
13519                     html : this.before
13520                 });
13521             }
13522             
13523             inputblock.cn.push(input);
13524             
13525             if(this.hasFeedback && !this.allowBlank){
13526                 inputblock.cls += ' has-feedback';
13527                 inputblock.cn.push(feedback);
13528             }
13529             
13530             if (this.after) {
13531                 inputblock.cn.push({
13532                     tag :'span',
13533                     cls : 'input-group-addon',
13534                     html : this.after
13535                 });
13536             }
13537             
13538         }
13539         
13540         
13541         cfg = this.getAutoCreateLabel( cfg, inputblock );
13542
13543          
13544         
13545         if (this.disabled) {
13546             input.disabled=true;
13547         }
13548         
13549         return cfg;
13550         
13551     },
13552     /**
13553      * return the real textarea element.
13554      */
13555     inputEl: function ()
13556     {
13557         return this.el.select('textarea.form-control',true).first();
13558     },
13559     
13560     /**
13561      * Clear any invalid styles/messages for this field
13562      */
13563     clearInvalid : function()
13564     {
13565         
13566         if(!this.el || this.preventMark){ // not rendered
13567             return;
13568         }
13569         
13570         var label = this.el.select('label', true).first();
13571         //var icon = this.el.select('i.fa-star', true).first();
13572         
13573         //if(label && icon){
13574         //    icon.remove();
13575         //}
13576         this.el.removeClass( this.validClass);
13577         this.inputEl().removeClass('is-invalid');
13578          
13579         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
13580             
13581             var feedback = this.el.select('.form-control-feedback', true).first();
13582             
13583             if(feedback){
13584                 this.el.select('.form-control-feedback', true).first().removeClass(this.invalidFeedbackClass);
13585             }
13586             
13587         }
13588         
13589         this.fireEvent('valid', this);
13590     },
13591     
13592      /**
13593      * Mark this field as valid
13594      */
13595     markValid : function()
13596     {
13597         if(!this.el  || this.preventMark){ // not rendered
13598             return;
13599         }
13600         
13601         this.el.removeClass([this.invalidClass, this.validClass]);
13602         this.inputEl().removeClass(['is-valid', 'is-invalid']);
13603         
13604         var feedback = this.el.select('.form-control-feedback', true).first();
13605             
13606         if(feedback){
13607             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13608         }
13609
13610         if(this.disabled || this.allowBlank){
13611             return;
13612         }
13613         
13614         var label = this.el.select('label', true).first();
13615         var icon = this.el.select('i.fa-star', true).first();
13616         
13617         //if(label && icon){
13618         //    icon.remove();
13619         //}
13620         if (Roo.bootstrap.version == 3) {
13621             this.el.addClass(this.validClass);
13622         } else {
13623             this.inputEl().addClass('is-valid');
13624         }
13625         
13626         
13627         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank && (this.getValue().length || this.forceFeedback)){
13628             
13629             var feedback = this.el.select('.form-control-feedback', true).first();
13630             
13631             if(feedback){
13632                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13633                 this.el.select('.form-control-feedback', true).first().addClass([this.validFeedbackClass]);
13634             }
13635             
13636         }
13637         
13638         this.fireEvent('valid', this);
13639     },
13640     
13641      /**
13642      * Mark this field as invalid
13643      * @param {String} msg The validation message
13644      */
13645     markInvalid : function(msg)
13646     {
13647         if(!this.el  || this.preventMark){ // not rendered
13648             return;
13649         }
13650         
13651         this.el.removeClass([this.invalidClass, this.validClass]);
13652         this.inputEl().removeClass(['is-valid', 'is-invalid']);
13653         
13654         var feedback = this.el.select('.form-control-feedback', true).first();
13655             
13656         if(feedback){
13657             this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13658         }
13659
13660         if(this.disabled || this.allowBlank){
13661             return;
13662         }
13663         
13664         var label = this.el.select('label', true).first();
13665         //var icon = this.el.select('i.fa-star', true).first();
13666         
13667         //if(!this.getValue().length && label && !icon){
13668           /*  this.el.createChild({
13669                 tag : 'i',
13670                 cls : 'text-danger fa fa-lg fa-star',
13671                 tooltip : 'This field is required',
13672                 style : 'margin-right:5px;'
13673             }, label, true);
13674             */
13675         //}
13676         
13677         if (Roo.bootstrap.version == 3) {
13678             this.el.addClass(this.invalidClass);
13679         } else {
13680             this.inputEl().addClass('is-invalid');
13681         }
13682         
13683         // fixme ... this may be depricated need to test..
13684         if(this.hasFeedback && this.inputType != 'hidden' && !this.allowBlank){
13685             
13686             var feedback = this.el.select('.form-control-feedback', true).first();
13687             
13688             if(feedback){
13689                 this.el.select('.form-control-feedback', true).first().removeClass([this.invalidFeedbackClass, this.validFeedbackClass]);
13690                 
13691                 if(this.getValue().length || this.forceFeedback){
13692                     this.el.select('.form-control-feedback', true).first().addClass([this.invalidFeedbackClass]);
13693                 }
13694                 
13695             }
13696             
13697         }
13698         
13699         this.fireEvent('invalid', this, msg);
13700     }
13701 });
13702
13703  
13704 /*
13705  * - LGPL
13706  *
13707  * trigger field - base class for combo..
13708  * 
13709  */
13710  
13711 /**
13712  * @class Roo.bootstrap.form.TriggerField
13713  * @extends Roo.bootstrap.form.Input
13714  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
13715  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
13716  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
13717  * for which you can provide a custom implementation.  For example:
13718  * <pre><code>
13719 var trigger = new Roo.bootstrap.form.TriggerField();
13720 trigger.onTriggerClick = myTriggerFn;
13721 trigger.applyTo('my-field');
13722 </code></pre>
13723  *
13724  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
13725  * {@link Roo.bootstrap.form.DateField} and {@link Roo.bootstrap.form.ComboBox} are perfect examples of this.
13726  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
13727  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
13728  * @cfg {String} caret (search|calendar) BS3 only - carat fa name
13729
13730  * @constructor
13731  * Create a new TriggerField.
13732  * @param {Object} config Configuration options (valid {@Roo.bootstrap.form.Input} config options will also be applied
13733  * to the base TextField)
13734  */
13735 Roo.bootstrap.form.TriggerField = function(config){
13736     this.mimicing = false;
13737     Roo.bootstrap.form.TriggerField.superclass.constructor.call(this, config);
13738 };
13739
13740 Roo.extend(Roo.bootstrap.form.TriggerField, Roo.bootstrap.form.Input,  {
13741     /**
13742      * @cfg {String} triggerClass A CSS class to apply to the trigger
13743      */
13744      /**
13745      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
13746      */
13747     hideTrigger:false,
13748
13749     /**
13750      * @cfg {Boolean} removable (true|false) special filter default false
13751      */
13752     removable : false,
13753     
13754     /** @cfg {Boolean} grow @hide */
13755     /** @cfg {Number} growMin @hide */
13756     /** @cfg {Number} growMax @hide */
13757
13758     /**
13759      * @hide 
13760      * @method
13761      */
13762     autoSize: Roo.emptyFn,
13763     // private
13764     monitorTab : true,
13765     // private
13766     deferHeight : true,
13767
13768     
13769     actionMode : 'wrap',
13770     
13771     caret : false,
13772     
13773     
13774     getAutoCreate : function(){
13775        
13776         var align = this.labelAlign || this.parentLabelAlign();
13777         
13778         var id = Roo.id();
13779         
13780         var cfg = {
13781             cls: 'form-group' //input-group
13782         };
13783         
13784         
13785         var input =  {
13786             tag: 'input',
13787             id : id,
13788             type : this.inputType,
13789             cls : 'form-control',
13790             autocomplete: 'new-password',
13791             placeholder : this.placeholder || '' 
13792             
13793         };
13794         if (this.name) {
13795             input.name = this.name;
13796         }
13797         if (this.size) {
13798             input.cls += ' input-' + this.size;
13799         }
13800         
13801         if (this.disabled) {
13802             input.disabled=true;
13803         }
13804         
13805         var inputblock = input;
13806         
13807         if(this.hasFeedback && !this.allowBlank){
13808             
13809             var feedback = {
13810                 tag: 'span',
13811                 cls: 'glyphicon form-control-feedback'
13812             };
13813             
13814             if(this.removable && !this.editable  ){
13815                 inputblock = {
13816                     cls : 'has-feedback',
13817                     cn :  [
13818                         inputblock,
13819                         {
13820                             tag: 'button',
13821                             html : 'x',
13822                             cls : 'roo-combo-removable-btn close'
13823                         },
13824                         feedback
13825                     ] 
13826                 };
13827             } else {
13828                 inputblock = {
13829                     cls : 'has-feedback',
13830                     cn :  [
13831                         inputblock,
13832                         feedback
13833                     ] 
13834                 };
13835             }
13836
13837         } else {
13838             if(this.removable && !this.editable ){
13839                 inputblock = {
13840                     cls : 'roo-removable',
13841                     cn :  [
13842                         inputblock,
13843                         {
13844                             tag: 'button',
13845                             html : 'x',
13846                             cls : 'roo-combo-removable-btn close'
13847                         }
13848                     ] 
13849                 };
13850             }
13851         }
13852         
13853         if (this.before || this.after) {
13854             
13855             inputblock = {
13856                 cls : 'input-group',
13857                 cn :  [] 
13858             };
13859             if (this.before) {
13860                 inputblock.cn.push({
13861                     tag :'span',
13862                     cls : 'input-group-addon input-group-prepend input-group-text',
13863                     html : this.before
13864                 });
13865             }
13866             
13867             inputblock.cn.push(input);
13868             
13869             if(this.hasFeedback && !this.allowBlank){
13870                 inputblock.cls += ' has-feedback';
13871                 inputblock.cn.push(feedback);
13872             }
13873             
13874             if (this.after) {
13875                 inputblock.cn.push({
13876                     tag :'span',
13877                     cls : 'input-group-addon input-group-append input-group-text',
13878                     html : this.after
13879                 });
13880             }
13881             
13882         };
13883         
13884       
13885         
13886         var ibwrap = inputblock;
13887         
13888         if(this.multiple){
13889             ibwrap = {
13890                 tag: 'ul',
13891                 cls: 'roo-select2-choices',
13892                 cn:[
13893                     {
13894                         tag: 'li',
13895                         cls: 'roo-select2-search-field',
13896                         cn: [
13897
13898                             inputblock
13899                         ]
13900                     }
13901                 ]
13902             };
13903                 
13904         }
13905         
13906         var combobox = {
13907             cls: 'roo-select2-container input-group',
13908             cn: [
13909                  {
13910                     tag: 'input',
13911                     type : 'hidden',
13912                     cls: 'form-hidden-field'
13913                 },
13914                 ibwrap
13915             ]
13916         };
13917         
13918         if(!this.multiple && this.showToggleBtn){
13919             
13920             var caret = {
13921                         tag: 'span',
13922                         cls: 'caret'
13923              };
13924             if (this.caret != false) {
13925                 caret = {
13926                      tag: 'i',
13927                      cls: 'fa fa-' + this.caret
13928                 };
13929                 
13930             }
13931             
13932             combobox.cn.push({
13933                 tag :'span',
13934                 cls : 'input-group-addon input-group-append input-group-text btn dropdown-toggle',
13935                 cn : [
13936                     Roo.bootstrap.version == 3 ? caret : '',
13937                     {
13938                         tag: 'span',
13939                         cls: 'combobox-clear',
13940                         cn  : [
13941                             {
13942                                 tag : 'i',
13943                                 cls: 'icon-remove'
13944                             }
13945                         ]
13946                     }
13947                 ]
13948
13949             })
13950         }
13951         
13952         if(this.multiple){
13953             combobox.cls += ' roo-select2-container-multi';
13954         }
13955          var indicator = {
13956             tag : 'i',
13957             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
13958             tooltip : 'This field is required'
13959         };
13960       
13961         if (this.allowBlank) {
13962             indicator = {
13963                 tag : 'i',
13964                 style : 'display:none'
13965             };
13966         }
13967          
13968         
13969         
13970         if (align ==='left' && this.fieldLabel.length) {
13971             
13972             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
13973
13974             cfg.cn = [
13975                 indicator,
13976                 {
13977                     tag: 'label',
13978                     'for' :  id,
13979                     cls : 'control-label',
13980                     html : this.fieldLabel
13981
13982                 },
13983                 {
13984                     cls : "", 
13985                     cn: [
13986                         combobox
13987                     ]
13988                 }
13989
13990             ];
13991             
13992             var labelCfg = cfg.cn[1];
13993             var contentCfg = cfg.cn[2];
13994             
13995             if(this.indicatorpos == 'right'){
13996                 cfg.cn = [
13997                     {
13998                         tag: 'label',
13999                         'for' :  id,
14000                         cls : 'control-label',
14001                         cn : [
14002                             {
14003                                 tag : 'span',
14004                                 html : this.fieldLabel
14005                             },
14006                             indicator
14007                         ]
14008                     },
14009                     {
14010                         cls : "", 
14011                         cn: [
14012                             combobox
14013                         ]
14014                     }
14015
14016                 ];
14017                 
14018                 labelCfg = cfg.cn[0];
14019                 contentCfg = cfg.cn[1];
14020             }
14021             
14022             if(this.labelWidth > 12){
14023                 labelCfg.style = "width: " + this.labelWidth + 'px';
14024             }
14025             
14026             if(this.labelWidth < 13 && this.labelmd == 0){
14027                 this.labelmd = this.labelWidth;
14028             }
14029             
14030             if(this.labellg > 0){
14031                 labelCfg.cls += ' col-lg-' + this.labellg;
14032                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
14033             }
14034             
14035             if(this.labelmd > 0){
14036                 labelCfg.cls += ' col-md-' + this.labelmd;
14037                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
14038             }
14039             
14040             if(this.labelsm > 0){
14041                 labelCfg.cls += ' col-sm-' + this.labelsm;
14042                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
14043             }
14044             
14045             if(this.labelxs > 0){
14046                 labelCfg.cls += ' col-xs-' + this.labelxs;
14047                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
14048             }
14049             
14050         } else if ( this.fieldLabel.length) {
14051 //                Roo.log(" label");
14052             cfg.cn = [
14053                 indicator,
14054                {
14055                    tag: 'label',
14056                    //cls : 'input-group-addon',
14057                    html : this.fieldLabel
14058
14059                },
14060
14061                combobox
14062
14063             ];
14064             
14065             if(this.indicatorpos == 'right'){
14066                 
14067                 cfg.cn = [
14068                     {
14069                        tag: 'label',
14070                        cn : [
14071                            {
14072                                tag : 'span',
14073                                html : this.fieldLabel
14074                            },
14075                            indicator
14076                        ]
14077
14078                     },
14079                     combobox
14080
14081                 ];
14082
14083             }
14084
14085         } else {
14086             
14087 //                Roo.log(" no label && no align");
14088                 cfg = combobox
14089                      
14090                 
14091         }
14092         
14093         var settings=this;
14094         ['xs','sm','md','lg'].map(function(size){
14095             if (settings[size]) {
14096                 cfg.cls += ' col-' + size + '-' + settings[size];
14097             }
14098         });
14099         
14100         return cfg;
14101         
14102     },
14103     
14104     
14105     
14106     // private
14107     onResize : function(w, h){
14108 //        Roo.bootstrap.form.TriggerField.superclass.onResize.apply(this, arguments);
14109 //        if(typeof w == 'number'){
14110 //            var x = w - this.trigger.getWidth();
14111 //            this.inputEl().setWidth(this.adjustWidth('input', x));
14112 //            this.trigger.setStyle('left', x+'px');
14113 //        }
14114     },
14115
14116     // private
14117     adjustSize : Roo.BoxComponent.prototype.adjustSize,
14118
14119     // private
14120     getResizeEl : function(){
14121         return this.inputEl();
14122     },
14123
14124     // private
14125     getPositionEl : function(){
14126         return this.inputEl();
14127     },
14128
14129     // private
14130     alignErrorIcon : function(){
14131         this.errorIcon.alignTo(this.inputEl(), 'tl-tr', [2, 0]);
14132     },
14133
14134     // private
14135     initEvents : function(){
14136         
14137         this.createList();
14138         
14139         Roo.bootstrap.form.TriggerField.superclass.initEvents.call(this);
14140         //this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
14141         if(!this.multiple && this.showToggleBtn){
14142             this.trigger = this.el.select('span.dropdown-toggle',true).first();
14143             if(this.hideTrigger){
14144                 this.trigger.setDisplayed(false);
14145             }
14146             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
14147         }
14148         
14149         if(this.multiple){
14150             this.inputEl().on("click", this.onTriggerClick, this, {preventDefault:true});
14151         }
14152         
14153         if(this.removable && !this.editable && !this.tickable){
14154             var close = this.closeTriggerEl();
14155             
14156             if(close){
14157                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
14158                 close.on('click', this.removeBtnClick, this, close);
14159             }
14160         }
14161         
14162         //this.trigger.addClassOnOver('x-form-trigger-over');
14163         //this.trigger.addClassOnClick('x-form-trigger-click');
14164         
14165         //if(!this.width){
14166         //    this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
14167         //}
14168     },
14169     
14170     closeTriggerEl : function()
14171     {
14172         var close = this.el.select('.roo-combo-removable-btn', true).first();
14173         return close ? close : false;
14174     },
14175     
14176     removeBtnClick : function(e, h, el)
14177     {
14178         e.preventDefault();
14179         
14180         if(this.fireEvent("remove", this) !== false){
14181             this.reset();
14182             this.fireEvent("afterremove", this)
14183         }
14184     },
14185     
14186     createList : function()
14187     {
14188         this.list = Roo.get(document.body).createChild({
14189             tag: Roo.bootstrap.version == 4 ? 'div' : 'ul',
14190             cls: 'typeahead typeahead-long dropdown-menu shadow',
14191             style: 'display:none'
14192         });
14193         
14194         this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';;
14195         
14196     },
14197
14198     // private
14199     initTrigger : function(){
14200        
14201     },
14202
14203     // private
14204     onDestroy : function(){
14205         if(this.trigger){
14206             this.trigger.removeAllListeners();
14207           //  this.trigger.remove();
14208         }
14209         //if(this.wrap){
14210         //    this.wrap.remove();
14211         //}
14212         Roo.bootstrap.form.TriggerField.superclass.onDestroy.call(this);
14213     },
14214
14215     // private
14216     onFocus : function(){
14217         Roo.bootstrap.form.TriggerField.superclass.onFocus.call(this);
14218         /*
14219         if(!this.mimicing){
14220             this.wrap.addClass('x-trigger-wrap-focus');
14221             this.mimicing = true;
14222             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
14223             if(this.monitorTab){
14224                 this.el.on("keydown", this.checkTab, this);
14225             }
14226         }
14227         */
14228     },
14229
14230     // private
14231     checkTab : function(e){
14232         if(e.getKey() == e.TAB){
14233             this.triggerBlur();
14234         }
14235     },
14236
14237     // private
14238     onBlur : function(){
14239         // do nothing
14240     },
14241
14242     // private
14243     mimicBlur : function(e, t){
14244         /*
14245         if(!this.wrap.contains(t) && this.validateBlur()){
14246             this.triggerBlur();
14247         }
14248         */
14249     },
14250
14251     // private
14252     triggerBlur : function(){
14253         this.mimicing = false;
14254         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
14255         if(this.monitorTab){
14256             this.el.un("keydown", this.checkTab, this);
14257         }
14258         //this.wrap.removeClass('x-trigger-wrap-focus');
14259         Roo.bootstrap.form.TriggerField.superclass.onBlur.call(this);
14260     },
14261
14262     // private
14263     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
14264     validateBlur : function(e, t){
14265         return true;
14266     },
14267
14268     // private
14269     onDisable : function(){
14270         this.inputEl().dom.disabled = true;
14271         //Roo.bootstrap.form.TriggerField.superclass.onDisable.call(this);
14272         //if(this.wrap){
14273         //    this.wrap.addClass('x-item-disabled');
14274         //}
14275     },
14276
14277     // private
14278     onEnable : function(){
14279         this.inputEl().dom.disabled = false;
14280         //Roo.bootstrap.form.TriggerField.superclass.onEnable.call(this);
14281         //if(this.wrap){
14282         //    this.el.removeClass('x-item-disabled');
14283         //}
14284     },
14285
14286     // private
14287     onShow : function(){
14288         var ae = this.getActionEl();
14289         
14290         if(ae){
14291             ae.dom.style.display = '';
14292             ae.dom.style.visibility = 'visible';
14293         }
14294     },
14295
14296     // private
14297     
14298     onHide : function(){
14299         var ae = this.getActionEl();
14300         ae.dom.style.display = 'none';
14301     },
14302
14303     /**
14304      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
14305      * by an implementing function.
14306      * @method
14307      * @param {EventObject} e
14308      */
14309     onTriggerClick : Roo.emptyFn
14310 });
14311  
14312 /*
14313 * Licence: LGPL
14314 */
14315
14316 /**
14317  * @class Roo.bootstrap.form.CardUploader
14318  * @extends Roo.bootstrap.Button
14319  * Bootstrap Card Uploader class - it's a button which when you add files to it, adds cards below with preview and the name...
14320  * @cfg {Number} errorTimeout default 3000
14321  * @cfg {Array}  images  an array of ?? Img objects ??? when loading existing files..
14322  * @cfg {Array}  html The button text.
14323
14324  *
14325  * @constructor
14326  * Create a new CardUploader
14327  * @param {Object} config The config object
14328  */
14329
14330 Roo.bootstrap.form.CardUploader = function(config){
14331     
14332  
14333     
14334     Roo.bootstrap.form.CardUploader.superclass.constructor.call(this, config);
14335     
14336     
14337     this.fileCollection   = new Roo.util.MixedCollection(false,function(r) {
14338         return r.data.id
14339      });
14340     
14341      this.addEvents({
14342          // raw events
14343         /**
14344          * @event preview
14345          * When a image is clicked on - and needs to display a slideshow or similar..
14346          * @param {Roo.bootstrap.Card} this
14347          * @param {Object} The image information data 
14348          *
14349          */
14350         'preview' : true,
14351          /**
14352          * @event download
14353          * When a the download link is clicked
14354          * @param {Roo.bootstrap.Card} this
14355          * @param {Object} The image information data  contains 
14356          */
14357         'download' : true
14358         
14359     });
14360 };
14361  
14362 Roo.extend(Roo.bootstrap.form.CardUploader, Roo.bootstrap.form.Input,  {
14363     
14364      
14365     errorTimeout : 3000,
14366      
14367     images : false,
14368    
14369     fileCollection : false,
14370     allowBlank : true,
14371     
14372     getAutoCreate : function()
14373     {
14374         
14375         var cfg =  {
14376             cls :'form-group' ,
14377             cn : [
14378                
14379                 {
14380                     tag: 'label',
14381                    //cls : 'input-group-addon',
14382                     html : this.fieldLabel
14383
14384                 },
14385
14386                 {
14387                     tag: 'input',
14388                     type : 'hidden',
14389                     name : this.name,
14390                     value : this.value,
14391                     cls : 'd-none  form-control'
14392                 },
14393                 
14394                 {
14395                     tag: 'input',
14396                     multiple : 'multiple',
14397                     type : 'file',
14398                     cls : 'd-none  roo-card-upload-selector'
14399                 },
14400                 
14401                 {
14402                     cls : 'roo-card-uploader-button-container w-100 mb-2'
14403                 },
14404                 {
14405                     cls : 'card-columns roo-card-uploader-container'
14406                 }
14407
14408             ]
14409         };
14410            
14411          
14412         return cfg;
14413     },
14414     
14415     getChildContainer : function() /// what children are added to.
14416     {
14417         return this.containerEl;
14418     },
14419    
14420     getButtonContainer : function() /// what children are added to.
14421     {
14422         return this.el.select(".roo-card-uploader-button-container").first();
14423     },
14424    
14425     initEvents : function()
14426     {
14427         
14428         Roo.bootstrap.form.Input.prototype.initEvents.call(this);
14429         
14430         var t = this;
14431         this.addxtype({
14432             xns: Roo.bootstrap,
14433
14434             xtype : 'Button',
14435             container_method : 'getButtonContainer' ,            
14436             html :  this.html, // fix changable?
14437             cls : 'w-100 ',
14438             listeners : {
14439                 'click' : function(btn, e) {
14440                     t.onClick(e);
14441                 }
14442             }
14443         });
14444         
14445         
14446         
14447         
14448         this.urlAPI = (window.createObjectURL && window) || 
14449                                 (window.URL && URL.revokeObjectURL && URL) || 
14450                                 (window.webkitURL && webkitURL);
14451                         
14452          
14453          
14454          
14455         this.selectorEl = this.el.select('.roo-card-upload-selector', true).first();
14456         
14457         this.selectorEl.on('change', this.onFileSelected, this);
14458         if (this.images) {
14459             var t = this;
14460             this.images.forEach(function(img) {
14461                 t.addCard(img)
14462             });
14463             this.images = false;
14464         }
14465         this.containerEl = this.el.select('.roo-card-uploader-container', true).first();
14466          
14467        
14468     },
14469     
14470    
14471     onClick : function(e)
14472     {
14473         e.preventDefault();
14474          
14475         this.selectorEl.dom.click();
14476          
14477     },
14478     
14479     onFileSelected : function(e)
14480     {
14481         e.preventDefault();
14482         
14483         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
14484             return;
14485         }
14486         
14487         Roo.each(this.selectorEl.dom.files, function(file){    
14488             this.addFile(file);
14489         }, this);
14490          
14491     },
14492     
14493       
14494     
14495       
14496     
14497     addFile : function(file)
14498     {
14499            
14500         if(typeof(file) === 'string'){
14501             throw "Add file by name?"; // should not happen
14502             return;
14503         }
14504         
14505         if(!file || !this.urlAPI){
14506             return;
14507         }
14508         
14509         // file;
14510         // file.type;
14511         
14512         var _this = this;
14513         
14514         
14515         var url = _this.urlAPI.createObjectURL( file);
14516            
14517         this.addCard({
14518             id : Roo.bootstrap.form.CardUploader.ID--,
14519             is_uploaded : false,
14520             src : url,
14521             srcfile : file,
14522             title : file.name,
14523             mimetype : file.type,
14524             preview : false,
14525             is_deleted : 0
14526         });
14527         
14528     },
14529     
14530     /**
14531      * addCard - add an Attachment to the uploader
14532      * @param data - the data about the image to upload
14533      *
14534      * {
14535           id : 123
14536           title : "Title of file",
14537           is_uploaded : false,
14538           src : "http://.....",
14539           srcfile : { the File upload object },
14540           mimetype : file.type,
14541           preview : false,
14542           is_deleted : 0
14543           .. any other data...
14544         }
14545      *
14546      * 
14547     */
14548     
14549     addCard : function (data)
14550     {
14551         // hidden input element?
14552         // if the file is not an image...
14553         //then we need to use something other that and header_image
14554         var t = this;
14555         //   remove.....
14556         var footer = [
14557             {
14558                 xns : Roo.bootstrap,
14559                 xtype : 'CardFooter',
14560                  items: [
14561                     {
14562                         xns : Roo.bootstrap,
14563                         xtype : 'Element',
14564                         cls : 'd-flex',
14565                         items : [
14566                             
14567                             {
14568                                 xns : Roo.bootstrap,
14569                                 xtype : 'Button',
14570                                 html : String.format("<small>{0}</small>", data.title),
14571                                 cls : 'col-10 text-left',
14572                                 size: 'sm',
14573                                 weight: 'link',
14574                                 fa : 'download',
14575                                 listeners : {
14576                                     click : function() {
14577                                      
14578                                         t.fireEvent( "download", t, data );
14579                                     }
14580                                 }
14581                             },
14582                           
14583                             {
14584                                 xns : Roo.bootstrap,
14585                                 xtype : 'Button',
14586                                 style: 'max-height: 28px; ',
14587                                 size : 'sm',
14588                                 weight: 'danger',
14589                                 cls : 'col-2',
14590                                 fa : 'times',
14591                                 listeners : {
14592                                     click : function() {
14593                                         t.removeCard(data.id)
14594                                     }
14595                                 }
14596                             }
14597                         ]
14598                     }
14599                     
14600                 ] 
14601             }
14602             
14603         ];
14604         
14605         var cn = this.addxtype(
14606             {
14607                  
14608                 xns : Roo.bootstrap,
14609                 xtype : 'Card',
14610                 closeable : true,
14611                 header : !data.mimetype.match(/image/) && !data.preview ? "Document": false,
14612                 header_image : data.mimetype.match(/image/) ? data.src  : data.preview,
14613                 header_image_fit_square: true, // fixme  - we probably need to use the 'Img' element to do stuff like this.
14614                 data : data,
14615                 html : false,
14616                  
14617                 items : footer,
14618                 initEvents : function() {
14619                     Roo.bootstrap.Card.prototype.initEvents.call(this);
14620                     var card = this;
14621                     this.imgEl = this.el.select('.card-img-top').first();
14622                     if (this.imgEl) {
14623                         this.imgEl.on('click', function() { t.fireEvent( "preview", t, data ); }, this);
14624                         this.imgEl.set({ 'pointer' : 'cursor' });
14625                                   
14626                     }
14627                     this.getCardFooter().addClass('p-1');
14628                     
14629                   
14630                 }
14631                 
14632             }
14633         );
14634         // dont' really need ot update items.
14635         // this.items.push(cn);
14636         this.fileCollection.add(cn);
14637         
14638         if (!data.srcfile) {
14639             this.updateInput();
14640             return;
14641         }
14642             
14643         var _t = this;
14644         var reader = new FileReader();
14645         reader.addEventListener("load", function() {  
14646             data.srcdata =  reader.result;
14647             _t.updateInput();
14648         });
14649         reader.readAsDataURL(data.srcfile);
14650         
14651         
14652         
14653     },
14654     removeCard : function(id)
14655     {
14656         
14657         var card  = this.fileCollection.get(id);
14658         card.data.is_deleted = 1;
14659         card.data.src = ''; /// delete the source - so it reduces size of not uploaded images etc.
14660         //this.fileCollection.remove(card);
14661         //this.items = this.items.filter(function(e) { return e != card });
14662         // dont' really need ot update items.
14663         card.el.dom.parentNode.removeChild(card.el.dom);
14664         this.updateInput();
14665
14666         
14667     },
14668     reset: function()
14669     {
14670         this.fileCollection.each(function(card) {
14671             if (card.el.dom && card.el.dom.parentNode) {
14672                 card.el.dom.parentNode.removeChild(card.el.dom);
14673             }
14674         });
14675         this.fileCollection.clear();
14676         this.updateInput();
14677     },
14678     
14679     updateInput : function()
14680     {
14681          var data = [];
14682         this.fileCollection.each(function(e) {
14683             data.push(e.data);
14684             
14685         });
14686         this.inputEl().dom.value = JSON.stringify(data);
14687         
14688         
14689         
14690     }
14691     
14692     
14693 });
14694
14695
14696 Roo.bootstrap.form.CardUploader.ID = -1;/*
14697  * Based on:
14698  * Ext JS Library 1.1.1
14699  * Copyright(c) 2006-2007, Ext JS, LLC.
14700  *
14701  * Originally Released Under LGPL - original licence link has changed is not relivant.
14702  *
14703  * Fork - LGPL
14704  * <script type="text/javascript">
14705  */
14706
14707
14708 /**
14709  * @class Roo.data.SortTypes
14710  * @static
14711  * Defines the default sorting (casting?) comparison functions used when sorting data.
14712  */
14713 Roo.data.SortTypes = {
14714     /**
14715      * Default sort that does nothing
14716      * @param {Mixed} s The value being converted
14717      * @return {Mixed} The comparison value
14718      */
14719     none : function(s){
14720         return s;
14721     },
14722     
14723     /**
14724      * The regular expression used to strip tags
14725      * @type {RegExp}
14726      * @property
14727      */
14728     stripTagsRE : /<\/?[^>]+>/gi,
14729     
14730     /**
14731      * Strips all HTML tags to sort on text only
14732      * @param {Mixed} s The value being converted
14733      * @return {String} The comparison value
14734      */
14735     asText : function(s){
14736         return String(s).replace(this.stripTagsRE, "");
14737     },
14738     
14739     /**
14740      * Strips all HTML tags to sort on text only - Case insensitive
14741      * @param {Mixed} s The value being converted
14742      * @return {String} The comparison value
14743      */
14744     asUCText : function(s){
14745         return String(s).toUpperCase().replace(this.stripTagsRE, "");
14746     },
14747     
14748     /**
14749      * Case insensitive string
14750      * @param {Mixed} s The value being converted
14751      * @return {String} The comparison value
14752      */
14753     asUCString : function(s) {
14754         return String(s).toUpperCase();
14755     },
14756     
14757     /**
14758      * Date sorting
14759      * @param {Mixed} s The value being converted
14760      * @return {Number} The comparison value
14761      */
14762     asDate : function(s) {
14763         if(!s){
14764             return 0;
14765         }
14766         if(s instanceof Date){
14767             return s.getTime();
14768         }
14769         return Date.parse(String(s));
14770     },
14771     
14772     /**
14773      * Float sorting
14774      * @param {Mixed} s The value being converted
14775      * @return {Float} The comparison value
14776      */
14777     asFloat : function(s) {
14778         var val = parseFloat(String(s).replace(/,/g, ""));
14779         if(isNaN(val)) {
14780             val = 0;
14781         }
14782         return val;
14783     },
14784     
14785     /**
14786      * Integer sorting
14787      * @param {Mixed} s The value being converted
14788      * @return {Number} The comparison value
14789      */
14790     asInt : function(s) {
14791         var val = parseInt(String(s).replace(/,/g, ""));
14792         if(isNaN(val)) {
14793             val = 0;
14794         }
14795         return val;
14796     }
14797 };/*
14798  * Based on:
14799  * Ext JS Library 1.1.1
14800  * Copyright(c) 2006-2007, Ext JS, LLC.
14801  *
14802  * Originally Released Under LGPL - original licence link has changed is not relivant.
14803  *
14804  * Fork - LGPL
14805  * <script type="text/javascript">
14806  */
14807
14808 /**
14809 * @class Roo.data.Record
14810  * Instances of this class encapsulate both record <em>definition</em> information, and record
14811  * <em>value</em> information for use in {@link Roo.data.Store} objects, or any code which needs
14812  * to access Records cached in an {@link Roo.data.Store} object.<br>
14813  * <p>
14814  * Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
14815  * Instances are usually only created by {@link Roo.data.Reader} implementations when processing unformatted data
14816  * objects.<br>
14817  * <p>
14818  * Record objects generated by this constructor inherit all the methods of Roo.data.Record listed below.
14819  * @constructor
14820  * This constructor should not be used to create Record objects. Instead, use the constructor generated by
14821  * {@link #create}. The parameters are the same.
14822  * @param {Array} data An associative Array of data values keyed by the field name.
14823  * @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
14824  * {@link Roo.data.Store} object which owns the Record to index its collection of Records. If
14825  * not specified an integer id is generated.
14826  */
14827 Roo.data.Record = function(data, id){
14828     this.id = (id || id === 0) ? id : ++Roo.data.Record.AUTO_ID;
14829     this.data = data;
14830 };
14831
14832 /**
14833  * Generate a constructor for a specific record layout.
14834  * @param {Array} o An Array of field definition objects which specify field names, and optionally,
14835  * data types, and a mapping for an {@link Roo.data.Reader} to extract the field's value from a data object.
14836  * Each field definition object may contain the following properties: <ul>
14837  * <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,
14838  * for example the <em>dataIndex</em> property in column definition objects passed to {@link Roo.grid.ColumnModel}</p></li>
14839  * <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Roo.data.Reader} implementation
14840  * that is creating the Record to access the data value from the data object. If an {@link Roo.data.JsonReader}
14841  * is being used, then this is a string containing the javascript expression to reference the data relative to 
14842  * the record item's root. If an {@link Roo.data.XmlReader} is being used, this is an {@link Roo.DomQuery} path
14843  * to the data item relative to the record element. If the mapping expression is the same as the field name,
14844  * this may be omitted.</p></li>
14845  * <li><b>type</b> : String<p style="margin-left:1em">(Optional) The data type for conversion to displayable value. Possible values are
14846  * <ul><li>auto (Default, implies no conversion)</li>
14847  * <li>string</li>
14848  * <li>int</li>
14849  * <li>float</li>
14850  * <li>boolean</li>
14851  * <li>date</li></ul></p></li>
14852  * <li><b>sortType</b> : Mixed<p style="margin-left:1em">(Optional) A member of {@link Roo.data.SortTypes}.</p></li>
14853  * <li><b>sortDir</b> : String<p style="margin-left:1em">(Optional) Initial direction to sort. "ASC" or "DESC"</p></li>
14854  * <li><b>convert</b> : Function<p style="margin-left:1em">(Optional) A function which converts the value provided
14855  * by the Reader into an object that will be stored in the Record. It is passed the
14856  * following parameters:<ul>
14857  * <li><b>v</b> : Mixed<p style="margin-left:1em">The data value as read by the Reader.</p></li>
14858  * </ul></p></li>
14859  * <li><b>dateFormat</b> : String<p style="margin-left:1em">(Optional) A format String for the Date.parseDate function.</p></li>
14860  * </ul>
14861  * <br>usage:<br><pre><code>
14862 var TopicRecord = Roo.data.Record.create(
14863     {name: 'title', mapping: 'topic_title'},
14864     {name: 'author', mapping: 'username'},
14865     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
14866     {name: 'lastPost', mapping: 'post_time', type: 'date'},
14867     {name: 'lastPoster', mapping: 'user2'},
14868     {name: 'excerpt', mapping: 'post_text'}
14869 );
14870
14871 var myNewRecord = new TopicRecord({
14872     title: 'Do my job please',
14873     author: 'noobie',
14874     totalPosts: 1,
14875     lastPost: new Date(),
14876     lastPoster: 'Animal',
14877     excerpt: 'No way dude!'
14878 });
14879 myStore.add(myNewRecord);
14880 </code></pre>
14881  * @method create
14882  * @static
14883  */
14884 Roo.data.Record.create = function(o){
14885     var f = function(){
14886         f.superclass.constructor.apply(this, arguments);
14887     };
14888     Roo.extend(f, Roo.data.Record);
14889     var p = f.prototype;
14890     p.fields = new Roo.util.MixedCollection(false, function(field){
14891         return field.name;
14892     });
14893     for(var i = 0, len = o.length; i < len; i++){
14894         p.fields.add(new Roo.data.Field(o[i]));
14895     }
14896     f.getField = function(name){
14897         return p.fields.get(name);  
14898     };
14899     return f;
14900 };
14901
14902 Roo.data.Record.AUTO_ID = 1000;
14903 Roo.data.Record.EDIT = 'edit';
14904 Roo.data.Record.REJECT = 'reject';
14905 Roo.data.Record.COMMIT = 'commit';
14906
14907 Roo.data.Record.prototype = {
14908     /**
14909      * Readonly flag - true if this record has been modified.
14910      * @type Boolean
14911      */
14912     dirty : false,
14913     editing : false,
14914     error: null,
14915     modified: null,
14916
14917     // private
14918     join : function(store){
14919         this.store = store;
14920     },
14921
14922     /**
14923      * Set the named field to the specified value.
14924      * @param {String} name The name of the field to set.
14925      * @param {Object} value The value to set the field to.
14926      */
14927     set : function(name, value){
14928         if(this.data[name] == value){
14929             return;
14930         }
14931         this.dirty = true;
14932         if(!this.modified){
14933             this.modified = {};
14934         }
14935         if(typeof this.modified[name] == 'undefined'){
14936             this.modified[name] = this.data[name];
14937         }
14938         this.data[name] = value;
14939         if(!this.editing && this.store){
14940             this.store.afterEdit(this);
14941         }       
14942     },
14943
14944     /**
14945      * Get the value of the named field.
14946      * @param {String} name The name of the field to get the value of.
14947      * @return {Object} The value of the field.
14948      */
14949     get : function(name){
14950         return this.data[name]; 
14951     },
14952
14953     // private
14954     beginEdit : function(){
14955         this.editing = true;
14956         this.modified = {}; 
14957     },
14958
14959     // private
14960     cancelEdit : function(){
14961         this.editing = false;
14962         delete this.modified;
14963     },
14964
14965     // private
14966     endEdit : function(){
14967         this.editing = false;
14968         if(this.dirty && this.store){
14969             this.store.afterEdit(this);
14970         }
14971     },
14972
14973     /**
14974      * Usually called by the {@link Roo.data.Store} which owns the Record.
14975      * Rejects all changes made to the Record since either creation, or the last commit operation.
14976      * Modified fields are reverted to their original values.
14977      * <p>
14978      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
14979      * of reject operations.
14980      */
14981     reject : function(){
14982         var m = this.modified;
14983         for(var n in m){
14984             if(typeof m[n] != "function"){
14985                 this.data[n] = m[n];
14986             }
14987         }
14988         this.dirty = false;
14989         delete this.modified;
14990         this.editing = false;
14991         if(this.store){
14992             this.store.afterReject(this);
14993         }
14994     },
14995
14996     /**
14997      * Usually called by the {@link Roo.data.Store} which owns the Record.
14998      * Commits all changes made to the Record since either creation, or the last commit operation.
14999      * <p>
15000      * Developers should subscribe to the {@link Roo.data.Store#update} event to have their code notified
15001      * of commit operations.
15002      */
15003     commit : function(){
15004         this.dirty = false;
15005         delete this.modified;
15006         this.editing = false;
15007         if(this.store){
15008             this.store.afterCommit(this);
15009         }
15010     },
15011
15012     // private
15013     hasError : function(){
15014         return this.error != null;
15015     },
15016
15017     // private
15018     clearError : function(){
15019         this.error = null;
15020     },
15021
15022     /**
15023      * Creates a copy of this record.
15024      * @param {String} id (optional) A new record id if you don't want to use this record's id
15025      * @return {Record}
15026      */
15027     copy : function(newId) {
15028         return new this.constructor(Roo.apply({}, this.data), newId || this.id);
15029     }
15030 };/*
15031  * Based on:
15032  * Ext JS Library 1.1.1
15033  * Copyright(c) 2006-2007, Ext JS, LLC.
15034  *
15035  * Originally Released Under LGPL - original licence link has changed is not relivant.
15036  *
15037  * Fork - LGPL
15038  * <script type="text/javascript">
15039  */
15040
15041
15042
15043 /**
15044  * @class Roo.data.Store
15045  * @extends Roo.util.Observable
15046  * The Store class encapsulates a client side cache of {@link Roo.data.Record} objects which provide input data
15047  * for widgets such as the Roo.grid.Grid, or the Roo.form.ComboBox.<br>
15048  * <p>
15049  * 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
15050  * has no knowledge of the format of the data returned by the Proxy.<br>
15051  * <p>
15052  * A Store object uses its configured implementation of {@link Roo.data.DataReader} to create {@link Roo.data.Record}
15053  * instances from the data object. These records are cached and made available through accessor functions.
15054  * @constructor
15055  * Creates a new Store.
15056  * @param {Object} config A config object containing the objects needed for the Store to access data,
15057  * and read the data into Records.
15058  */
15059 Roo.data.Store = function(config){
15060     this.data = new Roo.util.MixedCollection(false);
15061     this.data.getKey = function(o){
15062         return o.id;
15063     };
15064     this.baseParams = {};
15065     // private
15066     this.paramNames = {
15067         "start" : "start",
15068         "limit" : "limit",
15069         "sort" : "sort",
15070         "dir" : "dir",
15071         "multisort" : "_multisort"
15072     };
15073
15074     if(config && config.data){
15075         this.inlineData = config.data;
15076         delete config.data;
15077     }
15078
15079     Roo.apply(this, config);
15080     
15081     if(this.reader){ // reader passed
15082         this.reader = Roo.factory(this.reader, Roo.data);
15083         this.reader.xmodule = this.xmodule || false;
15084         if(!this.recordType){
15085             this.recordType = this.reader.recordType;
15086         }
15087         if(this.reader.onMetaChange){
15088             this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
15089         }
15090     }
15091
15092     if(this.recordType){
15093         this.fields = this.recordType.prototype.fields;
15094     }
15095     this.modified = [];
15096
15097     this.addEvents({
15098         /**
15099          * @event datachanged
15100          * Fires when the data cache has changed, and a widget which is using this Store
15101          * as a Record cache should refresh its view.
15102          * @param {Store} this
15103          */
15104         datachanged : true,
15105         /**
15106          * @event metachange
15107          * Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
15108          * @param {Store} this
15109          * @param {Object} meta The JSON metadata
15110          */
15111         metachange : true,
15112         /**
15113          * @event add
15114          * Fires when Records have been added to the Store
15115          * @param {Store} this
15116          * @param {Roo.data.Record[]} records The array of Records added
15117          * @param {Number} index The index at which the record(s) were added
15118          */
15119         add : true,
15120         /**
15121          * @event remove
15122          * Fires when a Record has been removed from the Store
15123          * @param {Store} this
15124          * @param {Roo.data.Record} record The Record that was removed
15125          * @param {Number} index The index at which the record was removed
15126          */
15127         remove : true,
15128         /**
15129          * @event update
15130          * Fires when a Record has been updated
15131          * @param {Store} this
15132          * @param {Roo.data.Record} record The Record that was updated
15133          * @param {String} operation The update operation being performed.  Value may be one of:
15134          * <pre><code>
15135  Roo.data.Record.EDIT
15136  Roo.data.Record.REJECT
15137  Roo.data.Record.COMMIT
15138          * </code></pre>
15139          */
15140         update : true,
15141         /**
15142          * @event clear
15143          * Fires when the data cache has been cleared.
15144          * @param {Store} this
15145          */
15146         clear : true,
15147         /**
15148          * @event beforeload
15149          * Fires before a request is made for a new data object.  If the beforeload handler returns false
15150          * the load action will be canceled.
15151          * @param {Store} this
15152          * @param {Object} options The loading options that were specified (see {@link #load} for details)
15153          */
15154         beforeload : true,
15155         /**
15156          * @event beforeloadadd
15157          * Fires after a new set of Records has been loaded.
15158          * @param {Store} this
15159          * @param {Roo.data.Record[]} records The Records that were loaded
15160          * @param {Object} options The loading options that were specified (see {@link #load} for details)
15161          */
15162         beforeloadadd : true,
15163         /**
15164          * @event load
15165          * Fires after a new set of Records has been loaded, before they are added to the store.
15166          * @param {Store} this
15167          * @param {Roo.data.Record[]} records The Records that were loaded
15168          * @param {Object} options The loading options that were specified (see {@link #load} for details)
15169          * @params {Object} return from reader
15170          */
15171         load : true,
15172         /**
15173          * @event loadexception
15174          * Fires if an exception occurs in the Proxy during loading.
15175          * Called with the signature of the Proxy's "loadexception" event.
15176          * If you return Json { data: [] , success: false, .... } then this will be thrown with the following args
15177          * 
15178          * @param {Proxy} 
15179          * @param {Object} ret return data from JsonData.reader() - success, totalRecords, records
15180          * @param {Object} opts - load Options
15181          * @param {Object} jsonData from your request (normally this contains the Exception)
15182          */
15183         loadexception : true
15184     });
15185     
15186     if(this.proxy){
15187         this.proxy = Roo.factory(this.proxy, Roo.data);
15188         this.proxy.xmodule = this.xmodule || false;
15189         this.relayEvents(this.proxy,  ["loadexception"]);
15190     }
15191     this.sortToggle = {};
15192     this.sortOrder = []; // array of order of sorting - updated by grid if multisort is enabled.
15193
15194     Roo.data.Store.superclass.constructor.call(this);
15195
15196     if(this.inlineData){
15197         this.loadData(this.inlineData);
15198         delete this.inlineData;
15199     }
15200 };
15201
15202 Roo.extend(Roo.data.Store, Roo.util.Observable, {
15203      /**
15204     * @cfg {boolean} isLocal   flag if data is locally available (and can be always looked up
15205     * without a remote query - used by combo/forms at present.
15206     */
15207     
15208     /**
15209     * @cfg {Roo.data.DataProxy} proxy [required] The Proxy object which provides access to a data object.
15210     */
15211     /**
15212     * @cfg {Array} data Inline data to be loaded when the store is initialized.
15213     */
15214     /**
15215     * @cfg {Roo.data.DataReader} reader [required]  The Reader object which processes the data object and returns
15216     * an Array of Roo.data.record objects which are cached keyed by their <em>id</em> property.
15217     */
15218     /**
15219     * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
15220     * on any HTTP request
15221     */
15222     /**
15223     * @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
15224     */
15225     /**
15226     * @cfg {Boolean} multiSort enable multi column sorting (sort is based on the order of columns, remote only at present)
15227     */
15228     multiSort: false,
15229     /**
15230     * @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
15231     * version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
15232     */
15233     remoteSort : false,
15234
15235     /**
15236     * @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
15237      * loaded or when a record is removed. (defaults to false).
15238     */
15239     pruneModifiedRecords : false,
15240
15241     // private
15242     lastOptions : null,
15243
15244     /**
15245      * Add Records to the Store and fires the add event.
15246      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
15247      */
15248     add : function(records){
15249         records = [].concat(records);
15250         for(var i = 0, len = records.length; i < len; i++){
15251             records[i].join(this);
15252         }
15253         var index = this.data.length;
15254         this.data.addAll(records);
15255         this.fireEvent("add", this, records, index);
15256     },
15257
15258     /**
15259      * Remove a Record from the Store and fires the remove event.
15260      * @param {Ext.data.Record} record The Roo.data.Record object to remove from the cache.
15261      */
15262     remove : function(record){
15263         var index = this.data.indexOf(record);
15264         this.data.removeAt(index);
15265  
15266         if(this.pruneModifiedRecords){
15267             this.modified.remove(record);
15268         }
15269         this.fireEvent("remove", this, record, index);
15270     },
15271
15272     /**
15273      * Remove all Records from the Store and fires the clear event.
15274      */
15275     removeAll : function(){
15276         this.data.clear();
15277         if(this.pruneModifiedRecords){
15278             this.modified = [];
15279         }
15280         this.fireEvent("clear", this);
15281     },
15282
15283     /**
15284      * Inserts Records to the Store at the given index and fires the add event.
15285      * @param {Number} index The start index at which to insert the passed Records.
15286      * @param {Roo.data.Record[]} records An Array of Roo.data.Record objects to add to the cache.
15287      */
15288     insert : function(index, records){
15289         records = [].concat(records);
15290         for(var i = 0, len = records.length; i < len; i++){
15291             this.data.insert(index, records[i]);
15292             records[i].join(this);
15293         }
15294         this.fireEvent("add", this, records, index);
15295     },
15296
15297     /**
15298      * Get the index within the cache of the passed Record.
15299      * @param {Roo.data.Record} record The Roo.data.Record object to to find.
15300      * @return {Number} The index of the passed Record. Returns -1 if not found.
15301      */
15302     indexOf : function(record){
15303         return this.data.indexOf(record);
15304     },
15305
15306     /**
15307      * Get the index within the cache of the Record with the passed id.
15308      * @param {String} id The id of the Record to find.
15309      * @return {Number} The index of the Record. Returns -1 if not found.
15310      */
15311     indexOfId : function(id){
15312         return this.data.indexOfKey(id);
15313     },
15314
15315     /**
15316      * Get the Record with the specified id.
15317      * @param {String} id The id of the Record to find.
15318      * @return {Roo.data.Record} The Record with the passed id. Returns undefined if not found.
15319      */
15320     getById : function(id){
15321         return this.data.key(id);
15322     },
15323
15324     /**
15325      * Get the Record at the specified index.
15326      * @param {Number} index The index of the Record to find.
15327      * @return {Roo.data.Record} The Record at the passed index. Returns undefined if not found.
15328      */
15329     getAt : function(index){
15330         return this.data.itemAt(index);
15331     },
15332
15333     /**
15334      * Returns a range of Records between specified indices.
15335      * @param {Number} startIndex (optional) The starting index (defaults to 0)
15336      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
15337      * @return {Roo.data.Record[]} An array of Records
15338      */
15339     getRange : function(start, end){
15340         return this.data.getRange(start, end);
15341     },
15342
15343     // private
15344     storeOptions : function(o){
15345         o = Roo.apply({}, o);
15346         delete o.callback;
15347         delete o.scope;
15348         this.lastOptions = o;
15349     },
15350
15351     /**
15352      * Loads the Record cache from the configured Proxy using the configured Reader.
15353      * <p>
15354      * If using remote paging, then the first load call must specify the <em>start</em>
15355      * and <em>limit</em> properties in the options.params property to establish the initial
15356      * position within the dataset, and the number of Records to cache on each read from the Proxy.
15357      * <p>
15358      * <strong>It is important to note that for remote data sources, loading is asynchronous,
15359      * and this call will return before the new data has been loaded. Perform any post-processing
15360      * in a callback function, or in a "load" event handler.</strong>
15361      * <p>
15362      * @param {Object} options An object containing properties which control loading options:<ul>
15363      * <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
15364      * <li>params.data {Object} if you are using a MemoryProxy / JsonReader, use this as the data to load stuff..
15365      * <pre>
15366                 {
15367                     data : data,  // array of key=>value data like JsonReader
15368                     total : data.length,
15369                     success : true
15370                     
15371                 }
15372         </pre>
15373             }.</li>
15374      * <li>callback {Function} A function to be called after the Records have been loaded. The callback is
15375      * passed the following arguments:<ul>
15376      * <li>r : Roo.data.Record[]</li>
15377      * <li>options: Options object from the load call</li>
15378      * <li>success: Boolean success indicator</li></ul></li>
15379      * <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
15380      * <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
15381      * </ul>
15382      */
15383     load : function(options){
15384         options = options || {};
15385         if(this.fireEvent("beforeload", this, options) !== false){
15386             this.storeOptions(options);
15387             var p = Roo.apply(options.params || {}, this.baseParams);
15388             // if meta was not loaded from remote source.. try requesting it.
15389             if (!this.reader.metaFromRemote) {
15390                 p._requestMeta = 1;
15391             }
15392             if(this.sortInfo && this.remoteSort){
15393                 var pn = this.paramNames;
15394                 p[pn["sort"]] = this.sortInfo.field;
15395                 p[pn["dir"]] = this.sortInfo.direction;
15396             }
15397             if (this.multiSort) {
15398                 var pn = this.paramNames;
15399                 p[pn["multisort"]] = Roo.encode( { sort : this.sortToggle, order: this.sortOrder });
15400             }
15401             
15402             this.proxy.load(p, this.reader, this.loadRecords, this, options);
15403         }
15404     },
15405
15406     /**
15407      * Reloads the Record cache from the configured Proxy using the configured Reader and
15408      * the options from the last load operation performed.
15409      * @param {Object} options (optional) An object containing properties which may override the options
15410      * used in the last load operation. See {@link #load} for details (defaults to null, in which case
15411      * the most recently used options are reused).
15412      */
15413     reload : function(options){
15414         this.load(Roo.applyIf(options||{}, this.lastOptions));
15415     },
15416
15417     // private
15418     // Called as a callback by the Reader during a load operation.
15419     loadRecords : function(o, options, success){
15420          
15421         if(!o){
15422             if(success !== false){
15423                 this.fireEvent("load", this, [], options, o);
15424             }
15425             if(options.callback){
15426                 options.callback.call(options.scope || this, [], options, false);
15427             }
15428             return;
15429         }
15430         // if data returned failure - throw an exception.
15431         if (o.success === false) {
15432             // show a message if no listener is registered.
15433             if (!this.hasListener('loadexception') && typeof(o.raw.errorMsg) != 'undefined') {
15434                     Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
15435             }
15436             // loadmask wil be hooked into this..
15437             this.fireEvent("loadexception", this, o, options, o.raw.errorMsg);
15438             return;
15439         }
15440         var r = o.records, t = o.totalRecords || r.length;
15441         
15442         this.fireEvent("beforeloadadd", this, r, options, o);
15443         
15444         if(!options || options.add !== true){
15445             if(this.pruneModifiedRecords){
15446                 this.modified = [];
15447             }
15448             for(var i = 0, len = r.length; i < len; i++){
15449                 r[i].join(this);
15450             }
15451             if(this.snapshot){
15452                 this.data = this.snapshot;
15453                 delete this.snapshot;
15454             }
15455             this.data.clear();
15456             this.data.addAll(r);
15457             this.totalLength = t;
15458             this.applySort();
15459             this.fireEvent("datachanged", this);
15460         }else{
15461             this.totalLength = Math.max(t, this.data.length+r.length);
15462             this.add(r);
15463         }
15464         
15465         if(this.parent && !Roo.isIOS && !this.useNativeIOS && this.parent.emptyTitle.length) {
15466                 
15467             var e = new Roo.data.Record({});
15468
15469             e.set(this.parent.displayField, this.parent.emptyTitle);
15470             e.set(this.parent.valueField, '');
15471
15472             this.insert(0, e);
15473         }
15474             
15475         this.fireEvent("load", this, r, options, o);
15476         if(options.callback){
15477             options.callback.call(options.scope || this, r, options, true);
15478         }
15479     },
15480
15481
15482     /**
15483      * Loads data from a passed data block. A Reader which understands the format of the data
15484      * must have been configured in the constructor.
15485      * @param {Object} data The data block from which to read the Records.  The format of the data expected
15486      * is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
15487      * @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
15488      */
15489     loadData : function(o, append){
15490         var r = this.reader.readRecords(o);
15491         this.loadRecords(r, {add: append}, true);
15492     },
15493     
15494      /**
15495      * using 'cn' the nested child reader read the child array into it's child stores.
15496      * @param {Object} rec The record with a 'children array
15497      */
15498     loadDataFromChildren : function(rec)
15499     {
15500         this.loadData(this.reader.toLoadData(rec));
15501     },
15502     
15503
15504     /**
15505      * Gets the number of cached records.
15506      * <p>
15507      * <em>If using paging, this may not be the total size of the dataset. If the data object
15508      * used by the Reader contains the dataset size, then the getTotalCount() function returns
15509      * the data set size</em>
15510      */
15511     getCount : function(){
15512         return this.data.length || 0;
15513     },
15514
15515     /**
15516      * Gets the total number of records in the dataset as returned by the server.
15517      * <p>
15518      * <em>If using paging, for this to be accurate, the data object used by the Reader must contain
15519      * the dataset size</em>
15520      */
15521     getTotalCount : function(){
15522         return this.totalLength || 0;
15523     },
15524
15525     /**
15526      * Returns the sort state of the Store as an object with two properties:
15527      * <pre><code>
15528  field {String} The name of the field by which the Records are sorted
15529  direction {String} The sort order, "ASC" or "DESC"
15530      * </code></pre>
15531      */
15532     getSortState : function(){
15533         return this.sortInfo;
15534     },
15535
15536     // private
15537     applySort : function(){
15538         if(this.sortInfo && !this.remoteSort){
15539             var s = this.sortInfo, f = s.field;
15540             var st = this.fields.get(f).sortType;
15541             var fn = function(r1, r2){
15542                 var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
15543                 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
15544             };
15545             this.data.sort(s.direction, fn);
15546             if(this.snapshot && this.snapshot != this.data){
15547                 this.snapshot.sort(s.direction, fn);
15548             }
15549         }
15550     },
15551
15552     /**
15553      * Sets the default sort column and order to be used by the next load operation.
15554      * @param {String} fieldName The name of the field to sort by.
15555      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
15556      */
15557     setDefaultSort : function(field, dir){
15558         this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
15559     },
15560
15561     /**
15562      * Sort the Records.
15563      * If remote sorting is used, the sort is performed on the server, and the cache is
15564      * reloaded. If local sorting is used, the cache is sorted internally.
15565      * @param {String} fieldName The name of the field to sort by.
15566      * @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
15567      */
15568     sort : function(fieldName, dir){
15569         var f = this.fields.get(fieldName);
15570         if(!dir){
15571             this.sortToggle[f.name] = this.sortToggle[f.name] || f.sortDir;
15572             
15573             if(this.multiSort || (this.sortInfo && this.sortInfo.field == f.name) ){ // toggle sort dir
15574                 dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
15575             }else{
15576                 dir = f.sortDir;
15577             }
15578         }
15579         this.sortToggle[f.name] = dir;
15580         this.sortInfo = {field: f.name, direction: dir};
15581         if(!this.remoteSort){
15582             this.applySort();
15583             this.fireEvent("datachanged", this);
15584         }else{
15585             this.load(this.lastOptions);
15586         }
15587     },
15588
15589     /**
15590      * Calls the specified function for each of the Records in the cache.
15591      * @param {Function} fn The function to call. The Record is passed as the first parameter.
15592      * Returning <em>false</em> aborts and exits the iteration.
15593      * @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
15594      */
15595     each : function(fn, scope){
15596         this.data.each(fn, scope);
15597     },
15598
15599     /**
15600      * Gets all records modified since the last commit.  Modified records are persisted across load operations
15601      * (e.g., during paging).
15602      * @return {Roo.data.Record[]} An array of Records containing outstanding modifications.
15603      */
15604     getModifiedRecords : function(){
15605         return this.modified;
15606     },
15607
15608     // private
15609     createFilterFn : function(property, value, anyMatch){
15610         if(!value.exec){ // not a regex
15611             value = String(value);
15612             if(value.length == 0){
15613                 return false;
15614             }
15615             value = new RegExp((anyMatch === true ? '' : '^') + Roo.escapeRe(value), "i");
15616         }
15617         return function(r){
15618             return value.test(r.data[property]);
15619         };
15620     },
15621
15622     /**
15623      * Sums the value of <i>property</i> for each record between start and end and returns the result.
15624      * @param {String} property A field on your records
15625      * @param {Number} start The record index to start at (defaults to 0)
15626      * @param {Number} end The last record index to include (defaults to length - 1)
15627      * @return {Number} The sum
15628      */
15629     sum : function(property, start, end){
15630         var rs = this.data.items, v = 0;
15631         start = start || 0;
15632         end = (end || end === 0) ? end : rs.length-1;
15633
15634         for(var i = start; i <= end; i++){
15635             v += (rs[i].data[property] || 0);
15636         }
15637         return v;
15638     },
15639
15640     /**
15641      * Filter the records by a specified property.
15642      * @param {String} field A field on your records
15643      * @param {String/RegExp} value Either a string that the field
15644      * should start with or a RegExp to test against the field
15645      * @param {Boolean} anyMatch True to match any part not just the beginning
15646      */
15647     filter : function(property, value, anyMatch){
15648         var fn = this.createFilterFn(property, value, anyMatch);
15649         return fn ? this.filterBy(fn) : this.clearFilter();
15650     },
15651
15652     /**
15653      * Filter by a function. The specified function will be called with each
15654      * record in this data source. If the function returns true the record is included,
15655      * otherwise it is filtered.
15656      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
15657      * @param {Object} scope (optional) The scope of the function (defaults to this)
15658      */
15659     filterBy : function(fn, scope){
15660         this.snapshot = this.snapshot || this.data;
15661         this.data = this.queryBy(fn, scope||this);
15662         this.fireEvent("datachanged", this);
15663     },
15664
15665     /**
15666      * Query the records by a specified property.
15667      * @param {String} field A field on your records
15668      * @param {String/RegExp} value Either a string that the field
15669      * should start with or a RegExp to test against the field
15670      * @param {Boolean} anyMatch True to match any part not just the beginning
15671      * @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
15672      */
15673     query : function(property, value, anyMatch){
15674         var fn = this.createFilterFn(property, value, anyMatch);
15675         return fn ? this.queryBy(fn) : this.data.clone();
15676     },
15677
15678     /**
15679      * Query by a function. The specified function will be called with each
15680      * record in this data source. If the function returns true the record is included
15681      * in the results.
15682      * @param {Function} fn The function to be called, it will receive 2 args (record, id)
15683      * @param {Object} scope (optional) The scope of the function (defaults to this)
15684       @return {MixedCollection} Returns an Roo.util.MixedCollection of the matched records
15685      **/
15686     queryBy : function(fn, scope){
15687         var data = this.snapshot || this.data;
15688         return data.filterBy(fn, scope||this);
15689     },
15690
15691     /**
15692      * Collects unique values for a particular dataIndex from this store.
15693      * @param {String} dataIndex The property to collect
15694      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
15695      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
15696      * @return {Array} An array of the unique values
15697      **/
15698     collect : function(dataIndex, allowNull, bypassFilter){
15699         var d = (bypassFilter === true && this.snapshot) ?
15700                 this.snapshot.items : this.data.items;
15701         var v, sv, r = [], l = {};
15702         for(var i = 0, len = d.length; i < len; i++){
15703             v = d[i].data[dataIndex];
15704             sv = String(v);
15705             if((allowNull || !Roo.isEmpty(v)) && !l[sv]){
15706                 l[sv] = true;
15707                 r[r.length] = v;
15708             }
15709         }
15710         return r;
15711     },
15712
15713     /**
15714      * Revert to a view of the Record cache with no filtering applied.
15715      * @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
15716      */
15717     clearFilter : function(suppressEvent){
15718         if(this.snapshot && this.snapshot != this.data){
15719             this.data = this.snapshot;
15720             delete this.snapshot;
15721             if(suppressEvent !== true){
15722                 this.fireEvent("datachanged", this);
15723             }
15724         }
15725     },
15726
15727     // private
15728     afterEdit : function(record){
15729         if(this.modified.indexOf(record) == -1){
15730             this.modified.push(record);
15731         }
15732         this.fireEvent("update", this, record, Roo.data.Record.EDIT);
15733     },
15734     
15735     // private
15736     afterReject : function(record){
15737         this.modified.remove(record);
15738         this.fireEvent("update", this, record, Roo.data.Record.REJECT);
15739     },
15740
15741     // private
15742     afterCommit : function(record){
15743         this.modified.remove(record);
15744         this.fireEvent("update", this, record, Roo.data.Record.COMMIT);
15745     },
15746
15747     /**
15748      * Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
15749      * Store's "update" event, and perform updating when the third parameter is Roo.data.Record.COMMIT.
15750      */
15751     commitChanges : function(){
15752         var m = this.modified.slice(0);
15753         this.modified = [];
15754         for(var i = 0, len = m.length; i < len; i++){
15755             m[i].commit();
15756         }
15757     },
15758
15759     /**
15760      * Cancel outstanding changes on all changed records.
15761      */
15762     rejectChanges : function(){
15763         var m = this.modified.slice(0);
15764         this.modified = [];
15765         for(var i = 0, len = m.length; i < len; i++){
15766             m[i].reject();
15767         }
15768     },
15769
15770     onMetaChange : function(meta, rtype, o){
15771         this.recordType = rtype;
15772         this.fields = rtype.prototype.fields;
15773         delete this.snapshot;
15774         this.sortInfo = meta.sortInfo || this.sortInfo;
15775         this.modified = [];
15776         this.fireEvent('metachange', this, this.reader.meta);
15777     },
15778     
15779     moveIndex : function(data, type)
15780     {
15781         var index = this.indexOf(data);
15782         
15783         var newIndex = index + type;
15784         
15785         this.remove(data);
15786         
15787         this.insert(newIndex, data);
15788         
15789     }
15790 });/*
15791  * Based on:
15792  * Ext JS Library 1.1.1
15793  * Copyright(c) 2006-2007, Ext JS, LLC.
15794  *
15795  * Originally Released Under LGPL - original licence link has changed is not relivant.
15796  *
15797  * Fork - LGPL
15798  * <script type="text/javascript">
15799  */
15800
15801 /**
15802  * @class Roo.data.SimpleStore
15803  * @extends Roo.data.Store
15804  * Small helper class to make creating Stores from Array data easier.
15805  * @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
15806  * @cfg {Array} fields An array of field definition objects, or field name strings.
15807  * @cfg {Object} an existing reader (eg. copied from another store)
15808  * @cfg {Array} data The multi-dimensional array of data
15809  * @cfg {Roo.data.DataProxy} proxy [not-required]  
15810  * @cfg {Roo.data.Reader} reader  [not-required] 
15811  * @constructor
15812  * @param {Object} config
15813  */
15814 Roo.data.SimpleStore = function(config)
15815 {
15816     Roo.data.SimpleStore.superclass.constructor.call(this, {
15817         isLocal : true,
15818         reader: typeof(config.reader) != 'undefined' ? config.reader : new Roo.data.ArrayReader({
15819                 id: config.id
15820             },
15821             Roo.data.Record.create(config.fields)
15822         ),
15823         proxy : new Roo.data.MemoryProxy(config.data)
15824     });
15825     this.load();
15826 };
15827 Roo.extend(Roo.data.SimpleStore, Roo.data.Store);/*
15828  * Based on:
15829  * Ext JS Library 1.1.1
15830  * Copyright(c) 2006-2007, Ext JS, LLC.
15831  *
15832  * Originally Released Under LGPL - original licence link has changed is not relivant.
15833  *
15834  * Fork - LGPL
15835  * <script type="text/javascript">
15836  */
15837
15838 /**
15839 /**
15840  * @extends Roo.data.Store
15841  * @class Roo.data.JsonStore
15842  * Small helper class to make creating Stores for JSON data easier. <br/>
15843 <pre><code>
15844 var store = new Roo.data.JsonStore({
15845     url: 'get-images.php',
15846     root: 'images',
15847     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
15848 });
15849 </code></pre>
15850  * <b>Note: Although they are not listed, this class inherits all of the config options of Store,
15851  * JsonReader and HttpProxy (unless inline data is provided).</b>
15852  * @cfg {Array} fields An array of field definition objects, or field name strings.
15853  * @constructor
15854  * @param {Object} config
15855  */
15856 Roo.data.JsonStore = function(c){
15857     Roo.data.JsonStore.superclass.constructor.call(this, Roo.apply(c, {
15858         proxy: !c.data ? new Roo.data.HttpProxy({url: c.url}) : undefined,
15859         reader: new Roo.data.JsonReader(c, c.fields)
15860     }));
15861 };
15862 Roo.extend(Roo.data.JsonStore, Roo.data.Store);/*
15863  * Based on:
15864  * Ext JS Library 1.1.1
15865  * Copyright(c) 2006-2007, Ext JS, LLC.
15866  *
15867  * Originally Released Under LGPL - original licence link has changed is not relivant.
15868  *
15869  * Fork - LGPL
15870  * <script type="text/javascript">
15871  */
15872
15873  
15874 Roo.data.Field = function(config){
15875     if(typeof config == "string"){
15876         config = {name: config};
15877     }
15878     Roo.apply(this, config);
15879     
15880     if(!this.type){
15881         this.type = "auto";
15882     }
15883     
15884     var st = Roo.data.SortTypes;
15885     // named sortTypes are supported, here we look them up
15886     if(typeof this.sortType == "string"){
15887         this.sortType = st[this.sortType];
15888     }
15889     
15890     // set default sortType for strings and dates
15891     if(!this.sortType){
15892         switch(this.type){
15893             case "string":
15894                 this.sortType = st.asUCString;
15895                 break;
15896             case "date":
15897                 this.sortType = st.asDate;
15898                 break;
15899             default:
15900                 this.sortType = st.none;
15901         }
15902     }
15903
15904     // define once
15905     var stripRe = /[\$,%]/g;
15906
15907     // prebuilt conversion function for this field, instead of
15908     // switching every time we're reading a value
15909     if(!this.convert){
15910         var cv, dateFormat = this.dateFormat;
15911         switch(this.type){
15912             case "":
15913             case "auto":
15914             case undefined:
15915                 cv = function(v){ return v; };
15916                 break;
15917             case "string":
15918                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
15919                 break;
15920             case "int":
15921                 cv = function(v){
15922                     return v !== undefined && v !== null && v !== '' ?
15923                            parseInt(String(v).replace(stripRe, ""), 10) : '';
15924                     };
15925                 break;
15926             case "float":
15927                 cv = function(v){
15928                     return v !== undefined && v !== null && v !== '' ?
15929                            parseFloat(String(v).replace(stripRe, ""), 10) : ''; 
15930                     };
15931                 break;
15932             case "bool":
15933             case "boolean":
15934                 cv = function(v){ return v === true || v === "true" || v == 1; };
15935                 break;
15936             case "date":
15937                 cv = function(v){
15938                     if(!v){
15939                         return '';
15940                     }
15941                     if(v instanceof Date){
15942                         return v;
15943                     }
15944                     if(dateFormat){
15945                         if(dateFormat == "timestamp"){
15946                             return new Date(v*1000);
15947                         }
15948                         return Date.parseDate(v, dateFormat);
15949                     }
15950                     var parsed = Date.parse(v);
15951                     return parsed ? new Date(parsed) : null;
15952                 };
15953              break;
15954             
15955         }
15956         this.convert = cv;
15957     }
15958 };
15959
15960 Roo.data.Field.prototype = {
15961     dateFormat: null,
15962     defaultValue: "",
15963     mapping: null,
15964     sortType : null,
15965     sortDir : "ASC"
15966 };/*
15967  * Based on:
15968  * Ext JS Library 1.1.1
15969  * Copyright(c) 2006-2007, Ext JS, LLC.
15970  *
15971  * Originally Released Under LGPL - original licence link has changed is not relivant.
15972  *
15973  * Fork - LGPL
15974  * <script type="text/javascript">
15975  */
15976  
15977 // Base class for reading structured data from a data source.  This class is intended to be
15978 // extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
15979
15980 /**
15981  * @class Roo.data.DataReader
15982  * @abstract
15983  * Base class for reading structured data from a data source.  This class is intended to be
15984  * extended (see {Roo.data.ArrayReader}, {Roo.data.JsonReader} and {Roo.data.XmlReader}) and should not be created directly.
15985  */
15986
15987 Roo.data.DataReader = function(meta, recordType){
15988     
15989     this.meta = meta;
15990     
15991     this.recordType = recordType instanceof Array ? 
15992         Roo.data.Record.create(recordType) : recordType;
15993 };
15994
15995 Roo.data.DataReader.prototype = {
15996     
15997     
15998     readerType : 'Data',
15999      /**
16000      * Create an empty record
16001      * @param {Object} data (optional) - overlay some values
16002      * @return {Roo.data.Record} record created.
16003      */
16004     newRow :  function(d) {
16005         var da =  {};
16006         this.recordType.prototype.fields.each(function(c) {
16007             switch( c.type) {
16008                 case 'int' : da[c.name] = 0; break;
16009                 case 'date' : da[c.name] = new Date(); break;
16010                 case 'float' : da[c.name] = 0.0; break;
16011                 case 'boolean' : da[c.name] = false; break;
16012                 default : da[c.name] = ""; break;
16013             }
16014             
16015         });
16016         return new this.recordType(Roo.apply(da, d));
16017     }
16018     
16019     
16020 };/*
16021  * Based on:
16022  * Ext JS Library 1.1.1
16023  * Copyright(c) 2006-2007, Ext JS, LLC.
16024  *
16025  * Originally Released Under LGPL - original licence link has changed is not relivant.
16026  *
16027  * Fork - LGPL
16028  * <script type="text/javascript">
16029  */
16030
16031 /**
16032  * @class Roo.data.DataProxy
16033  * @extends Roo.util.Observable
16034  * @abstract
16035  * This class is an abstract base class for implementations which provide retrieval of
16036  * unformatted data objects.<br>
16037  * <p>
16038  * DataProxy implementations are usually used in conjunction with an implementation of Roo.data.DataReader
16039  * (of the appropriate type which knows how to parse the data object) to provide a block of
16040  * {@link Roo.data.Records} to an {@link Roo.data.Store}.<br>
16041  * <p>
16042  * Custom implementations must implement the load method as described in
16043  * {@link Roo.data.HttpProxy#load}.
16044  */
16045 Roo.data.DataProxy = function(){
16046     this.addEvents({
16047         /**
16048          * @event beforeload
16049          * Fires before a network request is made to retrieve a data object.
16050          * @param {Object} This DataProxy object.
16051          * @param {Object} params The params parameter to the load function.
16052          */
16053         beforeload : true,
16054         /**
16055          * @event load
16056          * Fires before the load method's callback is called.
16057          * @param {Object} This DataProxy object.
16058          * @param {Object} o The data object.
16059          * @param {Object} arg The callback argument object passed to the load function.
16060          */
16061         load : true,
16062         /**
16063          * @event loadexception
16064          * Fires if an Exception occurs during data retrieval.
16065          * @param {Object} This DataProxy object.
16066          * @param {Object} o The data object.
16067          * @param {Object} arg The callback argument object passed to the load function.
16068          * @param {Object} e The Exception.
16069          */
16070         loadexception : true
16071     });
16072     Roo.data.DataProxy.superclass.constructor.call(this);
16073 };
16074
16075 Roo.extend(Roo.data.DataProxy, Roo.util.Observable);
16076
16077     /**
16078      * @cfg {void} listeners (Not available) Constructor blocks listeners from being set
16079      */
16080 /*
16081  * Based on:
16082  * Ext JS Library 1.1.1
16083  * Copyright(c) 2006-2007, Ext JS, LLC.
16084  *
16085  * Originally Released Under LGPL - original licence link has changed is not relivant.
16086  *
16087  * Fork - LGPL
16088  * <script type="text/javascript">
16089  */
16090 /**
16091  * @class Roo.data.MemoryProxy
16092  * @extends Roo.data.DataProxy
16093  * An implementation of Roo.data.DataProxy that simply passes the data specified in its constructor
16094  * to the Reader when its load method is called.
16095  * @constructor
16096  * @param {Object} config  A config object containing the objects needed for the Store to access data,
16097  */
16098 Roo.data.MemoryProxy = function(config){
16099     var data = config;
16100     if (typeof(config) != 'undefined' && typeof(config.data) != 'undefined') {
16101         data = config.data;
16102     }
16103     Roo.data.MemoryProxy.superclass.constructor.call(this);
16104     this.data = data;
16105 };
16106
16107 Roo.extend(Roo.data.MemoryProxy, Roo.data.DataProxy, {
16108     
16109     /**
16110      *  @cfg {Object} data The data object which the Reader uses to construct a block of Roo.data.Records.
16111      */
16112     /**
16113      * Load data from the requested source (in this case an in-memory
16114      * data object passed to the constructor), read the data object into
16115      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
16116      * process that block using the passed callback.
16117      * @param {Object} params This parameter is not used by the MemoryProxy class.
16118      * @param {Roo.data.DataReader} reader The Reader object which converts the data
16119      * object into a block of Roo.data.Records.
16120      * @param {Function} callback The function into which to pass the block of Roo.data.records.
16121      * The function must be passed <ul>
16122      * <li>The Record block object</li>
16123      * <li>The "arg" argument from the load function</li>
16124      * <li>A boolean success indicator</li>
16125      * </ul>
16126      * @param {Object} scope The scope in which to call the callback
16127      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
16128      */
16129     load : function(params, reader, callback, scope, arg){
16130         params = params || {};
16131         var result;
16132         try {
16133             result = reader.readRecords(params.data ? params.data :this.data);
16134         }catch(e){
16135             this.fireEvent("loadexception", this, arg, null, e);
16136             callback.call(scope, null, arg, false);
16137             return;
16138         }
16139         callback.call(scope, result, arg, true);
16140     },
16141     
16142     // private
16143     update : function(params, records){
16144         
16145     }
16146 });/*
16147  * Based on:
16148  * Ext JS Library 1.1.1
16149  * Copyright(c) 2006-2007, Ext JS, LLC.
16150  *
16151  * Originally Released Under LGPL - original licence link has changed is not relivant.
16152  *
16153  * Fork - LGPL
16154  * <script type="text/javascript">
16155  */
16156 /**
16157  * @class Roo.data.HttpProxy
16158  * @extends Roo.data.DataProxy
16159  * An implementation of {@link Roo.data.DataProxy} that reads a data object from an {@link Roo.data.Connection} object
16160  * configured to reference a certain URL.<br><br>
16161  * <p>
16162  * <em>Note that this class cannot be used to retrieve data from a domain other than the domain
16163  * from which the running page was served.<br><br>
16164  * <p>
16165  * For cross-domain access to remote data, use an {@link Roo.data.ScriptTagProxy}.</em><br><br>
16166  * <p>
16167  * Be aware that to enable the browser to parse an XML document, the server must set
16168  * the Content-Type header in the HTTP response to "text/xml".
16169  * @constructor
16170  * @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
16171  * an {@link Roo.data.Connection} object.  If a Connection config is passed, the singleton {@link Roo.Ajax} object
16172  * will be used to make the request.
16173  */
16174 Roo.data.HttpProxy = function(conn){
16175     Roo.data.HttpProxy.superclass.constructor.call(this);
16176     // is conn a conn config or a real conn?
16177     this.conn = conn;
16178     this.useAjax = !conn || !conn.events;
16179   
16180 };
16181
16182 Roo.extend(Roo.data.HttpProxy, Roo.data.DataProxy, {
16183     // thse are take from connection...
16184     
16185     /**
16186      * @cfg {String} url  The default URL to be used for requests to the server. (defaults to undefined)
16187      */
16188     /**
16189      * @cfg {Object} extraParams  An object containing properties which are used as
16190      * extra parameters to each request made by this object. (defaults to undefined)
16191      */
16192     /**
16193      * @cfg {Object} defaultHeaders   An object containing request headers which are added
16194      *  to each request made by this object. (defaults to undefined)
16195      */
16196     /**
16197      * @cfg {String} method (GET|POST)  The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
16198      */
16199     /**
16200      * @cfg {Number} timeout The timeout in milliseconds to be used for requests. (defaults to 30000)
16201      */
16202      /**
16203      * @cfg {Boolean} autoAbort Whether this request should abort any pending requests. (defaults to false)
16204      * @type Boolean
16205      */
16206   
16207
16208     /**
16209      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
16210      * @type Boolean
16211      */
16212     /**
16213      * Return the {@link Roo.data.Connection} object being used by this Proxy.
16214      * @return {Connection} The Connection object. This object may be used to subscribe to events on
16215      * a finer-grained basis than the DataProxy events.
16216      */
16217     getConnection : function(){
16218         return this.useAjax ? Roo.Ajax : this.conn;
16219     },
16220
16221     /**
16222      * Load data from the configured {@link Roo.data.Connection}, read the data object into
16223      * a block of Roo.data.Records using the passed {@link Roo.data.DataReader} implementation, and
16224      * process that block using the passed callback.
16225      * @param {Object} params An object containing properties which are to be used as HTTP parameters
16226      * for the request to the remote server.
16227      * @param {Roo.data.DataReader} reader The Reader object which converts the data
16228      * object into a block of Roo.data.Records.
16229      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
16230      * The function must be passed <ul>
16231      * <li>The Record block object</li>
16232      * <li>The "arg" argument from the load function</li>
16233      * <li>A boolean success indicator</li>
16234      * </ul>
16235      * @param {Object} scope The scope in which to call the callback
16236      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
16237      */
16238     load : function(params, reader, callback, scope, arg){
16239         if(this.fireEvent("beforeload", this, params) !== false){
16240             var  o = {
16241                 params : params || {},
16242                 request: {
16243                     callback : callback,
16244                     scope : scope,
16245                     arg : arg
16246                 },
16247                 reader: reader,
16248                 callback : this.loadResponse,
16249                 scope: this
16250             };
16251             if(this.useAjax){
16252                 Roo.applyIf(o, this.conn);
16253                 if(this.activeRequest){
16254                     Roo.Ajax.abort(this.activeRequest);
16255                 }
16256                 this.activeRequest = Roo.Ajax.request(o);
16257             }else{
16258                 this.conn.request(o);
16259             }
16260         }else{
16261             callback.call(scope||this, null, arg, false);
16262         }
16263     },
16264
16265     // private
16266     loadResponse : function(o, success, response){
16267         delete this.activeRequest;
16268         if(!success){
16269             this.fireEvent("loadexception", this, o, response);
16270             o.request.callback.call(o.request.scope, null, o.request.arg, false);
16271             return;
16272         }
16273         var result;
16274         try {
16275             result = o.reader.read(response);
16276         }catch(e){
16277             o.success = false;
16278             o.raw = { errorMsg : response.responseText };
16279             this.fireEvent("loadexception", this, o, response, e);
16280             o.request.callback.call(o.request.scope, o, o.request.arg, false);
16281             return;
16282         }
16283         
16284         this.fireEvent("load", this, o, o.request.arg);
16285         o.request.callback.call(o.request.scope, result, o.request.arg, true);
16286     },
16287
16288     // private
16289     update : function(dataSet){
16290
16291     },
16292
16293     // private
16294     updateResponse : function(dataSet){
16295
16296     }
16297 });/*
16298  * Based on:
16299  * Ext JS Library 1.1.1
16300  * Copyright(c) 2006-2007, Ext JS, LLC.
16301  *
16302  * Originally Released Under LGPL - original licence link has changed is not relivant.
16303  *
16304  * Fork - LGPL
16305  * <script type="text/javascript">
16306  */
16307
16308 /**
16309  * @class Roo.data.ScriptTagProxy
16310  * An implementation of Roo.data.DataProxy that reads a data object from a URL which may be in a domain
16311  * other than the originating domain of the running page.<br><br>
16312  * <p>
16313  * <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
16314  * of the running page, you must use this class, rather than DataProxy.</em><br><br>
16315  * <p>
16316  * The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
16317  * source code that is used as the source inside a &lt;script> tag.<br><br>
16318  * <p>
16319  * In order for the browser to process the returned data, the server must wrap the data object
16320  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
16321  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
16322  * depending on whether the callback name was passed:
16323  * <p>
16324  * <pre><code>
16325 boolean scriptTag = false;
16326 String cb = request.getParameter("callback");
16327 if (cb != null) {
16328     scriptTag = true;
16329     response.setContentType("text/javascript");
16330 } else {
16331     response.setContentType("application/x-json");
16332 }
16333 Writer out = response.getWriter();
16334 if (scriptTag) {
16335     out.write(cb + "(");
16336 }
16337 out.print(dataBlock.toJsonString());
16338 if (scriptTag) {
16339     out.write(");");
16340 }
16341 </pre></code>
16342  *
16343  * @constructor
16344  * @param {Object} config A configuration object.
16345  */
16346 Roo.data.ScriptTagProxy = function(config){
16347     Roo.data.ScriptTagProxy.superclass.constructor.call(this);
16348     Roo.apply(this, config);
16349     this.head = document.getElementsByTagName("head")[0];
16350 };
16351
16352 Roo.data.ScriptTagProxy.TRANS_ID = 1000;
16353
16354 Roo.extend(Roo.data.ScriptTagProxy, Roo.data.DataProxy, {
16355     /**
16356      * @cfg {String} url The URL from which to request the data object.
16357      */
16358     /**
16359      * @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
16360      */
16361     timeout : 30000,
16362     /**
16363      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
16364      * the server the name of the callback function set up by the load call to process the returned data object.
16365      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
16366      * javascript output which calls this named function passing the data object as its only parameter.
16367      */
16368     callbackParam : "callback",
16369     /**
16370      *  @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
16371      * name to the request.
16372      */
16373     nocache : true,
16374
16375     /**
16376      * Load data from the configured URL, read the data object into
16377      * a block of Roo.data.Records using the passed Roo.data.DataReader implementation, and
16378      * process that block using the passed callback.
16379      * @param {Object} params An object containing properties which are to be used as HTTP parameters
16380      * for the request to the remote server.
16381      * @param {Roo.data.DataReader} reader The Reader object which converts the data
16382      * object into a block of Roo.data.Records.
16383      * @param {Function} callback The function into which to pass the block of Roo.data.Records.
16384      * The function must be passed <ul>
16385      * <li>The Record block object</li>
16386      * <li>The "arg" argument from the load function</li>
16387      * <li>A boolean success indicator</li>
16388      * </ul>
16389      * @param {Object} scope The scope in which to call the callback
16390      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
16391      */
16392     load : function(params, reader, callback, scope, arg){
16393         if(this.fireEvent("beforeload", this, params) !== false){
16394
16395             var p = Roo.urlEncode(Roo.apply(params, this.extraParams));
16396
16397             var url = this.url;
16398             url += (url.indexOf("?") != -1 ? "&" : "?") + p;
16399             if(this.nocache){
16400                 url += "&_dc=" + (new Date().getTime());
16401             }
16402             var transId = ++Roo.data.ScriptTagProxy.TRANS_ID;
16403             var trans = {
16404                 id : transId,
16405                 cb : "stcCallback"+transId,
16406                 scriptId : "stcScript"+transId,
16407                 params : params,
16408                 arg : arg,
16409                 url : url,
16410                 callback : callback,
16411                 scope : scope,
16412                 reader : reader
16413             };
16414             var conn = this;
16415
16416             window[trans.cb] = function(o){
16417                 conn.handleResponse(o, trans);
16418             };
16419
16420             url += String.format("&{0}={1}", this.callbackParam, trans.cb);
16421
16422             if(this.autoAbort !== false){
16423                 this.abort();
16424             }
16425
16426             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
16427
16428             var script = document.createElement("script");
16429             script.setAttribute("src", url);
16430             script.setAttribute("type", "text/javascript");
16431             script.setAttribute("id", trans.scriptId);
16432             this.head.appendChild(script);
16433
16434             this.trans = trans;
16435         }else{
16436             callback.call(scope||this, null, arg, false);
16437         }
16438     },
16439
16440     // private
16441     isLoading : function(){
16442         return this.trans ? true : false;
16443     },
16444
16445     /**
16446      * Abort the current server request.
16447      */
16448     abort : function(){
16449         if(this.isLoading()){
16450             this.destroyTrans(this.trans);
16451         }
16452     },
16453
16454     // private
16455     destroyTrans : function(trans, isLoaded){
16456         this.head.removeChild(document.getElementById(trans.scriptId));
16457         clearTimeout(trans.timeoutId);
16458         if(isLoaded){
16459             window[trans.cb] = undefined;
16460             try{
16461                 delete window[trans.cb];
16462             }catch(e){}
16463         }else{
16464             // if hasn't been loaded, wait for load to remove it to prevent script error
16465             window[trans.cb] = function(){
16466                 window[trans.cb] = undefined;
16467                 try{
16468                     delete window[trans.cb];
16469                 }catch(e){}
16470             };
16471         }
16472     },
16473
16474     // private
16475     handleResponse : function(o, trans){
16476         this.trans = false;
16477         this.destroyTrans(trans, true);
16478         var result;
16479         try {
16480             result = trans.reader.readRecords(o);
16481         }catch(e){
16482             this.fireEvent("loadexception", this, o, trans.arg, e);
16483             trans.callback.call(trans.scope||window, null, trans.arg, false);
16484             return;
16485         }
16486         this.fireEvent("load", this, o, trans.arg);
16487         trans.callback.call(trans.scope||window, result, trans.arg, true);
16488     },
16489
16490     // private
16491     handleFailure : function(trans){
16492         this.trans = false;
16493         this.destroyTrans(trans, false);
16494         this.fireEvent("loadexception", this, null, trans.arg);
16495         trans.callback.call(trans.scope||window, null, trans.arg, false);
16496     }
16497 });/*
16498  * Based on:
16499  * Ext JS Library 1.1.1
16500  * Copyright(c) 2006-2007, Ext JS, LLC.
16501  *
16502  * Originally Released Under LGPL - original licence link has changed is not relivant.
16503  *
16504  * Fork - LGPL
16505  * <script type="text/javascript">
16506  */
16507
16508 /**
16509  * @class Roo.data.JsonReader
16510  * @extends Roo.data.DataReader
16511  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
16512  * based on mappings in a provided Roo.data.Record constructor.
16513  * 
16514  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
16515  * in the reply previously. 
16516  * 
16517  * <p>
16518  * Example code:
16519  * <pre><code>
16520 var RecordDef = Roo.data.Record.create([
16521     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
16522     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
16523 ]);
16524 var myReader = new Roo.data.JsonReader({
16525     totalProperty: "results",    // The property which contains the total dataset size (optional)
16526     root: "rows",                // The property which contains an Array of row objects
16527     id: "id"                     // The property within each row object that provides an ID for the record (optional)
16528 }, RecordDef);
16529 </code></pre>
16530  * <p>
16531  * This would consume a JSON file like this:
16532  * <pre><code>
16533 { 'results': 2, 'rows': [
16534     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
16535     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
16536 }
16537 </code></pre>
16538  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
16539  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
16540  * paged from the remote server.
16541  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
16542  * @cfg {String} root name of the property which contains the Array of row objects.
16543  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
16544  * @cfg {Array} fields Array of field definition objects
16545  * @constructor
16546  * Create a new JsonReader
16547  * @param {Object} meta Metadata configuration options
16548  * @param {Object} recordType Either an Array of field definition objects,
16549  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
16550  */
16551 Roo.data.JsonReader = function(meta, recordType){
16552     
16553     meta = meta || {};
16554     // set some defaults:
16555     Roo.applyIf(meta, {
16556         totalProperty: 'total',
16557         successProperty : 'success',
16558         root : 'data',
16559         id : 'id'
16560     });
16561     
16562     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
16563 };
16564 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
16565     
16566     readerType : 'Json',
16567     
16568     /**
16569      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
16570      * Used by Store query builder to append _requestMeta to params.
16571      * 
16572      */
16573     metaFromRemote : false,
16574     /**
16575      * This method is only used by a DataProxy which has retrieved data from a remote server.
16576      * @param {Object} response The XHR object which contains the JSON data in its responseText.
16577      * @return {Object} data A data block which is used by an Roo.data.Store object as
16578      * a cache of Roo.data.Records.
16579      */
16580     read : function(response){
16581         var json = response.responseText;
16582        
16583         var o = /* eval:var:o */ eval("("+json+")");
16584         if(!o) {
16585             throw {message: "JsonReader.read: Json object not found"};
16586         }
16587         
16588         if(o.metaData){
16589             
16590             delete this.ef;
16591             this.metaFromRemote = true;
16592             this.meta = o.metaData;
16593             this.recordType = Roo.data.Record.create(o.metaData.fields);
16594             this.onMetaChange(this.meta, this.recordType, o);
16595         }
16596         return this.readRecords(o);
16597     },
16598
16599     // private function a store will implement
16600     onMetaChange : function(meta, recordType, o){
16601
16602     },
16603
16604     /**
16605          * @ignore
16606          */
16607     simpleAccess: function(obj, subsc) {
16608         return obj[subsc];
16609     },
16610
16611         /**
16612          * @ignore
16613          */
16614     getJsonAccessor: function(){
16615         var re = /[\[\.]/;
16616         return function(expr) {
16617             try {
16618                 return(re.test(expr))
16619                     ? new Function("obj", "return obj." + expr)
16620                     : function(obj){
16621                         return obj[expr];
16622                     };
16623             } catch(e){}
16624             return Roo.emptyFn;
16625         };
16626     }(),
16627
16628     /**
16629      * Create a data block containing Roo.data.Records from an XML document.
16630      * @param {Object} o An object which contains an Array of row objects in the property specified
16631      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
16632      * which contains the total size of the dataset.
16633      * @return {Object} data A data block which is used by an Roo.data.Store object as
16634      * a cache of Roo.data.Records.
16635      */
16636     readRecords : function(o){
16637         /**
16638          * After any data loads, the raw JSON data is available for further custom processing.
16639          * @type Object
16640          */
16641         this.o = o;
16642         var s = this.meta, Record = this.recordType,
16643             f = Record ? Record.prototype.fields : null, fi = f ? f.items : [], fl = f ? f.length : 0;
16644
16645 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
16646         if (!this.ef) {
16647             if(s.totalProperty) {
16648                     this.getTotal = this.getJsonAccessor(s.totalProperty);
16649                 }
16650                 if(s.successProperty) {
16651                     this.getSuccess = this.getJsonAccessor(s.successProperty);
16652                 }
16653                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
16654                 if (s.id) {
16655                         var g = this.getJsonAccessor(s.id);
16656                         this.getId = function(rec) {
16657                                 var r = g(rec);  
16658                                 return (r === undefined || r === "") ? null : r;
16659                         };
16660                 } else {
16661                         this.getId = function(){return null;};
16662                 }
16663             this.ef = [];
16664             for(var jj = 0; jj < fl; jj++){
16665                 f = fi[jj];
16666                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
16667                 this.ef[jj] = this.getJsonAccessor(map);
16668             }
16669         }
16670
16671         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
16672         if(s.totalProperty){
16673             var vt = parseInt(this.getTotal(o), 10);
16674             if(!isNaN(vt)){
16675                 totalRecords = vt;
16676             }
16677         }
16678         if(s.successProperty){
16679             var vs = this.getSuccess(o);
16680             if(vs === false || vs === 'false'){
16681                 success = false;
16682             }
16683         }
16684         var records = [];
16685         for(var i = 0; i < c; i++){
16686             var n = root[i];
16687             var values = {};
16688             var id = this.getId(n);
16689             for(var j = 0; j < fl; j++){
16690                 f = fi[j];
16691                                 var v = this.ef[j](n);
16692                                 if (!f.convert) {
16693                                         Roo.log('missing convert for ' + f.name);
16694                                         Roo.log(f);
16695                                         continue;
16696                                 }
16697                                 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
16698             }
16699                         if (!Record) {
16700                                 return {
16701                                         raw : { errorMsg : "JSON Reader Error: fields or metadata not available to create Record" },
16702                                         success : false,
16703                                         records : [],
16704                                         totalRecords : 0
16705                                 };
16706                         }
16707             var record = new Record(values, id);
16708             record.json = n;
16709             records[i] = record;
16710         }
16711         return {
16712             raw : o,
16713             success : success,
16714             records : records,
16715             totalRecords : totalRecords
16716         };
16717     },
16718     // used when loading children.. @see loadDataFromChildren
16719     toLoadData: function(rec)
16720     {
16721         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
16722         var data = typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
16723         return { data : data, total : data.length };
16724         
16725     }
16726 });/*
16727  * Based on:
16728  * Ext JS Library 1.1.1
16729  * Copyright(c) 2006-2007, Ext JS, LLC.
16730  *
16731  * Originally Released Under LGPL - original licence link has changed is not relivant.
16732  *
16733  * Fork - LGPL
16734  * <script type="text/javascript">
16735  */
16736
16737 /**
16738  * @class Roo.data.ArrayReader
16739  * @extends Roo.data.DataReader
16740  * Data reader class to create an Array of Roo.data.Record objects from an Array.
16741  * Each element of that Array represents a row of data fields. The
16742  * fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
16743  * of the field definition if it exists, or the field's ordinal position in the definition.<br>
16744  * <p>
16745  * Example code:.
16746  * <pre><code>
16747 var RecordDef = Roo.data.Record.create([
16748     {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
16749     {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
16750 ]);
16751 var myReader = new Roo.data.ArrayReader({
16752     id: 0                     // The subscript within row Array that provides an ID for the Record (optional)
16753 }, RecordDef);
16754 </code></pre>
16755  * <p>
16756  * This would consume an Array like this:
16757  * <pre><code>
16758 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
16759   </code></pre>
16760  
16761  * @constructor
16762  * Create a new JsonReader
16763  * @param {Object} meta Metadata configuration options.
16764  * @param {Object|Array} recordType Either an Array of field definition objects
16765  * 
16766  * @cfg {Array} fields Array of field definition objects
16767  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
16768  * as specified to {@link Roo.data.Record#create},
16769  * or an {@link Roo.data.Record} object
16770  *
16771  * 
16772  * created using {@link Roo.data.Record#create}.
16773  */
16774 Roo.data.ArrayReader = function(meta, recordType)
16775 {    
16776     Roo.data.ArrayReader.superclass.constructor.call(this, meta, recordType||meta.fields);
16777 };
16778
16779 Roo.extend(Roo.data.ArrayReader, Roo.data.JsonReader, {
16780     
16781       /**
16782      * Create a data block containing Roo.data.Records from an XML document.
16783      * @param {Object} o An Array of row objects which represents the dataset.
16784      * @return {Object} A data block which is used by an {@link Roo.data.Store} object as
16785      * a cache of Roo.data.Records.
16786      */
16787     readRecords : function(o)
16788     {
16789         var sid = this.meta ? this.meta.id : null;
16790         var recordType = this.recordType, fields = recordType.prototype.fields;
16791         var records = [];
16792         var root = o;
16793         for(var i = 0; i < root.length; i++){
16794             var n = root[i];
16795             var values = {};
16796             var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
16797             for(var j = 0, jlen = fields.length; j < jlen; j++){
16798                 var f = fields.items[j];
16799                 var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
16800                 var v = n[k] !== undefined ? n[k] : f.defaultValue;
16801                 v = f.convert(v);
16802                 values[f.name] = v;
16803             }
16804             var record = new recordType(values, id);
16805             record.json = n;
16806             records[records.length] = record;
16807         }
16808         return {
16809             records : records,
16810             totalRecords : records.length
16811         };
16812     },
16813     // used when loading children.. @see loadDataFromChildren
16814     toLoadData: function(rec)
16815     {
16816         // expect rec just to be an array.. eg [a,b,c, [...] << cn ]
16817         return typeof(rec.data.cn) == 'undefined' ? [] : rec.data.cn;
16818         
16819     }
16820     
16821     
16822 });/*
16823  * - LGPL
16824  * * 
16825  */
16826
16827 /**
16828  * @class Roo.bootstrap.form.ComboBox
16829  * @extends Roo.bootstrap.form.TriggerField
16830  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
16831  * @cfg {Boolean} append (true|false) default false
16832  * @cfg {Boolean} autoFocus (true|false) auto focus the first item, default true
16833  * @cfg {Boolean} tickable ComboBox with tickable selections (true|false), default false
16834  * @cfg {Boolean} triggerList trigger show the list or not (true|false) default true
16835  * @cfg {Boolean} showToggleBtn show toggle button or not (true|false) default true
16836  * @cfg {String} btnPosition set the position of the trigger button (left | right) default right
16837  * @cfg {Boolean} animate default true
16838  * @cfg {Boolean} emptyResultText only for touch device
16839  * @cfg {String} triggerText multiple combobox trigger button text default 'Select'
16840  * @cfg {String} emptyTitle default ''
16841  * @cfg {Number} width fixed with? experimental
16842  * @constructor
16843  * Create a new ComboBox.
16844  * @param {Object} config Configuration options
16845  */
16846 Roo.bootstrap.form.ComboBox = function(config){
16847     Roo.bootstrap.form.ComboBox.superclass.constructor.call(this, config);
16848     this.addEvents({
16849         /**
16850          * @event expand
16851          * Fires when the dropdown list is expanded
16852         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16853         */
16854         'expand' : true,
16855         /**
16856          * @event collapse
16857          * Fires when the dropdown list is collapsed
16858         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16859         */
16860         'collapse' : true,
16861         /**
16862          * @event beforeselect
16863          * Fires before a list item is selected. Return false to cancel the selection.
16864         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16865         * @param {Roo.data.Record} record The data record returned from the underlying store
16866         * @param {Number} index The index of the selected item in the dropdown list
16867         */
16868         'beforeselect' : true,
16869         /**
16870          * @event select
16871          * Fires when a list item is selected
16872         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16873         * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
16874         * @param {Number} index The index of the selected item in the dropdown list
16875         */
16876         'select' : true,
16877         /**
16878          * @event beforequery
16879          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
16880          * The event object passed has these properties:
16881         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16882         * @param {String} query The query
16883         * @param {Boolean} forceAll true to force "all" query
16884         * @param {Boolean} cancel true to cancel the query
16885         * @param {Object} e The query event object
16886         */
16887         'beforequery': true,
16888          /**
16889          * @event add
16890          * Fires when the 'add' icon is pressed (add a listener to enable add button)
16891         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16892         */
16893         'add' : true,
16894         /**
16895          * @event edit
16896          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
16897         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16898         * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
16899         */
16900         'edit' : true,
16901         /**
16902          * @event remove
16903          * Fires when the remove value from the combobox array
16904         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16905         */
16906         'remove' : true,
16907         /**
16908          * @event afterremove
16909          * Fires when the remove value from the combobox array
16910         * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16911         */
16912         'afterremove' : true,
16913         /**
16914          * @event specialfilter
16915          * Fires when specialfilter
16916             * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16917             */
16918         'specialfilter' : true,
16919         /**
16920          * @event tick
16921          * Fires when tick the element
16922             * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16923             */
16924         'tick' : true,
16925         /**
16926          * @event touchviewdisplay
16927          * Fires when touch view require special display (default is using displayField)
16928             * @param {Roo.bootstrap.form.ComboBox} combo This combo box
16929             * @param {Object} cfg set html .
16930             */
16931         'touchviewdisplay' : true
16932         
16933     });
16934     
16935     this.item = [];
16936     this.tickItems = [];
16937     
16938     this.selectedIndex = -1;
16939     if(this.mode == 'local'){
16940         if(config.queryDelay === undefined){
16941             this.queryDelay = 10;
16942         }
16943         if(config.minChars === undefined){
16944             this.minChars = 0;
16945         }
16946     }
16947 };
16948
16949 Roo.extend(Roo.bootstrap.form.ComboBox, Roo.bootstrap.form.TriggerField, {
16950      
16951     /**
16952      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
16953      * rendering into an Roo.Editor, defaults to false)
16954      */
16955     /**
16956      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
16957      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
16958      */
16959     /**
16960      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
16961      */
16962     /**
16963      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
16964      * the dropdown list (defaults to undefined, with no header element)
16965      */
16966
16967      /**
16968      * @cfg {String/Roo.Template} tpl The template to use to render the output default is  '<a class="dropdown-item" href="#">{' + this.displayField + '}</a>' 
16969      */
16970      
16971      /**
16972      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
16973      */
16974     listWidth: undefined,
16975     /**
16976      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
16977      * mode = 'remote' or 'text' if mode = 'local')
16978      */
16979     displayField: undefined,
16980     
16981     /**
16982      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
16983      * mode = 'remote' or 'value' if mode = 'local'). 
16984      * Note: use of a valueField requires the user make a selection
16985      * in order for a value to be mapped.
16986      */
16987     valueField: undefined,
16988     /**
16989      * @cfg {String} modalTitle The title of the dialog that pops up on mobile views.
16990      */
16991     modalTitle : '',
16992     
16993     /**
16994      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
16995      * field's data value (defaults to the underlying DOM element's name)
16996      */
16997     hiddenName: undefined,
16998     /**
16999      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
17000      */
17001     listClass: '',
17002     /**
17003      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
17004      */
17005     selectedClass: 'active',
17006     
17007     /**
17008      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
17009      */
17010     shadow:'sides',
17011     /**
17012      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
17013      * anchor positions (defaults to 'tl-bl')
17014      */
17015     listAlign: 'tl-bl?',
17016     /**
17017      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
17018      */
17019     maxHeight: 300,
17020     /**
17021      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
17022      * query specified by the allQuery config option (defaults to 'query')
17023      */
17024     triggerAction: 'query',
17025     /**
17026      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
17027      * (defaults to 4, does not apply if editable = false)
17028      */
17029     minChars : 4,
17030     /**
17031      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
17032      * delay (typeAheadDelay) if it matches a known value (defaults to false)
17033      */
17034     typeAhead: false,
17035     /**
17036      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
17037      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
17038      */
17039     queryDelay: 500,
17040     /**
17041      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
17042      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
17043      */
17044     pageSize: 0,
17045     /**
17046      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
17047      * when editable = true (defaults to false)
17048      */
17049     selectOnFocus:false,
17050     /**
17051      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
17052      */
17053     queryParam: 'query',
17054     /**
17055      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
17056      * when mode = 'remote' (defaults to 'Loading...')
17057      */
17058     loadingText: 'Loading...',
17059     /**
17060      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
17061      */
17062     resizable: false,
17063     /**
17064      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
17065      */
17066     handleHeight : 8,
17067     /**
17068      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
17069      * traditional select (defaults to true)
17070      */
17071     editable: true,
17072     /**
17073      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
17074      */
17075     allQuery: '',
17076     /**
17077      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
17078      */
17079     mode: 'remote',
17080     /**
17081      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
17082      * listWidth has a higher value)
17083      */
17084     minListWidth : 70,
17085     /**
17086      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
17087      * allow the user to set arbitrary text into the field (defaults to false)
17088      */
17089     forceSelection:false,
17090     /**
17091      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
17092      * if typeAhead = true (defaults to 250)
17093      */
17094     typeAheadDelay : 250,
17095     /**
17096      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
17097      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
17098      */
17099     valueNotFoundText : undefined,
17100     /**
17101      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
17102      */
17103     blockFocus : false,
17104     
17105     /**
17106      * @cfg {Boolean} disableClear Disable showing of clear button.
17107      */
17108     disableClear : false,
17109     /**
17110      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
17111      */
17112     alwaysQuery : false,
17113     
17114     /**
17115      * @cfg {Boolean} multiple  (true|false) ComboBobArray, default false
17116      */
17117     multiple : false,
17118     
17119     /**
17120      * @cfg {String} invalidClass DEPRICATED - uses BS4 is-valid now
17121      */
17122     invalidClass : "has-warning",
17123     
17124     /**
17125      * @cfg {String} validClass DEPRICATED - uses BS4 is-valid now
17126      */
17127     validClass : "has-success",
17128     
17129     /**
17130      * @cfg {Boolean} specialFilter (true|false) special filter default false
17131      */
17132     specialFilter : false,
17133     
17134     /**
17135      * @cfg {Boolean} mobileTouchView (true|false) show mobile touch view when using a mobile default true
17136      */
17137     mobileTouchView : true,
17138     
17139     /**
17140      * @cfg {Boolean} useNativeIOS (true|false) render it as classic select for ios, not support dynamic load data (default false)
17141      */
17142     useNativeIOS : false,
17143     
17144     /**
17145      * @cfg {Boolean} mobile_restrict_height (true|false) restrict height for touch view
17146      */
17147     mobile_restrict_height : false,
17148     
17149     ios_options : false,
17150     
17151     //private
17152     addicon : false,
17153     editicon: false,
17154     
17155     page: 0,
17156     hasQuery: false,
17157     append: false,
17158     loadNext: false,
17159     autoFocus : true,
17160     tickable : false,
17161     btnPosition : 'right',
17162     triggerList : true,
17163     showToggleBtn : true,
17164     animate : true,
17165     emptyResultText: 'Empty',
17166     triggerText : 'Select',
17167     emptyTitle : '',
17168     width : false,
17169     
17170     // element that contains real text value.. (when hidden is used..)
17171     
17172     getAutoCreate : function()
17173     {   
17174         var cfg = false;
17175         //render
17176         /*
17177          * Render classic select for iso
17178          */
17179         
17180         if(Roo.isIOS && this.useNativeIOS){
17181             cfg = this.getAutoCreateNativeIOS();
17182             return cfg;
17183         }
17184         
17185         /*
17186          * Touch Devices
17187          */
17188         
17189         if(Roo.isTouch && this.mobileTouchView){
17190             cfg = this.getAutoCreateTouchView();
17191             return cfg;;
17192         }
17193         
17194         /*
17195          *  Normal ComboBox
17196          */
17197         if(!this.tickable){
17198             cfg = Roo.bootstrap.form.ComboBox.superclass.getAutoCreate.call(this);
17199             return cfg;
17200         }
17201         
17202         /*
17203          *  ComboBox with tickable selections
17204          */
17205              
17206         var align = this.labelAlign || this.parentLabelAlign();
17207         
17208         cfg = {
17209             cls : 'form-group roo-combobox-tickable' //input-group
17210         };
17211         
17212         var btn_text_select = '';
17213         var btn_text_done = '';
17214         var btn_text_cancel = '';
17215         
17216         if (this.btn_text_show) {
17217             btn_text_select = 'Select';
17218             btn_text_done = 'Done';
17219             btn_text_cancel = 'Cancel'; 
17220         }
17221         
17222         var buttons = {
17223             tag : 'div',
17224             cls : 'tickable-buttons',
17225             cn : [
17226                 {
17227                     tag : 'button',
17228                     type : 'button',
17229                     cls : 'btn btn-link btn-edit pull-' + this.btnPosition,
17230                     //html : this.triggerText
17231                     html: btn_text_select
17232                 },
17233                 {
17234                     tag : 'button',
17235                     type : 'button',
17236                     name : 'ok',
17237                     cls : 'btn btn-link btn-ok pull-' + this.btnPosition,
17238                     //html : 'Done'
17239                     html: btn_text_done
17240                 },
17241                 {
17242                     tag : 'button',
17243                     type : 'button',
17244                     name : 'cancel',
17245                     cls : 'btn btn-link btn-cancel pull-' + this.btnPosition,
17246                     //html : 'Cancel'
17247                     html: btn_text_cancel
17248                 }
17249             ]
17250         };
17251         
17252         if(this.editable){
17253             buttons.cn.unshift({
17254                 tag: 'input',
17255                 cls: 'roo-select2-search-field-input'
17256             });
17257         }
17258         
17259         var _this = this;
17260         
17261         Roo.each(buttons.cn, function(c){
17262             if (_this.size) {
17263                 c.cls += ' btn-' + _this.size;
17264             }
17265
17266             if (_this.disabled) {
17267                 c.disabled = true;
17268             }
17269         });
17270         
17271         var box = {
17272             tag: 'div',
17273             style : 'display: contents',
17274             cn: [
17275                 {
17276                     tag: 'input',
17277                     type : 'hidden',
17278                     cls: 'form-hidden-field'
17279                 },
17280                 {
17281                     tag: 'ul',
17282                     cls: 'roo-select2-choices',
17283                     cn:[
17284                         {
17285                             tag: 'li',
17286                             cls: 'roo-select2-search-field',
17287                             cn: [
17288                                 buttons
17289                             ]
17290                         }
17291                     ]
17292                 }
17293             ]
17294         };
17295         
17296         var combobox = {
17297             cls: 'roo-select2-container input-group roo-select2-container-multi',
17298             cn: [
17299                 
17300                 box
17301 //                {
17302 //                    tag: 'ul',
17303 //                    cls: 'typeahead typeahead-long dropdown-menu',
17304 //                    style: 'display:none; max-height:' + this.maxHeight + 'px;'
17305 //                }
17306             ]
17307         };
17308         
17309         if(this.hasFeedback && !this.allowBlank){
17310             
17311             var feedback = {
17312                 tag: 'span',
17313                 cls: 'glyphicon form-control-feedback'
17314             };
17315
17316             combobox.cn.push(feedback);
17317         }
17318         
17319         
17320         
17321         var indicator = {
17322             tag : 'i',
17323             cls : 'roo-required-indicator ' + (this.indicatorpos == 'right'  ? 'right' : 'left') +'-indicator text-danger fa fa-lg fa-star',
17324             tooltip : 'This field is required'
17325         };
17326          
17327         if (this.allowBlank) {
17328             indicator = {
17329                 tag : 'i',
17330                 style : 'display:none'
17331             };
17332         } 
17333         if (align ==='left' && this.fieldLabel.length) {
17334             
17335             cfg.cls += ' roo-form-group-label-left'  + (Roo.bootstrap.version == 4 ? ' row' : '');
17336             
17337             cfg.cn = [
17338                 indicator,
17339                 {
17340                     tag: 'label',
17341                     'for' :  id,
17342                     cls : 'control-label col-form-label',
17343                     html : this.fieldLabel
17344
17345                 },
17346                 {
17347                     cls : "", 
17348                     cn: [
17349                         combobox
17350                     ]
17351                 }
17352
17353             ];
17354             
17355             var labelCfg = cfg.cn[1];
17356             var contentCfg = cfg.cn[2];
17357             
17358
17359             if(this.indicatorpos == 'right'){
17360                 
17361                 cfg.cn = [
17362                     {
17363                         tag: 'label',
17364                         'for' :  id,
17365                         cls : 'control-label col-form-label',
17366                         cn : [
17367                             {
17368                                 tag : 'span',
17369                                 html : this.fieldLabel
17370                             },
17371                             indicator
17372                         ]
17373                     },
17374                     {
17375                         cls : "",
17376                         cn: [
17377                             combobox
17378                         ]
17379                     }
17380
17381                 ];
17382                 
17383                 
17384                 
17385                 labelCfg = cfg.cn[0];
17386                 contentCfg = cfg.cn[1];
17387             
17388             }
17389             
17390             if(this.labelWidth > 12){
17391                 labelCfg.style = "width: " + this.labelWidth + 'px';
17392             }
17393             if(this.width * 1 > 0){
17394                 contentCfg.style = "width: " + this.width + 'px';
17395             }
17396             if(this.labelWidth < 13 && this.labelmd == 0){
17397                 this.labelmd = this.labelWidth;
17398             }
17399             
17400             if(this.labellg > 0){
17401                 labelCfg.cls += ' col-lg-' + this.labellg;
17402                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
17403             }
17404             
17405             if(this.labelmd > 0){
17406                 labelCfg.cls += ' col-md-' + this.labelmd;
17407                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
17408             }
17409             
17410             if(this.labelsm > 0){
17411                 labelCfg.cls += ' col-sm-' + this.labelsm;
17412                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
17413             }
17414             
17415             if(this.labelxs > 0){
17416                 labelCfg.cls += ' col-xs-' + this.labelxs;
17417                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
17418             }
17419                 
17420                 
17421         } else if ( this.fieldLabel.length) {
17422 //                Roo.log(" label");
17423                  cfg.cn = [
17424                    indicator,
17425                     {
17426                         tag: 'label',
17427                         //cls : 'input-group-addon',
17428                         html : this.fieldLabel
17429                     },
17430                     combobox
17431                 ];
17432                 
17433                 if(this.indicatorpos == 'right'){
17434                     cfg.cn = [
17435                         {
17436                             tag: 'label',
17437                             //cls : 'input-group-addon',
17438                             html : this.fieldLabel
17439                         },
17440                         indicator,
17441                         combobox
17442                     ];
17443                     
17444                 }
17445
17446         } else {
17447             
17448 //                Roo.log(" no label && no align");
17449                 cfg = combobox
17450                      
17451                 
17452         }
17453          
17454         var settings=this;
17455         ['xs','sm','md','lg'].map(function(size){
17456             if (settings[size]) {
17457                 cfg.cls += ' col-' + size + '-' + settings[size];
17458             }
17459         });
17460         
17461         return cfg;
17462         
17463     },
17464     
17465     _initEventsCalled : false,
17466     
17467     // private
17468     initEvents: function()
17469     {   
17470         if (this._initEventsCalled) { // as we call render... prevent looping...
17471             return;
17472         }
17473         this._initEventsCalled = true;
17474         
17475         if (!this.store) {
17476             throw "can not find store for combo";
17477         }
17478         
17479         this.indicator = this.indicatorEl();
17480         
17481         this.store = Roo.factory(this.store, Roo.data);
17482         this.store.parent = this;
17483         
17484         // if we are building from html. then this element is so complex, that we can not really
17485         // use the rendered HTML.
17486         // so we have to trash and replace the previous code.
17487         if (Roo.XComponent.build_from_html) {
17488             // remove this element....
17489             var e = this.el.dom, k=0;
17490             while (e ) { e = e.previousSibling;  ++k;}
17491
17492             this.el.remove();
17493             
17494             this.el=false;
17495             this.rendered = false;
17496             
17497             this.render(this.parent().getChildContainer(true), k);
17498         }
17499         
17500         if(Roo.isIOS && this.useNativeIOS){
17501             this.initIOSView();
17502             return;
17503         }
17504         
17505         /*
17506          * Touch Devices
17507          */
17508         
17509         if(Roo.isTouch && this.mobileTouchView){
17510             this.initTouchView();
17511             return;
17512         }
17513         
17514         if(this.tickable){
17515             this.initTickableEvents();
17516             return;
17517         }
17518         
17519         Roo.bootstrap.form.ComboBox.superclass.initEvents.call(this);
17520         
17521         if(this.hiddenName){
17522             
17523             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
17524             
17525             this.hiddenField.dom.value =
17526                 this.hiddenValue !== undefined ? this.hiddenValue :
17527                 this.value !== undefined ? this.value : '';
17528
17529             // prevent input submission
17530             this.el.dom.removeAttribute('name');
17531             this.hiddenField.dom.setAttribute('name', this.hiddenName);
17532              
17533              
17534         }
17535         //if(Roo.isGecko){
17536         //    this.el.dom.setAttribute('autocomplete', 'off');
17537         //}
17538         
17539         var cls = 'x-combo-list';
17540         
17541         //this.list = new Roo.Layer({
17542         //    shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
17543         //});
17544         
17545         var _this = this;
17546         
17547         (function(){
17548             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
17549             _this.list.setWidth(lw);
17550         }).defer(100);
17551         
17552         this.list.on('mouseover', this.onViewOver, this);
17553         this.list.on('mousemove', this.onViewMove, this);
17554         this.list.on('scroll', this.onViewScroll, this);
17555         
17556         /*
17557         this.list.swallowEvent('mousewheel');
17558         this.assetHeight = 0;
17559
17560         if(this.title){
17561             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
17562             this.assetHeight += this.header.getHeight();
17563         }
17564
17565         this.innerList = this.list.createChild({cls:cls+'-inner'});
17566         this.innerList.on('mouseover', this.onViewOver, this);
17567         this.innerList.on('mousemove', this.onViewMove, this);
17568         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
17569         
17570         if(this.allowBlank && !this.pageSize && !this.disableClear){
17571             this.footer = this.list.createChild({cls:cls+'-ft'});
17572             this.pageTb = new Roo.Toolbar(this.footer);
17573            
17574         }
17575         if(this.pageSize){
17576             this.footer = this.list.createChild({cls:cls+'-ft'});
17577             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
17578                     {pageSize: this.pageSize});
17579             
17580         }
17581         
17582         if (this.pageTb && this.allowBlank && !this.disableClear) {
17583             var _this = this;
17584             this.pageTb.add(new Roo.Toolbar.Fill(), {
17585                 cls: 'x-btn-icon x-btn-clear',
17586                 text: '&#160;',
17587                 handler: function()
17588                 {
17589                     _this.collapse();
17590                     _this.clearValue();
17591                     _this.onSelect(false, -1);
17592                 }
17593             });
17594         }
17595         if (this.footer) {
17596             this.assetHeight += this.footer.getHeight();
17597         }
17598         */
17599             
17600         if(!this.tpl){
17601             this.tpl = Roo.bootstrap.version == 4 ?
17602                 '<a class="dropdown-item" href="#">{' + this.displayField + '}</a>' :  // 4 does not need <li> and it get's really confisued.
17603                 '<li><a class="dropdown-item" href="#">{' + this.displayField + '}</a></li>';
17604         }
17605
17606         this.view = new Roo.View(this.list, this.tpl, {
17607             singleSelect:true, store: this.store, selectedClass: this.selectedClass
17608         });
17609         //this.view.wrapEl.setDisplayed(false);
17610         this.view.on('click', this.onViewClick, this);
17611         
17612         
17613         this.store.on('beforeload', this.onBeforeLoad, this);
17614         this.store.on('load', this.onLoad, this);
17615         this.store.on('loadexception', this.onLoadException, this);
17616         /*
17617         if(this.resizable){
17618             this.resizer = new Roo.Resizable(this.list,  {
17619                pinned:true, handles:'se'
17620             });
17621             this.resizer.on('resize', function(r, w, h){
17622                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
17623                 this.listWidth = w;
17624                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
17625                 this.restrictHeight();
17626             }, this);
17627             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
17628         }
17629         */
17630         if(!this.editable){
17631             this.editable = true;
17632             this.setEditable(false);
17633         }
17634         
17635         /*
17636         
17637         if (typeof(this.events.add.listeners) != 'undefined') {
17638             
17639             this.addicon = this.wrap.createChild(
17640                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
17641        
17642             this.addicon.on('click', function(e) {
17643                 this.fireEvent('add', this);
17644             }, this);
17645         }
17646         if (typeof(this.events.edit.listeners) != 'undefined') {
17647             
17648             this.editicon = this.wrap.createChild(
17649                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
17650             if (this.addicon) {
17651                 this.editicon.setStyle('margin-left', '40px');
17652             }
17653             this.editicon.on('click', function(e) {
17654                 
17655                 // we fire even  if inothing is selected..
17656                 this.fireEvent('edit', this, this.lastData );
17657                 
17658             }, this);
17659         }
17660         */
17661         
17662         this.keyNav = new Roo.KeyNav(this.inputEl(), {
17663             "up" : function(e){
17664                 this.inKeyMode = true;
17665                 this.selectPrev();
17666             },
17667
17668             "down" : function(e){
17669                 if(!this.isExpanded()){
17670                     this.onTriggerClick();
17671                 }else{
17672                     this.inKeyMode = true;
17673                     this.selectNext();
17674                 }
17675             },
17676
17677             "enter" : function(e){
17678 //                this.onViewClick();
17679                 //return true;
17680                 this.collapse();
17681                 
17682                 if(this.fireEvent("specialkey", this, e)){
17683                     this.onViewClick(false);
17684                 }
17685                 
17686                 return true;
17687             },
17688
17689             "esc" : function(e){
17690                 this.collapse();
17691             },
17692
17693             "tab" : function(e){
17694                 this.collapse();
17695                 
17696                 if(this.fireEvent("specialkey", this, e)){
17697                     this.onViewClick(false);
17698                 }
17699                 
17700                 return true;
17701             },
17702
17703             scope : this,
17704
17705             doRelay : function(foo, bar, hname){
17706                 if(hname == 'down' || this.scope.isExpanded()){
17707                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
17708                 }
17709                 return true;
17710             },
17711
17712             forceKeyDown: true
17713         });
17714         
17715         
17716         this.queryDelay = Math.max(this.queryDelay || 10,
17717                 this.mode == 'local' ? 10 : 250);
17718         
17719         
17720         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
17721         
17722         if(this.typeAhead){
17723             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
17724         }
17725         if(this.editable !== false){
17726             this.inputEl().on("keyup", this.onKeyUp, this);
17727         }
17728         if(this.forceSelection){
17729             this.inputEl().on('blur', this.doForce, this);
17730         }
17731         
17732         if(this.multiple){
17733             this.choices = this.el.select('ul.roo-select2-choices', true).first();
17734             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
17735         }
17736     },
17737     
17738     initTickableEvents: function()
17739     {   
17740         this.createList();
17741         
17742         if(this.hiddenName){
17743             
17744             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
17745             
17746             this.hiddenField.dom.value =
17747                 this.hiddenValue !== undefined ? this.hiddenValue :
17748                 this.value !== undefined ? this.value : '';
17749
17750             // prevent input submission
17751             this.el.dom.removeAttribute('name');
17752             this.hiddenField.dom.setAttribute('name', this.hiddenName);
17753              
17754              
17755         }
17756         
17757 //        this.list = this.el.select('ul.dropdown-menu',true).first();
17758         
17759         this.choices = this.el.select('ul.roo-select2-choices', true).first();
17760         this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
17761         if(this.triggerList){
17762             this.searchField.on("click", this.onSearchFieldClick, this, {preventDefault:true});
17763         }
17764          
17765         this.trigger = this.el.select('.tickable-buttons > .btn-edit', true).first();
17766         this.trigger.on("click", this.onTickableTriggerClick, this, {preventDefault:true});
17767         
17768         this.okBtn = this.el.select('.tickable-buttons > .btn-ok', true).first();
17769         this.cancelBtn = this.el.select('.tickable-buttons > .btn-cancel', true).first();
17770         
17771         this.okBtn.on('click', this.onTickableFooterButtonClick, this, this.okBtn);
17772         this.cancelBtn.on('click', this.onTickableFooterButtonClick, this, this.cancelBtn);
17773         
17774         this.trigger.setVisibilityMode(Roo.Element.DISPLAY);
17775         this.okBtn.setVisibilityMode(Roo.Element.DISPLAY);
17776         this.cancelBtn.setVisibilityMode(Roo.Element.DISPLAY);
17777         
17778         this.okBtn.hide();
17779         this.cancelBtn.hide();
17780         
17781         var _this = this;
17782         
17783         (function(){
17784             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
17785             _this.list.setWidth(lw);
17786         }).defer(100);
17787         
17788         this.list.on('mouseover', this.onViewOver, this);
17789         this.list.on('mousemove', this.onViewMove, this);
17790         
17791         this.list.on('scroll', this.onViewScroll, this);
17792         
17793         if(!this.tpl){
17794             this.tpl = '<li class="roo-select2-result"><div class="checkbox"><input id="{roo-id}"' + 
17795                 'type="checkbox" {roo-data-checked}><label for="{roo-id}"><b>{' + this.displayField + '}</b></label></div></li>';
17796         }
17797
17798         this.view = new Roo.View(this.list, this.tpl, {
17799             singleSelect:true,
17800             tickable:true,
17801             parent:this,
17802             store: this.store,
17803             selectedClass: this.selectedClass
17804         });
17805         
17806         //this.view.wrapEl.setDisplayed(false);
17807         this.view.on('click', this.onViewClick, this);
17808         
17809         
17810         
17811         this.store.on('beforeload', this.onBeforeLoad, this);
17812         this.store.on('load', this.onLoad, this);
17813         this.store.on('loadexception', this.onLoadException, this);
17814         
17815         if(this.editable){
17816             this.keyNav = new Roo.KeyNav(this.tickableInputEl(), {
17817                 "up" : function(e){
17818                     this.inKeyMode = true;
17819                     this.selectPrev();
17820                 },
17821
17822                 "down" : function(e){
17823                     this.inKeyMode = true;
17824                     this.selectNext();
17825                 },
17826
17827                 "enter" : function(e){
17828                     if(this.fireEvent("specialkey", this, e)){
17829                         this.onViewClick(false);
17830                     }
17831                     
17832                     return true;
17833                 },
17834
17835                 "esc" : function(e){
17836                     this.onTickableFooterButtonClick(e, false, false);
17837                 },
17838
17839                 "tab" : function(e){
17840                     this.fireEvent("specialkey", this, e);
17841                     
17842                     this.onTickableFooterButtonClick(e, false, false);
17843                     
17844                     return true;
17845                 },
17846
17847                 scope : this,
17848
17849                 doRelay : function(e, fn, key){
17850                     if(this.scope.isExpanded()){
17851                        return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
17852                     }
17853                     return true;
17854                 },
17855
17856                 forceKeyDown: true
17857             });
17858         }
17859         
17860         this.queryDelay = Math.max(this.queryDelay || 10,
17861                 this.mode == 'local' ? 10 : 250);
17862         
17863         
17864         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
17865         
17866         if(this.typeAhead){
17867             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
17868         }
17869         
17870         if(this.editable !== false){
17871             this.tickableInputEl().on("keyup", this.onKeyUp, this);
17872         }
17873         
17874         this.indicator = this.indicatorEl();
17875         
17876         if(this.indicator){
17877             this.indicator.setVisibilityMode(Roo.Element.DISPLAY);
17878             this.indicator.hide();
17879         }
17880         
17881     },
17882
17883     onDestroy : function(){
17884         if(this.view){
17885             this.view.setStore(null);
17886             this.view.el.removeAllListeners();
17887             this.view.el.remove();
17888             this.view.purgeListeners();
17889         }
17890         if(this.list){
17891             this.list.dom.innerHTML  = '';
17892         }
17893         
17894         if(this.store){
17895             this.store.un('beforeload', this.onBeforeLoad, this);
17896             this.store.un('load', this.onLoad, this);
17897             this.store.un('loadexception', this.onLoadException, this);
17898         }
17899         Roo.bootstrap.form.ComboBox.superclass.onDestroy.call(this);
17900     },
17901
17902     // private
17903     fireKey : function(e){
17904         if(e.isNavKeyPress() && !this.list.isVisible()){
17905             this.fireEvent("specialkey", this, e);
17906         }
17907     },
17908
17909     // private
17910     onResize: function(w, h)
17911     {
17912         
17913         
17914 //        Roo.bootstrap.form.ComboBox.superclass.onResize.apply(this, arguments);
17915 //        
17916 //        if(typeof w != 'number'){
17917 //            // we do not handle it!?!?
17918 //            return;
17919 //        }
17920 //        var tw = this.trigger.getWidth();
17921 //       // tw += this.addicon ? this.addicon.getWidth() : 0;
17922 //       // tw += this.editicon ? this.editicon.getWidth() : 0;
17923 //        var x = w - tw;
17924 //        this.inputEl().setWidth( this.adjustWidth('input', x));
17925 //            
17926 //        //this.trigger.setStyle('left', x+'px');
17927 //        
17928 //        if(this.list && this.listWidth === undefined){
17929 //            var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
17930 //            this.list.setWidth(lw);
17931 //            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
17932 //        }
17933         
17934     
17935         
17936     },
17937
17938     /**
17939      * Allow or prevent the user from directly editing the field text.  If false is passed,
17940      * the user will only be able to select from the items defined in the dropdown list.  This method
17941      * is the runtime equivalent of setting the 'editable' config option at config time.
17942      * @param {Boolean} value True to allow the user to directly edit the field text
17943      */
17944     setEditable : function(value){
17945         if(value == this.editable){
17946             return;
17947         }
17948         this.editable = value;
17949         if(!value){
17950             this.inputEl().dom.setAttribute('readOnly', true);
17951             this.inputEl().on('mousedown', this.onTriggerClick,  this);
17952             this.inputEl().addClass('x-combo-noedit');
17953         }else{
17954             this.inputEl().dom.removeAttribute('readOnly');
17955             this.inputEl().un('mousedown', this.onTriggerClick,  this);
17956             this.inputEl().removeClass('x-combo-noedit');
17957         }
17958     },
17959
17960     // private
17961     
17962     onBeforeLoad : function(combo,opts){
17963         if(!this.hasFocus){
17964             return;
17965         }
17966          if (!opts.add) {
17967             this.list.dom.innerHTML = '<li class="loading-indicator">'+(this.loadingText||'loading')+'</li>' ;
17968          }
17969         this.restrictHeight();
17970         this.selectedIndex = -1;
17971     },
17972
17973     // private
17974     onLoad : function(){
17975         
17976         this.hasQuery = false;
17977         
17978         if(!this.hasFocus){
17979             return;
17980         }
17981         
17982         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
17983             this.loading.hide();
17984         }
17985         
17986         if(this.store.getCount() > 0){
17987             
17988             this.expand();
17989             this.restrictHeight();
17990             if(this.lastQuery == this.allQuery){
17991                 if(this.editable && !this.tickable){
17992                     this.inputEl().dom.select();
17993                 }
17994                 
17995                 if(
17996                     !this.selectByValue(this.value, true) &&
17997                     this.autoFocus && 
17998                     (
17999                         !this.store.lastOptions ||
18000                         typeof(this.store.lastOptions.add) == 'undefined' || 
18001                         this.store.lastOptions.add != true
18002                     )
18003                 ){
18004                     this.select(0, true);
18005                 }
18006             }else{
18007                 if(this.autoFocus){
18008                     this.selectNext();
18009                 }
18010                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
18011                     this.taTask.delay(this.typeAheadDelay);
18012                 }
18013             }
18014         }else{
18015             this.onEmptyResults();
18016         }
18017         
18018         //this.el.focus();
18019     },
18020     // private
18021     onLoadException : function()
18022     {
18023         this.hasQuery = false;
18024         
18025         if(typeof(this.loading) !== 'undefined' && this.loading !== null){
18026             this.loading.hide();
18027         }
18028         
18029         if(this.tickable && this.editable){
18030             return;
18031         }
18032         
18033         this.collapse();
18034         // only causes errors at present
18035         //Roo.log(this.store.reader.jsonData);
18036         //if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
18037             // fixme
18038             //Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
18039         //}
18040         
18041         
18042     },
18043     // private
18044     onTypeAhead : function(){
18045         if(this.store.getCount() > 0){
18046             var r = this.store.getAt(0);
18047             var newValue = r.data[this.displayField];
18048             var len = newValue.length;
18049             var selStart = this.getRawValue().length;
18050             
18051             if(selStart != len){
18052                 this.setRawValue(newValue);
18053                 this.selectText(selStart, newValue.length);
18054             }
18055         }
18056     },
18057
18058     // private
18059     onSelect : function(record, index){
18060         
18061         if(this.fireEvent('beforeselect', this, record, index) !== false){
18062         
18063             this.setFromData(index > -1 ? record.data : false);
18064             
18065             this.collapse();
18066             this.fireEvent('select', this, record, index);
18067         }
18068     },
18069
18070     /**
18071      * Returns the currently selected field value or empty string if no value is set.
18072      * @return {String} value The selected value
18073      */
18074     getValue : function()
18075     {
18076         if(Roo.isIOS && this.useNativeIOS){
18077             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.valueField];
18078         }
18079         
18080         if(this.multiple){
18081             return (this.hiddenField) ? this.hiddenField.dom.value : this.value;
18082         }
18083         
18084         if(this.valueField){
18085             return typeof this.value != 'undefined' ? this.value : '';
18086         }else{
18087             return Roo.bootstrap.form.ComboBox.superclass.getValue.call(this);
18088         }
18089     },
18090     
18091     getRawValue : function()
18092     {
18093         if(Roo.isIOS && this.useNativeIOS){
18094             return this.ios_options[this.inputEl().dom.selectedIndex].data[this.displayField];
18095         }
18096         
18097         var v = this.inputEl().getValue();
18098         
18099         return v;
18100     },
18101
18102     /**
18103      * Clears any text/value currently set in the field
18104      */
18105     clearValue : function(){
18106         
18107         if(this.hiddenField){
18108             this.hiddenField.dom.value = '';
18109         }
18110         this.value = '';
18111         this.setRawValue('');
18112         this.lastSelectionText = '';
18113         this.lastData = false;
18114         
18115         var close = this.closeTriggerEl();
18116         
18117         if(close){
18118             close.hide();
18119         }
18120         
18121         this.validate();
18122         
18123     },
18124
18125     /**
18126      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
18127      * will be displayed in the field.  If the value does not match the data value of an existing item,
18128      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
18129      * Otherwise the field will be blank (although the value will still be set).
18130      * @param {String} value The value to match
18131      */
18132     setValue : function(v)
18133     {
18134         if(Roo.isIOS && this.useNativeIOS){
18135             this.setIOSValue(v);
18136             return;
18137         }
18138         
18139         if(this.multiple){
18140             this.syncValue();
18141             return;
18142         }
18143         
18144         var text = v;
18145         if(this.valueField){
18146             var r = this.findRecord(this.valueField, v);
18147             if(r){
18148                 text = r.data[this.displayField];
18149             }else if(this.valueNotFoundText !== undefined){
18150                 text = this.valueNotFoundText;
18151             }
18152         }
18153         this.lastSelectionText = text;
18154         if(this.hiddenField){
18155             this.hiddenField.dom.value = v;
18156         }
18157         Roo.bootstrap.form.ComboBox.superclass.setValue.call(this, text);
18158         this.value = v;
18159         
18160         var close = this.closeTriggerEl();
18161         
18162         if(close){
18163             (v && (v.length || v * 1 > 0)) ? close.show() : close.hide();
18164         }
18165         
18166         this.validate();
18167     },
18168     /**
18169      * @property {Object} the last set data for the element
18170      */
18171     
18172     lastData : false,
18173     /**
18174      * Sets the value of the field based on a object which is related to the record format for the store.
18175      * @param {Object} value the value to set as. or false on reset?
18176      */
18177     setFromData : function(o){
18178         
18179         if(this.multiple){
18180             this.addItem(o);
18181             return;
18182         }
18183             
18184         var dv = ''; // display value
18185         var vv = ''; // value value..
18186         this.lastData = o;
18187         if (this.displayField) {
18188             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
18189         } else {
18190             // this is an error condition!!!
18191             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
18192         }
18193         
18194         if(this.valueField){
18195             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
18196         }
18197         
18198         var close = this.closeTriggerEl();
18199         
18200         if(close){
18201             if(dv.length || vv * 1 > 0){
18202                 close.show() ;
18203                 this.blockFocus=true;
18204             } else {
18205                 close.hide();
18206             }             
18207         }
18208         
18209         if(this.hiddenField){
18210             this.hiddenField.dom.value = vv;
18211             
18212             this.lastSelectionText = dv;
18213             Roo.bootstrap.form.ComboBox.superclass.setValue.call(this, dv);
18214             this.value = vv;
18215             return;
18216         }
18217         // no hidden field.. - we store the value in 'value', but still display
18218         // display field!!!!
18219         this.lastSelectionText = dv;
18220         Roo.bootstrap.form.ComboBox.superclass.setValue.call(this, dv);
18221         this.value = vv;
18222         
18223         
18224         
18225     },
18226     // private
18227     reset : function(){
18228         // overridden so that last data is reset..
18229         
18230         if(this.multiple){
18231             this.clearItem();
18232             return;
18233         }
18234         
18235         this.setValue(this.originalValue);
18236         //this.clearInvalid();
18237         this.lastData = false;
18238         if (this.view) {
18239             this.view.clearSelections();
18240         }
18241         
18242         this.validate();
18243     },
18244     // private
18245     findRecord : function(prop, value){
18246         var record;
18247         if(this.store.getCount() > 0){
18248             this.store.each(function(r){
18249                 if(r.data[prop] == value){
18250                     record = r;
18251                     return false;
18252                 }
18253                 return true;
18254             });
18255         }
18256         return record;
18257     },
18258     
18259     getName: function()
18260     {
18261         // returns hidden if it's set..
18262         if (!this.rendered) {return ''};
18263         return !this.hiddenName && this.inputEl().dom.name  ? this.inputEl().dom.name : (this.hiddenName || '');
18264         
18265     },
18266     // private
18267     onViewMove : function(e, t){
18268         this.inKeyMode = false;
18269     },
18270
18271     // private
18272     onViewOver : function(e, t){
18273         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
18274             return;
18275         }
18276         var item = this.view.findItemFromChild(t);
18277         
18278         if(item){
18279             var index = this.view.indexOf(item);
18280             this.select(index, false);
18281         }
18282     },
18283
18284     // private
18285     onViewClick : function(view, doFocus, el, e)
18286     {
18287         var index = this.view.getSelectedIndexes()[0];
18288         
18289         var r = this.store.getAt(index);
18290         
18291         if(this.tickable){
18292             
18293             if(typeof(e) != 'undefined' && e.getTarget().nodeName.toLowerCase() != 'input'){
18294                 return;
18295             }
18296             
18297             var rm = false;
18298             var _this = this;
18299             
18300             Roo.each(this.tickItems, function(v,k){
18301                 
18302                 if(typeof(v) != 'undefined' && v[_this.valueField] == r.data[_this.valueField]){
18303                     Roo.log(v);
18304                     _this.tickItems.splice(k, 1);
18305                     
18306                     if(typeof(e) == 'undefined' && view == false){
18307                         Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = false;
18308                     }
18309                     
18310                     rm = true;
18311                     return;
18312                 }
18313             });
18314             
18315             if(rm){
18316                 return;
18317             }
18318             
18319             if(this.fireEvent('tick', this, r, index, Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked) !== false){
18320                 this.tickItems.push(r.data);
18321             }
18322             
18323             if(typeof(e) == 'undefined' && view == false){
18324                 Roo.get(_this.view.getNodes(index, index)[0]).select('input', true).first().dom.checked = true;
18325             }
18326                     
18327             return;
18328         }
18329         
18330         if(r){
18331             this.onSelect(r, index);
18332         }
18333         if(doFocus !== false && !this.blockFocus){
18334             this.inputEl().focus();
18335         }
18336     },
18337
18338     // private
18339     restrictHeight : function(){
18340         //this.innerList.dom.style.height = '';
18341         //var inner = this.innerList.dom;
18342         //var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
18343         //this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
18344         //this.list.beginUpdate();
18345         //this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
18346         this.list.alignTo(this.inputEl(), this.listAlign);
18347         this.list.alignTo(this.inputEl(), this.listAlign);
18348         //this.list.endUpdate();
18349     },
18350
18351     // private
18352     onEmptyResults : function(){
18353         
18354         if(this.tickable && this.editable){
18355             this.hasFocus = false;
18356             this.restrictHeight();
18357             return;
18358         }
18359         
18360         this.collapse();
18361     },
18362
18363     /**
18364      * Returns true if the dropdown list is expanded, else false.
18365      */
18366     isExpanded : function(){
18367         return this.list.isVisible();
18368     },
18369
18370     /**
18371      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
18372      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
18373      * @param {String} value The data value of the item to select
18374      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
18375      * selected item if it is not currently in view (defaults to true)
18376      * @return {Boolean} True if the value matched an item in the list, else false
18377      */
18378     selectByValue : function(v, scrollIntoView){
18379         if(v !== undefined && v !== null){
18380             var r = this.findRecord(this.valueField || this.displayField, v);
18381             if(r){
18382                 this.select(this.store.indexOf(r), scrollIntoView);
18383                 return true;
18384             }
18385         }
18386         return false;
18387     },
18388
18389     /**
18390      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
18391      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
18392      * @param {Number} index The zero-based index of the list item to select
18393      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
18394      * selected item if it is not currently in view (defaults to true)
18395      */
18396     select : function(index, scrollIntoView){
18397         this.selectedIndex = index;
18398         this.view.select(index);
18399         if(scrollIntoView !== false){
18400             var el = this.view.getNode(index);
18401             /*
18402              * el && !this.multiple && !this.tickable // not sure why we disable multiple before..
18403              */
18404             if(el){
18405                 this.list.scrollChildIntoView(el, false);
18406             }
18407         }
18408     },
18409
18410     // private
18411     selectNext : function(){
18412         var ct = this.store.getCount();
18413         if(ct > 0){
18414             if(this.selectedIndex == -1){
18415                 this.select(0);
18416             }else if(this.selectedIndex < ct-1){
18417                 this.select(this.selectedIndex+1);
18418             }
18419         }
18420     },
18421
18422     // private
18423     selectPrev : function(){
18424         var ct = this.store.getCount();
18425         if(ct > 0){
18426             if(this.selectedIndex == -1){
18427                 this.select(0);
18428             }else if(this.selectedIndex != 0){
18429                 this.select(this.selectedIndex-1);
18430             }
18431         }
18432     },
18433
18434     // private
18435     onKeyUp : function(e){
18436         if(this.editable !== false && !e.isSpecialKey()){
18437             this.lastKey = e.getKey();
18438             this.dqTask.delay(this.queryDelay);
18439         }
18440     },
18441
18442     // private
18443     validateBlur : function(){
18444         return !this.list || !this.list.isVisible();   
18445     },
18446
18447     // private
18448     initQuery : function(){
18449         
18450         var v = this.getRawValue();
18451         
18452         if(this.tickable && this.editable){
18453             v = this.tickableInputEl().getValue();
18454         }
18455         
18456         this.doQuery(v);
18457     },
18458
18459     // private
18460     doForce : function(){
18461         if(this.inputEl().dom.value.length > 0){
18462             this.inputEl().dom.value =
18463                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
18464              
18465         }
18466     },
18467
18468     /**
18469      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
18470      * query allowing the query action to be canceled if needed.
18471      * @param {String} query The SQL query to execute
18472      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
18473      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
18474      * saved in the current store (defaults to false)
18475      */
18476     doQuery : function(q, forceAll){
18477         
18478         if(q === undefined || q === null){
18479             q = '';
18480         }
18481         var qe = {
18482             query: q,
18483             forceAll: forceAll,
18484             combo: this,
18485             cancel:false
18486         };
18487         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
18488             return false;
18489         }
18490         q = qe.query;
18491         
18492         forceAll = qe.forceAll;
18493         if(forceAll === true || (q.length >= this.minChars)){
18494             
18495             this.hasQuery = true;
18496             
18497             if(this.lastQuery != q || this.alwaysQuery){
18498                 this.lastQuery = q;
18499                 if(this.mode == 'local'){
18500                     this.selectedIndex = -1;
18501                     if(forceAll){
18502                         this.store.clearFilter();
18503                     }else{
18504                         
18505                         if(this.specialFilter){
18506                             this.fireEvent('specialfilter', this);
18507                             this.onLoad();
18508                             return;
18509                         }
18510                         
18511                         this.store.filter(this.displayField, q);
18512                     }
18513                     
18514                     this.store.fireEvent("datachanged", this.store);
18515                     
18516                     this.onLoad();
18517                     
18518                     
18519                 }else{
18520                     
18521                     this.store.baseParams[this.queryParam] = q;
18522                     
18523                     var options = {params : this.getParams(q)};
18524                     
18525                     if(this.loadNext){
18526                         options.add = true;
18527                         options.params.start = this.page * this.pageSize;
18528                     }
18529                     
18530                     this.store.load(options);
18531                     
18532                     /*
18533                      *  this code will make the page width larger, at the beginning, the list not align correctly, 
18534                      *  we should expand the list on onLoad
18535                      *  so command out it
18536                      */
18537 //                    this.expand();
18538                 }
18539             }else{
18540                 this.selectedIndex = -1;
18541                 this.onLoad();   
18542             }
18543         }
18544         
18545         this.loadNext = false;
18546     },
18547     
18548     // private
18549     getParams : function(q){
18550         var p = {};
18551         //p[this.queryParam] = q;
18552         
18553         if(this.pageSize){
18554             p.start = 0;
18555             p.limit = this.pageSize;
18556         }
18557         return p;
18558     },
18559
18560     /**
18561      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
18562      */
18563     collapse : function(){
18564         if(!this.isExpanded()){
18565             return;
18566         }
18567         
18568         this.list.hide();
18569         
18570         this.hasFocus = false;
18571         
18572         if(this.tickable){
18573             this.okBtn.hide();
18574             this.cancelBtn.hide();
18575             this.trigger.show();
18576             
18577             if(this.editable){
18578                 this.tickableInputEl().dom.value = '';
18579                 this.tickableInputEl().blur();
18580             }
18581             
18582         }
18583         
18584         Roo.get(document).un('mousedown', this.collapseIf, this);
18585         Roo.get(document).un('mousewheel', this.collapseIf, this);
18586         if (!this.editable) {
18587             Roo.get(document).un('keydown', this.listKeyPress, this);
18588         }
18589         this.fireEvent('collapse', this);
18590         
18591         this.validate();
18592     },
18593
18594     // private
18595     collapseIf : function(e){
18596         var in_combo  = e.within(this.el);
18597         var in_list =  e.within(this.list);
18598         var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
18599         
18600         if (in_combo || in_list || is_list) {
18601             //e.stopPropagation();
18602             return;
18603         }
18604         
18605         if(this.tickable){
18606             this.onTickableFooterButtonClick(e, false, false);
18607         }
18608
18609         this.collapse();
18610         
18611     },
18612
18613     /**
18614      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
18615      */
18616     expand : function(){
18617        
18618         if(this.isExpanded() || !this.hasFocus){
18619             return;
18620         }
18621         
18622         var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
18623         this.list.setWidth(lw);
18624         
18625         Roo.log('expand');
18626         
18627         this.list.show();
18628         
18629         this.restrictHeight();
18630         
18631         if(this.tickable){
18632             
18633             this.tickItems = Roo.apply([], this.item);
18634             
18635             this.okBtn.show();
18636             this.cancelBtn.show();
18637             this.trigger.hide();
18638             
18639             if(this.editable){
18640                 this.tickableInputEl().focus();
18641             }
18642             
18643         }
18644         
18645         Roo.get(document).on('mousedown', this.collapseIf, this);
18646         Roo.get(document).on('mousewheel', this.collapseIf, this);
18647         if (!this.editable) {
18648             Roo.get(document).on('keydown', this.listKeyPress, this);
18649         }
18650         
18651         this.fireEvent('expand', this);
18652     },
18653
18654     // private
18655     // Implements the default empty TriggerField.onTriggerClick function
18656     onTriggerClick : function(e)
18657     {
18658         Roo.log('trigger click');
18659         
18660         if(this.disabled || !this.triggerList){
18661             return;
18662         }
18663         
18664         this.page = 0;
18665         this.loadNext = false;
18666         
18667         if(this.isExpanded()){
18668             this.collapse();
18669             if (!this.blockFocus) {
18670                 this.inputEl().focus();
18671             }
18672             
18673         }else {
18674             this.hasFocus = true;
18675             if(this.triggerAction == 'all') {
18676                 this.doQuery(this.allQuery, true);
18677             } else {
18678                 this.doQuery(this.getRawValue());
18679             }
18680             if (!this.blockFocus) {
18681                 this.inputEl().focus();
18682             }
18683         }
18684     },
18685     
18686     onTickableTriggerClick : function(e)
18687     {
18688         if(this.disabled){
18689             return;
18690         }
18691         
18692         this.page = 0;
18693         this.loadNext = false;
18694         this.hasFocus = true;
18695         
18696         if(this.triggerAction == 'all') {
18697             this.doQuery(this.allQuery, true);
18698         } else {
18699             this.doQuery(this.getRawValue());
18700         }
18701     },
18702     
18703     onSearchFieldClick : function(e)
18704     {
18705         if(this.hasFocus && !this.disabled && e.getTarget().nodeName.toLowerCase() != 'button'){
18706             this.onTickableFooterButtonClick(e, false, false);
18707             return;
18708         }
18709         
18710         if(this.hasFocus || this.disabled || e.getTarget().nodeName.toLowerCase() == 'button'){
18711             return;
18712         }
18713         
18714         this.page = 0;
18715         this.loadNext = false;
18716         this.hasFocus = true;
18717         
18718         if(this.triggerAction == 'all') {
18719             this.doQuery(this.allQuery, true);
18720         } else {
18721             this.doQuery(this.getRawValue());
18722         }
18723     },
18724     
18725     listKeyPress : function(e)
18726     {
18727         //Roo.log('listkeypress');
18728         // scroll to first matching element based on key pres..
18729         if (e.isSpecialKey()) {
18730             return false;
18731         }
18732         var k = String.fromCharCode(e.getKey()).toUpperCase();
18733         //Roo.log(k);
18734         var match  = false;
18735         var csel = this.view.getSelectedNodes();
18736         var cselitem = false;
18737         if (csel.length) {
18738             var ix = this.view.indexOf(csel[0]);
18739             cselitem  = this.store.getAt(ix);
18740             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
18741                 cselitem = false;
18742             }
18743             
18744         }
18745         
18746         this.store.each(function(v) { 
18747             if (cselitem) {
18748                 // start at existing selection.
18749                 if (cselitem.id == v.id) {
18750                     cselitem = false;
18751                 }
18752                 return true;
18753             }
18754                 
18755             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
18756                 match = this.store.indexOf(v);
18757                 return false;
18758             }
18759             return true;
18760         }, this);
18761         
18762         if (match === false) {
18763             return true; // no more action?
18764         }
18765         // scroll to?
18766         this.view.select(match);
18767         var sn = Roo.get(this.view.getSelectedNodes()[0]);
18768         sn.scrollIntoView(sn.dom.parentNode, false);
18769     },
18770     
18771     onViewScroll : function(e, t){
18772         
18773         if(this.view.el.getScroll().top == 0 ||this.view.el.getScroll().top < this.view.el.dom.scrollHeight - this.view.el.dom.clientHeight || !this.hasFocus || !this.append || this.hasQuery){
18774             return;
18775         }
18776         
18777         this.hasQuery = true;
18778         
18779         this.loading = this.list.select('.loading', true).first();
18780         
18781         if(this.loading === null){
18782             this.list.createChild({
18783                 tag: 'div',
18784                 cls: 'loading roo-select2-more-results roo-select2-active',
18785                 html: 'Loading more results...'
18786             });
18787             
18788             this.loading = this.list.select('.loading', true).first();
18789             
18790             this.loading.setVisibilityMode(Roo.Element.DISPLAY);
18791             
18792             this.loading.hide();
18793         }
18794         
18795         this.loading.show();
18796         
18797         var _combo = this;
18798         
18799         this.page++;
18800         this.loadNext = true;
18801         
18802         (function() { _combo.doQuery(_combo.allQuery, true); }).defer(500);
18803         
18804         return;
18805     },
18806     
18807     addItem : function(o)
18808     {   
18809         var dv = ''; // display value
18810         
18811         if (this.displayField) {
18812             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
18813         } else {
18814             // this is an error condition!!!
18815             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
18816         }
18817         
18818         if(!dv.length){
18819             return;
18820         }
18821         
18822         var choice = this.choices.createChild({
18823             tag: 'li',
18824             cls: 'roo-select2-search-choice',
18825             cn: [
18826                 {
18827                     tag: 'div',
18828                     html: dv
18829                 },
18830                 {
18831                     tag: 'a',
18832                     href: '#',
18833                     cls: 'roo-select2-search-choice-close fa fa-times',
18834                     tabindex: '-1'
18835                 }
18836             ]
18837             
18838         }, this.searchField);
18839         
18840         var close = choice.select('a.roo-select2-search-choice-close', true).first();
18841         
18842         close.on('click', this.onRemoveItem, this, { item : choice, data : o} );
18843         
18844         this.item.push(o);
18845         
18846         this.lastData = o;
18847         
18848         this.syncValue();
18849         
18850         this.inputEl().dom.value = '';
18851         
18852         this.validate();
18853     },
18854     
18855     onRemoveItem : function(e, _self, o)
18856     {
18857         e.preventDefault();
18858         
18859         this.lastItem = Roo.apply([], this.item);
18860         
18861         var index = this.item.indexOf(o.data) * 1;
18862         
18863         if( index < 0){
18864             Roo.log('not this item?!');
18865             return;
18866         }
18867         
18868         this.item.splice(index, 1);
18869         o.item.remove();
18870         
18871         this.syncValue();
18872         
18873         this.fireEvent('remove', this, e);
18874         
18875         this.validate();
18876         
18877     },
18878     
18879     syncValue : function()
18880     {
18881         if(!this.item.length){
18882             this.clearValue();
18883             return;
18884         }
18885             
18886         var value = [];
18887         var _this = this;
18888         Roo.each(this.item, function(i){
18889             if(_this.valueField){
18890                 value.push(i[_this.valueField]);
18891                 return;
18892             }
18893
18894             value.push(i);
18895         });
18896
18897         this.value = value.join(',');
18898
18899         if(this.hiddenField){
18900             this.hiddenField.dom.value = this.value;
18901         }
18902         
18903         this.store.fireEvent("datachanged", this.store);
18904         
18905         this.validate();
18906     },
18907     
18908     clearItem : function()
18909     {
18910         if(!this.multiple){
18911             return;
18912         }
18913         
18914         this.item = [];
18915         
18916         Roo.each(this.choices.select('>li.roo-select2-search-choice', true).elements, function(c){
18917            c.remove();
18918         });
18919         
18920         this.syncValue();
18921         
18922         this.validate();
18923         
18924         if(this.tickable && !Roo.isTouch){
18925             this.view.refresh();
18926         }
18927     },
18928     
18929     inputEl: function ()
18930     {
18931         if(Roo.isIOS && this.useNativeIOS){
18932             return this.el.select('select.roo-ios-select', true).first();
18933         }
18934         
18935         if(Roo.isTouch && this.mobileTouchView){
18936             return this.el.select('input.form-control',true).first();
18937         }
18938         
18939         if(this.tickable){
18940             return this.searchField;
18941         }
18942         
18943         return this.el.select('input.form-control',true).first();
18944     },
18945     
18946     onTickableFooterButtonClick : function(e, btn, el)
18947     {
18948         e.preventDefault();
18949         
18950         this.lastItem = Roo.apply([], this.item);
18951         
18952         if(btn && btn.name == 'cancel'){
18953             this.tickItems = Roo.apply([], this.item);
18954             this.collapse();
18955             return;
18956         }
18957         
18958         this.clearItem();
18959         
18960         var _this = this;
18961         
18962         Roo.each(this.tickItems, function(o){
18963             _this.addItem(o);
18964         });
18965         
18966         this.collapse();
18967         
18968     },
18969     
18970     validate : function()
18971     {
18972         if(this.getVisibilityEl().hasClass('hidden')){
18973             return true;
18974         }
18975         
18976         var v = this.getRawValue();
18977         
18978         if(this.multiple){
18979             v = this.getValue();
18980         }
18981         
18982         if(this.disabled || this.allowBlank || v.length){
18983             this.markValid();
18984             return true;
18985         }
18986         
18987         this.markInvalid();
18988         return false;
18989     },
18990     
18991     tickableInputEl : function()
18992     {
18993         if(!this.tickable || !this.editable){
18994             return this.inputEl();
18995         }
18996         
18997         return this.inputEl().select('.roo-select2-search-field-input', true).first();
18998     },
18999     
19000     
19001     getAutoCreateTouchView : function()
19002     {
19003         var id = Roo.id();
19004         
19005         var cfg = {
19006             cls: 'form-group' //input-group
19007         };
19008         
19009         var input =  {
19010             tag: 'input',
19011             id : id,
19012             type : this.inputType,
19013             cls : 'form-control x-combo-noedit',
19014             autocomplete: 'new-password',
19015             placeholder : this.placeholder || '',
19016             readonly : true
19017         };
19018         
19019         if (this.name) {
19020             input.name = this.name;
19021         }
19022         
19023         if (this.size) {
19024             input.cls += ' input-' + this.size;
19025         }
19026         
19027         if (this.disabled) {
19028             input.disabled = true;
19029         }
19030         
19031         var inputblock = {
19032             cls : 'roo-combobox-wrap',
19033             cn : [
19034                 input
19035             ]
19036         };
19037         
19038         if(this.before){
19039             inputblock.cls += ' input-group';
19040             
19041             inputblock.cn.unshift({
19042                 tag :'span',
19043                 cls : 'input-group-addon input-group-prepend input-group-text',
19044                 html : this.before
19045             });
19046         }
19047         
19048         if(this.removable && !this.multiple){
19049             inputblock.cls += ' roo-removable';
19050             
19051             inputblock.cn.push({
19052                 tag: 'button',
19053                 html : 'x',
19054                 cls : 'roo-combo-removable-btn close'
19055             });
19056         }
19057
19058         if(this.hasFeedback && !this.allowBlank){
19059             
19060             inputblock.cls += ' has-feedback';
19061             
19062             inputblock.cn.push({
19063                 tag: 'span',
19064                 cls: 'glyphicon form-control-feedback'
19065             });
19066             
19067         }
19068         
19069         if (this.after) {
19070             
19071             inputblock.cls += (this.before) ? '' : ' input-group';
19072             
19073             inputblock.cn.push({
19074                 tag :'span',
19075                 cls : 'input-group-addon input-group-append input-group-text',
19076                 html : this.after
19077             });
19078         }
19079
19080         
19081         var ibwrap = inputblock;
19082         
19083         if(this.multiple){
19084             ibwrap = {
19085                 tag: 'ul',
19086                 cls: 'roo-select2-choices',
19087                 cn:[
19088                     {
19089                         tag: 'li',
19090                         cls: 'roo-select2-search-field',
19091                         cn: [
19092
19093                             inputblock
19094                         ]
19095                     }
19096                 ]
19097             };
19098         
19099             
19100         }
19101         
19102         var combobox = {
19103             cls: 'roo-select2-container input-group roo-touchview-combobox ',
19104             cn: [
19105                 {
19106                     tag: 'input',
19107                     type : 'hidden',
19108                     cls: 'form-hidden-field'
19109                 },
19110                 ibwrap
19111             ]
19112         };
19113         
19114         if(!this.multiple && this.showToggleBtn){
19115             
19116             var caret = {
19117                 cls: 'caret'
19118             };
19119             
19120             if (this.caret != false) {
19121                 caret = {
19122                      tag: 'i',
19123                      cls: 'fa fa-' + this.caret
19124                 };
19125                 
19126             }
19127             
19128             combobox.cn.push({
19129                 tag :'span',
19130                 cls : 'input-group-addon input-group-append input-group-text btn dropdown-toggle',
19131                 cn : [
19132                     Roo.bootstrap.version == 3 ? caret : '',
19133                     {
19134                         tag: 'span',
19135                         cls: 'combobox-clear',
19136                         cn  : [
19137                             {
19138                                 tag : 'i',
19139                                 cls: 'icon-remove'
19140                             }
19141                         ]
19142                     }
19143                 ]
19144
19145             })
19146         }
19147         
19148         if(this.multiple){
19149             combobox.cls += ' roo-select2-container-multi';
19150         }
19151         
19152         var required =  this.allowBlank ?  {
19153                     tag : 'i',
19154                     style: 'display: none'
19155                 } : {
19156                    tag : 'i',
19157                    cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
19158                    tooltip : 'This field is required'
19159                 };
19160         
19161         var align = this.labelAlign || this.parentLabelAlign();
19162         
19163         if (align ==='left' && this.fieldLabel.length) {
19164
19165             cfg.cn = [
19166                 required,
19167                 {
19168                     tag: 'label',
19169                     cls : 'control-label col-form-label',
19170                     html : this.fieldLabel
19171
19172                 },
19173                 {
19174                     cls : 'roo-combobox-wrap ', 
19175                     cn: [
19176                         combobox
19177                     ]
19178                 }
19179             ];
19180             
19181             var labelCfg = cfg.cn[1];
19182             var contentCfg = cfg.cn[2];
19183             
19184
19185             if(this.indicatorpos == 'right'){
19186                 cfg.cn = [
19187                     {
19188                         tag: 'label',
19189                         'for' :  id,
19190                         cls : 'control-label col-form-label',
19191                         cn : [
19192                             {
19193                                 tag : 'span',
19194                                 html : this.fieldLabel
19195                             },
19196                             required
19197                         ]
19198                     },
19199                     {
19200                         cls : "roo-combobox-wrap ",
19201                         cn: [
19202                             combobox
19203                         ]
19204                     }
19205
19206                 ];
19207                 
19208                 labelCfg = cfg.cn[0];
19209                 contentCfg = cfg.cn[1];
19210             }
19211             
19212            
19213             
19214             if(this.labelWidth > 12){
19215                 labelCfg.style = "width: " + this.labelWidth + 'px';
19216             }
19217            
19218             if(this.labelWidth < 13 && this.labelmd == 0){
19219                 this.labelmd = this.labelWidth;
19220             }
19221             
19222             if(this.labellg > 0){
19223                 labelCfg.cls += ' col-lg-' + this.labellg;
19224                 contentCfg.cls += ' col-lg-' + (12 - this.labellg);
19225             }
19226             
19227             if(this.labelmd > 0){
19228                 labelCfg.cls += ' col-md-' + this.labelmd;
19229                 contentCfg.cls += ' col-md-' + (12 - this.labelmd);
19230             }
19231             
19232             if(this.labelsm > 0){
19233                 labelCfg.cls += ' col-sm-' + this.labelsm;
19234                 contentCfg.cls += ' col-sm-' + (12 - this.labelsm);
19235             }
19236             
19237             if(this.labelxs > 0){
19238                 labelCfg.cls += ' col-xs-' + this.labelxs;
19239                 contentCfg.cls += ' col-xs-' + (12 - this.labelxs);
19240             }
19241                 
19242                 
19243         } else if ( this.fieldLabel.length) {
19244             cfg.cn = [
19245                required,
19246                 {
19247                     tag: 'label',
19248                     cls : 'control-label',
19249                     html : this.fieldLabel
19250
19251                 },
19252                 {
19253                     cls : '', 
19254                     cn: [
19255                         combobox
19256                     ]
19257                 }
19258             ];
19259             
19260             if(this.indicatorpos == 'right'){
19261                 cfg.cn = [
19262                     {
19263                         tag: 'label',
19264                         cls : 'control-label',
19265                         html : this.fieldLabel,
19266                         cn : [
19267                             required
19268                         ]
19269                     },
19270                     {
19271                         cls : '', 
19272                         cn: [
19273                             combobox
19274                         ]
19275                     }
19276                 ];
19277             }
19278         } else {
19279             cfg.cn = combobox;    
19280         }
19281         
19282         
19283         var settings = this;
19284         
19285         ['xs','sm','md','lg'].map(function(size){
19286             if (settings[size]) {
19287                 cfg.cls += ' col-' + size + '-' + settings[size];
19288             }
19289         });
19290         
19291         return cfg;
19292     },
19293     
19294     initTouchView : function()
19295     {
19296         this.renderTouchView();
19297         
19298         this.touchViewEl.on('scroll', function(){
19299             this.el.dom.scrollTop = 0;
19300         }, this);
19301         
19302         this.originalValue = this.getValue();
19303         
19304         this.triggerEl = this.el.select('span.dropdown-toggle',true).first();
19305         
19306         this.inputEl().on("click", this.showTouchView, this);
19307         if (this.triggerEl) {
19308             this.triggerEl.on("click", this.showTouchView, this);
19309         }
19310         
19311         
19312         this.touchViewFooterEl.select('.roo-touch-view-cancel', true).first().on('click', this.hideTouchView, this);
19313         this.touchViewFooterEl.select('.roo-touch-view-ok', true).first().on('click', this.setTouchViewValue, this);
19314         
19315         this.maskEl = new Roo.LoadMask(this.touchViewEl, { store : this.store, msgCls: 'roo-el-mask-msg' });
19316         
19317         this.store.on('beforeload', this.onTouchViewBeforeLoad, this);
19318         this.store.on('load', this.onTouchViewLoad, this);
19319         this.store.on('loadexception', this.onTouchViewLoadException, this);
19320         
19321         if(this.hiddenName){
19322             
19323             this.hiddenField = this.el.select('input.form-hidden-field',true).first();
19324             
19325             this.hiddenField.dom.value =
19326                 this.hiddenValue !== undefined ? this.hiddenValue :
19327                 this.value !== undefined ? this.value : '';
19328         
19329             this.el.dom.removeAttribute('name');
19330             this.hiddenField.dom.setAttribute('name', this.hiddenName);
19331         }
19332         
19333         if(this.multiple){
19334             this.choices = this.el.select('ul.roo-select2-choices', true).first();
19335             this.searchField = this.el.select('ul li.roo-select2-search-field', true).first();
19336         }
19337         
19338         if(this.removable && !this.multiple){
19339             var close = this.closeTriggerEl();
19340             if(close){
19341                 close.setVisibilityMode(Roo.Element.DISPLAY).hide();
19342                 close.on('click', this.removeBtnClick, this, close);
19343             }
19344         }
19345         /*
19346          * fix the bug in Safari iOS8
19347          */
19348         this.inputEl().on("focus", function(e){
19349             document.activeElement.blur();
19350         }, this);
19351         
19352         this._touchViewMask = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
19353         
19354         return;
19355         
19356         
19357     },
19358     
19359     renderTouchView : function()
19360     {
19361         this.touchViewEl = Roo.get(document.body).createChild(Roo.bootstrap.form.ComboBox.touchViewTemplate);
19362         this.touchViewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19363         
19364         this.touchViewHeaderEl = this.touchViewEl.select('.modal-header', true).first();
19365         this.touchViewHeaderEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19366         
19367         this.touchViewBodyEl = this.touchViewEl.select('.modal-body', true).first();
19368         this.touchViewBodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19369         this.touchViewBodyEl.setStyle('overflow', 'auto');
19370         
19371         this.touchViewListGroup = this.touchViewBodyEl.select('.list-group', true).first();
19372         this.touchViewListGroup.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19373         
19374         this.touchViewFooterEl = this.touchViewEl.select('.modal-footer', true).first();
19375         this.touchViewFooterEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
19376         
19377     },
19378     
19379     showTouchView : function()
19380     {
19381         if(this.disabled){
19382             return;
19383         }
19384         
19385         this.touchViewHeaderEl.hide();
19386
19387         if(this.modalTitle.length){
19388             this.touchViewHeaderEl.dom.innerHTML = this.modalTitle;
19389             this.touchViewHeaderEl.show();
19390         }
19391
19392         this.touchViewEl.setStyle('z-index', Roo.bootstrap.Modal.zIndex++);
19393         this.touchViewEl.show();
19394
19395         this.touchViewEl.select('.modal-dialog', true).first().setStyle({ margin : '0px', width : '100%'});
19396         
19397         //this.touchViewEl.select('.modal-dialog > .modal-content', true).first().setSize(
19398         //        Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
19399
19400         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
19401
19402         if(this.modalTitle.length){
19403             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
19404         }
19405         
19406         this.touchViewBodyEl.setHeight(bodyHeight);
19407
19408         if(this.animate){
19409             var _this = this;
19410             (function(){ _this.touchViewEl.addClass(['in','show']); }).defer(50);
19411         }else{
19412             this.touchViewEl.addClass(['in','show']);
19413         }
19414         
19415         if(this._touchViewMask){
19416             Roo.get(document.body).addClass("x-body-masked");
19417             this._touchViewMask.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
19418             this._touchViewMask.setStyle('z-index', 10000);
19419             this._touchViewMask.addClass('show');
19420         }
19421         
19422         this.doTouchViewQuery();
19423         
19424     },
19425     
19426     hideTouchView : function()
19427     {
19428         this.touchViewEl.removeClass(['in','show']);
19429
19430         if(this.animate){
19431             var _this = this;
19432             (function(){ _this.touchViewEl.setStyle('display', 'none'); }).defer(150);
19433         }else{
19434             this.touchViewEl.setStyle('display', 'none');
19435         }
19436         
19437         if(this._touchViewMask){
19438             this._touchViewMask.removeClass('show');
19439             Roo.get(document.body).removeClass("x-body-masked");
19440         }
19441     },
19442     
19443     setTouchViewValue : function()
19444     {
19445         if(this.multiple){
19446             this.clearItem();
19447         
19448             var _this = this;
19449
19450             Roo.each(this.tickItems, function(o){
19451                 this.addItem(o);
19452             }, this);
19453         }
19454         
19455         this.hideTouchView();
19456     },
19457     
19458     doTouchViewQuery : function()
19459     {
19460         var qe = {
19461             query: '',
19462             forceAll: true,
19463             combo: this,
19464             cancel:false
19465         };
19466         
19467         if(this.fireEvent('beforequery', qe) ===false || qe.cancel){
19468             return false;
19469         }
19470         
19471         if(!this.alwaysQuery || this.mode == 'local'){
19472             this.onTouchViewLoad();
19473             return;
19474         }
19475         
19476         this.store.load();
19477     },
19478     
19479     onTouchViewBeforeLoad : function(combo,opts)
19480     {
19481         return;
19482     },
19483
19484     // private
19485     onTouchViewLoad : function()
19486     {
19487         if(this.store.getCount() < 1){
19488             this.onTouchViewEmptyResults();
19489             return;
19490         }
19491         
19492         this.clearTouchView();
19493         
19494         var rawValue = this.getRawValue();
19495         
19496         var template = (this.multiple) ? Roo.bootstrap.form.ComboBox.listItemCheckbox : Roo.bootstrap.form.ComboBox.listItemRadio;
19497         
19498         this.tickItems = [];
19499         
19500         this.store.data.each(function(d, rowIndex){
19501             var row = this.touchViewListGroup.createChild(template);
19502             
19503             if(typeof(d.data.cls) != 'undefined' && d.data.cls.length){
19504                 row.addClass(d.data.cls);
19505             }
19506             
19507             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
19508                 var cfg = {
19509                     data : d.data,
19510                     html : d.data[this.displayField]
19511                 };
19512                 
19513                 if(this.fireEvent('touchviewdisplay', this, cfg) !== false){
19514                     row.select('.roo-combobox-list-group-item-value', true).first().dom.innerHTML = cfg.html;
19515                 }
19516             }
19517             row.removeClass('selected');
19518             if(!this.multiple && this.valueField &&
19519                     typeof(d.data[this.valueField]) != 'undefined' && d.data[this.valueField] == this.getValue())
19520             {
19521                 // radio buttons..
19522                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
19523                 row.addClass('selected');
19524             }
19525             
19526             if(this.multiple && this.valueField &&
19527                     typeof(d.data[this.valueField]) != 'undefined' && this.getValue().indexOf(d.data[this.valueField]) != -1)
19528             {
19529                 
19530                 // checkboxes...
19531                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
19532                 this.tickItems.push(d.data);
19533             }
19534             
19535             row.on('click', this.onTouchViewClick, this, {row : row, rowIndex : rowIndex});
19536             
19537         }, this);
19538         
19539         var firstChecked = this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).first();
19540         
19541         var bodyHeight = Roo.lib.Dom.getViewHeight() - this.touchViewFooterEl.getHeight() + this.touchViewBodyEl.getPadding('tb');
19542
19543         if(this.modalTitle.length){
19544             bodyHeight = bodyHeight - this.touchViewHeaderEl.getHeight();
19545         }
19546
19547         var listHeight = this.touchViewListGroup.getHeight() + this.touchViewBodyEl.getPadding('tb') * 2;
19548         
19549         if(this.mobile_restrict_height && listHeight < bodyHeight){
19550             this.touchViewBodyEl.setHeight(listHeight);
19551         }
19552         
19553         var _this = this;
19554         
19555         if(firstChecked && listHeight > bodyHeight){
19556             (function() { firstChecked.findParent('li').scrollIntoView(_this.touchViewListGroup.dom); }).defer(500);
19557         }
19558         
19559     },
19560     
19561     onTouchViewLoadException : function()
19562     {
19563         this.hideTouchView();
19564     },
19565     
19566     onTouchViewEmptyResults : function()
19567     {
19568         this.clearTouchView();
19569         
19570         this.touchViewListGroup.createChild(Roo.bootstrap.form.ComboBox.emptyResult);
19571         
19572         this.touchViewListGroup.select('.roo-combobox-touch-view-empty-result', true).first().dom.innerHTML = this.emptyResultText;
19573         
19574     },
19575     
19576     clearTouchView : function()
19577     {
19578         this.touchViewListGroup.dom.innerHTML = '';
19579     },
19580     
19581     onTouchViewClick : function(e, el, o)
19582     {
19583         e.preventDefault();
19584         
19585         var row = o.row;
19586         var rowIndex = o.rowIndex;
19587         
19588         var r = this.store.getAt(rowIndex);
19589         
19590         if(this.fireEvent('beforeselect', this, r, rowIndex) !== false){
19591             
19592             if(!this.multiple){
19593                 Roo.each(this.touchViewListGroup.select('.list-group-item > .roo-combobox-list-group-item-box > input:checked', true).elements, function(c){
19594                     c.dom.removeAttribute('checked');
19595                 }, this);
19596
19597                 row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
19598
19599                 this.setFromData(r.data);
19600
19601                 var close = this.closeTriggerEl();
19602
19603                 if(close){
19604                     close.show();
19605                 }
19606
19607                 this.hideTouchView();
19608
19609                 this.fireEvent('select', this, r, rowIndex);
19610
19611                 return;
19612             }
19613
19614             if(this.valueField && typeof(r.data[this.valueField]) != 'undefined' && this.getValue().indexOf(r.data[this.valueField]) != -1){
19615                 row.select('.roo-combobox-list-group-item-box > input', true).first().dom.removeAttribute('checked');
19616                 this.tickItems.splice(this.tickItems.indexOf(r.data), 1);
19617                 return;
19618             }
19619
19620             row.select('.roo-combobox-list-group-item-box > input', true).first().attr('checked', true);
19621             this.addItem(r.data);
19622             this.tickItems.push(r.data);
19623         }
19624     },
19625     
19626     getAutoCreateNativeIOS : function()
19627     {
19628         var cfg = {
19629             cls: 'form-group' //input-group,
19630         };
19631         
19632         var combobox =  {
19633             tag: 'select',
19634             cls : 'roo-ios-select'
19635         };
19636         
19637         if (this.name) {
19638             combobox.name = this.name;
19639         }
19640         
19641         if (this.disabled) {
19642             combobox.disabled = true;
19643         }
19644         
19645         var settings = this;
19646         
19647         ['xs','sm','md','lg'].map(function(size){
19648             if (settings[size]) {
19649                 cfg.cls += ' col-' + size + '-' + settings[size];
19650             }
19651         });
19652         
19653         cfg.cn = combobox;
19654         
19655         return cfg;
19656         
19657     },
19658     
19659     initIOSView : function()
19660     {
19661         this.store.on('load', this.onIOSViewLoad, this);
19662         
19663         return;
19664     },
19665     
19666     onIOSViewLoad : function()
19667     {
19668         if(this.store.getCount() < 1){
19669             return;
19670         }
19671         
19672         this.clearIOSView();
19673         
19674         if(this.allowBlank) {
19675             
19676             var default_text = '-- SELECT --';
19677             
19678             if(this.placeholder.length){
19679                 default_text = this.placeholder;
19680             }
19681             
19682             if(this.emptyTitle.length){
19683                 default_text += ' - ' + this.emptyTitle + ' -';
19684             }
19685             
19686             var opt = this.inputEl().createChild({
19687                 tag: 'option',
19688                 value : 0,
19689                 html : default_text
19690             });
19691             
19692             var o = {};
19693             o[this.valueField] = 0;
19694             o[this.displayField] = default_text;
19695             
19696             this.ios_options.push({
19697                 data : o,
19698                 el : opt
19699             });
19700             
19701         }
19702         
19703         this.store.data.each(function(d, rowIndex){
19704             
19705             var html = '';
19706             
19707             if(this.displayField && typeof(d.data[this.displayField]) != 'undefined'){
19708                 html = d.data[this.displayField];
19709             }
19710             
19711             var value = '';
19712             
19713             if(this.valueField && typeof(d.data[this.valueField]) != 'undefined'){
19714                 value = d.data[this.valueField];
19715             }
19716             
19717             var option = {
19718                 tag: 'option',
19719                 value : value,
19720                 html : html
19721             };
19722             
19723             if(this.value == d.data[this.valueField]){
19724                 option['selected'] = true;
19725             }
19726             
19727             var opt = this.inputEl().createChild(option);
19728             
19729             this.ios_options.push({
19730                 data : d.data,
19731                 el : opt
19732             });
19733             
19734         }, this);
19735         
19736         this.inputEl().on('change', function(){
19737            this.fireEvent('select', this);
19738         }, this);
19739         
19740     },
19741     
19742     clearIOSView: function()
19743     {
19744         this.inputEl().dom.innerHTML = '';
19745         
19746         this.ios_options = [];
19747     },
19748     
19749     setIOSValue: function(v)
19750     {
19751         this.value = v;
19752         
19753         if(!this.ios_options){
19754             return;
19755         }
19756         
19757         Roo.each(this.ios_options, function(opts){
19758            
19759            opts.el.dom.removeAttribute('selected');
19760            
19761            if(opts.data[this.valueField] != v){
19762                return;
19763            }
19764            
19765            opts.el.dom.setAttribute('selected', true);
19766            
19767         }, this);
19768     }
19769
19770     /** 
19771     * @cfg {Boolean} grow 
19772     * @hide 
19773     */
19774     /** 
19775     * @cfg {Number} growMin 
19776     * @hide 
19777     */
19778     /** 
19779     * @cfg {Number} growMax 
19780     * @hide 
19781     */
19782     /**
19783      * @hide
19784      * @method autoSize
19785      */
19786 });
19787
19788 Roo.apply(Roo.bootstrap.form.ComboBox,  {
19789     
19790     header : {
19791         tag: 'div',
19792         cls: 'modal-header',
19793         cn: [
19794             {
19795                 tag: 'h4',
19796                 cls: 'modal-title'
19797             }
19798         ]
19799     },
19800     
19801     body : {
19802         tag: 'div',
19803         cls: 'modal-body',
19804         cn: [
19805             {
19806                 tag: 'ul',
19807                 cls: 'list-group'
19808             }
19809         ]
19810     },
19811     
19812     listItemRadio : {
19813         tag: 'li',
19814         cls: 'list-group-item',
19815         cn: [
19816             {
19817                 tag: 'span',
19818                 cls: 'roo-combobox-list-group-item-value'
19819             },
19820             {
19821                 tag: 'div',
19822                 cls: 'roo-combobox-list-group-item-box pull-xs-right radio-inline radio radio-info',
19823                 cn: [
19824                     {
19825                         tag: 'input',
19826                         type: 'radio'
19827                     },
19828                     {
19829                         tag: 'label'
19830                     }
19831                 ]
19832             }
19833         ]
19834     },
19835     
19836     listItemCheckbox : {
19837         tag: 'li',
19838         cls: 'list-group-item',
19839         cn: [
19840             {
19841                 tag: 'span',
19842                 cls: 'roo-combobox-list-group-item-value'
19843             },
19844             {
19845                 tag: 'div',
19846                 cls: 'roo-combobox-list-group-item-box pull-xs-right checkbox-inline checkbox checkbox-info',
19847                 cn: [
19848                     {
19849                         tag: 'input',
19850                         type: 'checkbox'
19851                     },
19852                     {
19853                         tag: 'label'
19854                     }
19855                 ]
19856             }
19857         ]
19858     },
19859     
19860     emptyResult : {
19861         tag: 'div',
19862         cls: 'alert alert-danger roo-combobox-touch-view-empty-result'
19863     },
19864     
19865     footer : {
19866         tag: 'div',
19867         cls: 'modal-footer',
19868         cn: [
19869             {
19870                 tag: 'div',
19871                 cls: 'row',
19872                 cn: [
19873                     {
19874                         tag: 'div',
19875                         cls: 'col-xs-6 text-left',
19876                         cn: {
19877                             tag: 'button',
19878                             cls: 'btn btn-danger roo-touch-view-cancel',
19879                             html: 'Cancel'
19880                         }
19881                     },
19882                     {
19883                         tag: 'div',
19884                         cls: 'col-xs-6 text-right',
19885                         cn: {
19886                             tag: 'button',
19887                             cls: 'btn btn-success roo-touch-view-ok',
19888                             html: 'OK'
19889                         }
19890                     }
19891                 ]
19892             }
19893         ]
19894         
19895     }
19896 });
19897
19898 Roo.apply(Roo.bootstrap.form.ComboBox,  {
19899     
19900     touchViewTemplate : {
19901         tag: 'div',
19902         cls: 'modal fade roo-combobox-touch-view',
19903         cn: [
19904             {
19905                 tag: 'div',
19906                 cls: 'modal-dialog',
19907                 style : 'position:fixed', // we have to fix position....
19908                 cn: [
19909                     {
19910                         tag: 'div',
19911                         cls: 'modal-content',
19912                         cn: [
19913                             Roo.bootstrap.form.ComboBox.header,
19914                             Roo.bootstrap.form.ComboBox.body,
19915                             Roo.bootstrap.form.ComboBox.footer
19916                         ]
19917                     }
19918                 ]
19919             }
19920         ]
19921     }
19922 });/*
19923  * Based on:
19924  * Ext JS Library 1.1.1
19925  * Copyright(c) 2006-2007, Ext JS, LLC.
19926  *
19927  * Originally Released Under LGPL - original licence link has changed is not relivant.
19928  *
19929  * Fork - LGPL
19930  * <script type="text/javascript">
19931  */
19932
19933 /**
19934  * @class Roo.View
19935  * @extends Roo.util.Observable
19936  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
19937  * This class also supports single and multi selection modes. <br>
19938  * Create a data model bound view:
19939  <pre><code>
19940  var store = new Roo.data.Store(...);
19941
19942  var view = new Roo.View({
19943     el : "my-element",
19944     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
19945  
19946     singleSelect: true,
19947     selectedClass: "ydataview-selected",
19948     store: store
19949  });
19950
19951  // listen for node click?
19952  view.on("click", function(vw, index, node, e){
19953  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
19954  });
19955
19956  // load XML data
19957  dataModel.load("foobar.xml");
19958  </code></pre>
19959  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
19960  * <br><br>
19961  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
19962  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
19963  * 
19964  * Note: old style constructor is still suported (container, template, config)
19965  * 
19966  * @constructor
19967  * Create a new View
19968  * @param {Object} config The config object
19969  * 
19970  */
19971 Roo.View = function(config, depreciated_tpl, depreciated_config){
19972     
19973     this.parent = false;
19974     
19975     if (typeof(depreciated_tpl) == 'undefined') {
19976         // new way.. - universal constructor.
19977         Roo.apply(this, config);
19978         this.el  = Roo.get(this.el);
19979     } else {
19980         // old format..
19981         this.el  = Roo.get(config);
19982         this.tpl = depreciated_tpl;
19983         Roo.apply(this, depreciated_config);
19984     }
19985     this.wrapEl  = this.el.wrap().wrap();
19986     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
19987     
19988     
19989     if(typeof(this.tpl) == "string"){
19990         this.tpl = new Roo.Template(this.tpl);
19991     } else {
19992         // support xtype ctors..
19993         this.tpl = new Roo.factory(this.tpl, Roo);
19994     }
19995     
19996     
19997     this.tpl.compile();
19998     
19999     /** @private */
20000     this.addEvents({
20001         /**
20002          * @event beforeclick
20003          * Fires before a click is processed. Returns false to cancel the default action.
20004          * @param {Roo.View} this
20005          * @param {Number} index The index of the target node
20006          * @param {HTMLElement} node The target node
20007          * @param {Roo.EventObject} e The raw event object
20008          */
20009             "beforeclick" : true,
20010         /**
20011          * @event click
20012          * Fires when a template node is clicked.
20013          * @param {Roo.View} this
20014          * @param {Number} index The index of the target node
20015          * @param {HTMLElement} node The target node
20016          * @param {Roo.EventObject} e The raw event object
20017          */
20018             "click" : true,
20019         /**
20020          * @event dblclick
20021          * Fires when a template node is double clicked.
20022          * @param {Roo.View} this
20023          * @param {Number} index The index of the target node
20024          * @param {HTMLElement} node The target node
20025          * @param {Roo.EventObject} e The raw event object
20026          */
20027             "dblclick" : true,
20028         /**
20029          * @event contextmenu
20030          * Fires when a template node is right clicked.
20031          * @param {Roo.View} this
20032          * @param {Number} index The index of the target node
20033          * @param {HTMLElement} node The target node
20034          * @param {Roo.EventObject} e The raw event object
20035          */
20036             "contextmenu" : true,
20037         /**
20038          * @event selectionchange
20039          * Fires when the selected nodes change.
20040          * @param {Roo.View} this
20041          * @param {Array} selections Array of the selected nodes
20042          */
20043             "selectionchange" : true,
20044     
20045         /**
20046          * @event beforeselect
20047          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
20048          * @param {Roo.View} this
20049          * @param {HTMLElement} node The node to be selected
20050          * @param {Array} selections Array of currently selected nodes
20051          */
20052             "beforeselect" : true,
20053         /**
20054          * @event preparedata
20055          * Fires on every row to render, to allow you to change the data.
20056          * @param {Roo.View} this
20057          * @param {Object} data to be rendered (change this)
20058          */
20059           "preparedata" : true
20060           
20061           
20062         });
20063
20064
20065
20066     this.el.on({
20067         "click": this.onClick,
20068         "dblclick": this.onDblClick,
20069         "contextmenu": this.onContextMenu,
20070         scope:this
20071     });
20072
20073     this.selections = [];
20074     this.nodes = [];
20075     this.cmp = new Roo.CompositeElementLite([]);
20076     if(this.store){
20077         this.store = Roo.factory(this.store, Roo.data);
20078         this.setStore(this.store, true);
20079     }
20080     
20081     if ( this.footer && this.footer.xtype) {
20082            
20083          var fctr = this.wrapEl.appendChild(document.createElement("div"));
20084         
20085         this.footer.dataSource = this.store;
20086         this.footer.container = fctr;
20087         this.footer = Roo.factory(this.footer, Roo);
20088         fctr.insertFirst(this.el);
20089         
20090         // this is a bit insane - as the paging toolbar seems to detach the el..
20091 //        dom.parentNode.parentNode.parentNode
20092          // they get detached?
20093     }
20094     
20095     
20096     Roo.View.superclass.constructor.call(this);
20097     
20098     
20099 };
20100
20101 Roo.extend(Roo.View, Roo.util.Observable, {
20102     
20103      /**
20104      * @cfg {Roo.data.Store} store Data store to load data from.
20105      */
20106     store : false,
20107     
20108     /**
20109      * @cfg {String|Roo.Element} el The container element.
20110      */
20111     el : '',
20112     
20113     /**
20114      * @cfg {String|Roo.Template} tpl The template used by this View 
20115      */
20116     tpl : false,
20117     /**
20118      * @cfg {String} dataName the named area of the template to use as the data area
20119      *                          Works with domtemplates roo-name="name"
20120      */
20121     dataName: false,
20122     /**
20123      * @cfg {String} selectedClass The css class to add to selected nodes
20124      */
20125     selectedClass : "x-view-selected",
20126      /**
20127      * @cfg {String} emptyText The empty text to show when nothing is loaded.
20128      */
20129     emptyText : "",
20130     
20131     /**
20132      * @cfg {String} text to display on mask (default Loading)
20133      */
20134     mask : false,
20135     /**
20136      * @cfg {Boolean} multiSelect Allow multiple selection
20137      */
20138     multiSelect : false,
20139     /**
20140      * @cfg {Boolean} singleSelect Allow single selection
20141      */
20142     singleSelect:  false,
20143     
20144     /**
20145      * @cfg {Boolean} toggleSelect - selecting 
20146      */
20147     toggleSelect : false,
20148     
20149     /**
20150      * @cfg {Boolean} tickable - selecting 
20151      */
20152     tickable : false,
20153     
20154     /**
20155      * Returns the element this view is bound to.
20156      * @return {Roo.Element}
20157      */
20158     getEl : function(){
20159         return this.wrapEl;
20160     },
20161     
20162     
20163
20164     /**
20165      * Refreshes the view. - called by datachanged on the store. - do not call directly.
20166      */
20167     refresh : function(){
20168         //Roo.log('refresh');
20169         var t = this.tpl;
20170         
20171         // if we are using something like 'domtemplate', then
20172         // the what gets used is:
20173         // t.applySubtemplate(NAME, data, wrapping data..)
20174         // the outer template then get' applied with
20175         //     the store 'extra data'
20176         // and the body get's added to the
20177         //      roo-name="data" node?
20178         //      <span class='roo-tpl-{name}'></span> ?????
20179         
20180         
20181         
20182         this.clearSelections();
20183         this.el.update("");
20184         var html = [];
20185         var records = this.store.getRange();
20186         if(records.length < 1) {
20187             
20188             // is this valid??  = should it render a template??
20189             
20190             this.el.update(this.emptyText);
20191             return;
20192         }
20193         var el = this.el;
20194         if (this.dataName) {
20195             this.el.update(t.apply(this.store.meta)); //????
20196             el = this.el.child('.roo-tpl-' + this.dataName);
20197         }
20198         
20199         for(var i = 0, len = records.length; i < len; i++){
20200             var data = this.prepareData(records[i].data, i, records[i]);
20201             this.fireEvent("preparedata", this, data, i, records[i]);
20202             
20203             var d = Roo.apply({}, data);
20204             
20205             if(this.tickable){
20206                 Roo.apply(d, {'roo-id' : Roo.id()});
20207                 
20208                 var _this = this;
20209             
20210                 Roo.each(this.parent.item, function(item){
20211                     if(item[_this.parent.valueField] != data[_this.parent.valueField]){
20212                         return;
20213                     }
20214                     Roo.apply(d, {'roo-data-checked' : 'checked'});
20215                 });
20216             }
20217             
20218             html[html.length] = Roo.util.Format.trim(
20219                 this.dataName ?
20220                     t.applySubtemplate(this.dataName, d, this.store.meta) :
20221                     t.apply(d)
20222             );
20223         }
20224         
20225         
20226         
20227         el.update(html.join(""));
20228         this.nodes = el.dom.childNodes;
20229         this.updateIndexes(0);
20230     },
20231     
20232
20233     /**
20234      * Function to override to reformat the data that is sent to
20235      * the template for each node.
20236      * DEPRICATED - use the preparedata event handler.
20237      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
20238      * a JSON object for an UpdateManager bound view).
20239      */
20240     prepareData : function(data, index, record)
20241     {
20242         this.fireEvent("preparedata", this, data, index, record);
20243         return data;
20244     },
20245
20246     onUpdate : function(ds, record){
20247         // Roo.log('on update');   
20248         this.clearSelections();
20249         var index = this.store.indexOf(record);
20250         var n = this.nodes[index];
20251         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
20252         n.parentNode.removeChild(n);
20253         this.updateIndexes(index, index);
20254     },
20255
20256     
20257     
20258 // --------- FIXME     
20259     onAdd : function(ds, records, index)
20260     {
20261         //Roo.log(['on Add', ds, records, index] );        
20262         this.clearSelections();
20263         if(this.nodes.length == 0){
20264             this.refresh();
20265             return;
20266         }
20267         var n = this.nodes[index];
20268         for(var i = 0, len = records.length; i < len; i++){
20269             var d = this.prepareData(records[i].data, i, records[i]);
20270             if(n){
20271                 this.tpl.insertBefore(n, d);
20272             }else{
20273                 
20274                 this.tpl.append(this.el, d);
20275             }
20276         }
20277         this.updateIndexes(index);
20278     },
20279
20280     onRemove : function(ds, record, index){
20281        // Roo.log('onRemove');
20282         this.clearSelections();
20283         var el = this.dataName  ?
20284             this.el.child('.roo-tpl-' + this.dataName) :
20285             this.el; 
20286         
20287         el.dom.removeChild(this.nodes[index]);
20288         this.updateIndexes(index);
20289     },
20290
20291     /**
20292      * Refresh an individual node.
20293      * @param {Number} index
20294      */
20295     refreshNode : function(index){
20296         this.onUpdate(this.store, this.store.getAt(index));
20297     },
20298
20299     updateIndexes : function(startIndex, endIndex){
20300         var ns = this.nodes;
20301         startIndex = startIndex || 0;
20302         endIndex = endIndex || ns.length - 1;
20303         for(var i = startIndex; i <= endIndex; i++){
20304             ns[i].nodeIndex = i;
20305         }
20306     },
20307
20308     /**
20309      * Changes the data store this view uses and refresh the view.
20310      * @param {Store} store
20311      */
20312     setStore : function(store, initial){
20313         if(!initial && this.store){
20314             this.store.un("datachanged", this.refresh);
20315             this.store.un("add", this.onAdd);
20316             this.store.un("remove", this.onRemove);
20317             this.store.un("update", this.onUpdate);
20318             this.store.un("clear", this.refresh);
20319             this.store.un("beforeload", this.onBeforeLoad);
20320             this.store.un("load", this.onLoad);
20321             this.store.un("loadexception", this.onLoad);
20322         }
20323         if(store){
20324           
20325             store.on("datachanged", this.refresh, this);
20326             store.on("add", this.onAdd, this);
20327             store.on("remove", this.onRemove, this);
20328             store.on("update", this.onUpdate, this);
20329             store.on("clear", this.refresh, this);
20330             store.on("beforeload", this.onBeforeLoad, this);
20331             store.on("load", this.onLoad, this);
20332             store.on("loadexception", this.onLoad, this);
20333         }
20334         
20335         if(store){
20336             this.refresh();
20337         }
20338     },
20339     /**
20340      * onbeforeLoad - masks the loading area.
20341      *
20342      */
20343     onBeforeLoad : function(store,opts)
20344     {
20345          //Roo.log('onBeforeLoad');   
20346         if (!opts.add) {
20347             this.el.update("");
20348         }
20349         this.el.mask(this.mask ? this.mask : "Loading" ); 
20350     },
20351     onLoad : function ()
20352     {
20353         this.el.unmask();
20354     },
20355     
20356
20357     /**
20358      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
20359      * @param {HTMLElement} node
20360      * @return {HTMLElement} The template node
20361      */
20362     findItemFromChild : function(node){
20363         var el = this.dataName  ?
20364             this.el.child('.roo-tpl-' + this.dataName,true) :
20365             this.el.dom; 
20366         
20367         if(!node || node.parentNode == el){
20368                     return node;
20369             }
20370             var p = node.parentNode;
20371             while(p && p != el){
20372             if(p.parentNode == el){
20373                 return p;
20374             }
20375             p = p.parentNode;
20376         }
20377             return null;
20378     },
20379
20380     /** @ignore */
20381     onClick : function(e){
20382         var item = this.findItemFromChild(e.getTarget());
20383         if(item){
20384             var index = this.indexOf(item);
20385             if(this.onItemClick(item, index, e) !== false){
20386                 this.fireEvent("click", this, index, item, e);
20387             }
20388         }else{
20389             this.clearSelections();
20390         }
20391     },
20392
20393     /** @ignore */
20394     onContextMenu : function(e){
20395         var item = this.findItemFromChild(e.getTarget());
20396         if(item){
20397             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
20398         }
20399     },
20400
20401     /** @ignore */
20402     onDblClick : function(e){
20403         var item = this.findItemFromChild(e.getTarget());
20404         if(item){
20405             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
20406         }
20407     },
20408
20409     onItemClick : function(item, index, e)
20410     {
20411         if(this.fireEvent("beforeclick", this, index, item, e) === false){
20412             return false;
20413         }
20414         if (this.toggleSelect) {
20415             var m = this.isSelected(item) ? 'unselect' : 'select';
20416             //Roo.log(m);
20417             var _t = this;
20418             _t[m](item, true, false);
20419             return true;
20420         }
20421         if(this.multiSelect || this.singleSelect){
20422             if(this.multiSelect && e.shiftKey && this.lastSelection){
20423                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
20424             }else{
20425                 this.select(item, this.multiSelect && e.ctrlKey);
20426                 this.lastSelection = item;
20427             }
20428             
20429             if(!this.tickable){
20430                 e.preventDefault();
20431             }
20432             
20433         }
20434         return true;
20435     },
20436
20437     /**
20438      * Get the number of selected nodes.
20439      * @return {Number}
20440      */
20441     getSelectionCount : function(){
20442         return this.selections.length;
20443     },
20444
20445     /**
20446      * Get the currently selected nodes.
20447      * @return {Array} An array of HTMLElements
20448      */
20449     getSelectedNodes : function(){
20450         return this.selections;
20451     },
20452
20453     /**
20454      * Get the indexes of the selected nodes.
20455      * @return {Array}
20456      */
20457     getSelectedIndexes : function(){
20458         var indexes = [], s = this.selections;
20459         for(var i = 0, len = s.length; i < len; i++){
20460             indexes.push(s[i].nodeIndex);
20461         }
20462         return indexes;
20463     },
20464
20465     /**
20466      * Clear all selections
20467      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
20468      */
20469     clearSelections : function(suppressEvent){
20470         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
20471             this.cmp.elements = this.selections;
20472             this.cmp.removeClass(this.selectedClass);
20473             this.selections = [];
20474             if(!suppressEvent){
20475                 this.fireEvent("selectionchange", this, this.selections);
20476             }
20477         }
20478     },
20479
20480     /**
20481      * Returns true if the passed node is selected
20482      * @param {HTMLElement/Number} node The node or node index
20483      * @return {Boolean}
20484      */
20485     isSelected : function(node){
20486         var s = this.selections;
20487         if(s.length < 1){
20488             return false;
20489         }
20490         node = this.getNode(node);
20491         return s.indexOf(node) !== -1;
20492     },
20493
20494     /**
20495      * Selects nodes.
20496      * @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
20497      * @param {Boolean} keepExisting (optional) true to keep existing selections
20498      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
20499      */
20500     select : function(nodeInfo, keepExisting, suppressEvent){
20501         if(nodeInfo instanceof Array){
20502             if(!keepExisting){
20503                 this.clearSelections(true);
20504             }
20505             for(var i = 0, len = nodeInfo.length; i < len; i++){
20506                 this.select(nodeInfo[i], true, true);
20507             }
20508             return;
20509         } 
20510         var node = this.getNode(nodeInfo);
20511         if(!node || this.isSelected(node)){
20512             return; // already selected.
20513         }
20514         if(!keepExisting){
20515             this.clearSelections(true);
20516         }
20517         
20518         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
20519             Roo.fly(node).addClass(this.selectedClass);
20520             this.selections.push(node);
20521             if(!suppressEvent){
20522                 this.fireEvent("selectionchange", this, this.selections);
20523             }
20524         }
20525         
20526         
20527     },
20528       /**
20529      * Unselects nodes.
20530      * @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
20531      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
20532      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
20533      */
20534     unselect : function(nodeInfo, keepExisting, suppressEvent)
20535     {
20536         if(nodeInfo instanceof Array){
20537             Roo.each(this.selections, function(s) {
20538                 this.unselect(s, nodeInfo);
20539             }, this);
20540             return;
20541         }
20542         var node = this.getNode(nodeInfo);
20543         if(!node || !this.isSelected(node)){
20544             //Roo.log("not selected");
20545             return; // not selected.
20546         }
20547         // fireevent???
20548         var ns = [];
20549         Roo.each(this.selections, function(s) {
20550             if (s == node ) {
20551                 Roo.fly(node).removeClass(this.selectedClass);
20552
20553                 return;
20554             }
20555             ns.push(s);
20556         },this);
20557         
20558         this.selections= ns;
20559         this.fireEvent("selectionchange", this, this.selections);
20560     },
20561
20562     /**
20563      * Gets a template node.
20564      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
20565      * @return {HTMLElement} The node or null if it wasn't found
20566      */
20567     getNode : function(nodeInfo){
20568         if(typeof nodeInfo == "string"){
20569             return document.getElementById(nodeInfo);
20570         }else if(typeof nodeInfo == "number"){
20571             return this.nodes[nodeInfo];
20572         }
20573         return nodeInfo;
20574     },
20575
20576     /**
20577      * Gets a range template nodes.
20578      * @param {Number} startIndex
20579      * @param {Number} endIndex
20580      * @return {Array} An array of nodes
20581      */
20582     getNodes : function(start, end){
20583         var ns = this.nodes;
20584         start = start || 0;
20585         end = typeof end == "undefined" ? ns.length - 1 : end;
20586         var nodes = [];
20587         if(start <= end){
20588             for(var i = start; i <= end; i++){
20589                 nodes.push(ns[i]);
20590             }
20591         } else{
20592             for(var i = start; i >= end; i--){
20593                 nodes.push(ns[i]);
20594             }
20595         }
20596         return nodes;
20597     },
20598
20599     /**
20600      * Finds the index of the passed node
20601      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
20602      * @return {Number} The index of the node or -1
20603      */
20604     indexOf : function(node){
20605         node = this.getNode(node);
20606         if(typeof node.nodeIndex == "number"){
20607             return node.nodeIndex;
20608         }
20609         var ns = this.nodes;
20610         for(var i = 0, len = ns.length; i < len; i++){
20611             if(ns[i] == node){
20612                 return i;
20613             }
20614         }
20615         return -1;
20616     }
20617 });
20618 /*
20619  * - LGPL
20620  *
20621  * based on jquery fullcalendar
20622  * 
20623  */
20624
20625 Roo.bootstrap = Roo.bootstrap || {};
20626 /**
20627  * @class Roo.bootstrap.Calendar
20628  * @extends Roo.bootstrap.Component
20629  * Bootstrap Calendar class
20630  * @cfg {Boolean} loadMask (true|false) default false
20631  * @cfg {Object} header generate the user specific header of the calendar, default false
20632
20633  * @constructor
20634  * Create a new Container
20635  * @param {Object} config The config object
20636  */
20637
20638
20639
20640 Roo.bootstrap.Calendar = function(config){
20641     Roo.bootstrap.Calendar.superclass.constructor.call(this, config);
20642      this.addEvents({
20643         /**
20644              * @event select
20645              * Fires when a date is selected
20646              * @param {DatePicker} this
20647              * @param {Date} date The selected date
20648              */
20649         'select': true,
20650         /**
20651              * @event monthchange
20652              * Fires when the displayed month changes 
20653              * @param {DatePicker} this
20654              * @param {Date} date The selected month
20655              */
20656         'monthchange': true,
20657         /**
20658              * @event evententer
20659              * Fires when mouse over an event
20660              * @param {Calendar} this
20661              * @param {event} Event
20662              */
20663         'evententer': true,
20664         /**
20665              * @event eventleave
20666              * Fires when the mouse leaves an
20667              * @param {Calendar} this
20668              * @param {event}
20669              */
20670         'eventleave': true,
20671         /**
20672              * @event eventclick
20673              * Fires when the mouse click an
20674              * @param {Calendar} this
20675              * @param {event}
20676              */
20677         'eventclick': true
20678         
20679     });
20680
20681 };
20682
20683 Roo.extend(Roo.bootstrap.Calendar, Roo.bootstrap.Component,  {
20684     
20685           /**
20686      * @cfg {Roo.data.Store} store
20687      * The data source for the calendar
20688      */
20689         store : false,
20690      /**
20691      * @cfg {Number} startDay
20692      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
20693      */
20694     startDay : 0,
20695     
20696     loadMask : false,
20697     
20698     header : false,
20699       
20700     getAutoCreate : function(){
20701         
20702         
20703         var fc_button = function(name, corner, style, content ) {
20704             return Roo.apply({},{
20705                 tag : 'span',
20706                 cls : 'fc-button fc-button-'+name+' fc-state-default ' + 
20707                          (corner.length ?
20708                             'fc-corner-' + corner.split(' ').join(' fc-corner-') :
20709                             ''
20710                         ),
20711                 html : '<SPAN class="fc-text-'+style+ '">'+content +'</SPAN>',
20712                 unselectable: 'on'
20713             });
20714         };
20715         
20716         var header = {};
20717         
20718         if(!this.header){
20719             header = {
20720                 tag : 'table',
20721                 cls : 'fc-header',
20722                 style : 'width:100%',
20723                 cn : [
20724                     {
20725                         tag: 'tr',
20726                         cn : [
20727                             {
20728                                 tag : 'td',
20729                                 cls : 'fc-header-left',
20730                                 cn : [
20731                                     fc_button('prev', 'left', 'arrow', '&#8249;' ),
20732                                     fc_button('next', 'right', 'arrow', '&#8250;' ),
20733                                     { tag: 'span', cls: 'fc-header-space' },
20734                                     fc_button('today', 'left right', '', 'today' )  // neds state disabled..
20735
20736
20737                                 ]
20738                             },
20739
20740                             {
20741                                 tag : 'td',
20742                                 cls : 'fc-header-center',
20743                                 cn : [
20744                                     {
20745                                         tag: 'span',
20746                                         cls: 'fc-header-title',
20747                                         cn : {
20748                                             tag: 'H2',
20749                                             html : 'month / year'
20750                                         }
20751                                     }
20752
20753                                 ]
20754                             },
20755                             {
20756                                 tag : 'td',
20757                                 cls : 'fc-header-right',
20758                                 cn : [
20759                               /*      fc_button('month', 'left', '', 'month' ),
20760                                     fc_button('week', '', '', 'week' ),
20761                                     fc_button('day', 'right', '', 'day' )
20762                                 */    
20763
20764                                 ]
20765                             }
20766
20767                         ]
20768                     }
20769                 ]
20770             };
20771         }
20772         
20773         header = this.header;
20774         
20775        
20776         var cal_heads = function() {
20777             var ret = [];
20778             // fixme - handle this.
20779             
20780             for (var i =0; i < Date.dayNames.length; i++) {
20781                 var d = Date.dayNames[i];
20782                 ret.push({
20783                     tag: 'th',
20784                     cls : 'fc-day-header fc-' + d.substring(0,3).toLowerCase() + ' fc-widget-header',
20785                     html : d.substring(0,3)
20786                 });
20787                 
20788             }
20789             ret[0].cls += ' fc-first';
20790             ret[6].cls += ' fc-last';
20791             return ret;
20792         };
20793         var cal_cell = function(n) {
20794             return  {
20795                 tag: 'td',
20796                 cls : 'fc-day fc-'+n + ' fc-widget-content', ///fc-other-month fc-past
20797                 cn : [
20798                     {
20799                         cn : [
20800                             {
20801                                 cls: 'fc-day-number',
20802                                 html: 'D'
20803                             },
20804                             {
20805                                 cls: 'fc-day-content',
20806                              
20807                                 cn : [
20808                                      {
20809                                         style: 'position: relative;' // height: 17px;
20810                                     }
20811                                 ]
20812                             }
20813                             
20814                             
20815                         ]
20816                     }
20817                 ]
20818                 
20819             }
20820         };
20821         var cal_rows = function() {
20822             
20823             var ret = [];
20824             for (var r = 0; r < 6; r++) {
20825                 var row= {
20826                     tag : 'tr',
20827                     cls : 'fc-week',
20828                     cn : []
20829                 };
20830                 
20831                 for (var i =0; i < Date.dayNames.length; i++) {
20832                     var d = Date.dayNames[i];
20833                     row.cn.push(cal_cell(d.substring(0,3).toLowerCase()));
20834
20835                 }
20836                 row.cn[0].cls+=' fc-first';
20837                 row.cn[0].cn[0].style = 'min-height:90px';
20838                 row.cn[6].cls+=' fc-last';
20839                 ret.push(row);
20840                 
20841             }
20842             ret[0].cls += ' fc-first';
20843             ret[4].cls += ' fc-prev-last';
20844             ret[5].cls += ' fc-last';
20845             return ret;
20846             
20847         };
20848         
20849         var cal_table = {
20850             tag: 'table',
20851             cls: 'fc-border-separate',
20852             style : 'width:100%',
20853             cellspacing  : 0,
20854             cn : [
20855                 { 
20856                     tag: 'thead',
20857                     cn : [
20858                         { 
20859                             tag: 'tr',
20860                             cls : 'fc-first fc-last',
20861                             cn : cal_heads()
20862                         }
20863                     ]
20864                 },
20865                 { 
20866                     tag: 'tbody',
20867                     cn : cal_rows()
20868                 }
20869                   
20870             ]
20871         };
20872          
20873          var cfg = {
20874             cls : 'fc fc-ltr',
20875             cn : [
20876                 header,
20877                 {
20878                     cls : 'fc-content',
20879                     style : "position: relative;",
20880                     cn : [
20881                         {
20882                             cls : 'fc-view fc-view-month fc-grid',
20883                             style : 'position: relative',
20884                             unselectable : 'on',
20885                             cn : [
20886                                 {
20887                                     cls : 'fc-event-container',
20888                                     style : 'position:absolute;z-index:8;top:0;left:0;'
20889                                 },
20890                                 cal_table
20891                             ]
20892                         }
20893                     ]
20894     
20895                 }
20896            ] 
20897             
20898         };
20899         
20900          
20901         
20902         return cfg;
20903     },
20904     
20905     
20906     initEvents : function()
20907     {
20908         if(!this.store){
20909             throw "can not find store for calendar";
20910         }
20911         
20912         var mark = {
20913             tag: "div",
20914             cls:"x-dlg-mask",
20915             style: "text-align:center",
20916             cn: [
20917                 {
20918                     tag: "div",
20919                     style: "background-color:white;width:50%;margin:250 auto",
20920                     cn: [
20921                         {
20922                             tag: "img",
20923                             src: Roo.rootURL + '/images/ux/lightbox/loading.gif' 
20924                         },
20925                         {
20926                             tag: "span",
20927                             html: "Loading"
20928                         }
20929                         
20930                     ]
20931                 }
20932             ]
20933         };
20934         this.maskEl = Roo.DomHelper.append(this.el.select('.fc-content', true).first(), mark, true);
20935         
20936         var size = this.el.select('.fc-content', true).first().getSize();
20937         this.maskEl.setSize(size.width, size.height);
20938         this.maskEl.enableDisplayMode("block");
20939         if(!this.loadMask){
20940             this.maskEl.hide();
20941         }
20942         
20943         this.store = Roo.factory(this.store, Roo.data);
20944         this.store.on('load', this.onLoad, this);
20945         this.store.on('beforeload', this.onBeforeLoad, this);
20946         
20947         this.resize();
20948         
20949         this.cells = this.el.select('.fc-day',true);
20950         //Roo.log(this.cells);
20951         this.textNodes = this.el.query('.fc-day-number');
20952         this.cells.addClassOnOver('fc-state-hover');
20953         
20954         this.el.select('.fc-button-prev',true).on('click', this.showPrevMonth, this);
20955         this.el.select('.fc-button-next',true).on('click', this.showNextMonth, this);
20956         this.el.select('.fc-button-today',true).on('click', this.showToday, this);
20957         this.el.select('.fc-button',true).addClassOnOver('fc-state-hover');
20958         
20959         this.on('monthchange', this.onMonthChange, this);
20960         
20961         this.update(new Date().clearTime());
20962     },
20963     
20964     resize : function() {
20965         var sz  = this.el.getSize();
20966         
20967         this.el.select('.fc-day-header',true).setWidth(sz.width / 7);
20968         this.el.select('.fc-day-content div',true).setHeight(34);
20969     },
20970     
20971     
20972     // private
20973     showPrevMonth : function(e){
20974         this.update(this.activeDate.add("mo", -1));
20975     },
20976     showToday : function(e){
20977         this.update(new Date().clearTime());
20978     },
20979     // private
20980     showNextMonth : function(e){
20981         this.update(this.activeDate.add("mo", 1));
20982     },
20983
20984     // private
20985     showPrevYear : function(){
20986         this.update(this.activeDate.add("y", -1));
20987     },
20988
20989     // private
20990     showNextYear : function(){
20991         this.update(this.activeDate.add("y", 1));
20992     },
20993
20994     
20995    // private
20996     update : function(date)
20997     {
20998         var vd = this.activeDate;
20999         this.activeDate = date;
21000 //        if(vd && this.el){
21001 //            var t = date.getTime();
21002 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
21003 //                Roo.log('using add remove');
21004 //                
21005 //                this.fireEvent('monthchange', this, date);
21006 //                
21007 //                this.cells.removeClass("fc-state-highlight");
21008 //                this.cells.each(function(c){
21009 //                   if(c.dateValue == t){
21010 //                       c.addClass("fc-state-highlight");
21011 //                       setTimeout(function(){
21012 //                            try{c.dom.firstChild.focus();}catch(e){}
21013 //                       }, 50);
21014 //                       return false;
21015 //                   }
21016 //                   return true;
21017 //                });
21018 //                return;
21019 //            }
21020 //        }
21021         
21022         var days = date.getDaysInMonth();
21023         
21024         var firstOfMonth = date.getFirstDateOfMonth();
21025         var startingPos = firstOfMonth.getDay()-this.startDay;
21026         
21027         if(startingPos < this.startDay){
21028             startingPos += 7;
21029         }
21030         
21031         var pm = date.add(Date.MONTH, -1);
21032         var prevStart = pm.getDaysInMonth()-startingPos;
21033 //        
21034         this.cells = this.el.select('.fc-day',true);
21035         this.textNodes = this.el.query('.fc-day-number');
21036         this.cells.addClassOnOver('fc-state-hover');
21037         
21038         var cells = this.cells.elements;
21039         var textEls = this.textNodes;
21040         
21041         Roo.each(cells, function(cell){
21042             cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
21043         });
21044         
21045         days += startingPos;
21046
21047         // convert everything to numbers so it's fast
21048         var day = 86400000;
21049         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
21050         //Roo.log(d);
21051         //Roo.log(pm);
21052         //Roo.log(prevStart);
21053         
21054         var today = new Date().clearTime().getTime();
21055         var sel = date.clearTime().getTime();
21056         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
21057         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
21058         var ddMatch = this.disabledDatesRE;
21059         var ddText = this.disabledDatesText;
21060         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
21061         var ddaysText = this.disabledDaysText;
21062         var format = this.format;
21063         
21064         var setCellClass = function(cal, cell){
21065             cell.row = 0;
21066             cell.events = [];
21067             cell.more = [];
21068             //Roo.log('set Cell Class');
21069             cell.title = "";
21070             var t = d.getTime();
21071             
21072             //Roo.log(d);
21073             
21074             cell.dateValue = t;
21075             if(t == today){
21076                 cell.className += " fc-today";
21077                 cell.className += " fc-state-highlight";
21078                 cell.title = cal.todayText;
21079             }
21080             if(t == sel){
21081                 // disable highlight in other month..
21082                 //cell.className += " fc-state-highlight";
21083                 
21084             }
21085             // disabling
21086             if(t < min) {
21087                 cell.className = " fc-state-disabled";
21088                 cell.title = cal.minText;
21089                 return;
21090             }
21091             if(t > max) {
21092                 cell.className = " fc-state-disabled";
21093                 cell.title = cal.maxText;
21094                 return;
21095             }
21096             if(ddays){
21097                 if(ddays.indexOf(d.getDay()) != -1){
21098                     cell.title = ddaysText;
21099                     cell.className = " fc-state-disabled";
21100                 }
21101             }
21102             if(ddMatch && format){
21103                 var fvalue = d.dateFormat(format);
21104                 if(ddMatch.test(fvalue)){
21105                     cell.title = ddText.replace("%0", fvalue);
21106                     cell.className = " fc-state-disabled";
21107                 }
21108             }
21109             
21110             if (!cell.initialClassName) {
21111                 cell.initialClassName = cell.dom.className;
21112             }
21113             
21114             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
21115         };
21116
21117         var i = 0;
21118         
21119         for(; i < startingPos; i++) {
21120             textEls[i].innerHTML = (++prevStart);
21121             d.setDate(d.getDate()+1);
21122             
21123             cells[i].className = "fc-past fc-other-month";
21124             setCellClass(this, cells[i]);
21125         }
21126         
21127         var intDay = 0;
21128         
21129         for(; i < days; i++){
21130             intDay = i - startingPos + 1;
21131             textEls[i].innerHTML = (intDay);
21132             d.setDate(d.getDate()+1);
21133             
21134             cells[i].className = ''; // "x-date-active";
21135             setCellClass(this, cells[i]);
21136         }
21137         var extraDays = 0;
21138         
21139         for(; i < 42; i++) {
21140             textEls[i].innerHTML = (++extraDays);
21141             d.setDate(d.getDate()+1);
21142             
21143             cells[i].className = "fc-future fc-other-month";
21144             setCellClass(this, cells[i]);
21145         }
21146         
21147         this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
21148         
21149         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
21150         
21151         this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
21152         this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
21153         
21154         if(totalRows != 6){
21155             this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
21156             this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
21157         }
21158         
21159         this.fireEvent('monthchange', this, date);
21160         
21161         
21162         /*
21163         if(!this.internalRender){
21164             var main = this.el.dom.firstChild;
21165             var w = main.offsetWidth;
21166             this.el.setWidth(w + this.el.getBorderWidth("lr"));
21167             Roo.fly(main).setWidth(w);
21168             this.internalRender = true;
21169             // opera does not respect the auto grow header center column
21170             // then, after it gets a width opera refuses to recalculate
21171             // without a second pass
21172             if(Roo.isOpera && !this.secondPass){
21173                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
21174                 this.secondPass = true;
21175                 this.update.defer(10, this, [date]);
21176             }
21177         }
21178         */
21179         
21180     },
21181     
21182     findCell : function(dt) {
21183         dt = dt.clearTime().getTime();
21184         var ret = false;
21185         this.cells.each(function(c){
21186             //Roo.log("check " +c.dateValue + '?=' + dt);
21187             if(c.dateValue == dt){
21188                 ret = c;
21189                 return false;
21190             }
21191             return true;
21192         });
21193         
21194         return ret;
21195     },
21196     
21197     findCells : function(ev) {
21198         var s = ev.start.clone().clearTime().getTime();
21199        // Roo.log(s);
21200         var e= ev.end.clone().clearTime().getTime();
21201        // Roo.log(e);
21202         var ret = [];
21203         this.cells.each(function(c){
21204              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
21205             
21206             if(c.dateValue > e){
21207                 return ;
21208             }
21209             if(c.dateValue < s){
21210                 return ;
21211             }
21212             ret.push(c);
21213         });
21214         
21215         return ret;    
21216     },
21217     
21218 //    findBestRow: function(cells)
21219 //    {
21220 //        var ret = 0;
21221 //        
21222 //        for (var i =0 ; i < cells.length;i++) {
21223 //            ret  = Math.max(cells[i].rows || 0,ret);
21224 //        }
21225 //        return ret;
21226 //        
21227 //    },
21228     
21229     
21230     addItem : function(ev)
21231     {
21232         // look for vertical location slot in
21233         var cells = this.findCells(ev);
21234         
21235 //        ev.row = this.findBestRow(cells);
21236         
21237         // work out the location.
21238         
21239         var crow = false;
21240         var rows = [];
21241         for(var i =0; i < cells.length; i++) {
21242             
21243             cells[i].row = cells[0].row;
21244             
21245             if(i == 0){
21246                 cells[i].row = cells[i].row + 1;
21247             }
21248             
21249             if (!crow) {
21250                 crow = {
21251                     start : cells[i],
21252                     end :  cells[i]
21253                 };
21254                 continue;
21255             }
21256             if (crow.start.getY() == cells[i].getY()) {
21257                 // on same row.
21258                 crow.end = cells[i];
21259                 continue;
21260             }
21261             // different row.
21262             rows.push(crow);
21263             crow = {
21264                 start: cells[i],
21265                 end : cells[i]
21266             };
21267             
21268         }
21269         
21270         rows.push(crow);
21271         ev.els = [];
21272         ev.rows = rows;
21273         ev.cells = cells;
21274         
21275         cells[0].events.push(ev);
21276         
21277         this.calevents.push(ev);
21278     },
21279     
21280     clearEvents: function() {
21281         
21282         if(!this.calevents){
21283             return;
21284         }
21285         
21286         Roo.each(this.cells.elements, function(c){
21287             c.row = 0;
21288             c.events = [];
21289             c.more = [];
21290         });
21291         
21292         Roo.each(this.calevents, function(e) {
21293             Roo.each(e.els, function(el) {
21294                 el.un('mouseenter' ,this.onEventEnter, this);
21295                 el.un('mouseleave' ,this.onEventLeave, this);
21296                 el.remove();
21297             },this);
21298         },this);
21299         
21300         Roo.each(Roo.select('.fc-more-event', true).elements, function(e){
21301             e.remove();
21302         });
21303         
21304     },
21305     
21306     renderEvents: function()
21307     {   
21308         var _this = this;
21309         
21310         this.cells.each(function(c) {
21311             
21312             if(c.row < 5){
21313                 return;
21314             }
21315             
21316             var ev = c.events;
21317             
21318             var r = 4;
21319             if(c.row != c.events.length){
21320                 r = 4 - (4 - (c.row - c.events.length));
21321             }
21322             
21323             c.events = ev.slice(0, r);
21324             c.more = ev.slice(r);
21325             
21326             if(c.more.length && c.more.length == 1){
21327                 c.events.push(c.more.pop());
21328             }
21329             
21330             c.row = (c.row - ev.length) + c.events.length + ((c.more.length) ? 1 : 0);
21331             
21332         });
21333             
21334         this.cells.each(function(c) {
21335             
21336             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, c.row * 20));
21337             
21338             
21339             for (var e = 0; e < c.events.length; e++){
21340                 var ev = c.events[e];
21341                 var rows = ev.rows;
21342                 
21343                 for(var i = 0; i < rows.length; i++) {
21344                 
21345                     // how many rows should it span..
21346
21347                     var  cfg = {
21348                         cls : 'roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable',
21349                         style : 'position: absolute', // left: 387px; width: 121px; top: 359px;
21350
21351                         unselectable : "on",
21352                         cn : [
21353                             {
21354                                 cls: 'fc-event-inner',
21355                                 cn : [
21356     //                                {
21357     //                                  tag:'span',
21358     //                                  cls: 'fc-event-time',
21359     //                                  html : cells.length > 1 ? '' : ev.time
21360     //                                },
21361                                     {
21362                                       tag:'span',
21363                                       cls: 'fc-event-title',
21364                                       html : String.format('{0}', ev.title)
21365                                     }
21366
21367
21368                                 ]
21369                             },
21370                             {
21371                                 cls: 'ui-resizable-handle ui-resizable-e',
21372                                 html : '&nbsp;&nbsp;&nbsp'
21373                             }
21374
21375                         ]
21376                     };
21377
21378                     if (i == 0) {
21379                         cfg.cls += ' fc-event-start';
21380                     }
21381                     if ((i+1) == rows.length) {
21382                         cfg.cls += ' fc-event-end';
21383                     }
21384
21385                     var ctr = _this.el.select('.fc-event-container',true).first();
21386                     var cg = ctr.createChild(cfg);
21387
21388                     var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
21389                     var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
21390
21391                     var r = (c.more.length) ? 1 : 0;
21392                     cg.setXY([sbox.x +2, sbox.y + ((c.row - c.events.length - r + e) * 20)]);    
21393                     cg.setWidth(ebox.right - sbox.x -2);
21394
21395                     cg.on('mouseenter' ,_this.onEventEnter, _this, ev);
21396                     cg.on('mouseleave' ,_this.onEventLeave, _this, ev);
21397                     cg.on('click', _this.onEventClick, _this, ev);
21398
21399                     ev.els.push(cg);
21400                     
21401                 }
21402                 
21403             }
21404             
21405             
21406             if(c.more.length){
21407                 var  cfg = {
21408                     cls : 'fc-more-event roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable fc-event-start fc-event-end',
21409                     style : 'position: absolute',
21410                     unselectable : "on",
21411                     cn : [
21412                         {
21413                             cls: 'fc-event-inner',
21414                             cn : [
21415                                 {
21416                                   tag:'span',
21417                                   cls: 'fc-event-title',
21418                                   html : 'More'
21419                                 }
21420
21421
21422                             ]
21423                         },
21424                         {
21425                             cls: 'ui-resizable-handle ui-resizable-e',
21426                             html : '&nbsp;&nbsp;&nbsp'
21427                         }
21428
21429                     ]
21430                 };
21431
21432                 var ctr = _this.el.select('.fc-event-container',true).first();
21433                 var cg = ctr.createChild(cfg);
21434
21435                 var sbox = c.select('.fc-day-content',true).first().getBox();
21436                 var ebox = c.select('.fc-day-content',true).first().getBox();
21437                 //Roo.log(cg);
21438                 cg.setXY([sbox.x +2, sbox.y +((c.row - 1) * 20)]);    
21439                 cg.setWidth(ebox.right - sbox.x -2);
21440
21441                 cg.on('click', _this.onMoreEventClick, _this, c.more);
21442                 
21443             }
21444             
21445         });
21446         
21447         
21448         
21449     },
21450     
21451     onEventEnter: function (e, el,event,d) {
21452         this.fireEvent('evententer', this, el, event);
21453     },
21454     
21455     onEventLeave: function (e, el,event,d) {
21456         this.fireEvent('eventleave', this, el, event);
21457     },
21458     
21459     onEventClick: function (e, el,event,d) {
21460         this.fireEvent('eventclick', this, el, event);
21461     },
21462     
21463     onMonthChange: function () {
21464         this.store.load();
21465     },
21466     
21467     onMoreEventClick: function(e, el, more)
21468     {
21469         var _this = this;
21470         
21471         this.calpopover.placement = 'right';
21472         this.calpopover.setTitle('More');
21473         
21474         this.calpopover.setContent('');
21475         
21476         var ctr = this.calpopover.el.select('.popover-content', true).first();
21477         
21478         Roo.each(more, function(m){
21479             var cfg = {
21480                 cls : 'fc-event-hori fc-event-draggable',
21481                 html : m.title
21482             };
21483             var cg = ctr.createChild(cfg);
21484             
21485             cg.on('click', _this.onEventClick, _this, m);
21486         });
21487         
21488         this.calpopover.show(el);
21489         
21490         
21491     },
21492     
21493     onLoad: function () 
21494     {   
21495         this.calevents = [];
21496         var cal = this;
21497         
21498         if(this.store.getCount() > 0){
21499             this.store.data.each(function(d){
21500                cal.addItem({
21501                     id : d.data.id,
21502                     start: (typeof(d.data.start_dt) === 'string') ? new Date.parseDate(d.data.start_dt, 'Y-m-d H:i:s') : d.data.start_dt,
21503                     end : (typeof(d.data.end_dt) === 'string') ? new Date.parseDate(d.data.end_dt, 'Y-m-d H:i:s') : d.data.end_dt,
21504                     time : d.data.start_time,
21505                     title : d.data.title,
21506                     description : d.data.description,
21507                     venue : d.data.venue
21508                 });
21509             });
21510         }
21511         
21512         this.renderEvents();
21513         
21514         if(this.calevents.length && this.loadMask){
21515             this.maskEl.hide();
21516         }
21517     },
21518     
21519     onBeforeLoad: function()
21520     {
21521         this.clearEvents();
21522         if(this.loadMask){
21523             this.maskEl.show();
21524         }
21525     }
21526 });
21527
21528  
21529  /*
21530  * - LGPL
21531  *
21532  * element
21533  * 
21534  */
21535
21536 /**
21537  * @class Roo.bootstrap.Popover
21538  * @extends Roo.bootstrap.Component
21539  * @parent none builder
21540  * @children Roo.bootstrap.Component
21541  * Bootstrap Popover class
21542  * @cfg {String} html contents of the popover   (or false to use children..)
21543  * @cfg {String} title of popover (or false to hide)
21544  * @cfg {String|function} (right|top|bottom|left|auto) placement how it is placed
21545  * @cfg {String} trigger click || hover (or false to trigger manually)
21546  * @cfg {Boolean} modal - popovers that are modal will mask the screen, and must be closed with another event.
21547  * @cfg {String|Boolean|Roo.Element} add click hander to trigger show over what element
21548  *      - if false and it has a 'parent' then it will be automatically added to that element
21549  *      - if string - Roo.get  will be called 
21550  * @cfg {Number} delay - delay before showing
21551  
21552  * @constructor
21553  * Create a new Popover
21554  * @param {Object} config The config object
21555  */
21556
21557 Roo.bootstrap.Popover = function(config){
21558     Roo.bootstrap.Popover.superclass.constructor.call(this, config);
21559     
21560     this.addEvents({
21561         // raw events
21562          /**
21563          * @event show
21564          * After the popover show
21565          * 
21566          * @param {Roo.bootstrap.Popover} this
21567          */
21568         "show" : true,
21569         /**
21570          * @event hide
21571          * After the popover hide
21572          * 
21573          * @param {Roo.bootstrap.Popover} this
21574          */
21575         "hide" : true
21576     });
21577 };
21578
21579 Roo.extend(Roo.bootstrap.Popover, Roo.bootstrap.Component,  {
21580     
21581     title: false,
21582     html: false,
21583     
21584     placement : 'right',
21585     trigger : 'hover', // hover
21586     modal : false,
21587     delay : 0,
21588     
21589     over: false,
21590     
21591     can_build_overlaid : false,
21592     
21593     maskEl : false, // the mask element
21594     headerEl : false,
21595     contentEl : false,
21596     alignEl : false, // when show is called with an element - this get's stored.
21597     
21598     getChildContainer : function()
21599     {
21600         return this.contentEl;
21601         
21602     },
21603     getPopoverHeader : function()
21604     {
21605         this.title = true; // flag not to hide it..
21606         this.headerEl.addClass('p-0');
21607         return this.headerEl
21608     },
21609     
21610     
21611     getAutoCreate : function(){
21612          
21613         var cfg = {
21614            cls : 'popover roo-dynamic shadow roo-popover' + (this.modal ? '-modal' : ''),
21615            style: 'display:block',
21616            cn : [
21617                 {
21618                     cls : 'arrow'
21619                 },
21620                 {
21621                     cls : 'popover-inner ',
21622                     cn : [
21623                         {
21624                             tag: 'h3',
21625                             cls: 'popover-title popover-header',
21626                             html : this.title === false ? '' : this.title
21627                         },
21628                         {
21629                             cls : 'popover-content popover-body '  + (this.cls || ''),
21630                             html : this.html || ''
21631                         }
21632                     ]
21633                     
21634                 }
21635            ]
21636         };
21637         
21638         return cfg;
21639     },
21640     /**
21641      * @param {string} the title
21642      */
21643     setTitle: function(str)
21644     {
21645         this.title = str;
21646         if (this.el) {
21647             this.headerEl.dom.innerHTML = str;
21648         }
21649         
21650     },
21651     /**
21652      * @param {string} the body content
21653      */
21654     setContent: function(str)
21655     {
21656         this.html = str;
21657         if (this.contentEl) {
21658             this.contentEl.dom.innerHTML = str;
21659         }
21660         
21661     },
21662     // as it get's added to the bottom of the page.
21663     onRender : function(ct, position)
21664     {
21665         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
21666         
21667         
21668         
21669         if(!this.el){
21670             var cfg = Roo.apply({},  this.getAutoCreate());
21671             cfg.id = Roo.id();
21672             
21673             if (this.cls) {
21674                 cfg.cls += ' ' + this.cls;
21675             }
21676             if (this.style) {
21677                 cfg.style = this.style;
21678             }
21679             //Roo.log("adding to ");
21680             this.el = Roo.get(document.body).createChild(cfg, position);
21681 //            Roo.log(this.el);
21682         }
21683         
21684         this.contentEl = this.el.select('.popover-content',true).first();
21685         this.headerEl =  this.el.select('.popover-title',true).first();
21686         
21687         var nitems = [];
21688         if(typeof(this.items) != 'undefined'){
21689             var items = this.items;
21690             delete this.items;
21691
21692             for(var i =0;i < items.length;i++) {
21693                 nitems.push(this.addxtype(Roo.apply({}, items[i])));
21694             }
21695         }
21696
21697         this.items = nitems;
21698         
21699         this.maskEl = Roo.DomHelper.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
21700         Roo.EventManager.onWindowResize(this.resizeMask, this, true);
21701         
21702         
21703         
21704         this.initEvents();
21705     },
21706     
21707     resizeMask : function()
21708     {
21709         this.maskEl.setSize(
21710             Roo.lib.Dom.getViewWidth(true),
21711             Roo.lib.Dom.getViewHeight(true)
21712         );
21713     },
21714     
21715     initEvents : function()
21716     {
21717         
21718         if (!this.modal) { 
21719             Roo.bootstrap.Popover.register(this);
21720         }
21721          
21722         this.arrowEl = this.el.select('.arrow',true).first();
21723         this.headerEl.setVisibilityMode(Roo.Element.DISPLAY); // probably not needed as it's default in BS4
21724         this.el.enableDisplayMode('block');
21725         this.el.hide();
21726  
21727         
21728         if (this.over === false && !this.parent()) {
21729             return; 
21730         }
21731         if (this.triggers === false) {
21732             return;
21733         }
21734          
21735         // support parent
21736         var on_el = (this.over == 'parent' || this.over === false) ? this.parent().el : Roo.get(this.over);
21737         var triggers = this.trigger ? this.trigger.split(' ') : [];
21738         Roo.each(triggers, function(trigger) {
21739         
21740             if (trigger == 'click') {
21741                 on_el.on('click', this.toggle, this);
21742             } else if (trigger != 'manual') {
21743                 var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin';
21744                 var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
21745       
21746                 on_el.on(eventIn  ,this.enter, this);
21747                 on_el.on(eventOut, this.leave, this);
21748             }
21749         }, this);
21750     },
21751     
21752     
21753     // private
21754     timeout : null,
21755     hoverState : null,
21756     
21757     toggle : function () {
21758         this.hoverState == 'in' ? this.leave() : this.enter();
21759     },
21760     
21761     enter : function () {
21762         
21763         clearTimeout(this.timeout);
21764     
21765         this.hoverState = 'in';
21766     
21767         if (!this.delay || !this.delay.show) {
21768             this.show();
21769             return;
21770         }
21771         var _t = this;
21772         this.timeout = setTimeout(function () {
21773             if (_t.hoverState == 'in') {
21774                 _t.show();
21775             }
21776         }, this.delay.show)
21777     },
21778     
21779     leave : function() {
21780         clearTimeout(this.timeout);
21781     
21782         this.hoverState = 'out';
21783     
21784         if (!this.delay || !this.delay.hide) {
21785             this.hide();
21786             return;
21787         }
21788         var _t = this;
21789         this.timeout = setTimeout(function () {
21790             if (_t.hoverState == 'out') {
21791                 _t.hide();
21792             }
21793         }, this.delay.hide)
21794     },
21795     
21796     /**
21797      * update the position of the dialog
21798      * normally this is needed if the popover get's bigger - due to a Table reload etc..
21799      * 
21800      *
21801      */
21802     
21803     doAlign : function()
21804     {
21805         
21806         if (this.alignEl) {
21807             this.updatePosition(this.placement, true);
21808              
21809         } else {
21810             // this is usually just done by the builder = to show the popoup in the middle of the scren.
21811             var es = this.el.getSize();
21812             var x = Roo.lib.Dom.getViewWidth()/2;
21813             var y = Roo.lib.Dom.getViewHeight()/2;
21814             this.el.setXY([ x-(es.width/2),  y-(es.height/2)] );
21815             
21816         }
21817
21818          
21819          
21820         
21821         
21822     },
21823     
21824     /**
21825      * Show the popover
21826      * @param {Roo.Element|string|Boolean} - element to align and point to. (set align to [ pos, offset ])
21827      * @param {string} (left|right|top|bottom) position
21828      */
21829     show : function (on_el, placement)
21830     {
21831         this.placement = typeof(placement) == 'undefined' ?  this.placement   : placement;
21832         on_el = on_el || false; // default to false
21833          
21834         if (!on_el) {
21835             if (this.parent() && (this.over == 'parent' || (this.over === false))) {
21836                 on_el = this.parent().el;
21837             } else if (this.over) {
21838                 on_el = Roo.get(this.over);
21839             }
21840             
21841         }
21842         
21843         this.alignEl = Roo.get( on_el );
21844
21845         if (!this.el) {
21846             this.render(document.body);
21847         }
21848         
21849         
21850          
21851         
21852         if (this.title === false) {
21853             this.headerEl.hide();
21854         }
21855         
21856        
21857         this.el.show();
21858         this.el.dom.style.display = 'block';
21859          
21860         this.doAlign();
21861         
21862         //var arrow = this.el.select('.arrow',true).first();
21863         //arrow.set(align[2], 
21864         
21865         this.el.addClass('in');
21866         
21867          
21868         
21869         this.hoverState = 'in';
21870         
21871         if (this.modal) {
21872             this.maskEl.setSize(Roo.lib.Dom.getViewWidth(true),   Roo.lib.Dom.getViewHeight(true));
21873             this.maskEl.setStyle('z-index', Roo.bootstrap.Popover.zIndex++);
21874             this.maskEl.dom.style.display = 'block';
21875             this.maskEl.addClass('show');
21876         }
21877         this.el.setStyle('z-index', Roo.bootstrap.Popover.zIndex++);
21878  
21879         this.fireEvent('show', this);
21880         
21881     },
21882     /**
21883      * fire this manually after loading a grid in the table for example
21884      * @param {string} (left|right|top|bottom) where to try and put it (use false to use the last one)
21885      * @param {Boolean} try and move it if we cant get right position.
21886      */
21887     updatePosition : function(placement, try_move)
21888     {
21889         // allow for calling with no parameters
21890         placement = placement   ? placement :  this.placement;
21891         try_move = typeof(try_move) == 'undefined' ? true : try_move;
21892         
21893         this.el.removeClass([
21894             'fade','top','bottom', 'left', 'right','in',
21895             'bs-popover-top','bs-popover-bottom', 'bs-popover-left', 'bs-popover-right'
21896         ]);
21897         this.el.addClass(placement + ' bs-popover-' + placement);
21898         
21899         if (!this.alignEl ) {
21900             return false;
21901         }
21902         
21903         switch (placement) {
21904             case 'right':
21905                 var exact = this.el.getAlignToXY(this.alignEl, 'tl-tr', [10,0]);
21906                 var offset = this.el.getAlignToXY(this.alignEl, 'tl-tr?',[10,0]);
21907                 if (!try_move || exact.equals(offset) || exact[0] == offset[0] ) {
21908                     //normal display... or moved up/down.
21909                     this.el.setXY(offset);
21910                     var xy = this.alignEl.getAnchorXY('tr', false);
21911                     xy[0]+=2;xy[1]+=5;
21912                     this.arrowEl.setXY(xy);
21913                     return true;
21914                 }
21915                 // continue through...
21916                 return this.updatePosition('left', false);
21917                 
21918             
21919             case 'left':
21920                 var exact = this.el.getAlignToXY(this.alignEl, 'tr-tl', [-10,0]);
21921                 var offset = this.el.getAlignToXY(this.alignEl, 'tr-tl?',[-10,0]);
21922                 if (!try_move || exact.equals(offset) || exact[0] == offset[0] ) {
21923                     //normal display... or moved up/down.
21924                     this.el.setXY(offset);
21925                     var xy = this.alignEl.getAnchorXY('tl', false);
21926                     xy[0]-=10;xy[1]+=5; // << fix me
21927                     this.arrowEl.setXY(xy);
21928                     return true;
21929                 }
21930                 // call self...
21931                 return this.updatePosition('right', false);
21932             
21933             case 'top':
21934                 var exact = this.el.getAlignToXY(this.alignEl, 'b-t', [0,-10]);
21935                 var offset = this.el.getAlignToXY(this.alignEl, 'b-t?',[0,-10]);
21936                 if (!try_move || exact.equals(offset) || exact[1] == offset[1] ) {
21937                     //normal display... or moved up/down.
21938                     this.el.setXY(offset);
21939                     var xy = this.alignEl.getAnchorXY('t', false);
21940                     xy[1]-=10; // << fix me
21941                     this.arrowEl.setXY(xy);
21942                     return true;
21943                 }
21944                 // fall through
21945                return this.updatePosition('bottom', false);
21946             
21947             case 'bottom':
21948                  var exact = this.el.getAlignToXY(this.alignEl, 't-b', [0,10]);
21949                 var offset = this.el.getAlignToXY(this.alignEl, 't-b?',[0,10]);
21950                 if (!try_move || exact.equals(offset) || exact[1] == offset[1] ) {
21951                     //normal display... or moved up/down.
21952                     this.el.setXY(offset);
21953                     var xy = this.alignEl.getAnchorXY('b', false);
21954                      xy[1]+=2; // << fix me
21955                     this.arrowEl.setXY(xy);
21956                     return true;
21957                 }
21958                 // fall through
21959                 return this.updatePosition('top', false);
21960                 
21961             
21962         }
21963         
21964         
21965         return false;
21966     },
21967     
21968     hide : function()
21969     {
21970         this.el.setXY([0,0]);
21971         this.el.removeClass('in');
21972         this.el.hide();
21973         this.hoverState = null;
21974         this.maskEl.hide(); // always..
21975         this.fireEvent('hide', this);
21976     }
21977     
21978 });
21979
21980
21981 Roo.apply(Roo.bootstrap.Popover, {
21982
21983     alignment : {
21984         'left' : ['r-l', [-10,0], 'left bs-popover-left'],
21985         'right' : ['l-br', [10,0], 'right bs-popover-right'],
21986         'bottom' : ['t-b', [0,10], 'top bs-popover-top'],
21987         'top' : [ 'b-t', [0,-10], 'bottom bs-popover-bottom']
21988     },
21989     
21990     zIndex : 20001,
21991
21992     clickHander : false,
21993     
21994     
21995
21996     onMouseDown : function(e)
21997     {
21998         if (this.popups.length &&  !e.getTarget(".roo-popover")) {
21999             /// what is nothing is showing..
22000             this.hideAll();
22001         }
22002          
22003     },
22004     
22005     
22006     popups : [],
22007     
22008     register : function(popup)
22009     {
22010         if (!Roo.bootstrap.Popover.clickHandler) {
22011             Roo.bootstrap.Popover.clickHandler = Roo.get(document).on("mousedown", Roo.bootstrap.Popover.onMouseDown, Roo.bootstrap.Popover);
22012         }
22013         // hide other popups.
22014         popup.on('show', Roo.bootstrap.Popover.onShow,  popup);
22015         popup.on('hide', Roo.bootstrap.Popover.onHide,  popup);
22016         this.hideAll(); //<< why?
22017         //this.popups.push(popup);
22018     },
22019     hideAll : function()
22020     {
22021         this.popups.forEach(function(p) {
22022             p.hide();
22023         });
22024     },
22025     onShow : function() {
22026         Roo.bootstrap.Popover.popups.push(this);
22027     },
22028     onHide : function() {
22029         Roo.bootstrap.Popover.popups.remove(this);
22030     } 
22031
22032 });
22033 /**
22034  * @class Roo.bootstrap.PopoverNav
22035  * @extends Roo.bootstrap.nav.Simplebar
22036  * @parent Roo.bootstrap.Popover
22037  * @children Roo.bootstrap.nav.Group Roo.bootstrap.Container
22038  * @licence LGPL
22039  * Bootstrap Popover header navigation class
22040  * FIXME? should this go under nav?
22041  *
22042  * 
22043  * @constructor
22044  * Create a new Popover Header Navigation 
22045  * @param {Object} config The config object
22046  */
22047
22048 Roo.bootstrap.PopoverNav = function(config){
22049     Roo.bootstrap.PopoverNav.superclass.constructor.call(this, config);
22050 };
22051
22052 Roo.extend(Roo.bootstrap.PopoverNav, Roo.bootstrap.nav.Simplebar,  {
22053     
22054     
22055     container_method : 'getPopoverHeader' 
22056     
22057      
22058     
22059     
22060    
22061 });
22062
22063  
22064
22065  /*
22066  * - LGPL
22067  *
22068  * Progress
22069  * 
22070  */
22071
22072 /**
22073  * @class Roo.bootstrap.Progress
22074  * @extends Roo.bootstrap.Component
22075  * @children Roo.bootstrap.ProgressBar
22076  * Bootstrap Progress class
22077  * @cfg {Boolean} striped striped of the progress bar
22078  * @cfg {Boolean} active animated of the progress bar
22079  * 
22080  * 
22081  * @constructor
22082  * Create a new Progress
22083  * @param {Object} config The config object
22084  */
22085
22086 Roo.bootstrap.Progress = function(config){
22087     Roo.bootstrap.Progress.superclass.constructor.call(this, config);
22088 };
22089
22090 Roo.extend(Roo.bootstrap.Progress, Roo.bootstrap.Component,  {
22091     
22092     striped : false,
22093     active: false,
22094     
22095     getAutoCreate : function(){
22096         var cfg = {
22097             tag: 'div',
22098             cls: 'progress'
22099         };
22100         
22101         
22102         if(this.striped){
22103             cfg.cls += ' progress-striped';
22104         }
22105       
22106         if(this.active){
22107             cfg.cls += ' active';
22108         }
22109         
22110         
22111         return cfg;
22112     }
22113    
22114 });
22115
22116  
22117
22118  /*
22119  * - LGPL
22120  *
22121  * ProgressBar
22122  * 
22123  */
22124
22125 /**
22126  * @class Roo.bootstrap.ProgressBar
22127  * @extends Roo.bootstrap.Component
22128  * Bootstrap ProgressBar class
22129  * @cfg {Number} aria_valuenow aria-value now
22130  * @cfg {Number} aria_valuemin aria-value min
22131  * @cfg {Number} aria_valuemax aria-value max
22132  * @cfg {String} label label for the progress bar
22133  * @cfg {String} panel (success | info | warning | danger )
22134  * @cfg {String} role role of the progress bar
22135  * @cfg {String} sr_only text
22136  * 
22137  * 
22138  * @constructor
22139  * Create a new ProgressBar
22140  * @param {Object} config The config object
22141  */
22142
22143 Roo.bootstrap.ProgressBar = function(config){
22144     Roo.bootstrap.ProgressBar.superclass.constructor.call(this, config);
22145 };
22146
22147 Roo.extend(Roo.bootstrap.ProgressBar, Roo.bootstrap.Component,  {
22148     
22149     aria_valuenow : 0,
22150     aria_valuemin : 0,
22151     aria_valuemax : 100,
22152     label : false,
22153     panel : false,
22154     role : false,
22155     sr_only: false,
22156     
22157     getAutoCreate : function()
22158     {
22159         
22160         var cfg = {
22161             tag: 'div',
22162             cls: 'progress-bar',
22163             style: 'width:' + Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%'
22164         };
22165         
22166         if(this.sr_only){
22167             cfg.cn = {
22168                 tag: 'span',
22169                 cls: 'sr-only',
22170                 html: this.sr_only
22171             }
22172         }
22173         
22174         if(this.role){
22175             cfg.role = this.role;
22176         }
22177         
22178         if(this.aria_valuenow){
22179             cfg['aria-valuenow'] = this.aria_valuenow;
22180         }
22181         
22182         if(this.aria_valuemin){
22183             cfg['aria-valuemin'] = this.aria_valuemin;
22184         }
22185         
22186         if(this.aria_valuemax){
22187             cfg['aria-valuemax'] = this.aria_valuemax;
22188         }
22189         
22190         if(this.label && !this.sr_only){
22191             cfg.html = this.label;
22192         }
22193         
22194         if(this.panel){
22195             cfg.cls += ' progress-bar-' + this.panel;
22196         }
22197         
22198         return cfg;
22199     },
22200     
22201     update : function(aria_valuenow)
22202     {
22203         this.aria_valuenow = aria_valuenow;
22204         
22205         this.el.setStyle('width', Math.ceil((this.aria_valuenow / this.aria_valuemax) * 100) + '%');
22206     }
22207    
22208 });
22209
22210  
22211
22212  /**
22213  * @class Roo.bootstrap.TabGroup
22214  * @extends Roo.bootstrap.Column
22215  * @children Roo.bootstrap.TabPanel
22216  * Bootstrap Column class
22217  * @cfg {String} navId the navigation id (for use with navbars) - will be auto generated if it does not exist..
22218  * @cfg {Boolean} carousel true to make the group behave like a carousel
22219  * @cfg {Boolean} bullets show bullets for the panels
22220  * @cfg {Boolean} autoslide (true|false) auto slide .. default false
22221  * @cfg {Number} timer auto slide timer .. default 0 millisecond
22222  * @cfg {Boolean} showarrow (true|false) show arrow default true
22223  * 
22224  * @constructor
22225  * Create a new TabGroup
22226  * @param {Object} config The config object
22227  */
22228
22229 Roo.bootstrap.TabGroup = function(config){
22230     Roo.bootstrap.TabGroup.superclass.constructor.call(this, config);
22231     if (!this.navId) {
22232         this.navId = Roo.id();
22233     }
22234     this.tabs = [];
22235     Roo.bootstrap.TabGroup.register(this);
22236     
22237 };
22238
22239 Roo.extend(Roo.bootstrap.TabGroup, Roo.bootstrap.Column,  {
22240     
22241     carousel : false,
22242     transition : false,
22243     bullets : 0,
22244     timer : 0,
22245     autoslide : false,
22246     slideFn : false,
22247     slideOnTouch : false,
22248     showarrow : true,
22249     
22250     getAutoCreate : function()
22251     {
22252         var cfg = Roo.apply({}, Roo.bootstrap.TabGroup.superclass.getAutoCreate.call(this));
22253         
22254         cfg.cls += ' tab-content';
22255         
22256         if (this.carousel) {
22257             cfg.cls += ' carousel slide';
22258             
22259             cfg.cn = [{
22260                cls : 'carousel-inner',
22261                cn : []
22262             }];
22263         
22264             if(this.bullets  && !Roo.isTouch){
22265                 
22266                 var bullets = {
22267                     cls : 'carousel-bullets',
22268                     cn : []
22269                 };
22270                
22271                 if(this.bullets_cls){
22272                     bullets.cls = bullets.cls + ' ' + this.bullets_cls;
22273                 }
22274                 
22275                 bullets.cn.push({
22276                     cls : 'clear'
22277                 });
22278                 
22279                 cfg.cn[0].cn.push(bullets);
22280             }
22281             
22282             if(this.showarrow){
22283                 cfg.cn[0].cn.push({
22284                     tag : 'div',
22285                     class : 'carousel-arrow',
22286                     cn : [
22287                         {
22288                             tag : 'div',
22289                             class : 'carousel-prev',
22290                             cn : [
22291                                 {
22292                                     tag : 'i',
22293                                     class : 'fa fa-chevron-left'
22294                                 }
22295                             ]
22296                         },
22297                         {
22298                             tag : 'div',
22299                             class : 'carousel-next',
22300                             cn : [
22301                                 {
22302                                     tag : 'i',
22303                                     class : 'fa fa-chevron-right'
22304                                 }
22305                             ]
22306                         }
22307                     ]
22308                 });
22309             }
22310             
22311         }
22312         
22313         return cfg;
22314     },
22315     
22316     initEvents:  function()
22317     {
22318 //        if(Roo.isTouch && this.slideOnTouch && !this.showarrow){
22319 //            this.el.on("touchstart", this.onTouchStart, this);
22320 //        }
22321         
22322         if(this.autoslide){
22323             var _this = this;
22324             
22325             this.slideFn = window.setInterval(function() {
22326                 _this.showPanelNext();
22327             }, this.timer);
22328         }
22329         
22330         if(this.showarrow){
22331             this.el.select('.carousel-prev', true).first().on('click', this.showPanelPrev, this);
22332             this.el.select('.carousel-next', true).first().on('click', this.showPanelNext, this);
22333         }
22334         
22335         
22336     },
22337     
22338 //    onTouchStart : function(e, el, o)
22339 //    {
22340 //        if(!this.slideOnTouch || !Roo.isTouch || Roo.get(e.getTarget()).hasClass('roo-button-text')){
22341 //            return;
22342 //        }
22343 //        
22344 //        this.showPanelNext();
22345 //    },
22346     
22347     
22348     getChildContainer : function()
22349     {
22350         return this.carousel ? this.el.select('.carousel-inner', true).first() : this.el;
22351     },
22352     
22353     /**
22354     * register a Navigation item
22355     * @param {Roo.bootstrap.nav.Item} the navitem to add
22356     */
22357     register : function(item)
22358     {
22359         this.tabs.push( item);
22360         item.navId = this.navId; // not really needed..
22361         this.addBullet();
22362     
22363     },
22364     
22365     getActivePanel : function()
22366     {
22367         var r = false;
22368         Roo.each(this.tabs, function(t) {
22369             if (t.active) {
22370                 r = t;
22371                 return false;
22372             }
22373             return null;
22374         });
22375         return r;
22376         
22377     },
22378     getPanelByName : function(n)
22379     {
22380         var r = false;
22381         Roo.each(this.tabs, function(t) {
22382             if (t.tabId == n) {
22383                 r = t;
22384                 return false;
22385             }
22386             return null;
22387         });
22388         return r;
22389     },
22390     indexOfPanel : function(p)
22391     {
22392         var r = false;
22393         Roo.each(this.tabs, function(t,i) {
22394             if (t.tabId == p.tabId) {
22395                 r = i;
22396                 return false;
22397             }
22398             return null;
22399         });
22400         return r;
22401     },
22402     /**
22403      * show a specific panel
22404      * @param {Roo.bootstrap.TabPanel|number|string} panel to change to (use the tabId to specify a specific one)
22405      * @return {boolean} false if panel was not shown (invalid entry or beforedeactivate fails.)
22406      */
22407     showPanel : function (pan)
22408     {
22409         if(this.transition || typeof(pan) == 'undefined'){
22410             Roo.log("waiting for the transitionend");
22411             return false;
22412         }
22413         
22414         if (typeof(pan) == 'number') {
22415             pan = this.tabs[pan];
22416         }
22417         
22418         if (typeof(pan) == 'string') {
22419             pan = this.getPanelByName(pan);
22420         }
22421         
22422         var cur = this.getActivePanel();
22423         
22424         if(!pan || !cur){
22425             Roo.log('pan or acitve pan is undefined');
22426             return false;
22427         }
22428         
22429         if (pan.tabId == this.getActivePanel().tabId) {
22430             return true;
22431         }
22432         
22433         if (false === cur.fireEvent('beforedeactivate')) {
22434             return false;
22435         }
22436         
22437         if(this.bullets > 0 && !Roo.isTouch){
22438             this.setActiveBullet(this.indexOfPanel(pan));
22439         }
22440         
22441         if (this.carousel && typeof(Roo.get(document.body).dom.style.transition) != 'undefined') {
22442             
22443             //class="carousel-item carousel-item-next carousel-item-left"
22444             
22445             this.transition = true;
22446             var dir = this.indexOfPanel(pan) > this.indexOfPanel(cur)  ? 'next' : 'prev';
22447             var lr = dir == 'next' ? 'left' : 'right';
22448             pan.el.addClass(dir); // or prev
22449             pan.el.addClass('carousel-item-' + dir); // or prev
22450             pan.el.dom.offsetWidth; // find the offset with - causing a reflow?
22451             cur.el.addClass(lr); // or right
22452             pan.el.addClass(lr);
22453             cur.el.addClass('carousel-item-' +lr); // or right
22454             pan.el.addClass('carousel-item-' +lr);
22455             
22456             
22457             var _this = this;
22458             cur.el.on('transitionend', function() {
22459                 Roo.log("trans end?");
22460                 
22461                 pan.el.removeClass([lr,dir, 'carousel-item-' + lr, 'carousel-item-' + dir]);
22462                 pan.setActive(true);
22463                 
22464                 cur.el.removeClass([lr, 'carousel-item-' + lr]);
22465                 cur.setActive(false);
22466                 
22467                 _this.transition = false;
22468                 
22469             }, this, { single:  true } );
22470             
22471             return true;
22472         }
22473         
22474         cur.setActive(false);
22475         pan.setActive(true);
22476         
22477         return true;
22478         
22479     },
22480     showPanelNext : function()
22481     {
22482         var i = this.indexOfPanel(this.getActivePanel());
22483         
22484         if (i >= this.tabs.length - 1 && !this.autoslide) {
22485             return;
22486         }
22487         
22488         if (i >= this.tabs.length - 1 && this.autoslide) {
22489             i = -1;
22490         }
22491         
22492         this.showPanel(this.tabs[i+1]);
22493     },
22494     
22495     showPanelPrev : function()
22496     {
22497         var i = this.indexOfPanel(this.getActivePanel());
22498         
22499         if (i  < 1 && !this.autoslide) {
22500             return;
22501         }
22502         
22503         if (i < 1 && this.autoslide) {
22504             i = this.tabs.length;
22505         }
22506         
22507         this.showPanel(this.tabs[i-1]);
22508     },
22509     
22510     
22511     addBullet: function()
22512     {
22513         if(!this.bullets || Roo.isTouch){
22514             return;
22515         }
22516         var ctr = this.el.select('.carousel-bullets',true).first();
22517         var i = this.el.select('.carousel-bullets .bullet',true).getCount() ;
22518         var bullet = ctr.createChild({
22519             cls : 'bullet bullet-' + i
22520         },ctr.dom.lastChild);
22521         
22522         
22523         var _this = this;
22524         
22525         bullet.on('click', (function(e, el, o, ii, t){
22526
22527             e.preventDefault();
22528
22529             this.showPanel(ii);
22530
22531             if(this.autoslide && this.slideFn){
22532                 clearInterval(this.slideFn);
22533                 this.slideFn = window.setInterval(function() {
22534                     _this.showPanelNext();
22535                 }, this.timer);
22536             }
22537
22538         }).createDelegate(this, [i, bullet], true));
22539                 
22540         
22541     },
22542      
22543     setActiveBullet : function(i)
22544     {
22545         if(Roo.isTouch){
22546             return;
22547         }
22548         
22549         Roo.each(this.el.select('.bullet', true).elements, function(el){
22550             el.removeClass('selected');
22551         });
22552
22553         var bullet = this.el.select('.bullet-' + i, true).first();
22554         
22555         if(!bullet){
22556             return;
22557         }
22558         
22559         bullet.addClass('selected');
22560     }
22561     
22562     
22563   
22564 });
22565
22566  
22567
22568  
22569  
22570 Roo.apply(Roo.bootstrap.TabGroup, {
22571     
22572     groups: {},
22573      /**
22574     * register a Navigation Group
22575     * @param {Roo.bootstrap.nav.Group} the navgroup to add
22576     */
22577     register : function(navgrp)
22578     {
22579         this.groups[navgrp.navId] = navgrp;
22580         
22581     },
22582     /**
22583     * fetch a Navigation Group based on the navigation ID
22584     * if one does not exist , it will get created.
22585     * @param {string} the navgroup to add
22586     * @returns {Roo.bootstrap.nav.Group} the navgroup 
22587     */
22588     get: function(navId) {
22589         if (typeof(this.groups[navId]) == 'undefined') {
22590             this.register(new Roo.bootstrap.TabGroup({ navId : navId }));
22591         }
22592         return this.groups[navId] ;
22593     }
22594     
22595     
22596     
22597 });
22598
22599  /*
22600  * - LGPL
22601  *
22602  * TabPanel
22603  * 
22604  */
22605
22606 /**
22607  * @class Roo.bootstrap.TabPanel
22608  * @extends Roo.bootstrap.Component
22609  * @children Roo.bootstrap.Component
22610  * Bootstrap TabPanel class
22611  * @cfg {Boolean} active panel active
22612  * @cfg {String} html panel content
22613  * @cfg {String} tabId  unique tab ID (will be autogenerated if not set. - used to match TabItem to Panel)
22614  * @cfg {String} navId The Roo.bootstrap.nav.Group which triggers show hide ()
22615  * @cfg {String} href click to link..
22616  * @cfg {Boolean} touchSlide if swiping slides tab to next panel (default off)
22617  * 
22618  * 
22619  * @constructor
22620  * Create a new TabPanel
22621  * @param {Object} config The config object
22622  */
22623
22624 Roo.bootstrap.TabPanel = function(config){
22625     Roo.bootstrap.TabPanel.superclass.constructor.call(this, config);
22626     this.addEvents({
22627         /**
22628              * @event changed
22629              * Fires when the active status changes
22630              * @param {Roo.bootstrap.TabPanel} this
22631              * @param {Boolean} state the new state
22632             
22633          */
22634         'changed': true,
22635         /**
22636              * @event beforedeactivate
22637              * Fires before a tab is de-activated - can be used to do validation on a form.
22638              * @param {Roo.bootstrap.TabPanel} this
22639              * @return {Boolean} false if there is an error
22640             
22641          */
22642         'beforedeactivate': true
22643      });
22644     
22645     this.tabId = this.tabId || Roo.id();
22646   
22647 };
22648
22649 Roo.extend(Roo.bootstrap.TabPanel, Roo.bootstrap.Component,  {
22650     
22651     active: false,
22652     html: false,
22653     tabId: false,
22654     navId : false,
22655     href : '',
22656     touchSlide : false,
22657     getAutoCreate : function(){
22658         
22659         
22660         var cfg = {
22661             tag: 'div',
22662             // item is needed for carousel - not sure if it has any effect otherwise
22663             cls: 'carousel-item tab-pane item' + ((this.href.length) ? ' clickable ' : ''),
22664             html: this.html || ''
22665         };
22666         
22667         if(this.active){
22668             cfg.cls += ' active';
22669         }
22670         
22671         if(this.tabId){
22672             cfg.tabId = this.tabId;
22673         }
22674         
22675         
22676         
22677         return cfg;
22678     },
22679     
22680     initEvents:  function()
22681     {
22682         var p = this.parent();
22683         
22684         this.navId = this.navId || p.navId;
22685         
22686         if (typeof(this.navId) != 'undefined') {
22687             // not really needed.. but just in case.. parent should be a NavGroup.
22688             var tg = Roo.bootstrap.TabGroup.get(this.navId);
22689             
22690             tg.register(this);
22691             
22692             var i = tg.tabs.length - 1;
22693             
22694             if(this.active && tg.bullets > 0 && i < tg.bullets){
22695                 tg.setActiveBullet(i);
22696             }
22697         }
22698         
22699         this.el.on('click', this.onClick, this);
22700         
22701         if(Roo.isTouch && this.touchSlide){
22702             this.el.on("touchstart", this.onTouchStart, this);
22703             this.el.on("touchmove", this.onTouchMove, this);
22704             this.el.on("touchend", this.onTouchEnd, this);
22705         }
22706         
22707     },
22708     
22709     onRender : function(ct, position)
22710     {
22711         Roo.bootstrap.TabPanel.superclass.onRender.call(this, ct, position);
22712     },
22713     
22714     setActive : function(state)
22715     {
22716         Roo.log("panel - set active " + this.tabId + "=" + state);
22717         
22718         this.active = state;
22719         if (!state) {
22720             this.el.removeClass('active');
22721             
22722         } else  if (!this.el.hasClass('active')) {
22723             this.el.addClass('active');
22724         }
22725         
22726         this.fireEvent('changed', this, state);
22727     },
22728     
22729     onClick : function(e)
22730     {
22731         e.preventDefault();
22732         
22733         if(!this.href.length){
22734             return;
22735         }
22736         
22737         window.location.href = this.href;
22738     },
22739     
22740     startX : 0,
22741     startY : 0,
22742     endX : 0,
22743     endY : 0,
22744     swiping : false,
22745     
22746     onTouchStart : function(e)
22747     {
22748         this.swiping = false;
22749         
22750         this.startX = e.browserEvent.touches[0].clientX;
22751         this.startY = e.browserEvent.touches[0].clientY;
22752     },
22753     
22754     onTouchMove : function(e)
22755     {
22756         this.swiping = true;
22757         
22758         this.endX = e.browserEvent.touches[0].clientX;
22759         this.endY = e.browserEvent.touches[0].clientY;
22760     },
22761     
22762     onTouchEnd : function(e)
22763     {
22764         if(!this.swiping){
22765             this.onClick(e);
22766             return;
22767         }
22768         
22769         var tabGroup = this.parent();
22770         
22771         if(this.endX > this.startX){ // swiping right
22772             tabGroup.showPanelPrev();
22773             return;
22774         }
22775         
22776         if(this.startX > this.endX){ // swiping left
22777             tabGroup.showPanelNext();
22778             return;
22779         }
22780     }
22781     
22782     
22783 });
22784  
22785
22786  
22787
22788  /*
22789  * - LGPL
22790  *
22791  * DateField
22792  * 
22793  */
22794
22795 /**
22796  * @class Roo.bootstrap.form.DateField
22797  * @extends Roo.bootstrap.form.Input
22798  * Bootstrap DateField class
22799  * @cfg {Number} weekStart default 0
22800  * @cfg {String} viewMode default empty, (months|years)
22801  * @cfg {String} minViewMode default empty, (months|years)
22802  * @cfg {Number} startDate default -Infinity
22803  * @cfg {Number} endDate default Infinity
22804  * @cfg {Boolean} todayHighlight default false
22805  * @cfg {Boolean} todayBtn default false
22806  * @cfg {Boolean} calendarWeeks default false
22807  * @cfg {Object} daysOfWeekDisabled default empty
22808  * @cfg {Boolean} singleMode default false (true | false)
22809  * 
22810  * @cfg {Boolean} keyboardNavigation default true
22811  * @cfg {String} language default en
22812  * 
22813  * @constructor
22814  * Create a new DateField
22815  * @param {Object} config The config object
22816  */
22817
22818 Roo.bootstrap.form.DateField = function(config){
22819     Roo.bootstrap.form.DateField.superclass.constructor.call(this, config);
22820      this.addEvents({
22821             /**
22822              * @event show
22823              * Fires when this field show.
22824              * @param {Roo.bootstrap.form.DateField} this
22825              * @param {Mixed} date The date value
22826              */
22827             show : true,
22828             /**
22829              * @event show
22830              * Fires when this field hide.
22831              * @param {Roo.bootstrap.form.DateField} this
22832              * @param {Mixed} date The date value
22833              */
22834             hide : true,
22835             /**
22836              * @event select
22837              * Fires when select a date.
22838              * @param {Roo.bootstrap.form.DateField} this
22839              * @param {Mixed} date The date value
22840              */
22841             select : true,
22842             /**
22843              * @event beforeselect
22844              * Fires when before select a date.
22845              * @param {Roo.bootstrap.form.DateField} this
22846              * @param {Mixed} date The date value
22847              */
22848             beforeselect : true
22849         });
22850 };
22851
22852 Roo.extend(Roo.bootstrap.form.DateField, Roo.bootstrap.form.Input,  {
22853     
22854     /**
22855      * @cfg {String} format
22856      * The default date format string which can be overriden for localization support.  The format must be
22857      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
22858      */
22859     format : "m/d/y",
22860     /**
22861      * @cfg {String} altFormats
22862      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
22863      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
22864      */
22865     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
22866     
22867     weekStart : 0,
22868     
22869     viewMode : '',
22870     
22871     minViewMode : '',
22872     
22873     todayHighlight : false,
22874     
22875     todayBtn: false,
22876     
22877     language: 'en',
22878     
22879     keyboardNavigation: true,
22880     
22881     calendarWeeks: false,
22882     
22883     startDate: -Infinity,
22884     
22885     endDate: Infinity,
22886     
22887     daysOfWeekDisabled: [],
22888     
22889     _events: [],
22890     
22891     singleMode : false,
22892     
22893     UTCDate: function()
22894     {
22895         return new Date(Date.UTC.apply(Date, arguments));
22896     },
22897     
22898     UTCToday: function()
22899     {
22900         var today = new Date();
22901         return this.UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
22902     },
22903     
22904     getDate: function() {
22905             var d = this.getUTCDate();
22906             return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
22907     },
22908     
22909     getUTCDate: function() {
22910             return this.date;
22911     },
22912     
22913     setDate: function(d) {
22914             this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
22915     },
22916     
22917     setUTCDate: function(d) {
22918             this.date = d;
22919             this.setValue(this.formatDate(this.date));
22920     },
22921         
22922     onRender: function(ct, position)
22923     {
22924         
22925         Roo.bootstrap.form.DateField.superclass.onRender.call(this, ct, position);
22926         
22927         this.language = this.language || 'en';
22928         this.language = this.language in Roo.bootstrap.form.DateField.dates ? this.language : this.language.split('-')[0];
22929         this.language = this.language in Roo.bootstrap.form.DateField.dates ? this.language : "en";
22930         
22931         this.isRTL = Roo.bootstrap.form.DateField.dates[this.language].rtl || false;
22932         this.format = this.format || 'm/d/y';
22933         this.isInline = false;
22934         this.isInput = true;
22935         this.component = this.el.select('.add-on', true).first() || false;
22936         this.component = (this.component && this.component.length === 0) ? false : this.component;
22937         this.hasInput = this.component && this.inputEl().length;
22938         
22939         if (typeof(this.minViewMode === 'string')) {
22940             switch (this.minViewMode) {
22941                 case 'months':
22942                     this.minViewMode = 1;
22943                     break;
22944                 case 'years':
22945                     this.minViewMode = 2;
22946                     break;
22947                 default:
22948                     this.minViewMode = 0;
22949                     break;
22950             }
22951         }
22952         
22953         if (typeof(this.viewMode === 'string')) {
22954             switch (this.viewMode) {
22955                 case 'months':
22956                     this.viewMode = 1;
22957                     break;
22958                 case 'years':
22959                     this.viewMode = 2;
22960                     break;
22961                 default:
22962                     this.viewMode = 0;
22963                     break;
22964             }
22965         }
22966                 
22967         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.form.DateField.template);
22968         
22969 //        this.el.select('>.input-group', true).first().createChild(Roo.bootstrap.form.DateField.template);
22970         
22971         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
22972         
22973         this.picker().on('mousedown', this.onMousedown, this);
22974         this.picker().on('click', this.onClick, this);
22975         
22976         this.picker().addClass('datepicker-dropdown');
22977         
22978         this.startViewMode = this.viewMode;
22979         
22980         if(this.singleMode){
22981             Roo.each(this.picker().select('thead > tr > th', true).elements, function(v){
22982                 v.setVisibilityMode(Roo.Element.DISPLAY);
22983                 v.hide();
22984             });
22985             
22986             Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
22987                 v.setStyle('width', '189px');
22988             });
22989         }
22990         
22991         Roo.each(this.picker().select('tfoot th.today', true).elements, function(v){
22992             if(!this.calendarWeeks){
22993                 v.remove();
22994                 return;
22995             }
22996             
22997             v.dom.innerHTML = Roo.bootstrap.form.DateField.dates[this.language].today;
22998             v.attr('colspan', function(i, val){
22999                 return parseInt(val) + 1;
23000             });
23001         });
23002                         
23003         
23004         this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
23005         
23006         this.setStartDate(this.startDate);
23007         this.setEndDate(this.endDate);
23008         
23009         this.setDaysOfWeekDisabled(this.daysOfWeekDisabled);
23010         
23011         this.fillDow();
23012         this.fillMonths();
23013         this.update();
23014         this.showMode();
23015         
23016         if(this.isInline) {
23017             this.showPopup();
23018         }
23019     },
23020     
23021     picker : function()
23022     {
23023         return this.pickerEl;
23024 //        return this.el.select('.datepicker', true).first();
23025     },
23026     
23027     fillDow: function()
23028     {
23029         var dowCnt = this.weekStart;
23030         
23031         var dow = {
23032             tag: 'tr',
23033             cn: [
23034                 
23035             ]
23036         };
23037         
23038         if(this.calendarWeeks){
23039             dow.cn.push({
23040                 tag: 'th',
23041                 cls: 'cw',
23042                 html: '&nbsp;'
23043             })
23044         }
23045         
23046         while (dowCnt < this.weekStart + 7) {
23047             dow.cn.push({
23048                 tag: 'th',
23049                 cls: 'dow',
23050                 html: Roo.bootstrap.form.DateField.dates[this.language].daysMin[(dowCnt++)%7]
23051             });
23052         }
23053         
23054         this.picker().select('>.datepicker-days thead', true).first().createChild(dow);
23055     },
23056     
23057     fillMonths: function()
23058     {    
23059         var i = 0;
23060         var months = this.picker().select('>.datepicker-months td', true).first();
23061         
23062         months.dom.innerHTML = '';
23063         
23064         while (i < 12) {
23065             var month = {
23066                 tag: 'span',
23067                 cls: 'month',
23068                 html: Roo.bootstrap.form.DateField.dates[this.language].monthsShort[i++]
23069             };
23070             
23071             months.createChild(month);
23072         }
23073         
23074     },
23075     
23076     update: function()
23077     {
23078         this.date = (typeof(this.date) === 'undefined' || ((typeof(this.date) === 'string') && !this.date.length)) ? this.UTCToday() : (typeof(this.date) === 'string') ? this.parseDate(this.date) : this.date;
23079         
23080         if (this.date < this.startDate) {
23081             this.viewDate = new Date(this.startDate);
23082         } else if (this.date > this.endDate) {
23083             this.viewDate = new Date(this.endDate);
23084         } else {
23085             this.viewDate = new Date(this.date);
23086         }
23087         
23088         this.fill();
23089     },
23090     
23091     fill: function() 
23092     {
23093         var d = new Date(this.viewDate),
23094                 year = d.getUTCFullYear(),
23095                 month = d.getUTCMonth(),
23096                 startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
23097                 startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
23098                 endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
23099                 endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
23100                 currentDate = this.date && this.date.valueOf(),
23101                 today = this.UTCToday();
23102         
23103         this.picker().select('>.datepicker-days thead th.switch', true).first().dom.innerHTML = Roo.bootstrap.form.DateField.dates[this.language].months[month]+' '+year;
23104         
23105 //        this.picker().select('>tfoot th.today', true).first().dom.innerHTML = Roo.bootstrap.form.DateField.dates[this.language].today;
23106         
23107 //        this.picker.select('>tfoot th.today').
23108 //                                              .text(dates[this.language].today)
23109 //                                              .toggle(this.todayBtn !== false);
23110     
23111         this.updateNavArrows();
23112         this.fillMonths();
23113                                                 
23114         var prevMonth = this.UTCDate(year, month-1, 28,0,0,0,0),
23115         
23116         day = prevMonth.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
23117          
23118         prevMonth.setUTCDate(day);
23119         
23120         prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
23121         
23122         var nextMonth = new Date(prevMonth);
23123         
23124         nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
23125         
23126         nextMonth = nextMonth.valueOf();
23127         
23128         var fillMonths = false;
23129         
23130         this.picker().select('>.datepicker-days tbody',true).first().dom.innerHTML = '';
23131         
23132         while(prevMonth.valueOf() <= nextMonth) {
23133             var clsName = '';
23134             
23135             if (prevMonth.getUTCDay() === this.weekStart) {
23136                 if(fillMonths){
23137                     this.picker().select('>.datepicker-days tbody',true).first().createChild(fillMonths);
23138                 }
23139                     
23140                 fillMonths = {
23141                     tag: 'tr',
23142                     cn: []
23143                 };
23144                 
23145                 if(this.calendarWeeks){
23146                     // ISO 8601: First week contains first thursday.
23147                     // ISO also states week starts on Monday, but we can be more abstract here.
23148                     var
23149                     // Start of current week: based on weekstart/current date
23150                     ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
23151                     // Thursday of this week
23152                     th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
23153                     // First Thursday of year, year from thursday
23154                     yth = new Date(+(yth = this.UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
23155                     // Calendar week: ms between thursdays, div ms per day, div 7 days
23156                     calWeek =  (th - yth) / 864e5 / 7 + 1;
23157                     
23158                     fillMonths.cn.push({
23159                         tag: 'td',
23160                         cls: 'cw',
23161                         html: calWeek
23162                     });
23163                 }
23164             }
23165             
23166             if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
23167                 clsName += ' old';
23168             } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
23169                 clsName += ' new';
23170             }
23171             if (this.todayHighlight &&
23172                 prevMonth.getUTCFullYear() == today.getFullYear() &&
23173                 prevMonth.getUTCMonth() == today.getMonth() &&
23174                 prevMonth.getUTCDate() == today.getDate()) {
23175                 clsName += ' today';
23176             }
23177             
23178             if (currentDate && prevMonth.valueOf() === currentDate) {
23179                 clsName += ' active';
23180             }
23181             
23182             if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
23183                     this.daysOfWeekDisabled.indexOf(prevMonth.getUTCDay()) !== -1) {
23184                     clsName += ' disabled';
23185             }
23186             
23187             fillMonths.cn.push({
23188                 tag: 'td',
23189                 cls: 'day ' + clsName,
23190                 html: prevMonth.getDate()
23191             });
23192             
23193             prevMonth.setDate(prevMonth.getDate()+1);
23194         }
23195           
23196         var currentYear = this.date && this.date.getUTCFullYear();
23197         var currentMonth = this.date && this.date.getUTCMonth();
23198         
23199         this.picker().select('>.datepicker-months th.switch',true).first().dom.innerHTML = year;
23200         
23201         Roo.each(this.picker().select('>.datepicker-months tbody span',true).elements, function(v,k){
23202             v.removeClass('active');
23203             
23204             if(currentYear === year && k === currentMonth){
23205                 v.addClass('active');
23206             }
23207             
23208             if (year < startYear || year > endYear || (year == startYear && k < startMonth) || (year == endYear && k > endMonth)) {
23209                 v.addClass('disabled');
23210             }
23211             
23212         });
23213         
23214         
23215         year = parseInt(year/10, 10) * 10;
23216         
23217         this.picker().select('>.datepicker-years th.switch', true).first().dom.innerHTML = year + '-' + (year + 9);
23218         
23219         this.picker().select('>.datepicker-years tbody td',true).first().dom.innerHTML = '';
23220         
23221         year -= 1;
23222         for (var i = -1; i < 11; i++) {
23223             this.picker().select('>.datepicker-years tbody td',true).first().createChild({
23224                 tag: 'span',
23225                 cls: 'year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : ''),
23226                 html: year
23227             });
23228             
23229             year += 1;
23230         }
23231     },
23232     
23233     showMode: function(dir) 
23234     {
23235         if (dir) {
23236             this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
23237         }
23238         
23239         Roo.each(this.picker().select('>div',true).elements, function(v){
23240             v.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
23241             v.hide();
23242         });
23243         this.picker().select('>.datepicker-'+Roo.bootstrap.form.DateField.modes[this.viewMode].clsName, true).first().show();
23244     },
23245     
23246     place: function()
23247     {
23248         if(this.isInline) {
23249             return;
23250         }
23251         
23252         this.picker().removeClass(['bottom', 'top']);
23253         
23254         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
23255             /*
23256              * place to the top of element!
23257              *
23258              */
23259             
23260             this.picker().addClass('top');
23261             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
23262             
23263             return;
23264         }
23265         
23266         this.picker().addClass('bottom');
23267         
23268         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
23269     },
23270     
23271     parseDate : function(value)
23272     {
23273         if(!value || value instanceof Date){
23274             return value;
23275         }
23276         var v = Date.parseDate(value, this.format);
23277         if (!v && (this.useIso || value.match(/^(\d{4})-0?(\d+)-0?(\d+)/))) {
23278             v = Date.parseDate(value, 'Y-m-d');
23279         }
23280         if(!v && this.altFormats){
23281             if(!this.altFormatsArray){
23282                 this.altFormatsArray = this.altFormats.split("|");
23283             }
23284             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
23285                 v = Date.parseDate(value, this.altFormatsArray[i]);
23286             }
23287         }
23288         return v;
23289     },
23290     
23291     formatDate : function(date, fmt)
23292     {   
23293         return (!date || !(date instanceof Date)) ?
23294         date : date.dateFormat(fmt || this.format);
23295     },
23296     
23297     onFocus : function()
23298     {
23299         Roo.bootstrap.form.DateField.superclass.onFocus.call(this);
23300         this.showPopup();
23301     },
23302     
23303     onBlur : function()
23304     {
23305         Roo.bootstrap.form.DateField.superclass.onBlur.call(this);
23306         
23307         var d = this.inputEl().getValue();
23308         
23309         this.setValue(d);
23310                 
23311         this.hidePopup();
23312     },
23313     
23314     showPopup : function()
23315     {
23316         this.picker().show();
23317         this.update();
23318         this.place();
23319         
23320         this.fireEvent('showpopup', this, this.date);
23321     },
23322     
23323     hidePopup : function()
23324     {
23325         if(this.isInline) {
23326             return;
23327         }
23328         this.picker().hide();
23329         this.viewMode = this.startViewMode;
23330         this.showMode();
23331         
23332         this.fireEvent('hidepopup', this, this.date);
23333         
23334     },
23335     
23336     onMousedown: function(e)
23337     {
23338         e.stopPropagation();
23339         e.preventDefault();
23340     },
23341     
23342     keyup: function(e)
23343     {
23344         Roo.bootstrap.form.DateField.superclass.keyup.call(this);
23345         this.update();
23346     },
23347
23348     setValue: function(v)
23349     {
23350         if(this.fireEvent('beforeselect', this, v) !== false){
23351             var d = new Date(this.parseDate(v) ).clearTime();
23352         
23353             if(isNaN(d.getTime())){
23354                 this.date = this.viewDate = '';
23355                 Roo.bootstrap.form.DateField.superclass.setValue.call(this, '');
23356                 return;
23357             }
23358
23359             v = this.formatDate(d);
23360
23361             Roo.bootstrap.form.DateField.superclass.setValue.call(this, v);
23362
23363             this.date = new Date(d.getTime() - d.getTimezoneOffset()*60000);
23364
23365             this.update();
23366
23367             this.fireEvent('select', this, this.date);
23368         }
23369     },
23370     
23371     getValue: function()
23372     {
23373         return this.formatDate(this.date);
23374     },
23375     
23376     fireKey: function(e)
23377     {
23378         if (!this.picker().isVisible()){
23379             if (e.keyCode == 27) { // allow escape to hide and re-show picker
23380                 this.showPopup();
23381             }
23382             return;
23383         }
23384         
23385         var dateChanged = false,
23386         dir, day, month,
23387         newDate, newViewDate;
23388         
23389         switch(e.keyCode){
23390             case 27: // escape
23391                 this.hidePopup();
23392                 e.preventDefault();
23393                 break;
23394             case 37: // left
23395             case 39: // right
23396                 if (!this.keyboardNavigation) {
23397                     break;
23398                 }
23399                 dir = e.keyCode == 37 ? -1 : 1;
23400                 
23401                 if (e.ctrlKey){
23402                     newDate = this.moveYear(this.date, dir);
23403                     newViewDate = this.moveYear(this.viewDate, dir);
23404                 } else if (e.shiftKey){
23405                     newDate = this.moveMonth(this.date, dir);
23406                     newViewDate = this.moveMonth(this.viewDate, dir);
23407                 } else {
23408                     newDate = new Date(this.date);
23409                     newDate.setUTCDate(this.date.getUTCDate() + dir);
23410                     newViewDate = new Date(this.viewDate);
23411                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
23412                 }
23413                 if (this.dateWithinRange(newDate)){
23414                     this.date = newDate;
23415                     this.viewDate = newViewDate;
23416                     this.setValue(this.formatDate(this.date));
23417 //                    this.update();
23418                     e.preventDefault();
23419                     dateChanged = true;
23420                 }
23421                 break;
23422             case 38: // up
23423             case 40: // down
23424                 if (!this.keyboardNavigation) {
23425                     break;
23426                 }
23427                 dir = e.keyCode == 38 ? -1 : 1;
23428                 if (e.ctrlKey){
23429                     newDate = this.moveYear(this.date, dir);
23430                     newViewDate = this.moveYear(this.viewDate, dir);
23431                 } else if (e.shiftKey){
23432                     newDate = this.moveMonth(this.date, dir);
23433                     newViewDate = this.moveMonth(this.viewDate, dir);
23434                 } else {
23435                     newDate = new Date(this.date);
23436                     newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
23437                     newViewDate = new Date(this.viewDate);
23438                     newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
23439                 }
23440                 if (this.dateWithinRange(newDate)){
23441                     this.date = newDate;
23442                     this.viewDate = newViewDate;
23443                     this.setValue(this.formatDate(this.date));
23444 //                    this.update();
23445                     e.preventDefault();
23446                     dateChanged = true;
23447                 }
23448                 break;
23449             case 13: // enter
23450                 this.setValue(this.formatDate(this.date));
23451                 this.hidePopup();
23452                 e.preventDefault();
23453                 break;
23454             case 9: // tab
23455                 this.setValue(this.formatDate(this.date));
23456                 this.hidePopup();
23457                 break;
23458             case 16: // shift
23459             case 17: // ctrl
23460             case 18: // alt
23461                 break;
23462             default :
23463                 this.hidePopup();
23464                 
23465         }
23466     },
23467     
23468     
23469     onClick: function(e) 
23470     {
23471         e.stopPropagation();
23472         e.preventDefault();
23473         
23474         var target = e.getTarget();
23475         
23476         if(target.nodeName.toLowerCase() === 'i'){
23477             target = Roo.get(target).dom.parentNode;
23478         }
23479         
23480         var nodeName = target.nodeName;
23481         var className = target.className;
23482         var html = target.innerHTML;
23483         //Roo.log(nodeName);
23484         
23485         switch(nodeName.toLowerCase()) {
23486             case 'th':
23487                 switch(className) {
23488                     case 'switch':
23489                         this.showMode(1);
23490                         break;
23491                     case 'prev':
23492                     case 'next':
23493                         var dir = Roo.bootstrap.form.DateField.modes[this.viewMode].navStep * (className == 'prev' ? -1 : 1);
23494                         switch(this.viewMode){
23495                                 case 0:
23496                                         this.viewDate = this.moveMonth(this.viewDate, dir);
23497                                         break;
23498                                 case 1:
23499                                 case 2:
23500                                         this.viewDate = this.moveYear(this.viewDate, dir);
23501                                         break;
23502                         }
23503                         this.fill();
23504                         break;
23505                     case 'today':
23506                         var date = new Date();
23507                         this.date = this.UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
23508 //                        this.fill()
23509                         this.setValue(this.formatDate(this.date));
23510                         
23511                         this.hidePopup();
23512                         break;
23513                 }
23514                 break;
23515             case 'span':
23516                 if (className.indexOf('disabled') < 0) {
23517                 if (!this.viewDate) {
23518                     this.viewDate = new Date();
23519                 }
23520                 this.viewDate.setUTCDate(1);
23521                     if (className.indexOf('month') > -1) {
23522                         this.viewDate.setUTCMonth(Roo.bootstrap.form.DateField.dates[this.language].monthsShort.indexOf(html));
23523                     } else {
23524                         var year = parseInt(html, 10) || 0;
23525                         this.viewDate.setUTCFullYear(year);
23526                         
23527                     }
23528                     
23529                     if(this.singleMode){
23530                         this.setValue(this.formatDate(this.viewDate));
23531                         this.hidePopup();
23532                         return;
23533                     }
23534                     
23535                     this.showMode(-1);
23536                     this.fill();
23537                 }
23538                 break;
23539                 
23540             case 'td':
23541                 //Roo.log(className);
23542                 if (className.indexOf('day') > -1 && className.indexOf('disabled') < 0 ){
23543                     var day = parseInt(html, 10) || 1;
23544                     var year =  (this.viewDate || new Date()).getUTCFullYear(),
23545                         month = (this.viewDate || new Date()).getUTCMonth();
23546
23547                     if (className.indexOf('old') > -1) {
23548                         if(month === 0 ){
23549                             month = 11;
23550                             year -= 1;
23551                         }else{
23552                             month -= 1;
23553                         }
23554                     } else if (className.indexOf('new') > -1) {
23555                         if (month == 11) {
23556                             month = 0;
23557                             year += 1;
23558                         } else {
23559                             month += 1;
23560                         }
23561                     }
23562                     //Roo.log([year,month,day]);
23563                     this.date = this.UTCDate(year, month, day,0,0,0,0);
23564                     this.viewDate = this.UTCDate(year, month, Math.min(28, day),0,0,0,0);
23565 //                    this.fill();
23566                     //Roo.log(this.formatDate(this.date));
23567                     this.setValue(this.formatDate(this.date));
23568                     this.hidePopup();
23569                 }
23570                 break;
23571         }
23572     },
23573     
23574     setStartDate: function(startDate)
23575     {
23576         this.startDate = startDate || -Infinity;
23577         if (this.startDate !== -Infinity) {
23578             this.startDate = this.parseDate(this.startDate);
23579         }
23580         this.update();
23581         this.updateNavArrows();
23582     },
23583
23584     setEndDate: function(endDate)
23585     {
23586         this.endDate = endDate || Infinity;
23587         if (this.endDate !== Infinity) {
23588             this.endDate = this.parseDate(this.endDate);
23589         }
23590         this.update();
23591         this.updateNavArrows();
23592     },
23593     
23594     setDaysOfWeekDisabled: function(daysOfWeekDisabled)
23595     {
23596         this.daysOfWeekDisabled = daysOfWeekDisabled || [];
23597         if (typeof(this.daysOfWeekDisabled) !== 'object') {
23598             this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
23599         }
23600         this.daysOfWeekDisabled = this.daysOfWeekDisabled.map(function (d) {
23601             return parseInt(d, 10);
23602         });
23603         this.update();
23604         this.updateNavArrows();
23605     },
23606     
23607     updateNavArrows: function() 
23608     {
23609         if(this.singleMode){
23610             return;
23611         }
23612         
23613         var d = new Date(this.viewDate),
23614         year = d.getUTCFullYear(),
23615         month = d.getUTCMonth();
23616         
23617         Roo.each(this.picker().select('.prev', true).elements, function(v){
23618             v.show();
23619             switch (this.viewMode) {
23620                 case 0:
23621
23622                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
23623                         v.hide();
23624                     }
23625                     break;
23626                 case 1:
23627                 case 2:
23628                     if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
23629                         v.hide();
23630                     }
23631                     break;
23632             }
23633         });
23634         
23635         Roo.each(this.picker().select('.next', true).elements, function(v){
23636             v.show();
23637             switch (this.viewMode) {
23638                 case 0:
23639
23640                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
23641                         v.hide();
23642                     }
23643                     break;
23644                 case 1:
23645                 case 2:
23646                     if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
23647                         v.hide();
23648                     }
23649                     break;
23650             }
23651         })
23652     },
23653     
23654     moveMonth: function(date, dir)
23655     {
23656         if (!dir) {
23657             return date;
23658         }
23659         var new_date = new Date(date.valueOf()),
23660         day = new_date.getUTCDate(),
23661         month = new_date.getUTCMonth(),
23662         mag = Math.abs(dir),
23663         new_month, test;
23664         dir = dir > 0 ? 1 : -1;
23665         if (mag == 1){
23666             test = dir == -1
23667             // If going back one month, make sure month is not current month
23668             // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
23669             ? function(){
23670                 return new_date.getUTCMonth() == month;
23671             }
23672             // If going forward one month, make sure month is as expected
23673             // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
23674             : function(){
23675                 return new_date.getUTCMonth() != new_month;
23676             };
23677             new_month = month + dir;
23678             new_date.setUTCMonth(new_month);
23679             // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
23680             if (new_month < 0 || new_month > 11) {
23681                 new_month = (new_month + 12) % 12;
23682             }
23683         } else {
23684             // For magnitudes >1, move one month at a time...
23685             for (var i=0; i<mag; i++) {
23686                 // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
23687                 new_date = this.moveMonth(new_date, dir);
23688             }
23689             // ...then reset the day, keeping it in the new month
23690             new_month = new_date.getUTCMonth();
23691             new_date.setUTCDate(day);
23692             test = function(){
23693                 return new_month != new_date.getUTCMonth();
23694             };
23695         }
23696         // Common date-resetting loop -- if date is beyond end of month, make it
23697         // end of month
23698         while (test()){
23699             new_date.setUTCDate(--day);
23700             new_date.setUTCMonth(new_month);
23701         }
23702         return new_date;
23703     },
23704
23705     moveYear: function(date, dir)
23706     {
23707         return this.moveMonth(date, dir*12);
23708     },
23709
23710     dateWithinRange: function(date)
23711     {
23712         return date >= this.startDate && date <= this.endDate;
23713     },
23714
23715     
23716     remove: function() 
23717     {
23718         this.picker().remove();
23719     },
23720     
23721     validateValue : function(value)
23722     {
23723         if(this.getVisibilityEl().hasClass('hidden')){
23724             return true;
23725         }
23726         
23727         if(value.length < 1)  {
23728             if(this.allowBlank){
23729                 return true;
23730             }
23731             return false;
23732         }
23733         
23734         if(value.length < this.minLength){
23735             return false;
23736         }
23737         if(value.length > this.maxLength){
23738             return false;
23739         }
23740         if(this.vtype){
23741             var vt = Roo.form.VTypes;
23742             if(!vt[this.vtype](value, this)){
23743                 return false;
23744             }
23745         }
23746         if(typeof this.validator == "function"){
23747             var msg = this.validator(value);
23748             if(msg !== true){
23749                 return false;
23750             }
23751         }
23752         
23753         if(this.regex && !this.regex.test(value)){
23754             return false;
23755         }
23756         
23757         if(typeof(this.parseDate(value)) == 'undefined'){
23758             return false;
23759         }
23760         
23761         if (this.endDate !== Infinity && this.parseDate(value).getTime() > this.endDate.getTime()) {
23762             return false;
23763         }      
23764         
23765         if (this.startDate !== -Infinity && this.parseDate(value).getTime() < this.startDate.getTime()) {
23766             return false;
23767         } 
23768         
23769         
23770         return true;
23771     },
23772     
23773     reset : function()
23774     {
23775         this.date = this.viewDate = '';
23776         
23777         Roo.bootstrap.form.DateField.superclass.setValue.call(this, '');
23778     }
23779    
23780 });
23781
23782 Roo.apply(Roo.bootstrap.form.DateField,  {
23783     
23784     head : {
23785         tag: 'thead',
23786         cn: [
23787         {
23788             tag: 'tr',
23789             cn: [
23790             {
23791                 tag: 'th',
23792                 cls: 'prev',
23793                 html: '<i class="fa fa-arrow-left"/>'
23794             },
23795             {
23796                 tag: 'th',
23797                 cls: 'switch',
23798                 colspan: '5'
23799             },
23800             {
23801                 tag: 'th',
23802                 cls: 'next',
23803                 html: '<i class="fa fa-arrow-right"/>'
23804             }
23805
23806             ]
23807         }
23808         ]
23809     },
23810     
23811     content : {
23812         tag: 'tbody',
23813         cn: [
23814         {
23815             tag: 'tr',
23816             cn: [
23817             {
23818                 tag: 'td',
23819                 colspan: '7'
23820             }
23821             ]
23822         }
23823         ]
23824     },
23825     
23826     footer : {
23827         tag: 'tfoot',
23828         cn: [
23829         {
23830             tag: 'tr',
23831             cn: [
23832             {
23833                 tag: 'th',
23834                 colspan: '7',
23835                 cls: 'today'
23836             }
23837                     
23838             ]
23839         }
23840         ]
23841     },
23842     
23843     dates:{
23844         en: {
23845             days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
23846             daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
23847             daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
23848             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
23849             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
23850             today: "Today"
23851         }
23852     },
23853     
23854     modes: [
23855     {
23856         clsName: 'days',
23857         navFnc: 'Month',
23858         navStep: 1
23859     },
23860     {
23861         clsName: 'months',
23862         navFnc: 'FullYear',
23863         navStep: 1
23864     },
23865     {
23866         clsName: 'years',
23867         navFnc: 'FullYear',
23868         navStep: 10
23869     }]
23870 });
23871
23872 Roo.apply(Roo.bootstrap.form.DateField,  {
23873   
23874     template : {
23875         tag: 'div',
23876         cls: 'datepicker dropdown-menu roo-dynamic shadow',
23877         cn: [
23878         {
23879             tag: 'div',
23880             cls: 'datepicker-days',
23881             cn: [
23882             {
23883                 tag: 'table',
23884                 cls: 'table-condensed',
23885                 cn:[
23886                 Roo.bootstrap.form.DateField.head,
23887                 {
23888                     tag: 'tbody'
23889                 },
23890                 Roo.bootstrap.form.DateField.footer
23891                 ]
23892             }
23893             ]
23894         },
23895         {
23896             tag: 'div',
23897             cls: 'datepicker-months',
23898             cn: [
23899             {
23900                 tag: 'table',
23901                 cls: 'table-condensed',
23902                 cn:[
23903                 Roo.bootstrap.form.DateField.head,
23904                 Roo.bootstrap.form.DateField.content,
23905                 Roo.bootstrap.form.DateField.footer
23906                 ]
23907             }
23908             ]
23909         },
23910         {
23911             tag: 'div',
23912             cls: 'datepicker-years',
23913             cn: [
23914             {
23915                 tag: 'table',
23916                 cls: 'table-condensed',
23917                 cn:[
23918                 Roo.bootstrap.form.DateField.head,
23919                 Roo.bootstrap.form.DateField.content,
23920                 Roo.bootstrap.form.DateField.footer
23921                 ]
23922             }
23923             ]
23924         }
23925         ]
23926     }
23927 });
23928
23929  
23930
23931  /*
23932  * - LGPL
23933  *
23934  * TimeField
23935  * 
23936  */
23937
23938 /**
23939  * @class Roo.bootstrap.form.TimeField
23940  * @extends Roo.bootstrap.form.Input
23941  * Bootstrap DateField class
23942  * @cfg {Number} minuteStep the minutes is always the multiple of a fixed number, default 1
23943  * 
23944  * 
23945  * @constructor
23946  * Create a new TimeField
23947  * @param {Object} config The config object
23948  */
23949
23950 Roo.bootstrap.form.TimeField = function(config){
23951     Roo.bootstrap.form.TimeField.superclass.constructor.call(this, config);
23952     this.addEvents({
23953             /**
23954              * @event show
23955              * Fires when this field show.
23956              * @param {Roo.bootstrap.form.DateField} thisthis
23957              * @param {Mixed} date The date value
23958              */
23959             show : true,
23960             /**
23961              * @event show
23962              * Fires when this field hide.
23963              * @param {Roo.bootstrap.form.DateField} this
23964              * @param {Mixed} date The date value
23965              */
23966             hide : true,
23967             /**
23968              * @event select
23969              * Fires when select a date.
23970              * @param {Roo.bootstrap.form.DateField} this
23971              * @param {Mixed} date The date value
23972              */
23973             select : true
23974         });
23975 };
23976
23977 Roo.extend(Roo.bootstrap.form.TimeField, Roo.bootstrap.form.Input,  {
23978     
23979     /**
23980      * @cfg {String} format
23981      * The default time format string which can be overriden for localization support.  The format must be
23982      * valid according to {@link Date#parseDate} (defaults to 'H:i').
23983      */
23984     format : "H:i",
23985     minuteStep : 1,
23986
23987     getAutoCreate : function()
23988     {
23989         this.after = '<i class="fa far fa-clock"></i>';
23990         return Roo.bootstrap.form.TimeField.superclass.getAutoCreate.call(this);
23991         
23992          
23993     },
23994     onRender: function(ct, position)
23995     {
23996         
23997         Roo.bootstrap.form.TimeField.superclass.onRender.call(this, ct, position);
23998                 
23999         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.form.TimeField.template);
24000         
24001         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
24002         
24003         this.pop = this.picker().select('>.datepicker-time',true).first();
24004         this.pop.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
24005         
24006         this.picker().on('mousedown', this.onMousedown, this);
24007         this.picker().on('click', this.onClick, this);
24008         
24009         this.picker().addClass('datepicker-dropdown');
24010     
24011         this.fillTime();
24012         this.update();
24013             
24014         this.pop.select('.hours-up', true).first().on('click', this.onIncrementHours, this);
24015         this.pop.select('.hours-down', true).first().on('click', this.onDecrementHours, this);
24016         this.pop.select('.minutes-up', true).first().on('click', this.onIncrementMinutes, this);
24017         this.pop.select('.minutes-down', true).first().on('click', this.onDecrementMinutes, this);
24018         this.pop.select('button.period', true).first().on('click', this.onTogglePeriod, this);
24019         this.pop.select('button.ok', true).first().on('click', this.setTime, this);
24020
24021     },
24022     
24023     fireKey: function(e){
24024         if (!this.picker().isVisible()){
24025             if (e.keyCode == 27) { // allow escape to hide and re-show picker
24026                 this.show();
24027             }
24028             return;
24029         }
24030
24031         e.preventDefault();
24032         
24033         switch(e.keyCode){
24034             case 27: // escape
24035                 this.hide();
24036                 break;
24037             case 37: // left
24038             case 39: // right
24039                 this.onTogglePeriod();
24040                 break;
24041             case 38: // up
24042                 this.onIncrementMinutes();
24043                 break;
24044             case 40: // down
24045                 this.onDecrementMinutes();
24046                 break;
24047             case 13: // enter
24048             case 9: // tab
24049                 this.setTime();
24050                 break;
24051         }
24052     },
24053     
24054     onClick: function(e) {
24055         e.stopPropagation();
24056         e.preventDefault();
24057     },
24058     
24059     picker : function()
24060     {
24061         return this.pickerEl;
24062     },
24063     
24064     fillTime: function()
24065     {    
24066         var time = this.pop.select('tbody', true).first();
24067         
24068         time.dom.innerHTML = '';
24069         
24070         time.createChild({
24071             tag: 'tr',
24072             cn: [
24073                 {
24074                     tag: 'td',
24075                     cn: [
24076                         {
24077                             tag: 'a',
24078                             href: '#',
24079                             cls: 'btn',
24080                             cn: [
24081                                 {
24082                                     tag: 'i',
24083                                     cls: 'hours-up fa fas fa-chevron-up'
24084                                 }
24085                             ]
24086                         } 
24087                     ]
24088                 },
24089                 {
24090                     tag: 'td',
24091                     cls: 'separator'
24092                 },
24093                 {
24094                     tag: 'td',
24095                     cn: [
24096                         {
24097                             tag: 'a',
24098                             href: '#',
24099                             cls: 'btn',
24100                             cn: [
24101                                 {
24102                                     tag: 'i',
24103                                     cls: 'minutes-up fa fas fa-chevron-up'
24104                                 }
24105                             ]
24106                         }
24107                     ]
24108                 },
24109                 {
24110                     tag: 'td',
24111                     cls: 'separator'
24112                 }
24113             ]
24114         });
24115         
24116         time.createChild({
24117             tag: 'tr',
24118             cn: [
24119                 {
24120                     tag: 'td',
24121                     cn: [
24122                         {
24123                             tag: 'span',
24124                             cls: 'timepicker-hour',
24125                             html: '00'
24126                         }  
24127                     ]
24128                 },
24129                 {
24130                     tag: 'td',
24131                     cls: 'separator',
24132                     html: ':'
24133                 },
24134                 {
24135                     tag: 'td',
24136                     cn: [
24137                         {
24138                             tag: 'span',
24139                             cls: 'timepicker-minute',
24140                             html: '00'
24141                         }  
24142                     ]
24143                 },
24144                 {
24145                     tag: 'td',
24146                     cls: 'separator'
24147                 },
24148                 {
24149                     tag: 'td',
24150                     cn: [
24151                         {
24152                             tag: 'button',
24153                             type: 'button',
24154                             cls: 'btn btn-primary period',
24155                             html: 'AM'
24156                             
24157                         }
24158                     ]
24159                 }
24160             ]
24161         });
24162         
24163         time.createChild({
24164             tag: 'tr',
24165             cn: [
24166                 {
24167                     tag: 'td',
24168                     cn: [
24169                         {
24170                             tag: 'a',
24171                             href: '#',
24172                             cls: 'btn',
24173                             cn: [
24174                                 {
24175                                     tag: 'span',
24176                                     cls: 'hours-down fa fas fa-chevron-down'
24177                                 }
24178                             ]
24179                         }
24180                     ]
24181                 },
24182                 {
24183                     tag: 'td',
24184                     cls: 'separator'
24185                 },
24186                 {
24187                     tag: 'td',
24188                     cn: [
24189                         {
24190                             tag: 'a',
24191                             href: '#',
24192                             cls: 'btn',
24193                             cn: [
24194                                 {
24195                                     tag: 'span',
24196                                     cls: 'minutes-down fa fas fa-chevron-down'
24197                                 }
24198                             ]
24199                         }
24200                     ]
24201                 },
24202                 {
24203                     tag: 'td',
24204                     cls: 'separator'
24205                 }
24206             ]
24207         });
24208         
24209     },
24210     
24211     update: function()
24212     {
24213         
24214         this.time = (typeof(this.time) === 'undefined') ? new Date() : this.time;
24215         
24216         this.fill();
24217     },
24218     
24219     fill: function() 
24220     {
24221         var hours = this.time.getHours();
24222         var minutes = this.time.getMinutes();
24223         var period = 'AM';
24224         
24225         if(hours > 11){
24226             period = 'PM';
24227         }
24228         
24229         if(hours == 0){
24230             hours = 12;
24231         }
24232         
24233         
24234         if(hours > 12){
24235             hours = hours - 12;
24236         }
24237         
24238         if(hours < 10){
24239             hours = '0' + hours;
24240         }
24241         
24242         if(minutes < 10){
24243             minutes = '0' + minutes;
24244         }
24245         
24246         this.pop.select('.timepicker-hour', true).first().dom.innerHTML = hours;
24247         this.pop.select('.timepicker-minute', true).first().dom.innerHTML = minutes;
24248         this.pop.select('button', true).first().dom.innerHTML = period;
24249         
24250     },
24251     
24252     place: function()
24253     {   
24254         this.picker().removeClass(['bottom-left', 'bottom-right', 'top-left', 'top-right']);
24255         
24256         var cls = ['bottom'];
24257         
24258         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){ // top
24259             cls.pop();
24260             cls.push('top');
24261         }
24262         
24263         cls.push('right');
24264         
24265         if((Roo.lib.Dom.getViewWidth() + Roo.get(document.body).getScroll().left) - (this.inputEl().getLeft() + this.picker().getWidth()) < 0){ // left
24266             cls.pop();
24267             cls.push('left');
24268         }
24269         //this.picker().setXY(20000,20000);
24270         this.picker().addClass(cls.join('-'));
24271         
24272         var _this = this;
24273         
24274         Roo.each(cls, function(c){
24275             if(c == 'bottom'){
24276                 (function() {
24277                  //  
24278                 }).defer(200);
24279                  _this.picker().alignTo(_this.inputEl(),   "tr-br", [0, 10], false);
24280                 //_this.picker().setTop(_this.inputEl().getHeight());
24281                 return;
24282             }
24283             if(c == 'top'){
24284                  _this.picker().alignTo(_this.inputEl(),   "br-tr", [0, 10], false);
24285                 
24286                 //_this.picker().setTop(0 - _this.picker().getHeight());
24287                 return;
24288             }
24289             /*
24290             if(c == 'left'){
24291                 _this.picker().setLeft(_this.inputEl().getLeft() + _this.inputEl().getWidth() - _this.el.getLeft() - _this.picker().getWidth());
24292                 return;
24293             }
24294             if(c == 'right'){
24295                 _this.picker().setLeft(_this.inputEl().getLeft() - _this.el.getLeft());
24296                 return;
24297             }
24298             */
24299         });
24300         
24301     },
24302   
24303     onFocus : function()
24304     {
24305         Roo.bootstrap.form.TimeField.superclass.onFocus.call(this);
24306         this.show();
24307     },
24308     
24309     onBlur : function()
24310     {
24311         Roo.bootstrap.form.TimeField.superclass.onBlur.call(this);
24312         this.hide();
24313     },
24314     
24315     show : function()
24316     {
24317         this.picker().show();
24318         this.pop.show();
24319         this.update();
24320         this.place();
24321         
24322         this.fireEvent('show', this, this.date);
24323     },
24324     
24325     hide : function()
24326     {
24327         this.picker().hide();
24328         this.pop.hide();
24329         
24330         this.fireEvent('hide', this, this.date);
24331     },
24332     
24333     setTime : function()
24334     {
24335         this.hide();
24336         this.setValue(this.time.format(this.format));
24337         
24338         this.fireEvent('select', this, this.date);
24339         
24340         
24341     },
24342     
24343     onMousedown: function(e){
24344         e.stopPropagation();
24345         e.preventDefault();
24346     },
24347     
24348     onIncrementHours: function()
24349     {
24350         Roo.log('onIncrementHours');
24351         this.time = this.time.add(Date.HOUR, 1);
24352         this.update();
24353         
24354     },
24355     
24356     onDecrementHours: function()
24357     {
24358         Roo.log('onDecrementHours');
24359         this.time = this.time.add(Date.HOUR, -1);
24360         this.update();
24361     },
24362     
24363     onIncrementMinutes: function()
24364     {
24365         Roo.log('onIncrementMinutes');
24366         var minutesToAdd = Math.round((parseInt(this.time.format('i')) + this.minuteStep) / this.minuteStep) * this.minuteStep - parseInt(this.time.format('i'));
24367         this.time = this.time.add(Date.MINUTE, minutesToAdd);
24368         this.update();
24369     },
24370     
24371     onDecrementMinutes: function()
24372     {
24373         Roo.log('onDecrementMinutes');
24374         var minutesToSubtract = parseInt(this.time.format('i')) - Math.round((parseInt(this.time.format('i')) - this.minuteStep) / this.minuteStep) * this.minuteStep;
24375         this.time = this.time.add(Date.MINUTE, -1 * minutesToSubtract);
24376         this.update();
24377     },
24378     
24379     onTogglePeriod: function()
24380     {
24381         Roo.log('onTogglePeriod');
24382         this.time = this.time.add(Date.HOUR, 12);
24383         this.update();
24384     }
24385     
24386    
24387 });
24388  
24389
24390 Roo.apply(Roo.bootstrap.form.TimeField,  {
24391   
24392     template : {
24393         tag: 'div',
24394         cls: 'datepicker dropdown-menu',
24395         cn: [
24396             {
24397                 tag: 'div',
24398                 cls: 'datepicker-time',
24399                 cn: [
24400                 {
24401                     tag: 'table',
24402                     cls: 'table-condensed',
24403                     cn:[
24404                         {
24405                             tag: 'tbody',
24406                             cn: [
24407                                 {
24408                                     tag: 'tr',
24409                                     cn: [
24410                                     {
24411                                         tag: 'td',
24412                                         colspan: '7'
24413                                     }
24414                                     ]
24415                                 }
24416                             ]
24417                         },
24418                         {
24419                             tag: 'tfoot',
24420                             cn: [
24421                                 {
24422                                     tag: 'tr',
24423                                     cn: [
24424                                     {
24425                                         tag: 'th',
24426                                         colspan: '7',
24427                                         cls: '',
24428                                         cn: [
24429                                             {
24430                                                 tag: 'button',
24431                                                 cls: 'btn btn-info ok',
24432                                                 html: 'OK'
24433                                             }
24434                                         ]
24435                                     }
24436                     
24437                                     ]
24438                                 }
24439                             ]
24440                         }
24441                     ]
24442                 }
24443                 ]
24444             }
24445         ]
24446     }
24447 });
24448
24449  
24450
24451  /*
24452  * - LGPL
24453  *
24454  * MonthField
24455  * 
24456  */
24457
24458 /**
24459  * @class Roo.bootstrap.form.MonthField
24460  * @extends Roo.bootstrap.form.Input
24461  * Bootstrap MonthField class
24462  * 
24463  * @cfg {String} language default en
24464  * 
24465  * @constructor
24466  * Create a new MonthField
24467  * @param {Object} config The config object
24468  */
24469
24470 Roo.bootstrap.form.MonthField = function(config){
24471     Roo.bootstrap.form.MonthField.superclass.constructor.call(this, config);
24472     
24473     this.addEvents({
24474         /**
24475          * @event show
24476          * Fires when this field show.
24477          * @param {Roo.bootstrap.form.MonthField} this
24478          * @param {Mixed} date The date value
24479          */
24480         show : true,
24481         /**
24482          * @event show
24483          * Fires when this field hide.
24484          * @param {Roo.bootstrap.form.MonthField} this
24485          * @param {Mixed} date The date value
24486          */
24487         hide : true,
24488         /**
24489          * @event select
24490          * Fires when select a date.
24491          * @param {Roo.bootstrap.form.MonthField} this
24492          * @param {String} oldvalue The old value
24493          * @param {String} newvalue The new value
24494          */
24495         select : true
24496     });
24497 };
24498
24499 Roo.extend(Roo.bootstrap.form.MonthField, Roo.bootstrap.form.Input,  {
24500     
24501     onRender: function(ct, position)
24502     {
24503         
24504         Roo.bootstrap.form.MonthField.superclass.onRender.call(this, ct, position);
24505         
24506         this.language = this.language || 'en';
24507         this.language = this.language in Roo.bootstrap.form.MonthField.dates ? this.language : this.language.split('-')[0];
24508         this.language = this.language in Roo.bootstrap.form.MonthField.dates ? this.language : "en";
24509         
24510         this.isRTL = Roo.bootstrap.form.MonthField.dates[this.language].rtl || false;
24511         this.isInline = false;
24512         this.isInput = true;
24513         this.component = this.el.select('.add-on', true).first() || false;
24514         this.component = (this.component && this.component.length === 0) ? false : this.component;
24515         this.hasInput = this.component && this.inputEL().length;
24516         
24517         this.pickerEl = Roo.get(document.body).createChild(Roo.bootstrap.form.MonthField.template);
24518         
24519         this.picker().setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
24520         
24521         this.picker().on('mousedown', this.onMousedown, this);
24522         this.picker().on('click', this.onClick, this);
24523         
24524         this.picker().addClass('datepicker-dropdown');
24525         
24526         Roo.each(this.picker().select('tbody > tr > td', true).elements, function(v){
24527             v.setStyle('width', '189px');
24528         });
24529         
24530         this.fillMonths();
24531         
24532         this.update();
24533         
24534         if(this.isInline) {
24535             this.show();
24536         }
24537         
24538     },
24539     
24540     setValue: function(v, suppressEvent)
24541     {   
24542         var o = this.getValue();
24543         
24544         Roo.bootstrap.form.MonthField.superclass.setValue.call(this, v);
24545         
24546         this.update();
24547
24548         if(suppressEvent !== true){
24549             this.fireEvent('select', this, o, v);
24550         }
24551         
24552     },
24553     
24554     getValue: function()
24555     {
24556         return this.value;
24557     },
24558     
24559     onClick: function(e) 
24560     {
24561         e.stopPropagation();
24562         e.preventDefault();
24563         
24564         var target = e.getTarget();
24565         
24566         if(target.nodeName.toLowerCase() === 'i'){
24567             target = Roo.get(target).dom.parentNode;
24568         }
24569         
24570         var nodeName = target.nodeName;
24571         var className = target.className;
24572         var html = target.innerHTML;
24573         
24574         if(nodeName.toLowerCase() != 'span' || className.indexOf('disabled') > -1 || className.indexOf('month') == -1){
24575             return;
24576         }
24577         
24578         this.vIndex = Roo.bootstrap.form.MonthField.dates[this.language].monthsShort.indexOf(html);
24579         
24580         this.setValue(Roo.bootstrap.form.MonthField.dates[this.language].months[this.vIndex]);
24581         
24582         this.hide();
24583                         
24584     },
24585     
24586     picker : function()
24587     {
24588         return this.pickerEl;
24589     },
24590     
24591     fillMonths: function()
24592     {    
24593         var i = 0;
24594         var months = this.picker().select('>.datepicker-months td', true).first();
24595         
24596         months.dom.innerHTML = '';
24597         
24598         while (i < 12) {
24599             var month = {
24600                 tag: 'span',
24601                 cls: 'month',
24602                 html: Roo.bootstrap.form.MonthField.dates[this.language].monthsShort[i++]
24603             };
24604             
24605             months.createChild(month);
24606         }
24607         
24608     },
24609     
24610     update: function()
24611     {
24612         var _this = this;
24613         
24614         if(typeof(this.vIndex) == 'undefined' && this.value.length){
24615             this.vIndex = Roo.bootstrap.form.MonthField.dates[this.language].months.indexOf(this.value);
24616         }
24617         
24618         Roo.each(this.pickerEl.select('> .datepicker-months tbody > tr > td > span', true).elements, function(e, k){
24619             e.removeClass('active');
24620             
24621             if(typeof(_this.vIndex) != 'undefined' && k == _this.vIndex){
24622                 e.addClass('active');
24623             }
24624         })
24625     },
24626     
24627     place: function()
24628     {
24629         if(this.isInline) {
24630             return;
24631         }
24632         
24633         this.picker().removeClass(['bottom', 'top']);
24634         
24635         if((Roo.lib.Dom.getViewHeight() + Roo.get(document.body).getScroll().top) - (this.inputEl().getBottom() + this.picker().getHeight()) < 0){
24636             /*
24637              * place to the top of element!
24638              *
24639              */
24640             
24641             this.picker().addClass('top');
24642             this.picker().setTop(this.inputEl().getTop() - this.picker().getHeight()).setLeft(this.inputEl().getLeft());
24643             
24644             return;
24645         }
24646         
24647         this.picker().addClass('bottom');
24648         
24649         this.picker().setTop(this.inputEl().getBottom()).setLeft(this.inputEl().getLeft());
24650     },
24651     
24652     onFocus : function()
24653     {
24654         Roo.bootstrap.form.MonthField.superclass.onFocus.call(this);
24655         this.show();
24656     },
24657     
24658     onBlur : function()
24659     {
24660         Roo.bootstrap.form.MonthField.superclass.onBlur.call(this);
24661         
24662         var d = this.inputEl().getValue();
24663         
24664         this.setValue(d);
24665                 
24666         this.hide();
24667     },
24668     
24669     show : function()
24670     {
24671         this.picker().show();
24672         this.picker().select('>.datepicker-months', true).first().show();
24673         this.update();
24674         this.place();
24675         
24676         this.fireEvent('show', this, this.date);
24677     },
24678     
24679     hide : function()
24680     {
24681         if(this.isInline) {
24682             return;
24683         }
24684         this.picker().hide();
24685         this.fireEvent('hide', this, this.date);
24686         
24687     },
24688     
24689     onMousedown: function(e)
24690     {
24691         e.stopPropagation();
24692         e.preventDefault();
24693     },
24694     
24695     keyup: function(e)
24696     {
24697         Roo.bootstrap.form.MonthField.superclass.keyup.call(this);
24698         this.update();
24699     },
24700
24701     fireKey: function(e)
24702     {
24703         if (!this.picker().isVisible()){
24704             if (e.keyCode == 27)   {// allow escape to hide and re-show picker
24705                 this.show();
24706             }
24707             return;
24708         }
24709         
24710         var dir;
24711         
24712         switch(e.keyCode){
24713             case 27: // escape
24714                 this.hide();
24715                 e.preventDefault();
24716                 break;
24717             case 37: // left
24718             case 39: // right
24719                 dir = e.keyCode == 37 ? -1 : 1;
24720                 
24721                 this.vIndex = this.vIndex + dir;
24722                 
24723                 if(this.vIndex < 0){
24724                     this.vIndex = 0;
24725                 }
24726                 
24727                 if(this.vIndex > 11){
24728                     this.vIndex = 11;
24729                 }
24730                 
24731                 if(isNaN(this.vIndex)){
24732                     this.vIndex = 0;
24733                 }
24734                 
24735                 this.setValue(Roo.bootstrap.form.MonthField.dates[this.language].months[this.vIndex]);
24736                 
24737                 break;
24738             case 38: // up
24739             case 40: // down
24740                 
24741                 dir = e.keyCode == 38 ? -1 : 1;
24742                 
24743                 this.vIndex = this.vIndex + dir * 4;
24744                 
24745                 if(this.vIndex < 0){
24746                     this.vIndex = 0;
24747                 }
24748                 
24749                 if(this.vIndex > 11){
24750                     this.vIndex = 11;
24751                 }
24752                 
24753                 if(isNaN(this.vIndex)){
24754                     this.vIndex = 0;
24755                 }
24756                 
24757                 this.setValue(Roo.bootstrap.form.MonthField.dates[this.language].months[this.vIndex]);
24758                 break;
24759                 
24760             case 13: // enter
24761                 
24762                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
24763                     this.setValue(Roo.bootstrap.form.MonthField.dates[this.language].months[this.vIndex]);
24764                 }
24765                 
24766                 this.hide();
24767                 e.preventDefault();
24768                 break;
24769             case 9: // tab
24770                 if(typeof(this.vIndex) != 'undefined' && !isNaN(this.vIndex)){
24771                     this.setValue(Roo.bootstrap.form.MonthField.dates[this.language].months[this.vIndex]);
24772                 }
24773                 this.hide();
24774                 break;
24775             case 16: // shift
24776             case 17: // ctrl
24777             case 18: // alt
24778                 break;
24779             default :
24780                 this.hide();
24781                 
24782         }
24783     },
24784     
24785     remove: function() 
24786     {
24787         this.picker().remove();
24788     }
24789    
24790 });
24791
24792 Roo.apply(Roo.bootstrap.form.MonthField,  {
24793     
24794     content : {
24795         tag: 'tbody',
24796         cn: [
24797         {
24798             tag: 'tr',
24799             cn: [
24800             {
24801                 tag: 'td',
24802                 colspan: '7'
24803             }
24804             ]
24805         }
24806         ]
24807     },
24808     
24809     dates:{
24810         en: {
24811             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
24812             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
24813         }
24814     }
24815 });
24816
24817 Roo.apply(Roo.bootstrap.form.MonthField,  {
24818   
24819     template : {
24820         tag: 'div',
24821         cls: 'datepicker dropdown-menu roo-dynamic',
24822         cn: [
24823             {
24824                 tag: 'div',
24825                 cls: 'datepicker-months',
24826                 cn: [
24827                 {
24828                     tag: 'table',
24829                     cls: 'table-condensed',
24830                     cn:[
24831                         Roo.bootstrap.form.DateField.content
24832                     ]
24833                 }
24834                 ]
24835             }
24836         ]
24837     }
24838 });
24839
24840  
24841
24842  
24843  /*
24844  * - LGPL
24845  *
24846  * CheckBox
24847  * 
24848  */
24849
24850 /**
24851  * @class Roo.bootstrap.form.CheckBox
24852  * @extends Roo.bootstrap.form.Input
24853  * Bootstrap CheckBox class
24854  * 
24855  * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
24856  * @cfg {String} inputValue The value that should go into the generated input element's value when checked.
24857  * @cfg {String} boxLabel The text that appears beside the checkbox
24858  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the checkbox
24859  * @cfg {Boolean} checked initnal the element
24860  * @cfg {Boolean} inline inline the element (default false)
24861  * @cfg {String} groupId the checkbox group id // normal just use for checkbox
24862  * @cfg {String} tooltip label tooltip
24863  * 
24864  * @constructor
24865  * Create a new CheckBox
24866  * @param {Object} config The config object
24867  */
24868
24869 Roo.bootstrap.form.CheckBox = function(config){
24870     Roo.bootstrap.form.CheckBox.superclass.constructor.call(this, config);
24871    
24872     this.addEvents({
24873         /**
24874         * @event check
24875         * Fires when the element is checked or unchecked.
24876         * @param {Roo.bootstrap.form.CheckBox} this This input
24877         * @param {Boolean} checked The new checked value
24878         */
24879        check : true,
24880        /**
24881         * @event click
24882         * Fires when the element is click.
24883         * @param {Roo.bootstrap.form.CheckBox} this This input
24884         */
24885        click : true
24886     });
24887     
24888 };
24889
24890 Roo.extend(Roo.bootstrap.form.CheckBox, Roo.bootstrap.form.Input,  {
24891   
24892     inputType: 'checkbox',
24893     inputValue: 1,
24894     valueOff: 0,
24895     boxLabel: false,
24896     checked: false,
24897     weight : false,
24898     inline: false,
24899     tooltip : '',
24900     
24901     // checkbox success does not make any sense really.. 
24902     invalidClass : "",
24903     validClass : "",
24904     
24905     
24906     getAutoCreate : function()
24907     {
24908         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
24909         
24910         var id = Roo.id();
24911         
24912         var cfg = {};
24913         
24914         cfg.cls = 'form-group form-check ' + this.inputType; //input-group
24915         
24916         if(this.inline){
24917             cfg.cls += ' ' + this.inputType + '-inline  form-check-inline';
24918         }
24919         
24920         var input =  {
24921             tag: 'input',
24922             id : id,
24923             type : this.inputType,
24924             value : this.inputValue,
24925             cls : 'roo-' + this.inputType, //'form-box',
24926             placeholder : this.placeholder || ''
24927             
24928         };
24929         
24930         if(this.inputType != 'radio'){
24931             var hidden =  {
24932                 tag: 'input',
24933                 type : 'hidden',
24934                 cls : 'roo-hidden-value',
24935                 value : this.checked ? this.inputValue : this.valueOff
24936             };
24937         }
24938         
24939             
24940         if (this.weight) { // Validity check?
24941             cfg.cls += " " + this.inputType + "-" + this.weight;
24942         }
24943         
24944         if (this.disabled) {
24945             input.disabled=true;
24946         }
24947         
24948         if(this.checked){
24949             input.checked = this.checked;
24950         }
24951         
24952         if (this.name) {
24953             
24954             input.name = this.name;
24955             
24956             if(this.inputType != 'radio'){
24957                 hidden.name = this.name;
24958                 input.name = '_hidden_' + this.name;
24959             }
24960         }
24961         
24962         if (this.size) {
24963             input.cls += ' input-' + this.size;
24964         }
24965         
24966         var settings=this;
24967         
24968         ['xs','sm','md','lg'].map(function(size){
24969             if (settings[size]) {
24970                 cfg.cls += ' col-' + size + '-' + settings[size];
24971             }
24972         });
24973         
24974         var inputblock = input;
24975          
24976         if (this.before || this.after) {
24977             
24978             inputblock = {
24979                 cls : 'input-group',
24980                 cn :  [] 
24981             };
24982             
24983             if (this.before) {
24984                 inputblock.cn.push({
24985                     tag :'span',
24986                     cls : 'input-group-addon',
24987                     html : this.before
24988                 });
24989             }
24990             
24991             inputblock.cn.push(input);
24992             
24993             if(this.inputType != 'radio'){
24994                 inputblock.cn.push(hidden);
24995             }
24996             
24997             if (this.after) {
24998                 inputblock.cn.push({
24999                     tag :'span',
25000                     cls : 'input-group-addon',
25001                     html : this.after
25002                 });
25003             }
25004             
25005         }
25006         var boxLabelCfg = false;
25007         
25008         if(this.boxLabel){
25009            
25010             boxLabelCfg = {
25011                 tag: 'label',
25012                 //'for': id, // box label is handled by onclick - so no for...
25013                 cls: 'box-label',
25014                 html: this.boxLabel
25015             };
25016             if(this.tooltip){
25017                 boxLabelCfg.tooltip = this.tooltip;
25018             }
25019              
25020         }
25021         
25022         
25023         if (align ==='left' && this.fieldLabel.length) {
25024 //                Roo.log("left and has label");
25025             cfg.cn = [
25026                 {
25027                     tag: 'label',
25028                     'for' :  id,
25029                     cls : 'control-label',
25030                     html : this.fieldLabel
25031                 },
25032                 {
25033                     cls : "", 
25034                     cn: [
25035                         inputblock
25036                     ]
25037                 }
25038             ];
25039             
25040             if (boxLabelCfg) {
25041                 cfg.cn[1].cn.push(boxLabelCfg);
25042             }
25043             
25044             if(this.labelWidth > 12){
25045                 cfg.cn[0].style = "width: " + this.labelWidth + 'px';
25046             }
25047             
25048             if(this.labelWidth < 13 && this.labelmd == 0){
25049                 this.labelmd = this.labelWidth;
25050             }
25051             
25052             if(this.labellg > 0){
25053                 cfg.cn[0].cls += ' col-lg-' + this.labellg;
25054                 cfg.cn[1].cls += ' col-lg-' + (12 - this.labellg);
25055             }
25056             
25057             if(this.labelmd > 0){
25058                 cfg.cn[0].cls += ' col-md-' + this.labelmd;
25059                 cfg.cn[1].cls += ' col-md-' + (12 - this.labelmd);
25060             }
25061             
25062             if(this.labelsm > 0){
25063                 cfg.cn[0].cls += ' col-sm-' + this.labelsm;
25064                 cfg.cn[1].cls += ' col-sm-' + (12 - this.labelsm);
25065             }
25066             
25067             if(this.labelxs > 0){
25068                 cfg.cn[0].cls += ' col-xs-' + this.labelxs;
25069                 cfg.cn[1].cls += ' col-xs-' + (12 - this.labelxs);
25070             }
25071             
25072         } else if ( this.fieldLabel.length) {
25073 //                Roo.log(" label");
25074                 cfg.cn = [
25075                    
25076                     {
25077                         tag: this.boxLabel ? 'span' : 'label',
25078                         'for': id,
25079                         cls: 'control-label box-input-label',
25080                         //cls : 'input-group-addon',
25081                         html : this.fieldLabel
25082                     },
25083                     
25084                     inputblock
25085                     
25086                 ];
25087                 if (boxLabelCfg) {
25088                     cfg.cn.push(boxLabelCfg);
25089                 }
25090
25091         } else {
25092             
25093 //                Roo.log(" no label && no align");
25094                 cfg.cn = [  inputblock ] ;
25095                 if (boxLabelCfg) {
25096                     cfg.cn.push(boxLabelCfg);
25097                 }
25098
25099                 
25100         }
25101         
25102        
25103         
25104         if(this.inputType != 'radio'){
25105             cfg.cn.push(hidden);
25106         }
25107         
25108         return cfg;
25109         
25110     },
25111     
25112     /**
25113      * return the real input element.
25114      */
25115     inputEl: function ()
25116     {
25117         return this.el.select('input.roo-' + this.inputType,true).first();
25118     },
25119     hiddenEl: function ()
25120     {
25121         return this.el.select('input.roo-hidden-value',true).first();
25122     },
25123     
25124     labelEl: function()
25125     {
25126         return this.el.select('label.control-label',true).first();
25127     },
25128     /* depricated... */
25129     
25130     label: function()
25131     {
25132         return this.labelEl();
25133     },
25134     
25135     boxLabelEl: function()
25136     {
25137         return this.el.select('label.box-label',true).first();
25138     },
25139     
25140     initEvents : function()
25141     {
25142 //        Roo.bootstrap.form.CheckBox.superclass.initEvents.call(this);
25143         
25144         this.inputEl().on('click', this.onClick,  this);
25145         
25146         if (this.boxLabel) { 
25147             this.el.select('label.box-label',true).first().on('click', this.onClick,  this);
25148         }
25149         
25150         this.startValue = this.getValue();
25151         
25152         if(this.groupId){
25153             Roo.bootstrap.form.CheckBox.register(this);
25154         }
25155     },
25156     
25157     onClick : function(e)
25158     {   
25159         if(this.fireEvent('click', this, e) !== false){
25160             this.setChecked(!this.checked);
25161         }
25162         
25163     },
25164     
25165     setChecked : function(state,suppressEvent)
25166     {
25167         this.startValue = this.getValue();
25168
25169         if(this.inputType == 'radio'){
25170             
25171             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25172                 e.dom.checked = false;
25173             });
25174             
25175             this.inputEl().dom.checked = true;
25176             
25177             this.inputEl().dom.value = this.inputValue;
25178             
25179             if(suppressEvent !== true){
25180                 this.fireEvent('check', this, true);
25181             }
25182             
25183             this.validate();
25184             
25185             return;
25186         }
25187         
25188         this.checked = state;
25189         
25190         this.inputEl().dom.checked = state;
25191         
25192         
25193         this.hiddenEl().dom.value = state ? this.inputValue : this.valueOff;
25194         
25195         if(suppressEvent !== true){
25196             this.fireEvent('check', this, state);
25197         }
25198         
25199         this.validate();
25200     },
25201     
25202     getValue : function()
25203     {
25204         if(this.inputType == 'radio'){
25205             return this.getGroupValue();
25206         }
25207         
25208         return this.hiddenEl().dom.value;
25209         
25210     },
25211     
25212     getGroupValue : function()
25213     {
25214         if(typeof(this.el.up('form').child('input[name='+this.name+']:checked', true)) == 'undefined'){
25215             return '';
25216         }
25217         
25218         return this.el.up('form').child('input[name='+this.name+']:checked', true).value;
25219     },
25220     
25221     setValue : function(v,suppressEvent)
25222     {
25223         if(this.inputType == 'radio'){
25224             this.setGroupValue(v, suppressEvent);
25225             return;
25226         }
25227         
25228         this.setChecked(((typeof(v) == 'undefined') ? this.checked : (String(v) === String(this.inputValue))), suppressEvent);
25229         
25230         this.validate();
25231     },
25232     
25233     setGroupValue : function(v, suppressEvent)
25234     {
25235         this.startValue = this.getValue();
25236         
25237         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25238             e.dom.checked = false;
25239             
25240             if(e.dom.value == v){
25241                 e.dom.checked = true;
25242             }
25243         });
25244         
25245         if(suppressEvent !== true){
25246             this.fireEvent('check', this, true);
25247         }
25248
25249         this.validate();
25250         
25251         return;
25252     },
25253     
25254     validate : function()
25255     {
25256         if(this.getVisibilityEl().hasClass('hidden')){
25257             return true;
25258         }
25259         
25260         if(
25261                 this.disabled || 
25262                 (this.inputType == 'radio' && this.validateRadio()) ||
25263                 (this.inputType == 'checkbox' && this.validateCheckbox())
25264         ){
25265             this.markValid();
25266             return true;
25267         }
25268         
25269         this.markInvalid();
25270         return false;
25271     },
25272     
25273     validateRadio : function()
25274     {
25275         if(this.getVisibilityEl().hasClass('hidden')){
25276             return true;
25277         }
25278         
25279         if(this.allowBlank){
25280             return true;
25281         }
25282         
25283         var valid = false;
25284         
25285         Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25286             if(!e.dom.checked){
25287                 return;
25288             }
25289             
25290             valid = true;
25291             
25292             return false;
25293         });
25294         
25295         return valid;
25296     },
25297     
25298     validateCheckbox : function()
25299     {
25300         if(!this.groupId){
25301             return (this.getValue() == this.inputValue || this.allowBlank) ? true : false;
25302             //return (this.getValue() == this.inputValue) ? true : false;
25303         }
25304         
25305         var group = Roo.bootstrap.form.CheckBox.get(this.groupId);
25306         
25307         if(!group){
25308             return false;
25309         }
25310         
25311         var r = false;
25312         
25313         for(var i in group){
25314             if(group[i].el.isVisible(true)){
25315                 r = false;
25316                 break;
25317             }
25318             
25319             r = true;
25320         }
25321         
25322         for(var i in group){
25323             if(r){
25324                 break;
25325             }
25326             
25327             r = (group[i].getValue() == group[i].inputValue) ? true : false;
25328         }
25329         
25330         return r;
25331     },
25332     
25333     /**
25334      * Mark this field as valid
25335      */
25336     markValid : function()
25337     {
25338         var _this = this;
25339         
25340         this.fireEvent('valid', this);
25341         
25342         var label = Roo.bootstrap.form.FieldLabel.get(this.name + '-group');
25343         
25344         if(this.groupId){
25345             label = Roo.bootstrap.form.FieldLabel.get(this.groupId + '-group');
25346         }
25347         
25348         if(label){
25349             label.markValid();
25350         }
25351
25352         if(this.inputType == 'radio'){
25353             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25354                 var fg = e.findParent('.form-group', false, true);
25355                 if (Roo.bootstrap.version == 3) {
25356                     fg.removeClass([_this.invalidClass, _this.validClass]);
25357                     fg.addClass(_this.validClass);
25358                 } else {
25359                     fg.removeClass(['is-valid', 'is-invalid']);
25360                     fg.addClass('is-valid');
25361                 }
25362             });
25363             
25364             return;
25365         }
25366
25367         if(!this.groupId){
25368             var fg = this.el.findParent('.form-group', false, true);
25369             if (Roo.bootstrap.version == 3) {
25370                 fg.removeClass([this.invalidClass, this.validClass]);
25371                 fg.addClass(this.validClass);
25372             } else {
25373                 fg.removeClass(['is-valid', 'is-invalid']);
25374                 fg.addClass('is-valid');
25375             }
25376             return;
25377         }
25378         
25379         var group = Roo.bootstrap.form.CheckBox.get(this.groupId);
25380         
25381         if(!group){
25382             return;
25383         }
25384         
25385         for(var i in group){
25386             var fg = group[i].el.findParent('.form-group', false, true);
25387             if (Roo.bootstrap.version == 3) {
25388                 fg.removeClass([this.invalidClass, this.validClass]);
25389                 fg.addClass(this.validClass);
25390             } else {
25391                 fg.removeClass(['is-valid', 'is-invalid']);
25392                 fg.addClass('is-valid');
25393             }
25394         }
25395     },
25396     
25397      /**
25398      * Mark this field as invalid
25399      * @param {String} msg The validation message
25400      */
25401     markInvalid : function(msg)
25402     {
25403         if(this.allowBlank){
25404             return;
25405         }
25406         
25407         var _this = this;
25408         
25409         this.fireEvent('invalid', this, msg);
25410         
25411         var label = Roo.bootstrap.form.FieldLabel.get(this.name + '-group');
25412         
25413         if(this.groupId){
25414             label = Roo.bootstrap.form.FieldLabel.get(this.groupId + '-group');
25415         }
25416         
25417         if(label){
25418             label.markInvalid();
25419         }
25420             
25421         if(this.inputType == 'radio'){
25422             
25423             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25424                 var fg = e.findParent('.form-group', false, true);
25425                 if (Roo.bootstrap.version == 3) {
25426                     fg.removeClass([_this.invalidClass, _this.validClass]);
25427                     fg.addClass(_this.invalidClass);
25428                 } else {
25429                     fg.removeClass(['is-invalid', 'is-valid']);
25430                     fg.addClass('is-invalid');
25431                 }
25432             });
25433             
25434             return;
25435         }
25436         
25437         if(!this.groupId){
25438             var fg = this.el.findParent('.form-group', false, true);
25439             if (Roo.bootstrap.version == 3) {
25440                 fg.removeClass([_this.invalidClass, _this.validClass]);
25441                 fg.addClass(_this.invalidClass);
25442             } else {
25443                 fg.removeClass(['is-invalid', 'is-valid']);
25444                 fg.addClass('is-invalid');
25445             }
25446             return;
25447         }
25448         
25449         var group = Roo.bootstrap.form.CheckBox.get(this.groupId);
25450         
25451         if(!group){
25452             return;
25453         }
25454         
25455         for(var i in group){
25456             var fg = group[i].el.findParent('.form-group', false, true);
25457             if (Roo.bootstrap.version == 3) {
25458                 fg.removeClass([_this.invalidClass, _this.validClass]);
25459                 fg.addClass(_this.invalidClass);
25460             } else {
25461                 fg.removeClass(['is-invalid', 'is-valid']);
25462                 fg.addClass('is-invalid');
25463             }
25464         }
25465         
25466     },
25467     
25468     clearInvalid : function()
25469     {
25470         Roo.bootstrap.form.Input.prototype.clearInvalid.call(this);
25471         
25472         // this.el.findParent('.form-group', false, true).removeClass([this.invalidClass, this.validClass]);
25473         
25474         var label = Roo.bootstrap.form.FieldLabel.get(this.name + '-group');
25475         
25476         if (label && label.iconEl) {
25477             label.iconEl.removeClass([ label.validClass, label.invalidClass ]);
25478             label.iconEl.removeClass(['is-invalid', 'is-valid']);
25479         }
25480     },
25481     
25482     disable : function()
25483     {
25484         if(this.inputType != 'radio'){
25485             Roo.bootstrap.form.CheckBox.superclass.disable.call(this);
25486             return;
25487         }
25488         
25489         var _this = this;
25490         
25491         if(this.rendered){
25492             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25493                 _this.getActionEl().addClass(this.disabledClass);
25494                 e.dom.disabled = true;
25495             });
25496         }
25497         
25498         this.disabled = true;
25499         this.fireEvent("disable", this);
25500         return this;
25501     },
25502
25503     enable : function()
25504     {
25505         if(this.inputType != 'radio'){
25506             Roo.bootstrap.form.CheckBox.superclass.enable.call(this);
25507             return;
25508         }
25509         
25510         var _this = this;
25511         
25512         if(this.rendered){
25513             Roo.each(this.el.up('form').select('input[name='+this.name+']', true).elements, function(e){
25514                 _this.getActionEl().removeClass(this.disabledClass);
25515                 e.dom.disabled = false;
25516             });
25517         }
25518         
25519         this.disabled = false;
25520         this.fireEvent("enable", this);
25521         return this;
25522     },
25523     
25524     setBoxLabel : function(v)
25525     {
25526         this.boxLabel = v;
25527         
25528         if(this.rendered){
25529             this.el.select('label.box-label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
25530         }
25531     }
25532
25533 });
25534
25535 Roo.apply(Roo.bootstrap.form.CheckBox, {
25536     
25537     groups: {},
25538     
25539      /**
25540     * register a CheckBox Group
25541     * @param {Roo.bootstrap.form.CheckBox} the CheckBox to add
25542     */
25543     register : function(checkbox)
25544     {
25545         if(typeof(this.groups[checkbox.groupId]) == 'undefined'){
25546             this.groups[checkbox.groupId] = {};
25547         }
25548         
25549         if(this.groups[checkbox.groupId].hasOwnProperty(checkbox.name)){
25550             return;
25551         }
25552         
25553         this.groups[checkbox.groupId][checkbox.name] = checkbox;
25554         
25555     },
25556     /**
25557     * fetch a CheckBox Group based on the group ID
25558     * @param {string} the group ID
25559     * @returns {Roo.bootstrap.form.CheckBox} the CheckBox group
25560     */
25561     get: function(groupId) {
25562         if (typeof(this.groups[groupId]) == 'undefined') {
25563             return false;
25564         }
25565         
25566         return this.groups[groupId] ;
25567     }
25568     
25569     
25570 });
25571 /*
25572  * - LGPL
25573  *
25574  * RadioItem
25575  * 
25576  */
25577
25578 /**
25579  * @class Roo.bootstrap.form.Radio
25580  * @extends Roo.bootstrap.Component
25581  * Bootstrap Radio class
25582  * @cfg {String} boxLabel - the label associated
25583  * @cfg {String} value - the value of radio
25584  * 
25585  * @constructor
25586  * Create a new Radio
25587  * @param {Object} config The config object
25588  */
25589 Roo.bootstrap.form.Radio = function(config){
25590     Roo.bootstrap.form.Radio.superclass.constructor.call(this, config);
25591     
25592 };
25593
25594 Roo.extend(Roo.bootstrap.form.Radio, Roo.bootstrap.Component, {
25595     
25596     boxLabel : '',
25597     
25598     value : '',
25599     
25600     getAutoCreate : function()
25601     {
25602         var cfg = {
25603             tag : 'div',
25604             cls : 'form-group radio',
25605             cn : [
25606                 {
25607                     tag : 'label',
25608                     cls : 'box-label',
25609                     html : this.boxLabel
25610                 }
25611             ]
25612         };
25613         
25614         return cfg;
25615     },
25616     
25617     initEvents : function() 
25618     {
25619         this.parent().register(this);
25620         
25621         this.el.on('click', this.onClick, this);
25622         
25623     },
25624     
25625     onClick : function(e)
25626     {
25627         if(this.parent().fireEvent('click', this.parent(), this, e) !== false){
25628             this.setChecked(true);
25629         }
25630     },
25631     
25632     setChecked : function(state, suppressEvent)
25633     {
25634         this.parent().setValue(this.value, suppressEvent);
25635         
25636     },
25637     
25638     setBoxLabel : function(v)
25639     {
25640         this.boxLabel = v;
25641         
25642         if(this.rendered){
25643             this.el.select('label.box-label',true).first().dom.innerHTML = (v === null || v === undefined ? '' : v);
25644         }
25645     }
25646     
25647 });
25648  
25649
25650  /*
25651  * - LGPL
25652  *
25653  * Input
25654  * 
25655  */
25656
25657 /**
25658  * @class Roo.bootstrap.form.SecurePass
25659  * @extends Roo.bootstrap.form.Input
25660  * Bootstrap SecurePass class
25661  *
25662  * 
25663  * @constructor
25664  * Create a new SecurePass
25665  * @param {Object} config The config object
25666  */
25667  
25668 Roo.bootstrap.form.SecurePass = function (config) {
25669     // these go here, so the translation tool can replace them..
25670     this.errors = {
25671         PwdEmpty: "Please type a password, and then retype it to confirm.",
25672         PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
25673         PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
25674         PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
25675         IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
25676         FNInPwd: "Your password can't contain your first name. Please type a different password.",
25677         LNInPwd: "Your password can't contain your last name. Please type a different password.",
25678         TooWeak: "Your password is Too Weak."
25679     },
25680     this.meterLabel = "Password strength:";
25681     this.pwdStrengths = ["Too Weak", "Weak", "Medium", "Strong"];
25682     this.meterClass = [
25683         "roo-password-meter-tooweak", 
25684         "roo-password-meter-weak", 
25685         "roo-password-meter-medium", 
25686         "roo-password-meter-strong", 
25687         "roo-password-meter-grey"
25688     ];
25689     
25690     this.errors = {};
25691     
25692     Roo.bootstrap.form.SecurePass.superclass.constructor.call(this, config);
25693 }
25694
25695 Roo.extend(Roo.bootstrap.form.SecurePass, Roo.bootstrap.form.Input, {
25696     /**
25697      * @cfg {String/Object} errors A Error spec, or true for a default spec (defaults to
25698      * {
25699      *  PwdEmpty: "Please type a password, and then retype it to confirm.",
25700      *  PwdShort: "Your password must be at least 6 characters long. Please type a different password.",
25701      *  PwdLong: "Your password can't contain more than 16 characters. Please type a different password.",
25702      *  PwdBadChar: "The password contains characters that aren't allowed. Please type a different password.",
25703      *  IDInPwd: "Your password can't include the part of your ID. Please type a different password.",
25704      *  FNInPwd: "Your password can't contain your first name. Please type a different password.",
25705      *  LNInPwd: "Your password can't contain your last name. Please type a different password."
25706      * })
25707      */
25708     // private
25709     
25710     meterWidth: 300,
25711     errorMsg :'',    
25712     errors: false,
25713     imageRoot: '/',
25714     /**
25715      * @cfg {String/Object} Label for the strength meter (defaults to
25716      * 'Password strength:')
25717      */
25718     // private
25719     meterLabel: '',
25720     /**
25721      * @cfg {String/Object} pwdStrengths A pwdStrengths spec, or true for a default spec (defaults to
25722      * ['Weak', 'Medium', 'Strong'])
25723      */
25724     // private    
25725     pwdStrengths: false,    
25726     // private
25727     strength: 0,
25728     // private
25729     _lastPwd: null,
25730     // private
25731     kCapitalLetter: 0,
25732     kSmallLetter: 1,
25733     kDigit: 2,
25734     kPunctuation: 3,
25735     
25736     insecure: false,
25737     // private
25738     initEvents: function ()
25739     {
25740         Roo.bootstrap.form.SecurePass.superclass.initEvents.call(this);
25741
25742         if (this.el.is('input[type=password]') && Roo.isSafari) {
25743             this.el.on('keydown', this.SafariOnKeyDown, this);
25744         }
25745
25746         this.el.on('keyup', this.checkStrength, this, {buffer: 50});
25747     },
25748     // private
25749     onRender: function (ct, position)
25750     {
25751         Roo.bootstrap.form.SecurePass.superclass.onRender.call(this, ct, position);
25752         this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
25753         this.trigger = this.wrap.createChild({tag: 'div', cls: 'StrengthMeter ' + this.triggerClass});
25754
25755         this.trigger.createChild({
25756                    cn: [
25757                     {
25758                     //id: 'PwdMeter',
25759                     tag: 'div',
25760                     cls: 'roo-password-meter-grey col-xs-12',
25761                     style: {
25762                         //width: 0,
25763                         //width: this.meterWidth + 'px'                                                
25764                         }
25765                     },
25766                     {                            
25767                          cls: 'roo-password-meter-text'                          
25768                     }
25769                 ]            
25770         });
25771
25772          
25773         if (this.hideTrigger) {
25774             this.trigger.setDisplayed(false);
25775         }
25776         this.setSize(this.width || '', this.height || '');
25777     },
25778     // private
25779     onDestroy: function ()
25780     {
25781         if (this.trigger) {
25782             this.trigger.removeAllListeners();
25783             this.trigger.remove();
25784         }
25785         if (this.wrap) {
25786             this.wrap.remove();
25787         }
25788         Roo.bootstrap.form.TriggerField.superclass.onDestroy.call(this);
25789     },
25790     // private
25791     checkStrength: function ()
25792     {
25793         var pwd = this.inputEl().getValue();
25794         if (pwd == this._lastPwd) {
25795             return;
25796         }
25797
25798         var strength;
25799         if (this.ClientSideStrongPassword(pwd)) {
25800             strength = 3;
25801         } else if (this.ClientSideMediumPassword(pwd)) {
25802             strength = 2;
25803         } else if (this.ClientSideWeakPassword(pwd)) {
25804             strength = 1;
25805         } else {
25806             strength = 0;
25807         }
25808         
25809         Roo.log('strength1: ' + strength);
25810         
25811         //var pm = this.trigger.child('div/div/div').dom;
25812         var pm = this.trigger.child('div/div');
25813         pm.removeClass(this.meterClass);
25814         pm.addClass(this.meterClass[strength]);
25815                 
25816         
25817         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
25818                 
25819         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
25820         
25821         this._lastPwd = pwd;
25822     },
25823     reset: function ()
25824     {
25825         Roo.bootstrap.form.SecurePass.superclass.reset.call(this);
25826         
25827         this._lastPwd = '';
25828         
25829         var pm = this.trigger.child('div/div');
25830         pm.removeClass(this.meterClass);
25831         pm.addClass('roo-password-meter-grey');        
25832         
25833         
25834         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
25835         
25836         pt.innerHTML = '';
25837         this.inputEl().dom.type='password';
25838     },
25839     // private
25840     validateValue: function (value)
25841     {
25842         if (!Roo.bootstrap.form.SecurePass.superclass.validateValue.call(this, value)) {
25843             return false;
25844         }
25845         if (value.length == 0) {
25846             if (this.allowBlank) {
25847                 this.clearInvalid();
25848                 return true;
25849             }
25850
25851             this.markInvalid(this.errors.PwdEmpty);
25852             this.errorMsg = this.errors.PwdEmpty;
25853             return false;
25854         }
25855         
25856         if(this.insecure){
25857             return true;
25858         }
25859         
25860         if (!value.match(/[\x21-\x7e]+/)) {
25861             this.markInvalid(this.errors.PwdBadChar);
25862             this.errorMsg = this.errors.PwdBadChar;
25863             return false;
25864         }
25865         if (value.length < 6) {
25866             this.markInvalid(this.errors.PwdShort);
25867             this.errorMsg = this.errors.PwdShort;
25868             return false;
25869         }
25870         if (value.length > 16) {
25871             this.markInvalid(this.errors.PwdLong);
25872             this.errorMsg = this.errors.PwdLong;
25873             return false;
25874         }
25875         var strength;
25876         if (this.ClientSideStrongPassword(value)) {
25877             strength = 3;
25878         } else if (this.ClientSideMediumPassword(value)) {
25879             strength = 2;
25880         } else if (this.ClientSideWeakPassword(value)) {
25881             strength = 1;
25882         } else {
25883             strength = 0;
25884         }
25885
25886         
25887         if (strength < 2) {
25888             //this.markInvalid(this.errors.TooWeak);
25889             this.errorMsg = this.errors.TooWeak;
25890             //return false;
25891         }
25892         
25893         
25894         console.log('strength2: ' + strength);
25895         
25896         //var pm = this.trigger.child('div/div/div').dom;
25897         
25898         var pm = this.trigger.child('div/div');
25899         pm.removeClass(this.meterClass);
25900         pm.addClass(this.meterClass[strength]);
25901                 
25902         var pt = this.trigger.child('/div').child('>*[class=roo-password-meter-text]').dom;        
25903                 
25904         pt.innerHTML = this.meterLabel + '&nbsp;' + this.pwdStrengths[strength];
25905         
25906         this.errorMsg = ''; 
25907         return true;
25908     },
25909     // private
25910     CharacterSetChecks: function (type)
25911     {
25912         this.type = type;
25913         this.fResult = false;
25914     },
25915     // private
25916     isctype: function (character, type)
25917     {
25918         switch (type) {  
25919             case this.kCapitalLetter:
25920                 if (character >= 'A' && character <= 'Z') {
25921                     return true;
25922                 }
25923                 break;
25924             
25925             case this.kSmallLetter:
25926                 if (character >= 'a' && character <= 'z') {
25927                     return true;
25928                 }
25929                 break;
25930             
25931             case this.kDigit:
25932                 if (character >= '0' && character <= '9') {
25933                     return true;
25934                 }
25935                 break;
25936             
25937             case this.kPunctuation:
25938                 if ('!@#$%^&*()_+-=\'";:[{]}|.>,</?`~'.indexOf(character) >= 0) {
25939                     return true;
25940                 }
25941                 break;
25942             
25943             default:
25944                 return false;
25945         }
25946
25947     },
25948     // private
25949     IsLongEnough: function (pwd, size)
25950     {
25951         return !(pwd == null || isNaN(size) || pwd.length < size);
25952     },
25953     // private
25954     SpansEnoughCharacterSets: function (word, nb)
25955     {
25956         if (!this.IsLongEnough(word, nb))
25957         {
25958             return false;
25959         }
25960
25961         var characterSetChecks = new Array(
25962             new this.CharacterSetChecks(this.kCapitalLetter), new this.CharacterSetChecks(this.kSmallLetter),
25963             new this.CharacterSetChecks(this.kDigit), new this.CharacterSetChecks(this.kPunctuation)
25964         );
25965         
25966         for (var index = 0; index < word.length; ++index) {
25967             for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
25968                 if (!characterSetChecks[nCharSet].fResult && this.isctype(word.charAt(index), characterSetChecks[nCharSet].type)) {
25969                     characterSetChecks[nCharSet].fResult = true;
25970                     break;
25971                 }
25972             }
25973         }
25974
25975         var nCharSets = 0;
25976         for (var nCharSet = 0; nCharSet < characterSetChecks.length; ++nCharSet) {
25977             if (characterSetChecks[nCharSet].fResult) {
25978                 ++nCharSets;
25979             }
25980         }
25981
25982         if (nCharSets < nb) {
25983             return false;
25984         }
25985         return true;
25986     },
25987     // private
25988     ClientSideStrongPassword: function (pwd)
25989     {
25990         return this.IsLongEnough(pwd, 8) && this.SpansEnoughCharacterSets(pwd, 3);
25991     },
25992     // private
25993     ClientSideMediumPassword: function (pwd)
25994     {
25995         return this.IsLongEnough(pwd, 7) && this.SpansEnoughCharacterSets(pwd, 2);
25996     },
25997     // private
25998     ClientSideWeakPassword: function (pwd)
25999     {
26000         return this.IsLongEnough(pwd, 6) || !this.IsLongEnough(pwd, 0);
26001     }
26002           
26003 });Roo.rtf = {}; // namespace
26004 Roo.rtf.Hex = function(hex)
26005 {
26006     this.hexstr = hex;
26007 };
26008 Roo.rtf.Paragraph = function(opts)
26009 {
26010     this.content = []; ///??? is that used?
26011 };Roo.rtf.Span = function(opts)
26012 {
26013     this.value = opts.value;
26014 };
26015
26016 Roo.rtf.Group = function(parent)
26017 {
26018     // we dont want to acutally store parent - it will make debug a nightmare..
26019     this.content = [];
26020     this.cn  = [];
26021      
26022        
26023     
26024 };
26025
26026 Roo.rtf.Group.prototype = {
26027     ignorable : false,
26028     content: false,
26029     cn: false,
26030     addContent : function(node) {
26031         // could set styles...
26032         this.content.push(node);
26033     },
26034     addChild : function(cn)
26035     {
26036         this.cn.push(cn);
26037     },
26038     // only for images really...
26039     toDataURL : function()
26040     {
26041         var mimetype = false;
26042         switch(true) {
26043             case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0: 
26044                 mimetype = "image/png";
26045                 break;
26046              case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
26047                 mimetype = "image/jpeg";
26048                 break;
26049             default :
26050                 return 'about:blank'; // ?? error?
26051         }
26052         
26053         
26054         var hexstring = this.content[this.content.length-1].value;
26055         
26056         return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
26057             return String.fromCharCode(parseInt(a, 16));
26058         }).join(""));
26059     }
26060     
26061 };
26062 // this looks like it's normally the {rtf{ .... }}
26063 Roo.rtf.Document = function()
26064 {
26065     // we dont want to acutally store parent - it will make debug a nightmare..
26066     this.rtlch  = [];
26067     this.content = [];
26068     this.cn = [];
26069     
26070 };
26071 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, { 
26072     addChild : function(cn)
26073     {
26074         this.cn.push(cn);
26075         switch(cn.type) {
26076             case 'rtlch': // most content seems to be inside this??
26077             case 'listtext':
26078             case 'shpinst':
26079                 this.rtlch.push(cn);
26080                 return;
26081             default:
26082                 this[cn.type] = cn;
26083         }
26084         
26085     },
26086     
26087     getElementsByType : function(type)
26088     {
26089         var ret =  [];
26090         this._getElementsByType(type, ret, this.cn, 'rtf');
26091         return ret;
26092     },
26093     _getElementsByType : function (type, ret, search_array, path)
26094     {
26095         search_array.forEach(function(n,i) {
26096             if (n.type == type) {
26097                 n.path = path + '/' + n.type + ':' + i;
26098                 ret.push(n);
26099             }
26100             if (n.cn.length > 0) {
26101                 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
26102             }
26103         },this);
26104     }
26105     
26106 });
26107  
26108 Roo.rtf.Ctrl = function(opts)
26109 {
26110     this.value = opts.value;
26111     this.param = opts.param;
26112 };
26113 /**
26114  *
26115  *
26116  * based on this https://github.com/iarna/rtf-parser
26117  * it's really only designed to extract pict from pasted RTF 
26118  *
26119  * usage:
26120  *
26121  *  var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
26122  *  
26123  *
26124  */
26125
26126  
26127
26128
26129
26130 Roo.rtf.Parser = function(text) {
26131     //super({objectMode: true})
26132     this.text = '';
26133     this.parserState = this.parseText;
26134     
26135     // these are for interpeter...
26136     this.doc = {};
26137     ///this.parserState = this.parseTop
26138     this.groupStack = [];
26139     this.hexStore = [];
26140     this.doc = false;
26141     
26142     this.groups = []; // where we put the return.
26143     
26144     for (var ii = 0; ii < text.length; ++ii) {
26145         ++this.cpos;
26146         
26147         if (text[ii] === '\n') {
26148             ++this.row;
26149             this.col = 1;
26150         } else {
26151             ++this.col;
26152         }
26153         this.parserState(text[ii]);
26154     }
26155     
26156     
26157     
26158 };
26159 Roo.rtf.Parser.prototype = {
26160     text : '', // string being parsed..
26161     controlWord : '',
26162     controlWordParam :  '',
26163     hexChar : '',
26164     doc : false,
26165     group: false,
26166     groupStack : false,
26167     hexStore : false,
26168     
26169     
26170     cpos : 0, 
26171     row : 1, // reportin?
26172     col : 1, //
26173
26174      
26175     push : function (el)
26176     {
26177         var m = 'cmd'+ el.type;
26178         if (typeof(this[m]) == 'undefined') {
26179             Roo.log('invalid cmd:' + el.type);
26180             return;
26181         }
26182         this[m](el);
26183         //Roo.log(el);
26184     },
26185     flushHexStore : function()
26186     {
26187         if (this.hexStore.length < 1) {
26188             return;
26189         }
26190         var hexstr = this.hexStore.map(
26191             function(cmd) {
26192                 return cmd.value;
26193         }).join('');
26194         
26195         this.group.addContent( new Roo.rtf.Hex( hexstr ));
26196               
26197             
26198         this.hexStore.splice(0)
26199         
26200     },
26201     
26202     cmdgroupstart : function()
26203     {
26204         this.flushHexStore();
26205         if (this.group) {
26206             this.groupStack.push(this.group);
26207         }
26208          // parent..
26209         if (this.doc === false) {
26210             this.group = this.doc = new Roo.rtf.Document();
26211             return;
26212             
26213         }
26214         this.group = new Roo.rtf.Group(this.group);
26215     },
26216     cmdignorable : function()
26217     {
26218         this.flushHexStore();
26219         this.group.ignorable = true;
26220     },
26221     cmdendparagraph : function()
26222     {
26223         this.flushHexStore();
26224         this.group.addContent(new Roo.rtf.Paragraph());
26225     },
26226     cmdgroupend : function ()
26227     {
26228         this.flushHexStore();
26229         var endingGroup = this.group;
26230         
26231         
26232         this.group = this.groupStack.pop();
26233         if (this.group) {
26234             this.group.addChild(endingGroup);
26235         }
26236         
26237         
26238         
26239         var doc = this.group || this.doc;
26240         //if (endingGroup instanceof FontTable) {
26241         //  doc.fonts = endingGroup.table
26242         //} else if (endingGroup instanceof ColorTable) {
26243         //  doc.colors = endingGroup.table
26244         //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
26245         if (endingGroup.ignorable === false) {
26246             //code
26247             this.groups.push(endingGroup);
26248            // Roo.log( endingGroup );
26249         }
26250             //Roo.each(endingGroup.content, function(item)) {
26251             //    doc.addContent(item);
26252             //}
26253             //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
26254         //}
26255     },
26256     cmdtext : function (cmd)
26257     {
26258         this.flushHexStore();
26259         if (!this.group) { // an RTF fragment, missing the {\rtf1 header
26260             //this.group = this.doc
26261             return;  // we really don't care about stray text...
26262         }
26263         this.group.addContent(new Roo.rtf.Span(cmd));
26264     },
26265     cmdcontrolword : function (cmd)
26266     {
26267         this.flushHexStore();
26268         if (!this.group.type) {
26269             this.group.type = cmd.value;
26270             return;
26271         }
26272         this.group.addContent(new Roo.rtf.Ctrl(cmd));
26273         // we actually don't care about ctrl words...
26274         return ;
26275         /*
26276         var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
26277         if (this[method]) {
26278             this[method](cmd.param)
26279         } else {
26280             if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
26281         }
26282         */
26283     },
26284     cmdhexchar : function(cmd) {
26285         this.hexStore.push(cmd);
26286     },
26287     cmderror : function(cmd) {
26288         throw cmd.value;
26289     },
26290     
26291     /*
26292       _flush (done) {
26293         if (this.text !== '\u0000') this.emitText()
26294         done()
26295       }
26296       */
26297       
26298       
26299     parseText : function(c)
26300     {
26301         if (c === '\\') {
26302             this.parserState = this.parseEscapes;
26303         } else if (c === '{') {
26304             this.emitStartGroup();
26305         } else if (c === '}') {
26306             this.emitEndGroup();
26307         } else if (c === '\x0A' || c === '\x0D') {
26308             // cr/lf are noise chars
26309         } else {
26310             this.text += c;
26311         }
26312     },
26313     
26314     parseEscapes: function (c)
26315     {
26316         if (c === '\\' || c === '{' || c === '}') {
26317             this.text += c;
26318             this.parserState = this.parseText;
26319         } else {
26320             this.parserState = this.parseControlSymbol;
26321             this.parseControlSymbol(c);
26322         }
26323     },
26324     parseControlSymbol: function(c)
26325     {
26326         if (c === '~') {
26327             this.text += '\u00a0'; // nbsp
26328             this.parserState = this.parseText
26329         } else if (c === '-') {
26330              this.text += '\u00ad'; // soft hyphen
26331         } else if (c === '_') {
26332             this.text += '\u2011'; // non-breaking hyphen
26333         } else if (c === '*') {
26334             this.emitIgnorable();
26335             this.parserState = this.parseText;
26336         } else if (c === "'") {
26337             this.parserState = this.parseHexChar;
26338         } else if (c === '|') { // formula cacter
26339             this.emitFormula();
26340             this.parserState = this.parseText;
26341         } else if (c === ':') { // subentry in an index entry
26342             this.emitIndexSubEntry();
26343             this.parserState = this.parseText;
26344         } else if (c === '\x0a') {
26345             this.emitEndParagraph();
26346             this.parserState = this.parseText;
26347         } else if (c === '\x0d') {
26348             this.emitEndParagraph();
26349             this.parserState = this.parseText;
26350         } else {
26351             this.parserState = this.parseControlWord;
26352             this.parseControlWord(c);
26353         }
26354     },
26355     parseHexChar: function (c)
26356     {
26357         if (/^[A-Fa-f0-9]$/.test(c)) {
26358             this.hexChar += c;
26359             if (this.hexChar.length >= 2) {
26360               this.emitHexChar();
26361               this.parserState = this.parseText;
26362             }
26363             return;
26364         }
26365         this.emitError("Invalid character \"" + c + "\" in hex literal.");
26366         this.parserState = this.parseText;
26367         
26368     },
26369     parseControlWord : function(c)
26370     {
26371         if (c === ' ') {
26372             this.emitControlWord();
26373             this.parserState = this.parseText;
26374         } else if (/^[-\d]$/.test(c)) {
26375             this.parserState = this.parseControlWordParam;
26376             this.controlWordParam += c;
26377         } else if (/^[A-Za-z]$/.test(c)) {
26378           this.controlWord += c;
26379         } else {
26380           this.emitControlWord();
26381           this.parserState = this.parseText;
26382           this.parseText(c);
26383         }
26384     },
26385     parseControlWordParam : function (c) {
26386         if (/^\d$/.test(c)) {
26387           this.controlWordParam += c;
26388         } else if (c === ' ') {
26389           this.emitControlWord();
26390           this.parserState = this.parseText;
26391         } else {
26392           this.emitControlWord();
26393           this.parserState = this.parseText;
26394           this.parseText(c);
26395         }
26396     },
26397     
26398     
26399     
26400     
26401     emitText : function () {
26402         if (this.text === '') {
26403             return;
26404         }
26405         this.push({
26406             type: 'text',
26407             value: this.text,
26408             pos: this.cpos,
26409             row: this.row,
26410             col: this.col
26411         });
26412         this.text = ''
26413     },
26414     emitControlWord : function ()
26415     {
26416         this.emitText();
26417         if (this.controlWord === '') {
26418             // do we want to track this - it seems just to cause problems.
26419             //this.emitError('empty control word');
26420         } else {
26421             this.push({
26422                   type: 'controlword',
26423                   value: this.controlWord,
26424                   param: this.controlWordParam !== '' && Number(this.controlWordParam),
26425                   pos: this.cpos,
26426                   row: this.row,
26427                   col: this.col
26428             });
26429         }
26430         this.controlWord = '';
26431         this.controlWordParam = '';
26432     },
26433     emitStartGroup : function ()
26434     {
26435         this.emitText();
26436         this.push({
26437             type: 'groupstart',
26438             pos: this.cpos,
26439             row: this.row,
26440             col: this.col
26441         });
26442     },
26443     emitEndGroup : function ()
26444     {
26445         this.emitText();
26446         this.push({
26447             type: 'groupend',
26448             pos: this.cpos,
26449             row: this.row,
26450             col: this.col
26451         });
26452     },
26453     emitIgnorable : function ()
26454     {
26455         this.emitText();
26456         this.push({
26457             type: 'ignorable',
26458             pos: this.cpos,
26459             row: this.row,
26460             col: this.col
26461         });
26462     },
26463     emitHexChar : function ()
26464     {
26465         this.emitText();
26466         this.push({
26467             type: 'hexchar',
26468             value: this.hexChar,
26469             pos: this.cpos,
26470             row: this.row,
26471             col: this.col
26472         });
26473         this.hexChar = ''
26474     },
26475     emitError : function (message)
26476     {
26477       this.emitText();
26478       this.push({
26479             type: 'error',
26480             value: message,
26481             row: this.row,
26482             col: this.col,
26483             char: this.cpos //,
26484             //stack: new Error().stack
26485         });
26486     },
26487     emitEndParagraph : function () {
26488         this.emitText();
26489         this.push({
26490             type: 'endparagraph',
26491             pos: this.cpos,
26492             row: this.row,
26493             col: this.col
26494         });
26495     }
26496      
26497 } ; 
26498 /**
26499  * @class Roo.htmleditor.Filter
26500  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
26501  * @cfg {DomElement} node The node to iterate and filter
26502  * @cfg {boolean|String|Array} tag Tags to replace 
26503  * @constructor
26504  * Create a new Filter.
26505  * @param {Object} config Configuration options
26506  */
26507
26508
26509
26510 Roo.htmleditor.Filter = function(cfg) {
26511     Roo.apply(this.cfg);
26512     // this does not actually call walk as it's really just a abstract class
26513 }
26514
26515
26516 Roo.htmleditor.Filter.prototype = {
26517     
26518     node: false,
26519     
26520     tag: false,
26521
26522     // overrride to do replace comments.
26523     replaceComment : false,
26524     
26525     // overrride to do replace or do stuff with tags..
26526     replaceTag : false,
26527     
26528     walk : function(dom)
26529     {
26530         Roo.each( Array.from(dom.childNodes), function( e ) {
26531             switch(true) {
26532                 
26533                 case e.nodeType == 8 &&  this.replaceComment  !== false: // comment
26534                     this.replaceComment(e);
26535                     return;
26536                 
26537                 case e.nodeType != 1: //not a node.
26538                     return;
26539                 
26540                 case this.tag === true: // everything
26541                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1:
26542                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":":
26543                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
26544                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
26545                     if (this.replaceTag && false === this.replaceTag(e)) {
26546                         return;
26547                     }
26548                     if (e.hasChildNodes()) {
26549                         this.walk(e);
26550                     }
26551                     return;
26552                 
26553                 default:    // tags .. that do not match.
26554                     if (e.hasChildNodes()) {
26555                         this.walk(e);
26556                     }
26557             }
26558             
26559         }, this);
26560         
26561     },
26562     
26563     
26564     removeNodeKeepChildren : function( node)
26565     {
26566     
26567         ar = Array.from(node.childNodes);
26568         for (var i = 0; i < ar.length; i++) {
26569          
26570             node.removeChild(ar[i]);
26571             // what if we need to walk these???
26572             node.parentNode.insertBefore(ar[i], node);
26573            
26574         }
26575         node.parentNode.removeChild(node);
26576     }
26577 }; 
26578
26579 /**
26580  * @class Roo.htmleditor.FilterAttributes
26581  * clean attributes and  styles including http:// etc.. in attribute
26582  * @constructor
26583 * Run a new Attribute Filter
26584 * @param {Object} config Configuration options
26585  */
26586 Roo.htmleditor.FilterAttributes = function(cfg)
26587 {
26588     Roo.apply(this, cfg);
26589     this.attrib_black = this.attrib_black || [];
26590     this.attrib_white = this.attrib_white || [];
26591
26592     this.attrib_clean = this.attrib_clean || [];
26593     this.style_white = this.style_white || [];
26594     this.style_black = this.style_black || [];
26595     this.walk(cfg.node);
26596 }
26597
26598 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
26599 {
26600     tag: true, // all tags
26601     
26602     attrib_black : false, // array
26603     attrib_clean : false,
26604     attrib_white : false,
26605
26606     style_white : false,
26607     style_black : false,
26608      
26609      
26610     replaceTag : function(node)
26611     {
26612         if (!node.attributes || !node.attributes.length) {
26613             return true;
26614         }
26615         
26616         for (var i = node.attributes.length-1; i > -1 ; i--) {
26617             var a = node.attributes[i];
26618             //console.log(a);
26619             if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
26620                 node.removeAttribute(a.name);
26621                 continue;
26622             }
26623             
26624             
26625             
26626             if (a.name.toLowerCase().substr(0,2)=='on')  {
26627                 node.removeAttribute(a.name);
26628                 continue;
26629             }
26630             
26631             
26632             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
26633                 node.removeAttribute(a.name);
26634                 continue;
26635             }
26636             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
26637                 this.cleanAttr(node,a.name,a.value); // fixme..
26638                 continue;
26639             }
26640             if (a.name == 'style') {
26641                 this.cleanStyle(node,a.name,a.value);
26642                 continue;
26643             }
26644             /// clean up MS crap..
26645             // tecnically this should be a list of valid class'es..
26646             
26647             
26648             if (a.name == 'class') {
26649                 if (a.value.match(/^Mso/)) {
26650                     node.removeAttribute('class');
26651                 }
26652                 
26653                 if (a.value.match(/^body$/)) {
26654                     node.removeAttribute('class');
26655                 }
26656                 continue;
26657             }
26658             
26659             
26660             // style cleanup!?
26661             // class cleanup?
26662             
26663         }
26664         return true; // clean children
26665     },
26666         
26667     cleanAttr: function(node, n,v)
26668     {
26669         
26670         if (v.match(/^\./) || v.match(/^\//)) {
26671             return;
26672         }
26673         if (v.match(/^(http|https):\/\//)
26674             || v.match(/^mailto:/) 
26675             || v.match(/^ftp:/)
26676             || v.match(/^data:/)
26677             ) {
26678             return;
26679         }
26680         if (v.match(/^#/)) {
26681             return;
26682         }
26683         if (v.match(/^\{/)) { // allow template editing.
26684             return;
26685         }
26686 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
26687         node.removeAttribute(n);
26688         
26689     },
26690     cleanStyle : function(node,  n,v)
26691     {
26692         if (v.match(/expression/)) { //XSS?? should we even bother..
26693             node.removeAttribute(n);
26694             return;
26695         }
26696         
26697         var parts = v.split(/;/);
26698         var clean = [];
26699         
26700         Roo.each(parts, function(p) {
26701             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
26702             if (!p.length) {
26703                 return true;
26704             }
26705             var l = p.split(':').shift().replace(/\s+/g,'');
26706             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
26707             
26708             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
26709                 return true;
26710             }
26711             //Roo.log()
26712             // only allow 'c whitelisted system attributes'
26713             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
26714                 return true;
26715             }
26716             
26717             
26718             clean.push(p);
26719             return true;
26720         },this);
26721         if (clean.length) { 
26722             node.setAttribute(n, clean.join(';'));
26723         } else {
26724             node.removeAttribute(n);
26725         }
26726         
26727     }
26728         
26729         
26730         
26731     
26732 });/**
26733  * @class Roo.htmleditor.FilterBlack
26734  * remove blacklisted elements.
26735  * @constructor
26736  * Run a new Blacklisted Filter
26737  * @param {Object} config Configuration options
26738  */
26739
26740 Roo.htmleditor.FilterBlack = function(cfg)
26741 {
26742     Roo.apply(this, cfg);
26743     this.walk(cfg.node);
26744 }
26745
26746 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
26747 {
26748     tag : true, // all elements.
26749    
26750     replaceTag : function(n)
26751     {
26752         n.parentNode.removeChild(n);
26753     }
26754 });
26755 /**
26756  * @class Roo.htmleditor.FilterComment
26757  * remove comments.
26758  * @constructor
26759 * Run a new Comments Filter
26760 * @param {Object} config Configuration options
26761  */
26762 Roo.htmleditor.FilterComment = function(cfg)
26763 {
26764     this.walk(cfg.node);
26765 }
26766
26767 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
26768 {
26769   
26770     replaceComment : function(n)
26771     {
26772         n.parentNode.removeChild(n);
26773     }
26774 });/**
26775  * @class Roo.htmleditor.FilterKeepChildren
26776  * remove tags but keep children
26777  * @constructor
26778  * Run a new Keep Children Filter
26779  * @param {Object} config Configuration options
26780  */
26781
26782 Roo.htmleditor.FilterKeepChildren = function(cfg)
26783 {
26784     Roo.apply(this, cfg);
26785     if (this.tag === false) {
26786         return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
26787     }
26788     // hacky?
26789     if ((typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)) {
26790         this.cleanNamespace = true;
26791     }
26792         
26793     this.walk(cfg.node);
26794 }
26795
26796 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
26797 {
26798     cleanNamespace : false, // should really be an option, rather than using ':' inside of this tag.
26799   
26800     replaceTag : function(node)
26801     {
26802         // walk children...
26803         //Roo.log(node.tagName);
26804         var ar = Array.from(node.childNodes);
26805         //remove first..
26806         
26807         for (var i = 0; i < ar.length; i++) {
26808             var e = ar[i];
26809             if (e.nodeType == 1) {
26810                 if (
26811                     (typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1)
26812                     || // array and it matches
26813                     (typeof(this.tag) == 'string' && this.tag == e.tagName)
26814                     ||
26815                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)
26816                     ||
26817                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":")
26818                 ) {
26819                     this.replaceTag(ar[i]); // child is blacklisted as well...
26820                     continue;
26821                 }
26822             }
26823         }  
26824         ar = Array.from(node.childNodes);
26825         for (var i = 0; i < ar.length; i++) {
26826          
26827             node.removeChild(ar[i]);
26828             // what if we need to walk these???
26829             node.parentNode.insertBefore(ar[i], node);
26830             if (this.tag !== false) {
26831                 this.walk(ar[i]);
26832                 
26833             }
26834         }
26835         //Roo.log("REMOVE:" + node.tagName);
26836         node.parentNode.removeChild(node);
26837         return false; // don't walk children
26838         
26839         
26840     }
26841 });/**
26842  * @class Roo.htmleditor.FilterParagraph
26843  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
26844  * like on 'push' to remove the <p> tags and replace them with line breaks.
26845  * @constructor
26846  * Run a new Paragraph Filter
26847  * @param {Object} config Configuration options
26848  */
26849
26850 Roo.htmleditor.FilterParagraph = function(cfg)
26851 {
26852     // no need to apply config.
26853     this.walk(cfg.node);
26854 }
26855
26856 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
26857 {
26858     
26859      
26860     tag : 'P',
26861     
26862      
26863     replaceTag : function(node)
26864     {
26865         
26866         if (node.childNodes.length == 1 &&
26867             node.childNodes[0].nodeType == 3 &&
26868             node.childNodes[0].textContent.trim().length < 1
26869             ) {
26870             // remove and replace with '<BR>';
26871             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
26872             return false; // no need to walk..
26873         }
26874         var ar = Array.from(node.childNodes);
26875         for (var i = 0; i < ar.length; i++) {
26876             node.removeChild(ar[i]);
26877             // what if we need to walk these???
26878             node.parentNode.insertBefore(ar[i], node);
26879         }
26880         // now what about this?
26881         // <p> &nbsp; </p>
26882         
26883         // double BR.
26884         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
26885         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
26886         node.parentNode.removeChild(node);
26887         
26888         return false;
26889
26890     }
26891     
26892 });/**
26893  * @class Roo.htmleditor.FilterSpan
26894  * filter span's with no attributes out..
26895  * @constructor
26896  * Run a new Span Filter
26897  * @param {Object} config Configuration options
26898  */
26899
26900 Roo.htmleditor.FilterSpan = function(cfg)
26901 {
26902     // no need to apply config.
26903     this.walk(cfg.node);
26904 }
26905
26906 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
26907 {
26908      
26909     tag : 'SPAN',
26910      
26911  
26912     replaceTag : function(node)
26913     {
26914         if (node.attributes && node.attributes.length > 0) {
26915             return true; // walk if there are any.
26916         }
26917         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
26918         return false;
26919      
26920     }
26921     
26922 });/**
26923  * @class Roo.htmleditor.FilterTableWidth
26924   try and remove table width data - as that frequently messes up other stuff.
26925  * 
26926  *      was cleanTableWidths.
26927  *
26928  * Quite often pasting from word etc.. results in tables with column and widths.
26929  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
26930  *
26931  * @constructor
26932  * Run a new Table Filter
26933  * @param {Object} config Configuration options
26934  */
26935
26936 Roo.htmleditor.FilterTableWidth = function(cfg)
26937 {
26938     // no need to apply config.
26939     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
26940     this.walk(cfg.node);
26941 }
26942
26943 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
26944 {
26945      
26946      
26947     
26948     replaceTag: function(node) {
26949         
26950         
26951       
26952         if (node.hasAttribute('width')) {
26953             node.removeAttribute('width');
26954         }
26955         
26956          
26957         if (node.hasAttribute("style")) {
26958             // pretty basic...
26959             
26960             var styles = node.getAttribute("style").split(";");
26961             var nstyle = [];
26962             Roo.each(styles, function(s) {
26963                 if (!s.match(/:/)) {
26964                     return;
26965                 }
26966                 var kv = s.split(":");
26967                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
26968                     return;
26969                 }
26970                 // what ever is left... we allow.
26971                 nstyle.push(s);
26972             });
26973             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
26974             if (!nstyle.length) {
26975                 node.removeAttribute('style');
26976             }
26977         }
26978         
26979         return true; // continue doing children..
26980     }
26981 });/**
26982  * @class Roo.htmleditor.FilterWord
26983  * try and clean up all the mess that Word generates.
26984  * 
26985  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
26986  
26987  * @constructor
26988  * Run a new Span Filter
26989  * @param {Object} config Configuration options
26990  */
26991
26992 Roo.htmleditor.FilterWord = function(cfg)
26993 {
26994     // no need to apply config.
26995     this.replaceDocBullets(cfg.node);
26996     
26997     this.replaceAname(cfg.node);
26998     // this is disabled as the removal is done by other filters;
26999    // this.walk(cfg.node);
27000     this.replaceImageTable(cfg.node);
27001     
27002 }
27003
27004 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
27005 {
27006     tag: true,
27007      
27008     
27009     /**
27010      * Clean up MS wordisms...
27011      */
27012     replaceTag : function(node)
27013     {
27014          
27015         // no idea what this does - span with text, replaceds with just text.
27016         if(
27017                 node.nodeName == 'SPAN' &&
27018                 !node.hasAttributes() &&
27019                 node.childNodes.length == 1 &&
27020                 node.firstChild.nodeName == "#text"  
27021         ) {
27022             var textNode = node.firstChild;
27023             node.removeChild(textNode);
27024             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
27025                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
27026             }
27027             node.parentNode.insertBefore(textNode, node);
27028             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
27029                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
27030             }
27031             
27032             node.parentNode.removeChild(node);
27033             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
27034         }
27035         
27036    
27037         
27038         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
27039             node.parentNode.removeChild(node);
27040             return false; // dont do chidlren
27041         }
27042         //Roo.log(node.tagName);
27043         // remove - but keep children..
27044         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
27045             //Roo.log('-- removed');
27046             while (node.childNodes.length) {
27047                 var cn = node.childNodes[0];
27048                 node.removeChild(cn);
27049                 node.parentNode.insertBefore(cn, node);
27050                 // move node to parent - and clean it..
27051                 if (cn.nodeType == 1) {
27052                     this.replaceTag(cn);
27053                 }
27054                 
27055             }
27056             node.parentNode.removeChild(node);
27057             /// no need to iterate chidlren = it's got none..
27058             //this.iterateChildren(node, this.cleanWord);
27059             return false; // no need to iterate children.
27060         }
27061         // clean styles
27062         if (node.className.length) {
27063             
27064             var cn = node.className.split(/\W+/);
27065             var cna = [];
27066             Roo.each(cn, function(cls) {
27067                 if (cls.match(/Mso[a-zA-Z]+/)) {
27068                     return;
27069                 }
27070                 cna.push(cls);
27071             });
27072             node.className = cna.length ? cna.join(' ') : '';
27073             if (!cna.length) {
27074                 node.removeAttribute("class");
27075             }
27076         }
27077         
27078         if (node.hasAttribute("lang")) {
27079             node.removeAttribute("lang");
27080         }
27081         
27082         if (node.hasAttribute("style")) {
27083             
27084             var styles = node.getAttribute("style").split(";");
27085             var nstyle = [];
27086             Roo.each(styles, function(s) {
27087                 if (!s.match(/:/)) {
27088                     return;
27089                 }
27090                 var kv = s.split(":");
27091                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
27092                     return;
27093                 }
27094                 // what ever is left... we allow.
27095                 nstyle.push(s);
27096             });
27097             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
27098             if (!nstyle.length) {
27099                 node.removeAttribute('style');
27100             }
27101         }
27102         return true; // do children
27103         
27104         
27105         
27106     },
27107     
27108     styleToObject: function(node)
27109     {
27110         var styles = (node.getAttribute("style") || '').split(";");
27111         var ret = {};
27112         Roo.each(styles, function(s) {
27113             if (!s.match(/:/)) {
27114                 return;
27115             }
27116             var kv = s.split(":");
27117              
27118             // what ever is left... we allow.
27119             ret[kv[0].trim()] = kv[1];
27120         });
27121         return ret;
27122     },
27123     
27124     
27125     replaceAname : function (doc)
27126     {
27127         // replace all the a/name without..
27128         var aa = Array.from(doc.getElementsByTagName('a'));
27129         for (var i = 0; i  < aa.length; i++) {
27130             var a = aa[i];
27131             if (a.hasAttribute("name")) {
27132                 a.removeAttribute("name");
27133             }
27134             if (a.hasAttribute("href")) {
27135                 continue;
27136             }
27137             // reparent children.
27138             this.removeNodeKeepChildren(a);
27139             
27140         }
27141         
27142         
27143         
27144     },
27145
27146     
27147     
27148     replaceDocBullets : function(doc)
27149     {
27150         // this is a bit odd - but it appears some indents use ql-indent-1
27151          //Roo.log(doc.innerHTML);
27152         
27153         var listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
27154         for( var i = 0; i < listpara.length; i ++) {
27155             listpara[i].className = "MsoListParagraph";
27156         }
27157         
27158         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
27159         for( var i = 0; i < listpara.length; i ++) {
27160             listpara[i].className = "MsoListParagraph";
27161         }
27162         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
27163         for( var i = 0; i < listpara.length; i ++) {
27164             listpara[i].className = "MsoListParagraph";
27165         }
27166         listpara =  Array.from(doc.getElementsByClassName('ql-indent-1'));
27167         for( var i = 0; i < listpara.length; i ++) {
27168             listpara[i].className = "MsoListParagraph";
27169         }
27170         
27171         // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
27172         var htwo =  Array.from(doc.getElementsByTagName('h2'));
27173         for( var i = 0; i < htwo.length; i ++) {
27174             if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
27175                 htwo[i].className = "MsoListParagraph";
27176             }
27177         }
27178         listpara =  Array.from(doc.getElementsByClassName('MsoNormal'));
27179         for( var i = 0; i < listpara.length; i ++) {
27180             if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
27181                 listpara[i].className = "MsoListParagraph";
27182             } else {
27183                 listpara[i].className = "MsoNormalx";
27184             }
27185         }
27186        
27187         listpara = doc.getElementsByClassName('MsoListParagraph');
27188         // Roo.log(doc.innerHTML);
27189         
27190         
27191         
27192         while(listpara.length) {
27193             
27194             this.replaceDocBullet(listpara.item(0));
27195         }
27196       
27197     },
27198     
27199      
27200     
27201     replaceDocBullet : function(p)
27202     {
27203         // gather all the siblings.
27204         var ns = p,
27205             parent = p.parentNode,
27206             doc = parent.ownerDocument,
27207             items = [];
27208          
27209         //Roo.log("Parsing: " + p.innerText)    ;
27210         var listtype = 'ul';   
27211         while (ns) {
27212             if (ns.nodeType != 1) {
27213                 ns = ns.nextSibling;
27214                 continue;
27215             }
27216             if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
27217                 //Roo.log("Missing para r q1indent - got:" + ns.className);
27218                 break;
27219             }
27220             var spans = ns.getElementsByTagName('span');
27221             
27222             if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
27223                 items.push(ns);
27224                 ns = ns.nextSibling;
27225                 has_list = true;
27226                 if (!spans.length) {
27227                     continue;
27228                 }
27229                 var ff = '';
27230                 var se = spans[0];
27231                 for (var i = 0; i < spans.length;i++) {
27232                     se = spans[i];
27233                     if (se.hasAttribute('style')  && se.hasAttribute('style') && se.style.fontFamily != '') {
27234                         ff = se.style.fontFamily;
27235                         break;
27236                     }
27237                 }
27238                  
27239                     
27240                 //Roo.log("got font family: " + ff);
27241                 if (typeof(ff) != 'undefined' && !ff.match(/(Symbol|Wingdings)/) && "·o".indexOf(se.innerText.trim()) < 0) {
27242                     listtype = 'ol';
27243                 }
27244                 
27245                 continue;
27246             }
27247             //Roo.log("no mso-list?");
27248             
27249             var spans = ns.getElementsByTagName('span');
27250             if (!spans.length) {
27251                 break;
27252             }
27253             var has_list  = false;
27254             for(var i = 0; i < spans.length; i++) {
27255                 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
27256                     has_list = true;
27257                     break;
27258                 }
27259             }
27260             if (!has_list) {
27261                 break;
27262             }
27263             items.push(ns);
27264             ns = ns.nextSibling;
27265             
27266             
27267         }
27268         if (!items.length) {
27269             ns.className = "";
27270             return;
27271         }
27272         
27273         var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
27274         parent.insertBefore(ul, p);
27275         var lvl = 0;
27276         var stack = [ ul ];
27277         var last_li = false;
27278         
27279         var margin_to_depth = {};
27280         max_margins = -1;
27281         
27282         items.forEach(function(n, ipos) {
27283             //Roo.log("got innertHMLT=" + n.innerHTML);
27284             
27285             var spans = n.getElementsByTagName('span');
27286             if (!spans.length) {
27287                 //Roo.log("No spans found");
27288                  
27289                 parent.removeChild(n);
27290                 
27291                 
27292                 return; // skip it...
27293             }
27294            
27295                 
27296             var num = 1;
27297             var style = {};
27298             for(var i = 0; i < spans.length; i++) {
27299             
27300                 style = this.styleToObject(spans[i]);
27301                 if (typeof(style['mso-list']) == 'undefined') {
27302                     continue;
27303                 }
27304                 if (listtype == 'ol') {
27305                    num = spans[i].innerText.replace(/[^0-9]+]/g,'')  * 1;
27306                 }
27307                 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
27308                 break;
27309             }
27310             //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
27311             style = this.styleToObject(n); // mo-list is from the parent node.
27312             if (typeof(style['mso-list']) == 'undefined') {
27313                 //Roo.log("parent is missing level");
27314                   
27315                 parent.removeChild(n);
27316                  
27317                 return;
27318             }
27319             
27320             var margin = style['margin-left'];
27321             if (typeof(margin_to_depth[margin]) == 'undefined') {
27322                 max_margins++;
27323                 margin_to_depth[margin] = max_margins;
27324             }
27325             nlvl = margin_to_depth[margin] ;
27326              
27327             if (nlvl > lvl) {
27328                 //new indent
27329                 var nul = doc.createElement(listtype); // what about number lists...
27330                 if (!last_li) {
27331                     last_li = doc.createElement('li');
27332                     stack[lvl].appendChild(last_li);
27333                 }
27334                 last_li.appendChild(nul);
27335                 stack[nlvl] = nul;
27336                 
27337             }
27338             lvl = nlvl;
27339             
27340             // not starting at 1..
27341             if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
27342                 stack[nlvl].setAttribute("start", num);
27343             }
27344             
27345             var nli = stack[nlvl].appendChild(doc.createElement('li'));
27346             last_li = nli;
27347             nli.innerHTML = n.innerHTML;
27348             //Roo.log("innerHTML = " + n.innerHTML);
27349             parent.removeChild(n);
27350             
27351              
27352              
27353             
27354         },this);
27355         
27356         
27357         
27358         
27359     },
27360     
27361     replaceImageTable : function(doc)
27362     {
27363          /*
27364           <table cellpadding=0 cellspacing=0 align=left>
27365   <tr>
27366    <td width=423 height=0></td>
27367   </tr>
27368   <tr>
27369    <td></td>
27370    <td><img width=601 height=401
27371    src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
27372    v:shapes="Picture_x0020_2"></td>
27373   </tr>
27374  </table>
27375  */
27376         var imgs = Array.from(doc.getElementsByTagName('img'));
27377         Roo.each(imgs, function(img) {
27378             var td = img.parentNode;
27379             if (td.nodeName !=  'TD') {
27380                 return;
27381             }
27382             var tr = td.parentNode;
27383             if (tr.nodeName !=  'TR') {
27384                 return;
27385             }
27386             var tbody = tr.parentNode;
27387             if (tbody.nodeName !=  'TBODY') {
27388                 return;
27389             }
27390             var table = tbody.parentNode;
27391             if (table.nodeName !=  'TABLE') {
27392                 return;
27393             }
27394             // first row..
27395             
27396             if (table.getElementsByTagName('tr').length != 2) {
27397                 return;
27398             }
27399             if (table.getElementsByTagName('td').length != 3) {
27400                 return;
27401             }
27402             if (table.innerText.trim() != '') {
27403                 return;
27404             }
27405             var p = table.parentNode;
27406             img.parentNode.removeChild(img);
27407             p.insertBefore(img, table);
27408             p.removeChild(table);
27409             
27410             
27411             
27412         });
27413         
27414       
27415     }
27416     
27417 });
27418 /**
27419  * @class Roo.htmleditor.FilterStyleToTag
27420  * part of the word stuff... - certain 'styles' should be converted to tags.
27421  * eg.
27422  *   font-weight: bold -> bold
27423  *   ?? super / subscrit etc..
27424  * 
27425  * @constructor
27426 * Run a new style to tag filter.
27427 * @param {Object} config Configuration options
27428  */
27429 Roo.htmleditor.FilterStyleToTag = function(cfg)
27430 {
27431     
27432     this.tags = {
27433         B  : [ 'fontWeight' , 'bold'],
27434         I :  [ 'fontStyle' , 'italic'],
27435         //pre :  [ 'font-style' , 'italic'],
27436         // h1.. h6 ?? font-size?
27437         SUP : [ 'verticalAlign' , 'super' ],
27438         SUB : [ 'verticalAlign' , 'sub' ]
27439         
27440         
27441     };
27442     
27443     Roo.apply(this, cfg);
27444      
27445     
27446     this.walk(cfg.node);
27447     
27448     
27449     
27450 }
27451
27452
27453 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
27454 {
27455     tag: true, // all tags
27456     
27457     tags : false,
27458     
27459     
27460     replaceTag : function(node)
27461     {
27462         
27463         
27464         if (node.getAttribute("style") === null) {
27465             return true;
27466         }
27467         var inject = [];
27468         for (var k in this.tags) {
27469             if (node.style[this.tags[k][0]] == this.tags[k][1]) {
27470                 inject.push(k);
27471                 node.style.removeProperty(this.tags[k][0]);
27472             }
27473         }
27474         if (!inject.length) {
27475             return true; 
27476         }
27477         var cn = Array.from(node.childNodes);
27478         var nn = node;
27479         Roo.each(inject, function(t) {
27480             var nc = node.ownerDocument.createElement(t);
27481             nn.appendChild(nc);
27482             nn = nc;
27483         });
27484         for(var i = 0;i < cn.length;cn++) {
27485             node.removeChild(cn[i]);
27486             nn.appendChild(cn[i]);
27487         }
27488         return true /// iterate thru
27489     }
27490     
27491 })/**
27492  * @class Roo.htmleditor.FilterLongBr
27493  * BR/BR/BR - keep a maximum of 2...
27494  * @constructor
27495  * Run a new Long BR Filter
27496  * @param {Object} config Configuration options
27497  */
27498
27499 Roo.htmleditor.FilterLongBr = function(cfg)
27500 {
27501     // no need to apply config.
27502     this.walk(cfg.node);
27503 }
27504
27505 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
27506 {
27507     
27508      
27509     tag : 'BR',
27510     
27511      
27512     replaceTag : function(node)
27513     {
27514         
27515         var ps = node.nextSibling;
27516         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
27517             ps = ps.nextSibling;
27518         }
27519         
27520         if (!ps &&  [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) { 
27521             node.parentNode.removeChild(node); // remove last BR inside one fo these tags
27522             return false;
27523         }
27524         
27525         if (!ps || ps.nodeType != 1) {
27526             return false;
27527         }
27528         
27529         if (!ps || ps.tagName != 'BR') {
27530            
27531             return false;
27532         }
27533         
27534         
27535         
27536         
27537         
27538         if (!node.previousSibling) {
27539             return false;
27540         }
27541         var ps = node.previousSibling;
27542         
27543         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
27544             ps = ps.previousSibling;
27545         }
27546         if (!ps || ps.nodeType != 1) {
27547             return false;
27548         }
27549         // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
27550         if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
27551             return false;
27552         }
27553         
27554         node.parentNode.removeChild(node); // remove me...
27555         
27556         return false; // no need to do children
27557
27558     }
27559     
27560 }); 
27561
27562 /**
27563  * @class Roo.htmleditor.FilterBlock
27564  * removes id / data-block and contenteditable that are associated with blocks
27565  * usage should be done on a cloned copy of the dom
27566  * @constructor
27567 * Run a new Attribute Filter { node : xxxx }}
27568 * @param {Object} config Configuration options
27569  */
27570 Roo.htmleditor.FilterBlock = function(cfg)
27571 {
27572     Roo.apply(this, cfg);
27573     var qa = cfg.node.querySelectorAll;
27574     this.removeAttributes('data-block');
27575     this.removeAttributes('contenteditable');
27576     this.removeAttributes('id');
27577     
27578 }
27579
27580 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
27581 {
27582     node: true, // all tags
27583      
27584      
27585     removeAttributes : function(attr)
27586     {
27587         var ar = this.node.querySelectorAll('*[' + attr + ']');
27588         for (var i =0;i<ar.length;i++) {
27589             ar[i].removeAttribute(attr);
27590         }
27591     }
27592         
27593         
27594         
27595     
27596 });
27597 /***
27598  * This is based loosely on tinymce 
27599  * @class Roo.htmleditor.TidySerializer
27600  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
27601  * @constructor
27602  * @method Serializer
27603  * @param {Object} settings Name/value settings object.
27604  */
27605
27606
27607 Roo.htmleditor.TidySerializer = function(settings)
27608 {
27609     Roo.apply(this, settings);
27610     
27611     this.writer = new Roo.htmleditor.TidyWriter(settings);
27612     
27613     
27614
27615 };
27616 Roo.htmleditor.TidySerializer.prototype = {
27617     
27618     /**
27619      * @param {boolean} inner do the inner of the node.
27620      */
27621     inner : false,
27622     
27623     writer : false,
27624     
27625     /**
27626     * Serializes the specified node into a string.
27627     *
27628     * @example
27629     * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
27630     * @method serialize
27631     * @param {DomElement} node Node instance to serialize.
27632     * @return {String} String with HTML based on DOM tree.
27633     */
27634     serialize : function(node) {
27635         
27636         // = settings.validate;
27637         var writer = this.writer;
27638         var self  = this;
27639         this.handlers = {
27640             // #text
27641             3: function(node) {
27642                 
27643                 writer.text(node.nodeValue, node);
27644             },
27645             // #comment
27646             8: function(node) {
27647                 writer.comment(node.nodeValue);
27648             },
27649             // Processing instruction
27650             7: function(node) {
27651                 writer.pi(node.name, node.nodeValue);
27652             },
27653             // Doctype
27654             10: function(node) {
27655                 writer.doctype(node.nodeValue);
27656             },
27657             // CDATA
27658             4: function(node) {
27659                 writer.cdata(node.nodeValue);
27660             },
27661             // Document fragment
27662             11: function(node) {
27663                 node = node.firstChild;
27664                 if (!node) {
27665                     return;
27666                 }
27667                 while(node) {
27668                     self.walk(node);
27669                     node = node.nextSibling
27670                 }
27671             }
27672         };
27673         writer.reset();
27674         1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
27675         return writer.getContent();
27676     },
27677
27678     walk: function(node)
27679     {
27680         var attrName, attrValue, sortedAttrs, i, l, elementRule,
27681             handler = this.handlers[node.nodeType];
27682             
27683         if (handler) {
27684             handler(node);
27685             return;
27686         }
27687     
27688         var name = node.nodeName;
27689         var isEmpty = node.childNodes.length < 1;
27690       
27691         var writer = this.writer;
27692         var attrs = node.attributes;
27693         // Sort attributes
27694         
27695         writer.start(node.nodeName, attrs, isEmpty, node);
27696         if (isEmpty) {
27697             return;
27698         }
27699         node = node.firstChild;
27700         if (!node) {
27701             writer.end(name);
27702             return;
27703         }
27704         while (node) {
27705             this.walk(node);
27706             node = node.nextSibling;
27707         }
27708         writer.end(name);
27709         
27710     
27711     }
27712     // Serialize element and treat all non elements as fragments
27713    
27714 }; 
27715
27716 /***
27717  * This is based loosely on tinymce 
27718  * @class Roo.htmleditor.TidyWriter
27719  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
27720  *
27721  * Known issues?
27722  * - not tested much with 'PRE' formated elements.
27723  * 
27724  *
27725  *
27726  */
27727
27728 Roo.htmleditor.TidyWriter = function(settings)
27729 {
27730     
27731     // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
27732     Roo.apply(this, settings);
27733     this.html = [];
27734     this.state = [];
27735      
27736     this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
27737   
27738 }
27739 Roo.htmleditor.TidyWriter.prototype = {
27740
27741  
27742     state : false,
27743     
27744     indent :  '  ',
27745     
27746     // part of state...
27747     indentstr : '',
27748     in_pre: false,
27749     in_inline : false,
27750     last_inline : false,
27751     encode : false,
27752      
27753     
27754             /**
27755     * Writes the a start element such as <p id="a">.
27756     *
27757     * @method start
27758     * @param {String} name Name of the element.
27759     * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
27760     * @param {Boolean} empty Optional empty state if the tag should end like <br />.
27761     */
27762     start: function(name, attrs, empty, node)
27763     {
27764         var i, l, attr, value;
27765         
27766         // there are some situations where adding line break && indentation will not work. will not work.
27767         // <span / b / i ... formating?
27768         
27769         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
27770         var in_pre    = this.in_pre    || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
27771         
27772         var is_short   = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
27773         
27774         var add_lb = name == 'BR' ? false : in_inline;
27775         
27776         if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
27777             i_inline = false;
27778         }
27779
27780         var indentstr =  this.indentstr;
27781         
27782         // e_inline = elements that can be inline, but still allow \n before and after?
27783         // only 'BR' ??? any others?
27784         
27785         // ADD LINE BEFORE tage
27786         if (!this.in_pre) {
27787             if (in_inline) {
27788                 //code
27789                 if (name == 'BR') {
27790                     this.addLine();
27791                 } else if (this.lastElementEndsWS()) {
27792                     this.addLine();
27793                 } else{
27794                     // otherwise - no new line. (and dont indent.)
27795                     indentstr = '';
27796                 }
27797                 
27798             } else {
27799                 this.addLine();
27800             }
27801         } else {
27802             indentstr = '';
27803         }
27804         
27805         this.html.push(indentstr + '<', name.toLowerCase());
27806         
27807         if (attrs) {
27808             for (i = 0, l = attrs.length; i < l; i++) {
27809                 attr = attrs[i];
27810                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
27811             }
27812         }
27813      
27814         if (empty) {
27815             if (is_short) {
27816                 this.html[this.html.length] = '/>';
27817             } else {
27818                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
27819             }
27820             var e_inline = name == 'BR' ? false : this.in_inline;
27821             
27822             if (!e_inline && !this.in_pre) {
27823                 this.addLine();
27824             }
27825             return;
27826         
27827         }
27828         // not empty..
27829         this.html[this.html.length] = '>';
27830         
27831         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
27832         /*
27833         if (!in_inline && !in_pre) {
27834             var cn = node.firstChild;
27835             while(cn) {
27836                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
27837                     in_inline = true
27838                     break;
27839                 }
27840                 cn = cn.nextSibling;
27841             }
27842              
27843         }
27844         */
27845         
27846         
27847         this.pushState({
27848             indentstr : in_pre   ? '' : (this.indentstr + this.indent),
27849             in_pre : in_pre,
27850             in_inline :  in_inline
27851         });
27852         // add a line after if we are not in a
27853         
27854         if (!in_inline && !in_pre) {
27855             this.addLine();
27856         }
27857         
27858             
27859          
27860         
27861     },
27862     
27863     lastElementEndsWS : function()
27864     {
27865         var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
27866         if (value === false) {
27867             return true;
27868         }
27869         return value.match(/\s+$/);
27870         
27871     },
27872     
27873     /**
27874      * Writes the a end element such as </p>.
27875      *
27876      * @method end
27877      * @param {String} name Name of the element.
27878      */
27879     end: function(name) {
27880         var value;
27881         this.popState();
27882         var indentstr = '';
27883         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
27884         
27885         if (!this.in_pre && !in_inline) {
27886             this.addLine();
27887             indentstr  = this.indentstr;
27888         }
27889         this.html.push(indentstr + '</', name.toLowerCase(), '>');
27890         this.last_inline = in_inline;
27891         
27892         // pop the indent state..
27893     },
27894     /**
27895      * Writes a text node.
27896      *
27897      * In pre - we should not mess with the contents.
27898      * 
27899      *
27900      * @method text
27901      * @param {String} text String to write out.
27902      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
27903      */
27904     text: function(in_text, node)
27905     {
27906         // if not in whitespace critical
27907         if (in_text.length < 1) {
27908             return;
27909         }
27910         var text = new XMLSerializer().serializeToString(document.createTextNode(in_text)); // escape it properly?
27911         
27912         if (this.in_pre) {
27913             this.html[this.html.length] =  text;
27914             return;   
27915         }
27916         
27917         if (this.in_inline) {
27918             text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
27919             if (text != ' ') {
27920                 text = text.replace(/\s+/,' ');  // all white space to single white space
27921                 
27922                     
27923                 // if next tag is '<BR>', then we can trim right..
27924                 if (node.nextSibling &&
27925                     node.nextSibling.nodeType == 1 &&
27926                     node.nextSibling.nodeName == 'BR' )
27927                 {
27928                     text = text.replace(/\s+$/g,'');
27929                 }
27930                 // if previous tag was a BR, we can also trim..
27931                 if (node.previousSibling &&
27932                     node.previousSibling.nodeType == 1 &&
27933                     node.previousSibling.nodeName == 'BR' )
27934                 {
27935                     text = this.indentstr +  text.replace(/^\s+/g,'');
27936                 }
27937                 if (text.match(/\n/)) {
27938                     text = text.replace(
27939                         /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
27940                     );
27941                     // remoeve the last whitespace / line break.
27942                     text = text.replace(/\n\s+$/,'');
27943                 }
27944                 // repace long lines
27945                 
27946             }
27947              
27948             this.html[this.html.length] =  text;
27949             return;   
27950         }
27951         // see if previous element was a inline element.
27952         var indentstr = this.indentstr;
27953    
27954         text = text.replace(/\s+/g," "); // all whitespace into single white space.
27955         
27956         // should trim left?
27957         if (node.previousSibling &&
27958             node.previousSibling.nodeType == 1 &&
27959             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
27960         {
27961             indentstr = '';
27962             
27963         } else {
27964             this.addLine();
27965             text = text.replace(/^\s+/,''); // trim left
27966           
27967         }
27968         // should trim right?
27969         if (node.nextSibling &&
27970             node.nextSibling.nodeType == 1 &&
27971             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
27972         {
27973           // noop
27974             
27975         }  else {
27976             text = text.replace(/\s+$/,''); // trim right
27977         }
27978          
27979               
27980         
27981         
27982         
27983         if (text.length < 1) {
27984             return;
27985         }
27986         if (!text.match(/\n/)) {
27987             this.html.push(indentstr + text);
27988             return;
27989         }
27990         
27991         text = this.indentstr + text.replace(
27992             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
27993         );
27994         // remoeve the last whitespace / line break.
27995         text = text.replace(/\s+$/,''); 
27996         
27997         this.html.push(text);
27998         
27999         // split and indent..
28000         
28001         
28002     },
28003     /**
28004      * Writes a cdata node such as <![CDATA[data]]>.
28005      *
28006      * @method cdata
28007      * @param {String} text String to write out inside the cdata.
28008      */
28009     cdata: function(text) {
28010         this.html.push('<![CDATA[', text, ']]>');
28011     },
28012     /**
28013     * Writes a comment node such as <!-- Comment -->.
28014     *
28015     * @method cdata
28016     * @param {String} text String to write out inside the comment.
28017     */
28018    comment: function(text) {
28019        this.html.push('<!--', text, '-->');
28020    },
28021     /**
28022      * Writes a PI node such as <?xml attr="value" ?>.
28023      *
28024      * @method pi
28025      * @param {String} name Name of the pi.
28026      * @param {String} text String to write out inside the pi.
28027      */
28028     pi: function(name, text) {
28029         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
28030         this.indent != '' && this.html.push('\n');
28031     },
28032     /**
28033      * Writes a doctype node such as <!DOCTYPE data>.
28034      *
28035      * @method doctype
28036      * @param {String} text String to write out inside the doctype.
28037      */
28038     doctype: function(text) {
28039         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
28040     },
28041     /**
28042      * Resets the internal buffer if one wants to reuse the writer.
28043      *
28044      * @method reset
28045      */
28046     reset: function() {
28047         this.html.length = 0;
28048         this.state = [];
28049         this.pushState({
28050             indentstr : '',
28051             in_pre : false, 
28052             in_inline : false
28053         })
28054     },
28055     /**
28056      * Returns the contents that got serialized.
28057      *
28058      * @method getContent
28059      * @return {String} HTML contents that got written down.
28060      */
28061     getContent: function() {
28062         return this.html.join('').replace(/\n$/, '');
28063     },
28064     
28065     pushState : function(cfg)
28066     {
28067         this.state.push(cfg);
28068         Roo.apply(this, cfg);
28069     },
28070     
28071     popState : function()
28072     {
28073         if (this.state.length < 1) {
28074             return; // nothing to push
28075         }
28076         var cfg = {
28077             in_pre: false,
28078             indentstr : ''
28079         };
28080         this.state.pop();
28081         if (this.state.length > 0) {
28082             cfg = this.state[this.state.length-1]; 
28083         }
28084         Roo.apply(this, cfg);
28085     },
28086     
28087     addLine: function()
28088     {
28089         if (this.html.length < 1) {
28090             return;
28091         }
28092         
28093         
28094         var value = this.html[this.html.length - 1];
28095         if (value.length > 0 && '\n' !== value) {
28096             this.html.push('\n');
28097         }
28098     }
28099     
28100     
28101 //'pre script noscript style textarea video audio iframe object code'
28102 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
28103 // inline 
28104 };
28105
28106 Roo.htmleditor.TidyWriter.inline_elements = [
28107         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
28108         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
28109 ];
28110 Roo.htmleditor.TidyWriter.shortend_elements = [
28111     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
28112     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
28113 ];
28114
28115 Roo.htmleditor.TidyWriter.whitespace_elements = [
28116     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
28117 ];/***
28118  * This is based loosely on tinymce 
28119  * @class Roo.htmleditor.TidyEntities
28120  * @static
28121  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
28122  *
28123  * Not 100% sure this is actually used or needed.
28124  */
28125
28126 Roo.htmleditor.TidyEntities = {
28127     
28128     /**
28129      * initialize data..
28130      */
28131     init : function (){
28132      
28133         this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
28134        
28135     },
28136
28137
28138     buildEntitiesLookup: function(items, radix) {
28139         var i, chr, entity, lookup = {};
28140         if (!items) {
28141             return {};
28142         }
28143         items = typeof(items) == 'string' ? items.split(',') : items;
28144         radix = radix || 10;
28145         // Build entities lookup table
28146         for (i = 0; i < items.length; i += 2) {
28147             chr = String.fromCharCode(parseInt(items[i], radix));
28148             // Only add non base entities
28149             if (!this.baseEntities[chr]) {
28150                 entity = '&' + items[i + 1] + ';';
28151                 lookup[chr] = entity;
28152                 lookup[entity] = chr;
28153             }
28154         }
28155         return lookup;
28156         
28157     },
28158     
28159     asciiMap : {
28160             128: '€',
28161             130: '‚',
28162             131: 'ƒ',
28163             132: '„',
28164             133: '…',
28165             134: '†',
28166             135: '‡',
28167             136: 'ˆ',
28168             137: '‰',
28169             138: 'Š',
28170             139: '‹',
28171             140: 'Œ',
28172             142: 'Ž',
28173             145: '‘',
28174             146: '’',
28175             147: '“',
28176             148: '”',
28177             149: '•',
28178             150: '–',
28179             151: '—',
28180             152: '˜',
28181             153: '™',
28182             154: 'š',
28183             155: '›',
28184             156: 'œ',
28185             158: 'ž',
28186             159: 'Ÿ'
28187     },
28188     // Raw entities
28189     baseEntities : {
28190         '"': '&quot;',
28191         // Needs to be escaped since the YUI compressor would otherwise break the code
28192         '\'': '&#39;',
28193         '<': '&lt;',
28194         '>': '&gt;',
28195         '&': '&amp;',
28196         '`': '&#96;'
28197     },
28198     // Reverse lookup table for raw entities
28199     reverseEntities : {
28200         '&lt;': '<',
28201         '&gt;': '>',
28202         '&amp;': '&',
28203         '&quot;': '"',
28204         '&apos;': '\''
28205     },
28206     
28207     attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
28208     textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
28209     rawCharsRegExp : /[<>&\"\']/g,
28210     entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
28211     namedEntities  : false,
28212     namedEntitiesData : [ 
28213         '50',
28214         'nbsp',
28215         '51',
28216         'iexcl',
28217         '52',
28218         'cent',
28219         '53',
28220         'pound',
28221         '54',
28222         'curren',
28223         '55',
28224         'yen',
28225         '56',
28226         'brvbar',
28227         '57',
28228         'sect',
28229         '58',
28230         'uml',
28231         '59',
28232         'copy',
28233         '5a',
28234         'ordf',
28235         '5b',
28236         'laquo',
28237         '5c',
28238         'not',
28239         '5d',
28240         'shy',
28241         '5e',
28242         'reg',
28243         '5f',
28244         'macr',
28245         '5g',
28246         'deg',
28247         '5h',
28248         'plusmn',
28249         '5i',
28250         'sup2',
28251         '5j',
28252         'sup3',
28253         '5k',
28254         'acute',
28255         '5l',
28256         'micro',
28257         '5m',
28258         'para',
28259         '5n',
28260         'middot',
28261         '5o',
28262         'cedil',
28263         '5p',
28264         'sup1',
28265         '5q',
28266         'ordm',
28267         '5r',
28268         'raquo',
28269         '5s',
28270         'frac14',
28271         '5t',
28272         'frac12',
28273         '5u',
28274         'frac34',
28275         '5v',
28276         'iquest',
28277         '60',
28278         'Agrave',
28279         '61',
28280         'Aacute',
28281         '62',
28282         'Acirc',
28283         '63',
28284         'Atilde',
28285         '64',
28286         'Auml',
28287         '65',
28288         'Aring',
28289         '66',
28290         'AElig',
28291         '67',
28292         'Ccedil',
28293         '68',
28294         'Egrave',
28295         '69',
28296         'Eacute',
28297         '6a',
28298         'Ecirc',
28299         '6b',
28300         'Euml',
28301         '6c',
28302         'Igrave',
28303         '6d',
28304         'Iacute',
28305         '6e',
28306         'Icirc',
28307         '6f',
28308         'Iuml',
28309         '6g',
28310         'ETH',
28311         '6h',
28312         'Ntilde',
28313         '6i',
28314         'Ograve',
28315         '6j',
28316         'Oacute',
28317         '6k',
28318         'Ocirc',
28319         '6l',
28320         'Otilde',
28321         '6m',
28322         'Ouml',
28323         '6n',
28324         'times',
28325         '6o',
28326         'Oslash',
28327         '6p',
28328         'Ugrave',
28329         '6q',
28330         'Uacute',
28331         '6r',
28332         'Ucirc',
28333         '6s',
28334         'Uuml',
28335         '6t',
28336         'Yacute',
28337         '6u',
28338         'THORN',
28339         '6v',
28340         'szlig',
28341         '70',
28342         'agrave',
28343         '71',
28344         'aacute',
28345         '72',
28346         'acirc',
28347         '73',
28348         'atilde',
28349         '74',
28350         'auml',
28351         '75',
28352         'aring',
28353         '76',
28354         'aelig',
28355         '77',
28356         'ccedil',
28357         '78',
28358         'egrave',
28359         '79',
28360         'eacute',
28361         '7a',
28362         'ecirc',
28363         '7b',
28364         'euml',
28365         '7c',
28366         'igrave',
28367         '7d',
28368         'iacute',
28369         '7e',
28370         'icirc',
28371         '7f',
28372         'iuml',
28373         '7g',
28374         'eth',
28375         '7h',
28376         'ntilde',
28377         '7i',
28378         'ograve',
28379         '7j',
28380         'oacute',
28381         '7k',
28382         'ocirc',
28383         '7l',
28384         'otilde',
28385         '7m',
28386         'ouml',
28387         '7n',
28388         'divide',
28389         '7o',
28390         'oslash',
28391         '7p',
28392         'ugrave',
28393         '7q',
28394         'uacute',
28395         '7r',
28396         'ucirc',
28397         '7s',
28398         'uuml',
28399         '7t',
28400         'yacute',
28401         '7u',
28402         'thorn',
28403         '7v',
28404         'yuml',
28405         'ci',
28406         'fnof',
28407         'sh',
28408         'Alpha',
28409         'si',
28410         'Beta',
28411         'sj',
28412         'Gamma',
28413         'sk',
28414         'Delta',
28415         'sl',
28416         'Epsilon',
28417         'sm',
28418         'Zeta',
28419         'sn',
28420         'Eta',
28421         'so',
28422         'Theta',
28423         'sp',
28424         'Iota',
28425         'sq',
28426         'Kappa',
28427         'sr',
28428         'Lambda',
28429         'ss',
28430         'Mu',
28431         'st',
28432         'Nu',
28433         'su',
28434         'Xi',
28435         'sv',
28436         'Omicron',
28437         't0',
28438         'Pi',
28439         't1',
28440         'Rho',
28441         't3',
28442         'Sigma',
28443         't4',
28444         'Tau',
28445         't5',
28446         'Upsilon',
28447         't6',
28448         'Phi',
28449         't7',
28450         'Chi',
28451         't8',
28452         'Psi',
28453         't9',
28454         'Omega',
28455         'th',
28456         'alpha',
28457         'ti',
28458         'beta',
28459         'tj',
28460         'gamma',
28461         'tk',
28462         'delta',
28463         'tl',
28464         'epsilon',
28465         'tm',
28466         'zeta',
28467         'tn',
28468         'eta',
28469         'to',
28470         'theta',
28471         'tp',
28472         'iota',
28473         'tq',
28474         'kappa',
28475         'tr',
28476         'lambda',
28477         'ts',
28478         'mu',
28479         'tt',
28480         'nu',
28481         'tu',
28482         'xi',
28483         'tv',
28484         'omicron',
28485         'u0',
28486         'pi',
28487         'u1',
28488         'rho',
28489         'u2',
28490         'sigmaf',
28491         'u3',
28492         'sigma',
28493         'u4',
28494         'tau',
28495         'u5',
28496         'upsilon',
28497         'u6',
28498         'phi',
28499         'u7',
28500         'chi',
28501         'u8',
28502         'psi',
28503         'u9',
28504         'omega',
28505         'uh',
28506         'thetasym',
28507         'ui',
28508         'upsih',
28509         'um',
28510         'piv',
28511         '812',
28512         'bull',
28513         '816',
28514         'hellip',
28515         '81i',
28516         'prime',
28517         '81j',
28518         'Prime',
28519         '81u',
28520         'oline',
28521         '824',
28522         'frasl',
28523         '88o',
28524         'weierp',
28525         '88h',
28526         'image',
28527         '88s',
28528         'real',
28529         '892',
28530         'trade',
28531         '89l',
28532         'alefsym',
28533         '8cg',
28534         'larr',
28535         '8ch',
28536         'uarr',
28537         '8ci',
28538         'rarr',
28539         '8cj',
28540         'darr',
28541         '8ck',
28542         'harr',
28543         '8dl',
28544         'crarr',
28545         '8eg',
28546         'lArr',
28547         '8eh',
28548         'uArr',
28549         '8ei',
28550         'rArr',
28551         '8ej',
28552         'dArr',
28553         '8ek',
28554         'hArr',
28555         '8g0',
28556         'forall',
28557         '8g2',
28558         'part',
28559         '8g3',
28560         'exist',
28561         '8g5',
28562         'empty',
28563         '8g7',
28564         'nabla',
28565         '8g8',
28566         'isin',
28567         '8g9',
28568         'notin',
28569         '8gb',
28570         'ni',
28571         '8gf',
28572         'prod',
28573         '8gh',
28574         'sum',
28575         '8gi',
28576         'minus',
28577         '8gn',
28578         'lowast',
28579         '8gq',
28580         'radic',
28581         '8gt',
28582         'prop',
28583         '8gu',
28584         'infin',
28585         '8h0',
28586         'ang',
28587         '8h7',
28588         'and',
28589         '8h8',
28590         'or',
28591         '8h9',
28592         'cap',
28593         '8ha',
28594         'cup',
28595         '8hb',
28596         'int',
28597         '8hk',
28598         'there4',
28599         '8hs',
28600         'sim',
28601         '8i5',
28602         'cong',
28603         '8i8',
28604         'asymp',
28605         '8j0',
28606         'ne',
28607         '8j1',
28608         'equiv',
28609         '8j4',
28610         'le',
28611         '8j5',
28612         'ge',
28613         '8k2',
28614         'sub',
28615         '8k3',
28616         'sup',
28617         '8k4',
28618         'nsub',
28619         '8k6',
28620         'sube',
28621         '8k7',
28622         'supe',
28623         '8kl',
28624         'oplus',
28625         '8kn',
28626         'otimes',
28627         '8l5',
28628         'perp',
28629         '8m5',
28630         'sdot',
28631         '8o8',
28632         'lceil',
28633         '8o9',
28634         'rceil',
28635         '8oa',
28636         'lfloor',
28637         '8ob',
28638         'rfloor',
28639         '8p9',
28640         'lang',
28641         '8pa',
28642         'rang',
28643         '9ea',
28644         'loz',
28645         '9j0',
28646         'spades',
28647         '9j3',
28648         'clubs',
28649         '9j5',
28650         'hearts',
28651         '9j6',
28652         'diams',
28653         'ai',
28654         'OElig',
28655         'aj',
28656         'oelig',
28657         'b0',
28658         'Scaron',
28659         'b1',
28660         'scaron',
28661         'bo',
28662         'Yuml',
28663         'm6',
28664         'circ',
28665         'ms',
28666         'tilde',
28667         '802',
28668         'ensp',
28669         '803',
28670         'emsp',
28671         '809',
28672         'thinsp',
28673         '80c',
28674         'zwnj',
28675         '80d',
28676         'zwj',
28677         '80e',
28678         'lrm',
28679         '80f',
28680         'rlm',
28681         '80j',
28682         'ndash',
28683         '80k',
28684         'mdash',
28685         '80o',
28686         'lsquo',
28687         '80p',
28688         'rsquo',
28689         '80q',
28690         'sbquo',
28691         '80s',
28692         'ldquo',
28693         '80t',
28694         'rdquo',
28695         '80u',
28696         'bdquo',
28697         '810',
28698         'dagger',
28699         '811',
28700         'Dagger',
28701         '81g',
28702         'permil',
28703         '81p',
28704         'lsaquo',
28705         '81q',
28706         'rsaquo',
28707         '85c',
28708         'euro'
28709     ],
28710
28711          
28712     /**
28713      * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
28714      *
28715      * @method encodeRaw
28716      * @param {String} text Text to encode.
28717      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
28718      * @return {String} Entity encoded text.
28719      */
28720     encodeRaw: function(text, attr)
28721     {
28722         var t = this;
28723         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
28724             return t.baseEntities[chr] || chr;
28725         });
28726     },
28727     /**
28728      * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
28729      * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
28730      * and is exposed as the DOMUtils.encode function.
28731      *
28732      * @method encodeAllRaw
28733      * @param {String} text Text to encode.
28734      * @return {String} Entity encoded text.
28735      */
28736     encodeAllRaw: function(text) {
28737         var t = this;
28738         return ('' + text).replace(this.rawCharsRegExp, function(chr) {
28739             return t.baseEntities[chr] || chr;
28740         });
28741     },
28742     /**
28743      * Encodes the specified string using numeric entities. The core entities will be
28744      * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
28745      *
28746      * @method encodeNumeric
28747      * @param {String} text Text to encode.
28748      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
28749      * @return {String} Entity encoded text.
28750      */
28751     encodeNumeric: function(text, attr) {
28752         var t = this;
28753         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
28754             // Multi byte sequence convert it to a single entity
28755             if (chr.length > 1) {
28756                 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
28757             }
28758             return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
28759         });
28760     },
28761     /**
28762      * Encodes the specified string using named entities. The core entities will be encoded
28763      * as named ones but all non lower ascii characters will be encoded into named entities.
28764      *
28765      * @method encodeNamed
28766      * @param {String} text Text to encode.
28767      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
28768      * @param {Object} entities Optional parameter with entities to use.
28769      * @return {String} Entity encoded text.
28770      */
28771     encodeNamed: function(text, attr, entities) {
28772         var t = this;
28773         entities = entities || this.namedEntities;
28774         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
28775             return t.baseEntities[chr] || entities[chr] || chr;
28776         });
28777     },
28778     /**
28779      * Returns an encode function based on the name(s) and it's optional entities.
28780      *
28781      * @method getEncodeFunc
28782      * @param {String} name Comma separated list of encoders for example named,numeric.
28783      * @param {String} entities Optional parameter with entities to use instead of the built in set.
28784      * @return {function} Encode function to be used.
28785      */
28786     getEncodeFunc: function(name, entities) {
28787         entities = this.buildEntitiesLookup(entities) || this.namedEntities;
28788         var t = this;
28789         function encodeNamedAndNumeric(text, attr) {
28790             return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
28791                 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
28792             });
28793         }
28794
28795         function encodeCustomNamed(text, attr) {
28796             return t.encodeNamed(text, attr, entities);
28797         }
28798         // Replace + with , to be compatible with previous TinyMCE versions
28799         name = this.makeMap(name.replace(/\+/g, ','));
28800         // Named and numeric encoder
28801         if (name.named && name.numeric) {
28802             return this.encodeNamedAndNumeric;
28803         }
28804         // Named encoder
28805         if (name.named) {
28806             // Custom names
28807             if (entities) {
28808                 return encodeCustomNamed;
28809             }
28810             return this.encodeNamed;
28811         }
28812         // Numeric
28813         if (name.numeric) {
28814             return this.encodeNumeric;
28815         }
28816         // Raw encoder
28817         return this.encodeRaw;
28818     },
28819     /**
28820      * Decodes the specified string, this will replace entities with raw UTF characters.
28821      *
28822      * @method decode
28823      * @param {String} text Text to entity decode.
28824      * @return {String} Entity decoded string.
28825      */
28826     decode: function(text)
28827     {
28828         var  t = this;
28829         return text.replace(this.entityRegExp, function(all, numeric) {
28830             if (numeric) {
28831                 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
28832                 // Support upper UTF
28833                 if (numeric > 65535) {
28834                     numeric -= 65536;
28835                     return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
28836                 }
28837                 return t.asciiMap[numeric] || String.fromCharCode(numeric);
28838             }
28839             return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
28840         });
28841     },
28842     nativeDecode : function (text) {
28843         return text;
28844     },
28845     makeMap : function (items, delim, map) {
28846                 var i;
28847                 items = items || [];
28848                 delim = delim || ',';
28849                 if (typeof items == "string") {
28850                         items = items.split(delim);
28851                 }
28852                 map = map || {};
28853                 i = items.length;
28854                 while (i--) {
28855                         map[items[i]] = {};
28856                 }
28857                 return map;
28858         }
28859 };
28860     
28861     
28862     
28863 Roo.htmleditor.TidyEntities.init();
28864 /**
28865  * @class Roo.htmleditor.KeyEnter
28866  * Handle Enter press..
28867  * @cfg {Roo.HtmlEditorCore} core the editor.
28868  * @constructor
28869  * Create a new Filter.
28870  * @param {Object} config Configuration options
28871  */
28872
28873
28874
28875
28876
28877 Roo.htmleditor.KeyEnter = function(cfg) {
28878     Roo.apply(this, cfg);
28879     // this does not actually call walk as it's really just a abstract class
28880  
28881     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
28882 }
28883
28884 //Roo.htmleditor.KeyEnter.i = 0;
28885
28886
28887 Roo.htmleditor.KeyEnter.prototype = {
28888     
28889     core : false,
28890     
28891     keypress : function(e)
28892     {
28893         if (e.charCode != 13 && e.charCode != 10) {
28894             Roo.log([e.charCode,e]);
28895             return true;
28896         }
28897         e.preventDefault();
28898         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
28899         var doc = this.core.doc;
28900           //add a new line
28901        
28902     
28903         var sel = this.core.getSelection();
28904         var range = sel.getRangeAt(0);
28905         var n = range.commonAncestorContainer;
28906         var pc = range.closest([ 'ol', 'ul']);
28907         var pli = range.closest('li');
28908         if (!pc || e.ctrlKey) {
28909             // on it list, or ctrl pressed.
28910             if (!e.ctrlKey) {
28911                 sel.insertNode('br', 'after'); 
28912             } else {
28913                 // only do this if we have ctrl key..
28914                 var br = doc.createElement('br');
28915                 br.className = 'clear';
28916                 br.setAttribute('style', 'clear: both');
28917                 sel.insertNode(br, 'after'); 
28918             }
28919             
28920          
28921             this.core.undoManager.addEvent();
28922             this.core.fireEditorEvent(e);
28923             return false;
28924         }
28925         
28926         // deal with <li> insetion
28927         if (pli.innerText.trim() == '' &&
28928             pli.previousSibling &&
28929             pli.previousSibling.nodeName == 'LI' &&
28930             pli.previousSibling.innerText.trim() ==  '') {
28931             pli.parentNode.removeChild(pli.previousSibling);
28932             sel.cursorAfter(pc);
28933             this.core.undoManager.addEvent();
28934             this.core.fireEditorEvent(e);
28935             return false;
28936         }
28937     
28938         var li = doc.createElement('LI');
28939         li.innerHTML = '&nbsp;';
28940         if (!pli || !pli.firstSibling) {
28941             pc.appendChild(li);
28942         } else {
28943             pli.parentNode.insertBefore(li, pli.firstSibling);
28944         }
28945         sel.cursorText (li.firstChild);
28946       
28947         this.core.undoManager.addEvent();
28948         this.core.fireEditorEvent(e);
28949
28950         return false;
28951         
28952     
28953         
28954         
28955          
28956     }
28957 };
28958      
28959 /**
28960  * @class Roo.htmleditor.Block
28961  * Base class for html editor blocks - do not use it directly .. extend it..
28962  * @cfg {DomElement} node The node to apply stuff to.
28963  * @cfg {String} friendly_name the name that appears in the context bar about this block
28964  * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
28965  
28966  * @constructor
28967  * Create a new Filter.
28968  * @param {Object} config Configuration options
28969  */
28970
28971 Roo.htmleditor.Block  = function(cfg)
28972 {
28973     // do nothing .. should not be called really.
28974 }
28975 /**
28976  * factory method to get the block from an element (using cache if necessary)
28977  * @static
28978  * @param {HtmlElement} the dom element
28979  */
28980 Roo.htmleditor.Block.factory = function(node)
28981 {
28982     var cc = Roo.htmleditor.Block.cache;
28983     var id = Roo.get(node).id;
28984     if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
28985         Roo.htmleditor.Block.cache[id].readElement(node);
28986         return Roo.htmleditor.Block.cache[id];
28987     }
28988     var db  = node.getAttribute('data-block');
28989     if (!db) {
28990         db = node.nodeName.toLowerCase().toUpperCaseFirst();
28991     }
28992     var cls = Roo.htmleditor['Block' + db];
28993     if (typeof(cls) == 'undefined') {
28994         //Roo.log(node.getAttribute('data-block'));
28995         Roo.log("OOps missing block : " + 'Block' + db);
28996         return false;
28997     }
28998     Roo.htmleditor.Block.cache[id] = new cls({ node: node });
28999     return Roo.htmleditor.Block.cache[id];  /// should trigger update element
29000 };
29001
29002 /**
29003  * initalize all Elements from content that are 'blockable'
29004  * @static
29005  * @param the body element
29006  */
29007 Roo.htmleditor.Block.initAll = function(body, type)
29008 {
29009     if (typeof(type) == 'undefined') {
29010         var ia = Roo.htmleditor.Block.initAll;
29011         ia(body,'table');
29012         ia(body,'td');
29013         ia(body,'figure');
29014         return;
29015     }
29016     Roo.each(Roo.get(body).query(type), function(e) {
29017         Roo.htmleditor.Block.factory(e);    
29018     },this);
29019 };
29020 // question goes here... do we need to clear out this cache sometimes?
29021 // or show we make it relivant to the htmleditor.
29022 Roo.htmleditor.Block.cache = {};
29023
29024 Roo.htmleditor.Block.prototype = {
29025     
29026     node : false,
29027     
29028      // used by context menu
29029     friendly_name : 'Based Block',
29030     
29031     // text for button to delete this element
29032     deleteTitle : false,
29033     
29034     context : false,
29035     /**
29036      * Update a node with values from this object
29037      * @param {DomElement} node
29038      */
29039     updateElement : function(node)
29040     {
29041         Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
29042     },
29043      /**
29044      * convert to plain HTML for calling insertAtCursor..
29045      */
29046     toHTML : function()
29047     {
29048         return Roo.DomHelper.markup(this.toObject());
29049     },
29050     /**
29051      * used by readEleemnt to extract data from a node
29052      * may need improving as it's pretty basic
29053      
29054      * @param {DomElement} node
29055      * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
29056      * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
29057      * @param {String} style the style property - eg. text-align
29058      */
29059     getVal : function(node, tag, attr, style)
29060     {
29061         var n = node;
29062         if (tag !== true && n.tagName != tag.toUpperCase()) {
29063             // in theory we could do figure[3] << 3rd figure? or some more complex search..?
29064             // but kiss for now.
29065             n = node.getElementsByTagName(tag).item(0);
29066         }
29067         if (!n) {
29068             return '';
29069         }
29070         if (attr === false) {
29071             return n;
29072         }
29073         if (attr == 'html') {
29074             return n.innerHTML;
29075         }
29076         if (attr == 'style') {
29077             return n.style[style]; 
29078         }
29079         
29080         return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
29081             
29082     },
29083     /**
29084      * create a DomHelper friendly object - for use with 
29085      * Roo.DomHelper.markup / overwrite / etc..
29086      * (override this)
29087      */
29088     toObject : function()
29089     {
29090         return {};
29091     },
29092       /**
29093      * Read a node that has a 'data-block' property - and extract the values from it.
29094      * @param {DomElement} node - the node
29095      */
29096     readElement : function(node)
29097     {
29098         
29099     } 
29100     
29101     
29102 };
29103
29104  
29105
29106 /**
29107  * @class Roo.htmleditor.BlockFigure
29108  * Block that has an image and a figcaption
29109  * @cfg {String} image_src the url for the image
29110  * @cfg {String} align (left|right) alignment for the block default left
29111  * @cfg {String} caption the text to appear below  (and in the alt tag)
29112  * @cfg {String} caption_display (block|none) display or not the caption
29113  * @cfg {String|number} image_width the width of the image number or %?
29114  * @cfg {String|number} image_height the height of the image number or %?
29115  * 
29116  * @constructor
29117  * Create a new Filter.
29118  * @param {Object} config Configuration options
29119  */
29120
29121 Roo.htmleditor.BlockFigure = function(cfg)
29122 {
29123     if (cfg.node) {
29124         this.readElement(cfg.node);
29125         this.updateElement(cfg.node);
29126     }
29127     Roo.apply(this, cfg);
29128 }
29129 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
29130  
29131     
29132     // setable values.
29133     image_src: '',
29134     align: 'center',
29135     caption : '',
29136     caption_display : 'block',
29137     width : '100%',
29138     cls : '',
29139     href: '',
29140     video_url : '',
29141     
29142     // margin: '2%', not used
29143     
29144     text_align: 'left', //   (left|right) alignment for the text caption default left. - not used at present
29145
29146     
29147     // used by context menu
29148     friendly_name : 'Image with caption',
29149     deleteTitle : "Delete Image and Caption",
29150     
29151     contextMenu : function(toolbar)
29152     {
29153         
29154         var block = function() {
29155             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
29156         };
29157         
29158         
29159         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
29160         
29161         var syncValue = toolbar.editorcore.syncValue;
29162         
29163         var fields = {};
29164         
29165         return [
29166              {
29167                 xtype : 'TextItem',
29168                 text : "Source: ",
29169                 xns : rooui.Toolbar  //Boostrap?
29170             },
29171             {
29172                 xtype : 'Button',
29173                 text: 'Change Image URL',
29174                  
29175                 listeners : {
29176                     click: function (btn, state)
29177                     {
29178                         var b = block();
29179                         
29180                         Roo.MessageBox.show({
29181                             title : "Image Source URL",
29182                             msg : "Enter the url for the image",
29183                             buttons: Roo.MessageBox.OKCANCEL,
29184                             fn: function(btn, val){
29185                                 if (btn != 'ok') {
29186                                     return;
29187                                 }
29188                                 b.image_src = val;
29189                                 b.updateElement();
29190                                 syncValue();
29191                                 toolbar.editorcore.onEditorEvent();
29192                             },
29193                             minWidth:250,
29194                             prompt:true,
29195                             //multiline: multiline,
29196                             modal : true,
29197                             value : b.image_src
29198                         });
29199                     }
29200                 },
29201                 xns : rooui.Toolbar
29202             },
29203          
29204             {
29205                 xtype : 'Button',
29206                 text: 'Change Link URL',
29207                  
29208                 listeners : {
29209                     click: function (btn, state)
29210                     {
29211                         var b = block();
29212                         
29213                         Roo.MessageBox.show({
29214                             title : "Link URL",
29215                             msg : "Enter the url for the link - leave blank to have no link",
29216                             buttons: Roo.MessageBox.OKCANCEL,
29217                             fn: function(btn, val){
29218                                 if (btn != 'ok') {
29219                                     return;
29220                                 }
29221                                 b.href = val;
29222                                 b.updateElement();
29223                                 syncValue();
29224                                 toolbar.editorcore.onEditorEvent();
29225                             },
29226                             minWidth:250,
29227                             prompt:true,
29228                             //multiline: multiline,
29229                             modal : true,
29230                             value : b.href
29231                         });
29232                     }
29233                 },
29234                 xns : rooui.Toolbar
29235             },
29236             {
29237                 xtype : 'Button',
29238                 text: 'Show Video URL',
29239                  
29240                 listeners : {
29241                     click: function (btn, state)
29242                     {
29243                         Roo.MessageBox.alert("Video URL",
29244                             block().video_url == '' ? 'This image is not linked ot a video' :
29245                                 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
29246                     }
29247                 },
29248                 xns : rooui.Toolbar
29249             },
29250             
29251             
29252             {
29253                 xtype : 'TextItem',
29254                 text : "Width: ",
29255                 xns : rooui.Toolbar  //Boostrap?
29256             },
29257             {
29258                 xtype : 'ComboBox',
29259                 allowBlank : false,
29260                 displayField : 'val',
29261                 editable : true,
29262                 listWidth : 100,
29263                 triggerAction : 'all',
29264                 typeAhead : true,
29265                 valueField : 'val',
29266                 width : 70,
29267                 name : 'width',
29268                 listeners : {
29269                     select : function (combo, r, index)
29270                     {
29271                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29272                         var b = block();
29273                         b.width = r.get('val');
29274                         b.updateElement();
29275                         syncValue();
29276                         toolbar.editorcore.onEditorEvent();
29277                     }
29278                 },
29279                 xns : rooui.form,
29280                 store : {
29281                     xtype : 'SimpleStore',
29282                     data : [
29283                         ['100%'],
29284                         ['80%'],
29285                         ['50%'],
29286                         ['20%'],
29287                         ['10%']
29288                     ],
29289                     fields : [ 'val'],
29290                     xns : Roo.data
29291                 }
29292             },
29293             {
29294                 xtype : 'TextItem',
29295                 text : "Align: ",
29296                 xns : rooui.Toolbar  //Boostrap?
29297             },
29298             {
29299                 xtype : 'ComboBox',
29300                 allowBlank : false,
29301                 displayField : 'val',
29302                 editable : true,
29303                 listWidth : 100,
29304                 triggerAction : 'all',
29305                 typeAhead : true,
29306                 valueField : 'val',
29307                 width : 70,
29308                 name : 'align',
29309                 listeners : {
29310                     select : function (combo, r, index)
29311                     {
29312                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29313                         var b = block();
29314                         b.align = r.get('val');
29315                         b.updateElement();
29316                         syncValue();
29317                         toolbar.editorcore.onEditorEvent();
29318                     }
29319                 },
29320                 xns : rooui.form,
29321                 store : {
29322                     xtype : 'SimpleStore',
29323                     data : [
29324                         ['left'],
29325                         ['right'],
29326                         ['center']
29327                     ],
29328                     fields : [ 'val'],
29329                     xns : Roo.data
29330                 }
29331             },
29332             
29333             
29334             {
29335                 xtype : 'Button',
29336                 text: 'Hide Caption',
29337                 name : 'caption_display',
29338                 pressed : false,
29339                 enableToggle : true,
29340                 setValue : function(v) {
29341                     // this trigger toggle.
29342                      
29343                     this.setText(v ? "Hide Caption" : "Show Caption");
29344                     this.setPressed(v != 'block');
29345                 },
29346                 listeners : {
29347                     toggle: function (btn, state)
29348                     {
29349                         var b  = block();
29350                         b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
29351                         this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
29352                         b.updateElement();
29353                         syncValue();
29354                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29355                         toolbar.editorcore.onEditorEvent();
29356                     }
29357                 },
29358                 xns : rooui.Toolbar
29359             }
29360         ];
29361         
29362     },
29363     /**
29364      * create a DomHelper friendly object - for use with
29365      * Roo.DomHelper.markup / overwrite / etc..
29366      */
29367     toObject : function()
29368     {
29369         var d = document.createElement('div');
29370         d.innerHTML = this.caption;
29371         
29372         var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0; 
29373         
29374         var iw = this.align == 'center' ? this.width : '100%';
29375         var img =   {
29376             tag : 'img',
29377             contenteditable : 'false',
29378             src : this.image_src,
29379             alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
29380             style: {
29381                 width : iw,
29382                 maxWidth : iw + ' !important', // this is not getting rendered?
29383                 margin : m  
29384                 
29385             }
29386         };
29387         /*
29388         '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
29389                     '<a href="{2}">' + 
29390                         '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' + 
29391                     '</a>' + 
29392                 '</div>',
29393         */
29394                 
29395         if (this.href.length > 0) {
29396             img = {
29397                 tag : 'a',
29398                 href: this.href,
29399                 contenteditable : 'true',
29400                 cn : [
29401                     img
29402                 ]
29403             };
29404         }
29405         
29406         
29407         if (this.video_url.length > 0) {
29408             img = {
29409                 tag : 'div',
29410                 cls : this.cls,
29411                 frameborder : 0,
29412                 allowfullscreen : true,
29413                 width : 420,  // these are for video tricks - that we replace the outer
29414                 height : 315,
29415                 src : this.video_url,
29416                 cn : [
29417                     img
29418                 ]
29419             };
29420         }
29421         // we remove caption totally if its hidden... - will delete data.. but otherwise we end up with fake caption
29422         var captionhtml = this.caption_display == 'none' ? '' : (this.caption.length ? this.caption : "Caption");
29423         
29424   
29425         var ret =   {
29426             tag: 'figure',
29427             'data-block' : 'Figure',
29428             'data-width' : this.width, 
29429             contenteditable : 'false',
29430             
29431             style : {
29432                 display: 'block',
29433                 float :  this.align ,
29434                 maxWidth :  this.align == 'center' ? '100% !important' : (this.width + ' !important'),
29435                 width : this.align == 'center' ? '100%' : this.width,
29436                 margin:  '0px',
29437                 padding: this.align == 'center' ? '0' : '0 10px' ,
29438                 textAlign : this.align   // seems to work for email..
29439                 
29440             },
29441            
29442             
29443             align : this.align,
29444             cn : [
29445                 img,
29446               
29447                 {
29448                     tag: 'figcaption',
29449                     'data-display' : this.caption_display,
29450                     style : {
29451                         textAlign : 'left',
29452                         fontSize : '16px',
29453                         lineHeight : '24px',
29454                         display : this.caption_display,
29455                         maxWidth : (this.align == 'center' ?  this.width : '100%' ) + ' !important',
29456                         margin: m,
29457                         width: this.align == 'center' ?  this.width : '100%' 
29458                     
29459                          
29460                     },
29461                     cls : this.cls.length > 0 ? (this.cls  + '-thumbnail' ) : '',
29462                     cn : [
29463                         {
29464                             tag: 'div',
29465                             style  : {
29466                                 marginTop : '16px',
29467                                 textAlign : 'left'
29468                             },
29469                             align: 'left',
29470                             cn : [
29471                                 {
29472                                     // we can not rely on yahoo syndication to use CSS elements - so have to use  '<i>' to encase stuff.
29473                                     tag : 'i',
29474                                     contenteditable : true,
29475                                     html : captionhtml
29476                                 }
29477                                 
29478                             ]
29479                         }
29480                         
29481                     ]
29482                     
29483                 }
29484             ]
29485         };
29486         return ret;
29487          
29488     },
29489     
29490     readElement : function(node)
29491     {
29492         // this should not really come from the link...
29493         this.video_url = this.getVal(node, 'div', 'src');
29494         this.cls = this.getVal(node, 'div', 'class');
29495         this.href = this.getVal(node, 'a', 'href');
29496         
29497         
29498         this.image_src = this.getVal(node, 'img', 'src');
29499          
29500         this.align = this.getVal(node, 'figure', 'align');
29501         var figcaption = this.getVal(node, 'figcaption', false);
29502         if (figcaption !== '') {
29503             this.caption = this.getVal(figcaption, 'i', 'html');
29504         }
29505         
29506
29507         this.caption_display = this.getVal(node, 'figcaption', 'data-display');
29508         //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
29509         this.width = this.getVal(node, true, 'data-width');
29510         //this.margin = this.getVal(node, 'figure', 'style', 'margin');
29511         
29512     },
29513     removeNode : function()
29514     {
29515         return this.node;
29516     }
29517     
29518   
29519    
29520      
29521     
29522     
29523     
29524     
29525 })
29526
29527  
29528
29529 /**
29530  * @class Roo.htmleditor.BlockTable
29531  * Block that manages a table
29532  * 
29533  * @constructor
29534  * Create a new Filter.
29535  * @param {Object} config Configuration options
29536  */
29537
29538 Roo.htmleditor.BlockTable = function(cfg)
29539 {
29540     if (cfg.node) {
29541         this.readElement(cfg.node);
29542         this.updateElement(cfg.node);
29543     }
29544     Roo.apply(this, cfg);
29545     if (!cfg.node) {
29546         this.rows = [];
29547         for(var r = 0; r < this.no_row; r++) {
29548             this.rows[r] = [];
29549             for(var c = 0; c < this.no_col; c++) {
29550                 this.rows[r][c] = this.emptyCell();
29551             }
29552         }
29553     }
29554     
29555     
29556 }
29557 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
29558  
29559     rows : false,
29560     no_col : 1,
29561     no_row : 1,
29562     
29563     
29564     width: '100%',
29565     
29566     // used by context menu
29567     friendly_name : 'Table',
29568     deleteTitle : 'Delete Table',
29569     // context menu is drawn once..
29570     
29571     contextMenu : function(toolbar)
29572     {
29573         
29574         var block = function() {
29575             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
29576         };
29577         
29578         
29579         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
29580         
29581         var syncValue = toolbar.editorcore.syncValue;
29582         
29583         var fields = {};
29584         
29585         return [
29586             {
29587                 xtype : 'TextItem',
29588                 text : "Width: ",
29589                 xns : rooui.Toolbar  //Boostrap?
29590             },
29591             {
29592                 xtype : 'ComboBox',
29593                 allowBlank : false,
29594                 displayField : 'val',
29595                 editable : true,
29596                 listWidth : 100,
29597                 triggerAction : 'all',
29598                 typeAhead : true,
29599                 valueField : 'val',
29600                 width : 100,
29601                 name : 'width',
29602                 listeners : {
29603                     select : function (combo, r, index)
29604                     {
29605                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29606                         var b = block();
29607                         b.width = r.get('val');
29608                         b.updateElement();
29609                         syncValue();
29610                         toolbar.editorcore.onEditorEvent();
29611                     }
29612                 },
29613                 xns : rooui.form,
29614                 store : {
29615                     xtype : 'SimpleStore',
29616                     data : [
29617                         ['100%'],
29618                         ['auto']
29619                     ],
29620                     fields : [ 'val'],
29621                     xns : Roo.data
29622                 }
29623             },
29624             // -------- Cols
29625             
29626             {
29627                 xtype : 'TextItem',
29628                 text : "Columns: ",
29629                 xns : rooui.Toolbar  //Boostrap?
29630             },
29631          
29632             {
29633                 xtype : 'Button',
29634                 text: '-',
29635                 listeners : {
29636                     click : function (_self, e)
29637                     {
29638                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29639                         block().removeColumn();
29640                         syncValue();
29641                         toolbar.editorcore.onEditorEvent();
29642                     }
29643                 },
29644                 xns : rooui.Toolbar
29645             },
29646             {
29647                 xtype : 'Button',
29648                 text: '+',
29649                 listeners : {
29650                     click : function (_self, e)
29651                     {
29652                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29653                         block().addColumn();
29654                         syncValue();
29655                         toolbar.editorcore.onEditorEvent();
29656                     }
29657                 },
29658                 xns : rooui.Toolbar
29659             },
29660             // -------- ROWS
29661             {
29662                 xtype : 'TextItem',
29663                 text : "Rows: ",
29664                 xns : rooui.Toolbar  //Boostrap?
29665             },
29666          
29667             {
29668                 xtype : 'Button',
29669                 text: '-',
29670                 listeners : {
29671                     click : function (_self, e)
29672                     {
29673                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
29674                         block().removeRow();
29675                         syncValue();
29676                         toolbar.editorcore.onEditorEvent();
29677                     }
29678                 },
29679                 xns : rooui.Toolbar
29680             },
29681             {
29682                 xtype : 'Button',
29683                 text: '+',
29684                 listeners : {
29685                     click : function (_self, e)
29686                     {
29687                         block().addRow();
29688                         syncValue();
29689                         toolbar.editorcore.onEditorEvent();
29690                     }
29691                 },
29692                 xns : rooui.Toolbar
29693             },
29694             // -------- ROWS
29695             {
29696                 xtype : 'Button',
29697                 text: 'Reset Column Widths',
29698                 listeners : {
29699                     
29700                     click : function (_self, e)
29701                     {
29702                         block().resetWidths();
29703                         syncValue();
29704                         toolbar.editorcore.onEditorEvent();
29705                     }
29706                 },
29707                 xns : rooui.Toolbar
29708             } 
29709             
29710             
29711             
29712         ];
29713         
29714     },
29715     
29716     
29717   /**
29718      * create a DomHelper friendly object - for use with
29719      * Roo.DomHelper.markup / overwrite / etc..
29720      * ?? should it be called with option to hide all editing features?
29721      */
29722     toObject : function()
29723     {
29724         
29725         var ret = {
29726             tag : 'table',
29727             contenteditable : 'false', // this stops cell selection from picking the table.
29728             'data-block' : 'Table',
29729             style : {
29730                 width:  this.width,
29731                 border : 'solid 1px #000', // ??? hard coded?
29732                 'border-collapse' : 'collapse' 
29733             },
29734             cn : [
29735                 { tag : 'tbody' , cn : [] }
29736             ]
29737         };
29738         
29739         // do we have a head = not really 
29740         var ncols = 0;
29741         Roo.each(this.rows, function( row ) {
29742             var tr = {
29743                 tag: 'tr',
29744                 style : {
29745                     margin: '6px',
29746                     border : 'solid 1px #000',
29747                     textAlign : 'left' 
29748                 },
29749                 cn : [ ]
29750             };
29751             
29752             ret.cn[0].cn.push(tr);
29753             // does the row have any properties? ?? height?
29754             var nc = 0;
29755             Roo.each(row, function( cell ) {
29756                 
29757                 var td = {
29758                     tag : 'td',
29759                     contenteditable :  'true',
29760                     'data-block' : 'Td',
29761                     html : cell.html,
29762                     style : cell.style
29763                 };
29764                 if (cell.colspan > 1) {
29765                     td.colspan = cell.colspan ;
29766                     nc += cell.colspan;
29767                 } else {
29768                     nc++;
29769                 }
29770                 if (cell.rowspan > 1) {
29771                     td.rowspan = cell.rowspan ;
29772                 }
29773                 
29774                 
29775                 // widths ?
29776                 tr.cn.push(td);
29777                     
29778                 
29779             }, this);
29780             ncols = Math.max(nc, ncols);
29781             
29782             
29783         }, this);
29784         // add the header row..
29785         
29786         ncols++;
29787          
29788         
29789         return ret;
29790          
29791     },
29792     
29793     readElement : function(node)
29794     {
29795         node  = node ? node : this.node ;
29796         this.width = this.getVal(node, true, 'style', 'width') || '100%';
29797         
29798         this.rows = [];
29799         this.no_row = 0;
29800         var trs = Array.from(node.rows);
29801         trs.forEach(function(tr) {
29802             var row =  [];
29803             this.rows.push(row);
29804             
29805             this.no_row++;
29806             var no_column = 0;
29807             Array.from(tr.cells).forEach(function(td) {
29808                 
29809                 var add = {
29810                     colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
29811                     rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
29812                     style : td.hasAttribute('style') ? td.getAttribute('style') : '',
29813                     html : td.innerHTML
29814                 };
29815                 no_column += add.colspan;
29816                      
29817                 
29818                 row.push(add);
29819                 
29820                 
29821             },this);
29822             this.no_col = Math.max(this.no_col, no_column);
29823             
29824             
29825         },this);
29826         
29827         
29828     },
29829     normalizeRows: function()
29830     {
29831         var ret= [];
29832         var rid = -1;
29833         this.rows.forEach(function(row) {
29834             rid++;
29835             ret[rid] = [];
29836             row = this.normalizeRow(row);
29837             var cid = 0;
29838             row.forEach(function(c) {
29839                 while (typeof(ret[rid][cid]) != 'undefined') {
29840                     cid++;
29841                 }
29842                 if (typeof(ret[rid]) == 'undefined') {
29843                     ret[rid] = [];
29844                 }
29845                 ret[rid][cid] = c;
29846                 c.row = rid;
29847                 c.col = cid;
29848                 if (c.rowspan < 2) {
29849                     return;
29850                 }
29851                 
29852                 for(var i = 1 ;i < c.rowspan; i++) {
29853                     if (typeof(ret[rid+i]) == 'undefined') {
29854                         ret[rid+i] = [];
29855                     }
29856                     ret[rid+i][cid] = c;
29857                 }
29858             });
29859         }, this);
29860         return ret;
29861     
29862     },
29863     
29864     normalizeRow: function(row)
29865     {
29866         var ret= [];
29867         row.forEach(function(c) {
29868             if (c.colspan < 2) {
29869                 ret.push(c);
29870                 return;
29871             }
29872             for(var i =0 ;i < c.colspan; i++) {
29873                 ret.push(c);
29874             }
29875         });
29876         return ret;
29877     
29878     },
29879     
29880     deleteColumn : function(sel)
29881     {
29882         if (!sel || sel.type != 'col') {
29883             return;
29884         }
29885         if (this.no_col < 2) {
29886             return;
29887         }
29888         
29889         this.rows.forEach(function(row) {
29890             var cols = this.normalizeRow(row);
29891             var col = cols[sel.col];
29892             if (col.colspan > 1) {
29893                 col.colspan --;
29894             } else {
29895                 row.remove(col);
29896             }
29897             
29898         }, this);
29899         this.no_col--;
29900         
29901     },
29902     removeColumn : function()
29903     {
29904         this.deleteColumn({
29905             type: 'col',
29906             col : this.no_col-1
29907         });
29908         this.updateElement();
29909     },
29910     
29911      
29912     addColumn : function()
29913     {
29914         
29915         this.rows.forEach(function(row) {
29916             row.push(this.emptyCell());
29917            
29918         }, this);
29919         this.updateElement();
29920     },
29921     
29922     deleteRow : function(sel)
29923     {
29924         if (!sel || sel.type != 'row') {
29925             return;
29926         }
29927         
29928         if (this.no_row < 2) {
29929             return;
29930         }
29931         
29932         var rows = this.normalizeRows();
29933         
29934         
29935         rows[sel.row].forEach(function(col) {
29936             if (col.rowspan > 1) {
29937                 col.rowspan--;
29938             } else {
29939                 col.remove = 1; // flage it as removed.
29940             }
29941             
29942         }, this);
29943         var newrows = [];
29944         this.rows.forEach(function(row) {
29945             newrow = [];
29946             row.forEach(function(c) {
29947                 if (typeof(c.remove) == 'undefined') {
29948                     newrow.push(c);
29949                 }
29950                 
29951             });
29952             if (newrow.length > 0) {
29953                 newrows.push(row);
29954             }
29955         });
29956         this.rows =  newrows;
29957         
29958         
29959         
29960         this.no_row--;
29961         this.updateElement();
29962         
29963     },
29964     removeRow : function()
29965     {
29966         this.deleteRow({
29967             type: 'row',
29968             row : this.no_row-1
29969         });
29970         
29971     },
29972     
29973      
29974     addRow : function()
29975     {
29976         
29977         var row = [];
29978         for (var i = 0; i < this.no_col; i++ ) {
29979             
29980             row.push(this.emptyCell());
29981            
29982         }
29983         this.rows.push(row);
29984         this.updateElement();
29985         
29986     },
29987      
29988     // the default cell object... at present...
29989     emptyCell : function() {
29990         return (new Roo.htmleditor.BlockTd({})).toObject();
29991         
29992      
29993     },
29994     
29995     removeNode : function()
29996     {
29997         return this.node;
29998     },
29999     
30000     
30001     
30002     resetWidths : function()
30003     {
30004         Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
30005             var nn = Roo.htmleditor.Block.factory(n);
30006             nn.width = '';
30007             nn.updateElement(n);
30008         });
30009     }
30010     
30011     
30012     
30013     
30014 })
30015
30016 /**
30017  *
30018  * editing a TD?
30019  *
30020  * since selections really work on the table cell, then editing really should work from there
30021  *
30022  * The original plan was to support merging etc... - but that may not be needed yet..
30023  *
30024  * So this simple version will support:
30025  *   add/remove cols
30026  *   adjust the width +/-
30027  *   reset the width...
30028  *   
30029  *
30030  */
30031
30032
30033  
30034
30035 /**
30036  * @class Roo.htmleditor.BlockTable
30037  * Block that manages a table
30038  * 
30039  * @constructor
30040  * Create a new Filter.
30041  * @param {Object} config Configuration options
30042  */
30043
30044 Roo.htmleditor.BlockTd = function(cfg)
30045 {
30046     if (cfg.node) {
30047         this.readElement(cfg.node);
30048         this.updateElement(cfg.node);
30049     }
30050     Roo.apply(this, cfg);
30051      
30052     
30053     
30054 }
30055 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
30056  
30057     node : false,
30058     
30059     width: '',
30060     textAlign : 'left',
30061     valign : 'top',
30062     
30063     colspan : 1,
30064     rowspan : 1,
30065     
30066     
30067     // used by context menu
30068     friendly_name : 'Table Cell',
30069     deleteTitle : false, // use our customer delete
30070     
30071     // context menu is drawn once..
30072     
30073     contextMenu : function(toolbar)
30074     {
30075         
30076         var cell = function() {
30077             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
30078         };
30079         
30080         var table = function() {
30081             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
30082         };
30083         
30084         var lr = false;
30085         var saveSel = function()
30086         {
30087             lr = toolbar.editorcore.getSelection().getRangeAt(0);
30088         }
30089         var restoreSel = function()
30090         {
30091             if (lr) {
30092                 (function() {
30093                     toolbar.editorcore.focus();
30094                     var cr = toolbar.editorcore.getSelection();
30095                     cr.removeAllRanges();
30096                     cr.addRange(lr);
30097                     toolbar.editorcore.onEditorEvent();
30098                 }).defer(10, this);
30099                 
30100                 
30101             }
30102         }
30103         
30104         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
30105         
30106         var syncValue = toolbar.editorcore.syncValue;
30107         
30108         var fields = {};
30109         
30110         return [
30111             {
30112                 xtype : 'Button',
30113                 text : 'Edit Table',
30114                 listeners : {
30115                     click : function() {
30116                         var t = toolbar.tb.selectedNode.closest('table');
30117                         toolbar.editorcore.selectNode(t);
30118                         toolbar.editorcore.onEditorEvent();                        
30119                     }
30120                 }
30121                 
30122             },
30123               
30124            
30125              
30126             {
30127                 xtype : 'TextItem',
30128                 text : "Column Width: ",
30129                  xns : rooui.Toolbar 
30130                
30131             },
30132             {
30133                 xtype : 'Button',
30134                 text: '-',
30135                 listeners : {
30136                     click : function (_self, e)
30137                     {
30138                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30139                         cell().shrinkColumn();
30140                         syncValue();
30141                          toolbar.editorcore.onEditorEvent();
30142                     }
30143                 },
30144                 xns : rooui.Toolbar
30145             },
30146             {
30147                 xtype : 'Button',
30148                 text: '+',
30149                 listeners : {
30150                     click : function (_self, e)
30151                     {
30152                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30153                         cell().growColumn();
30154                         syncValue();
30155                         toolbar.editorcore.onEditorEvent();
30156                     }
30157                 },
30158                 xns : rooui.Toolbar
30159             },
30160             
30161             {
30162                 xtype : 'TextItem',
30163                 text : "Vertical Align: ",
30164                 xns : rooui.Toolbar  //Boostrap?
30165             },
30166             {
30167                 xtype : 'ComboBox',
30168                 allowBlank : false,
30169                 displayField : 'val',
30170                 editable : true,
30171                 listWidth : 100,
30172                 triggerAction : 'all',
30173                 typeAhead : true,
30174                 valueField : 'val',
30175                 width : 100,
30176                 name : 'valign',
30177                 listeners : {
30178                     select : function (combo, r, index)
30179                     {
30180                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30181                         var b = cell();
30182                         b.valign = r.get('val');
30183                         b.updateElement();
30184                         syncValue();
30185                         toolbar.editorcore.onEditorEvent();
30186                     }
30187                 },
30188                 xns : rooui.form,
30189                 store : {
30190                     xtype : 'SimpleStore',
30191                     data : [
30192                         ['top'],
30193                         ['middle'],
30194                         ['bottom'] // there are afew more... 
30195                     ],
30196                     fields : [ 'val'],
30197                     xns : Roo.data
30198                 }
30199             },
30200             
30201             {
30202                 xtype : 'TextItem',
30203                 text : "Merge Cells: ",
30204                  xns : rooui.Toolbar 
30205                
30206             },
30207             
30208             
30209             {
30210                 xtype : 'Button',
30211                 text: 'Right',
30212                 listeners : {
30213                     click : function (_self, e)
30214                     {
30215                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30216                         cell().mergeRight();
30217                         //block().growColumn();
30218                         syncValue();
30219                         toolbar.editorcore.onEditorEvent();
30220                     }
30221                 },
30222                 xns : rooui.Toolbar
30223             },
30224              
30225             {
30226                 xtype : 'Button',
30227                 text: 'Below',
30228                 listeners : {
30229                     click : function (_self, e)
30230                     {
30231                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30232                         cell().mergeBelow();
30233                         //block().growColumn();
30234                         syncValue();
30235                         toolbar.editorcore.onEditorEvent();
30236                     }
30237                 },
30238                 xns : rooui.Toolbar
30239             },
30240             {
30241                 xtype : 'TextItem',
30242                 text : "| ",
30243                  xns : rooui.Toolbar 
30244                
30245             },
30246             
30247             {
30248                 xtype : 'Button',
30249                 text: 'Split',
30250                 listeners : {
30251                     click : function (_self, e)
30252                     {
30253                         //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30254                         cell().split();
30255                         syncValue();
30256                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
30257                         toolbar.editorcore.onEditorEvent();
30258                                              
30259                     }
30260                 },
30261                 xns : rooui.Toolbar
30262             },
30263             {
30264                 xtype : 'Fill',
30265                 xns : rooui.Toolbar 
30266                
30267             },
30268         
30269           
30270             {
30271                 xtype : 'Button',
30272                 text: 'Delete',
30273                  
30274                 xns : rooui.Toolbar,
30275                 menu : {
30276                     xtype : 'Menu',
30277                     xns : rooui.menu,
30278                     items : [
30279                         {
30280                             xtype : 'Item',
30281                             html: 'Column',
30282                             listeners : {
30283                                 click : function (_self, e)
30284                                 {
30285                                     var t = table();
30286                                     
30287                                     cell().deleteColumn();
30288                                     syncValue();
30289                                     toolbar.editorcore.selectNode(t.node);
30290                                     toolbar.editorcore.onEditorEvent();   
30291                                 }
30292                             },
30293                             xns : rooui.menu
30294                         },
30295                         {
30296                             xtype : 'Item',
30297                             html: 'Row',
30298                             listeners : {
30299                                 click : function (_self, e)
30300                                 {
30301                                     var t = table();
30302                                     cell().deleteRow();
30303                                     syncValue();
30304                                     
30305                                     toolbar.editorcore.selectNode(t.node);
30306                                     toolbar.editorcore.onEditorEvent();   
30307                                                          
30308                                 }
30309                             },
30310                             xns : rooui.menu
30311                         },
30312                        {
30313                             xtype : 'Separator',
30314                             xns : rooui.menu
30315                         },
30316                         {
30317                             xtype : 'Item',
30318                             html: 'Table',
30319                             listeners : {
30320                                 click : function (_self, e)
30321                                 {
30322                                     var t = table();
30323                                     var nn = t.node.nextSibling || t.node.previousSibling;
30324                                     t.node.parentNode.removeChild(t.node);
30325                                     if (nn) { 
30326                                         toolbar.editorcore.selectNode(nn, true);
30327                                     }
30328                                     toolbar.editorcore.onEditorEvent();   
30329                                                          
30330                                 }
30331                             },
30332                             xns : rooui.menu
30333                         }
30334                     ]
30335                 }
30336             }
30337             
30338             // align... << fixme
30339             
30340         ];
30341         
30342     },
30343     
30344     
30345   /**
30346      * create a DomHelper friendly object - for use with
30347      * Roo.DomHelper.markup / overwrite / etc..
30348      * ?? should it be called with option to hide all editing features?
30349      */
30350  /**
30351      * create a DomHelper friendly object - for use with
30352      * Roo.DomHelper.markup / overwrite / etc..
30353      * ?? should it be called with option to hide all editing features?
30354      */
30355     toObject : function()
30356     {
30357         var ret = {
30358             tag : 'td',
30359             contenteditable : 'true', // this stops cell selection from picking the table.
30360             'data-block' : 'Td',
30361             valign : this.valign,
30362             style : {  
30363                 'text-align' :  this.textAlign,
30364                 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
30365                 'border-collapse' : 'collapse',
30366                 padding : '6px', // 8 for desktop / 4 for mobile
30367                 'vertical-align': this.valign
30368             },
30369             html : this.html
30370         };
30371         if (this.width != '') {
30372             ret.width = this.width;
30373             ret.style.width = this.width;
30374         }
30375         
30376         
30377         if (this.colspan > 1) {
30378             ret.colspan = this.colspan ;
30379         } 
30380         if (this.rowspan > 1) {
30381             ret.rowspan = this.rowspan ;
30382         }
30383         
30384            
30385         
30386         return ret;
30387          
30388     },
30389     
30390     readElement : function(node)
30391     {
30392         node  = node ? node : this.node ;
30393         this.width = node.style.width;
30394         this.colspan = Math.max(1,1*node.getAttribute('colspan'));
30395         this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
30396         this.html = node.innerHTML;
30397         if (node.style.textAlign != '') {
30398             this.textAlign = node.style.textAlign;
30399         }
30400         
30401         
30402     },
30403      
30404     // the default cell object... at present...
30405     emptyCell : function() {
30406         return {
30407             colspan :  1,
30408             rowspan :  1,
30409             textAlign : 'left',
30410             html : "&nbsp;" // is this going to be editable now?
30411         };
30412      
30413     },
30414     
30415     removeNode : function()
30416     {
30417         return this.node.closest('table');
30418          
30419     },
30420     
30421     cellData : false,
30422     
30423     colWidths : false,
30424     
30425     toTableArray  : function()
30426     {
30427         var ret = [];
30428         var tab = this.node.closest('tr').closest('table');
30429         Array.from(tab.rows).forEach(function(r, ri){
30430             ret[ri] = [];
30431         });
30432         var rn = 0;
30433         this.colWidths = [];
30434         var all_auto = true;
30435         Array.from(tab.rows).forEach(function(r, ri){
30436             
30437             var cn = 0;
30438             Array.from(r.cells).forEach(function(ce, ci){
30439                 var c =  {
30440                     cell : ce,
30441                     row : rn,
30442                     col: cn,
30443                     colspan : ce.colSpan,
30444                     rowspan : ce.rowSpan
30445                 };
30446                 if (ce.isEqualNode(this.node)) {
30447                     this.cellData = c;
30448                 }
30449                 // if we have been filled up by a row?
30450                 if (typeof(ret[rn][cn]) != 'undefined') {
30451                     while(typeof(ret[rn][cn]) != 'undefined') {
30452                         cn++;
30453                     }
30454                     c.col = cn;
30455                 }
30456                 
30457                 if (typeof(this.colWidths[cn]) == 'undefined' && c.colspan < 2) {
30458                     this.colWidths[cn] =   ce.style.width;
30459                     if (this.colWidths[cn] != '') {
30460                         all_auto = false;
30461                     }
30462                 }
30463                 
30464                 
30465                 if (c.colspan < 2 && c.rowspan < 2 ) {
30466                     ret[rn][cn] = c;
30467                     cn++;
30468                     return;
30469                 }
30470                 for(var j = 0; j < c.rowspan; j++) {
30471                     if (typeof(ret[rn+j]) == 'undefined') {
30472                         continue; // we have a problem..
30473                     }
30474                     ret[rn+j][cn] = c;
30475                     for(var i = 0; i < c.colspan; i++) {
30476                         ret[rn+j][cn+i] = c;
30477                     }
30478                 }
30479                 
30480                 cn += c.colspan;
30481             }, this);
30482             rn++;
30483         }, this);
30484         
30485         // initalize widths.?
30486         // either all widths or no widths..
30487         if (all_auto) {
30488             this.colWidths[0] = false; // no widths flag.
30489         }
30490         
30491         
30492         return ret;
30493         
30494     },
30495     
30496     
30497     
30498     
30499     mergeRight: function()
30500     {
30501          
30502         // get the contents of the next cell along..
30503         var tr = this.node.closest('tr');
30504         var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
30505         if (i >= tr.childNodes.length - 1) {
30506             return; // no cells on right to merge with.
30507         }
30508         var table = this.toTableArray();
30509         
30510         if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
30511             return; // nothing right?
30512         }
30513         var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
30514         // right cell - must be same rowspan and on the same row.
30515         if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
30516             return; // right hand side is not same rowspan.
30517         }
30518         
30519         
30520         
30521         this.node.innerHTML += ' ' + rc.cell.innerHTML;
30522         tr.removeChild(rc.cell);
30523         this.colspan += rc.colspan;
30524         this.node.setAttribute('colspan', this.colspan);
30525
30526         var table = this.toTableArray();
30527         this.normalizeWidths(table);
30528         this.updateWidths(table);
30529     },
30530     
30531     
30532     mergeBelow : function()
30533     {
30534         var table = this.toTableArray();
30535         if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
30536             return; // no row below
30537         }
30538         if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
30539             return; // nothing right?
30540         }
30541         var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
30542         
30543         if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
30544             return; // right hand side is not same rowspan.
30545         }
30546         this.node.innerHTML =  this.node.innerHTML + rc.cell.innerHTML ;
30547         rc.cell.parentNode.removeChild(rc.cell);
30548         this.rowspan += rc.rowspan;
30549         this.node.setAttribute('rowspan', this.rowspan);
30550     },
30551     
30552     split: function()
30553     {
30554         if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
30555             return;
30556         }
30557         var table = this.toTableArray();
30558         var cd = this.cellData;
30559         this.rowspan = 1;
30560         this.colspan = 1;
30561         
30562         for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
30563              
30564             
30565             for(var c = cd.col; c < cd.col + cd.colspan; c++) {
30566                 if (r == cd.row && c == cd.col) {
30567                     this.node.removeAttribute('rowspan');
30568                     this.node.removeAttribute('colspan');
30569                 }
30570                  
30571                 var ntd = this.node.cloneNode(); // which col/row should be 0..
30572                 ntd.removeAttribute('id'); 
30573                 ntd.style.width  = this.colWidths[c];
30574                 ntd.innerHTML = '';
30575                 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1   };
30576             }
30577             
30578         }
30579         this.redrawAllCells(table);
30580         
30581     },
30582     
30583     
30584     
30585     redrawAllCells: function(table)
30586     {
30587         
30588          
30589         var tab = this.node.closest('tr').closest('table');
30590         var ctr = tab.rows[0].parentNode;
30591         Array.from(tab.rows).forEach(function(r, ri){
30592             
30593             Array.from(r.cells).forEach(function(ce, ci){
30594                 ce.parentNode.removeChild(ce);
30595             });
30596             r.parentNode.removeChild(r);
30597         });
30598         for(var r = 0 ; r < table.length; r++) {
30599             var re = tab.rows[r];
30600             
30601             var re = tab.ownerDocument.createElement('tr');
30602             ctr.appendChild(re);
30603             for(var c = 0 ; c < table[r].length; c++) {
30604                 if (table[r][c].cell === false) {
30605                     continue;
30606                 }
30607                 
30608                 re.appendChild(table[r][c].cell);
30609                  
30610                 table[r][c].cell = false;
30611             }
30612         }
30613         
30614     },
30615     updateWidths : function(table)
30616     {
30617         for(var r = 0 ; r < table.length; r++) {
30618            
30619             for(var c = 0 ; c < table[r].length; c++) {
30620                 if (table[r][c].cell === false) {
30621                     continue;
30622                 }
30623                 
30624                 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
30625                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
30626                     el.width = Math.floor(this.colWidths[c])  +'%';
30627                     el.updateElement(el.node);
30628                 }
30629                 if (this.colWidths[0] != false && table[r][c].colspan > 1) {
30630                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
30631                     var width = 0;
30632                     for(var i = 0; i < table[r][c].colspan; i ++) {
30633                         width += Math.floor(this.colWidths[c + i]);
30634                     }
30635                     el.width = width  +'%';
30636                     el.updateElement(el.node);
30637                 }
30638                 table[r][c].cell = false; // done
30639             }
30640         }
30641     },
30642     normalizeWidths : function(table)
30643     {
30644         if (this.colWidths[0] === false) {
30645             var nw = 100.0 / this.colWidths.length;
30646             this.colWidths.forEach(function(w,i) {
30647                 this.colWidths[i] = nw;
30648             },this);
30649             return;
30650         }
30651     
30652         var t = 0, missing = [];
30653         
30654         this.colWidths.forEach(function(w,i) {
30655             //if you mix % and
30656             this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
30657             var add =  this.colWidths[i];
30658             if (add > 0) {
30659                 t+=add;
30660                 return;
30661             }
30662             missing.push(i);
30663             
30664             
30665         },this);
30666         var nc = this.colWidths.length;
30667         if (missing.length) {
30668             var mult = (nc - missing.length) / (1.0 * nc);
30669             var t = mult * t;
30670             var ew = (100 -t) / (1.0 * missing.length);
30671             this.colWidths.forEach(function(w,i) {
30672                 if (w > 0) {
30673                     this.colWidths[i] = w * mult;
30674                     return;
30675                 }
30676                 
30677                 this.colWidths[i] = ew;
30678             }, this);
30679             // have to make up numbers..
30680              
30681         }
30682         // now we should have all the widths..
30683         
30684     
30685     },
30686     
30687     shrinkColumn : function()
30688     {
30689         var table = this.toTableArray();
30690         this.normalizeWidths(table);
30691         var col = this.cellData.col;
30692         var nw = this.colWidths[col] * 0.8;
30693         if (nw < 5) {
30694             return;
30695         }
30696         var otherAdd = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
30697         this.colWidths.forEach(function(w,i) {
30698             if (i == col) {
30699                  this.colWidths[i] = nw;
30700                 return;
30701             }
30702             this.colWidths[i] += otherAdd
30703         }, this);
30704         this.updateWidths(table);
30705          
30706     },
30707     growColumn : function()
30708     {
30709         var table = this.toTableArray();
30710         this.normalizeWidths(table);
30711         var col = this.cellData.col;
30712         var nw = this.colWidths[col] * 1.2;
30713         if (nw > 90) {
30714             return;
30715         }
30716         var otherSub = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
30717         this.colWidths.forEach(function(w,i) {
30718             if (i == col) {
30719                 this.colWidths[i] = nw;
30720                 return;
30721             }
30722             this.colWidths[i] -= otherSub
30723         }, this);
30724         this.updateWidths(table);
30725          
30726     },
30727     deleteRow : function()
30728     {
30729         // delete this rows 'tr'
30730         // if any of the cells in this row have a rowspan > 1 && row!= this row..
30731         // then reduce the rowspan.
30732         var table = this.toTableArray();
30733         // this.cellData.row;
30734         for (var i =0;i< table[this.cellData.row].length ; i++) {
30735             var c = table[this.cellData.row][i];
30736             if (c.row != this.cellData.row) {
30737                 
30738                 c.rowspan--;
30739                 c.cell.setAttribute('rowspan', c.rowspan);
30740                 continue;
30741             }
30742             if (c.rowspan > 1) {
30743                 c.rowspan--;
30744                 c.cell.setAttribute('rowspan', c.rowspan);
30745             }
30746         }
30747         table.splice(this.cellData.row,1);
30748         this.redrawAllCells(table);
30749         
30750     },
30751     deleteColumn : function()
30752     {
30753         var table = this.toTableArray();
30754         
30755         for (var i =0;i< table.length ; i++) {
30756             var c = table[i][this.cellData.col];
30757             if (c.col != this.cellData.col) {
30758                 table[i][this.cellData.col].colspan--;
30759             } else if (c.colspan > 1) {
30760                 c.colspan--;
30761                 c.cell.setAttribute('colspan', c.colspan);
30762             }
30763             table[i].splice(this.cellData.col,1);
30764         }
30765         
30766         this.redrawAllCells(table);
30767     }
30768     
30769     
30770     
30771     
30772 })
30773
30774 //<script type="text/javascript">
30775
30776 /*
30777  * Based  Ext JS Library 1.1.1
30778  * Copyright(c) 2006-2007, Ext JS, LLC.
30779  * LGPL
30780  *
30781  */
30782  
30783 /**
30784  * @class Roo.HtmlEditorCore
30785  * @extends Roo.Component
30786  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
30787  *
30788  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
30789  */
30790
30791 Roo.HtmlEditorCore = function(config){
30792     
30793     
30794     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
30795     
30796     
30797     this.addEvents({
30798         /**
30799          * @event initialize
30800          * Fires when the editor is fully initialized (including the iframe)
30801          * @param {Roo.HtmlEditorCore} this
30802          */
30803         initialize: true,
30804         /**
30805          * @event activate
30806          * Fires when the editor is first receives the focus. Any insertion must wait
30807          * until after this event.
30808          * @param {Roo.HtmlEditorCore} this
30809          */
30810         activate: true,
30811          /**
30812          * @event beforesync
30813          * Fires before the textarea is updated with content from the editor iframe. Return false
30814          * to cancel the sync.
30815          * @param {Roo.HtmlEditorCore} this
30816          * @param {String} html
30817          */
30818         beforesync: true,
30819          /**
30820          * @event beforepush
30821          * Fires before the iframe editor is updated with content from the textarea. Return false
30822          * to cancel the push.
30823          * @param {Roo.HtmlEditorCore} this
30824          * @param {String} html
30825          */
30826         beforepush: true,
30827          /**
30828          * @event sync
30829          * Fires when the textarea is updated with content from the editor iframe.
30830          * @param {Roo.HtmlEditorCore} this
30831          * @param {String} html
30832          */
30833         sync: true,
30834          /**
30835          * @event push
30836          * Fires when the iframe editor is updated with content from the textarea.
30837          * @param {Roo.HtmlEditorCore} this
30838          * @param {String} html
30839          */
30840         push: true,
30841         
30842         /**
30843          * @event editorevent
30844          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
30845          * @param {Roo.HtmlEditorCore} this
30846          */
30847         editorevent: true 
30848          
30849         
30850     });
30851     
30852     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
30853     
30854     // defaults : white / black...
30855     this.applyBlacklists();
30856     
30857     
30858     
30859 };
30860
30861
30862 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
30863
30864
30865      /**
30866      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
30867      */
30868     
30869     owner : false,
30870     
30871      /**
30872      * @cfg {String} css styling for resizing. (used on bootstrap only)
30873      */
30874     resize : false,
30875      /**
30876      * @cfg {Number} height (in pixels)
30877      */   
30878     height: 300,
30879    /**
30880      * @cfg {Number} width (in pixels)
30881      */   
30882     width: 500,
30883      /**
30884      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
30885      *         if you are doing an email editor, this probably needs disabling, it's designed
30886      */
30887     autoClean: true,
30888     
30889     /**
30890      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
30891      */
30892     enableBlocks : true,
30893     /**
30894      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
30895      * 
30896      */
30897     stylesheets: false,
30898      /**
30899      * @cfg {String} language default en - language of text (usefull for rtl languages)
30900      * 
30901      */
30902     language: 'en',
30903     
30904     /**
30905      * @cfg {boolean} allowComments - default false - allow comments in HTML source
30906      *          - by default they are stripped - if you are editing email you may need this.
30907      */
30908     allowComments: false,
30909     // id of frame..
30910     frameId: false,
30911     
30912     // private properties
30913     validationEvent : false,
30914     deferHeight: true,
30915     initialized : false,
30916     activated : false,
30917     sourceEditMode : false,
30918     onFocus : Roo.emptyFn,
30919     iframePad:3,
30920     hideMode:'offsets',
30921     
30922     clearUp: true,
30923     
30924     // blacklist + whitelisted elements..
30925     black: false,
30926     white: false,
30927      
30928     bodyCls : '',
30929
30930     
30931     undoManager : false,
30932     /**
30933      * Protected method that will not generally be called directly. It
30934      * is called when the editor initializes the iframe with HTML contents. Override this method if you
30935      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
30936      */
30937     getDocMarkup : function(){
30938         // body styles..
30939         var st = '';
30940         
30941         // inherit styels from page...?? 
30942         if (this.stylesheets === false) {
30943             
30944             Roo.get(document.head).select('style').each(function(node) {
30945                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
30946             });
30947             
30948             Roo.get(document.head).select('link').each(function(node) { 
30949                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
30950             });
30951             
30952         } else if (!this.stylesheets.length) {
30953                 // simple..
30954                 st = '<style type="text/css">' +
30955                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
30956                    '</style>';
30957         } else {
30958             for (var i in this.stylesheets) {
30959                 if (typeof(this.stylesheets[i]) != 'string') {
30960                     continue;
30961                 }
30962                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
30963             }
30964             
30965         }
30966         
30967         st +=  '<style type="text/css">' +
30968             'IMG { cursor: pointer } ' +
30969         '</style>';
30970         
30971         st += '<meta name="google" content="notranslate">';
30972         
30973         var cls = 'notranslate roo-htmleditor-body';
30974         
30975         if(this.bodyCls.length){
30976             cls += ' ' + this.bodyCls;
30977         }
30978         
30979         return '<html  class="notranslate" translate="no"><head>' + st  +
30980             //<style type="text/css">' +
30981             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
30982             //'</style>' +
30983             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
30984     },
30985
30986     // private
30987     onRender : function(ct, position)
30988     {
30989         var _t = this;
30990         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
30991         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
30992         
30993         
30994         this.el.dom.style.border = '0 none';
30995         this.el.dom.setAttribute('tabIndex', -1);
30996         this.el.addClass('x-hidden hide');
30997         
30998         
30999         
31000         if(Roo.isIE){ // fix IE 1px bogus margin
31001             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
31002         }
31003        
31004         
31005         this.frameId = Roo.id();
31006         
31007         var ifcfg = {
31008             tag: 'iframe',
31009             cls: 'form-control', // bootstrap..
31010             id: this.frameId,
31011             name: this.frameId,
31012             frameBorder : 'no',
31013             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
31014         };
31015         if (this.resize) {
31016             ifcfg.style = { resize : this.resize };
31017         }
31018         
31019         var iframe = this.owner.wrap.createChild(ifcfg, this.el); 
31020         
31021         
31022         this.iframe = iframe.dom;
31023
31024         this.assignDocWin();
31025         
31026         this.doc.designMode = 'on';
31027        
31028         this.doc.open();
31029         this.doc.write(this.getDocMarkup());
31030         this.doc.close();
31031
31032         
31033         var task = { // must defer to wait for browser to be ready
31034             run : function(){
31035                 //console.log("run task?" + this.doc.readyState);
31036                 this.assignDocWin();
31037                 if(this.doc.body || this.doc.readyState == 'complete'){
31038                     try {
31039                         this.doc.designMode="on";
31040                         
31041                     } catch (e) {
31042                         return;
31043                     }
31044                     Roo.TaskMgr.stop(task);
31045                     this.initEditor.defer(10, this);
31046                 }
31047             },
31048             interval : 10,
31049             duration: 10000,
31050             scope: this
31051         };
31052         Roo.TaskMgr.start(task);
31053
31054     },
31055
31056     // private
31057     onResize : function(w, h)
31058     {
31059          Roo.log('resize: ' +w + ',' + h );
31060         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
31061         if(!this.iframe){
31062             return;
31063         }
31064         if(typeof w == 'number'){
31065             
31066             this.iframe.style.width = w + 'px';
31067         }
31068         if(typeof h == 'number'){
31069             
31070             this.iframe.style.height = h + 'px';
31071             if(this.doc){
31072                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
31073             }
31074         }
31075         
31076     },
31077
31078     /**
31079      * Toggles the editor between standard and source edit mode.
31080      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
31081      */
31082     toggleSourceEdit : function(sourceEditMode){
31083         
31084         this.sourceEditMode = sourceEditMode === true;
31085         
31086         if(this.sourceEditMode){
31087  
31088             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
31089             
31090         }else{
31091             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
31092             //this.iframe.className = '';
31093             this.deferFocus();
31094         }
31095         //this.setSize(this.owner.wrap.getSize());
31096         //this.fireEvent('editmodechange', this, this.sourceEditMode);
31097     },
31098
31099     
31100   
31101
31102     /**
31103      * Protected method that will not generally be called directly. If you need/want
31104      * custom HTML cleanup, this is the method you should override.
31105      * @param {String} html The HTML to be cleaned
31106      * return {String} The cleaned HTML
31107      */
31108     cleanHtml : function(html)
31109     {
31110         html = String(html);
31111         if(html.length > 5){
31112             if(Roo.isSafari){ // strip safari nonsense
31113                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
31114             }
31115         }
31116         if(html == '&nbsp;'){
31117             html = '';
31118         }
31119         return html;
31120     },
31121
31122     /**
31123      * HTML Editor -> Textarea
31124      * Protected method that will not generally be called directly. Syncs the contents
31125      * of the editor iframe with the textarea.
31126      */
31127     syncValue : function()
31128     {
31129         //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
31130         if(this.initialized){
31131             
31132             if (this.undoManager) {
31133                 this.undoManager.addEvent();
31134             }
31135
31136             
31137             var bd = (this.doc.body || this.doc.documentElement);
31138            
31139             
31140             var sel = this.win.getSelection();
31141             
31142             var div = document.createElement('div');
31143             div.innerHTML = bd.innerHTML;
31144             var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
31145             if (gtx.length > 0) {
31146                 var rm = gtx.item(0).parentNode;
31147                 rm.parentNode.removeChild(rm);
31148             }
31149             
31150            
31151             if (this.enableBlocks) {
31152                 new Roo.htmleditor.FilterBlock({ node : div });
31153             }
31154             
31155             var html = div.innerHTML;
31156             
31157             //?? tidy?
31158             if (this.autoClean) {
31159                 
31160                 new Roo.htmleditor.FilterAttributes({
31161                     node : div,
31162                     attrib_white : [
31163                             'href',
31164                             'src',
31165                             'name',
31166                             'align',
31167                             'colspan',
31168                             'rowspan',
31169                             'data-display',
31170                             'data-width',
31171                             'start' ,
31172                             'style',
31173                             // youtube embed.
31174                             'class',
31175                             'allowfullscreen',
31176                             'frameborder',
31177                             'width',
31178                             'height',
31179                             'alt'
31180                             ],
31181                     attrib_clean : ['href', 'src' ] 
31182                 });
31183                 
31184                 var tidy = new Roo.htmleditor.TidySerializer({
31185                     inner:  true
31186                 });
31187                 html  = tidy.serialize(div);
31188                 
31189             }
31190             
31191             
31192             if(Roo.isSafari){
31193                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
31194                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
31195                 if(m && m[1]){
31196                     html = '<div style="'+m[0]+'">' + html + '</div>';
31197                 }
31198             }
31199             html = this.cleanHtml(html);
31200             // fix up the special chars.. normaly like back quotes in word...
31201             // however we do not want to do this with chinese..
31202             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
31203                 
31204                 var cc = match.charCodeAt();
31205
31206                 // Get the character value, handling surrogate pairs
31207                 if (match.length == 2) {
31208                     // It's a surrogate pair, calculate the Unicode code point
31209                     var high = match.charCodeAt(0) - 0xD800;
31210                     var low  = match.charCodeAt(1) - 0xDC00;
31211                     cc = (high * 0x400) + low + 0x10000;
31212                 }  else if (
31213                     (cc >= 0x4E00 && cc < 0xA000 ) ||
31214                     (cc >= 0x3400 && cc < 0x4E00 ) ||
31215                     (cc >= 0xf900 && cc < 0xfb00 )
31216                 ) {
31217                         return match;
31218                 }  
31219          
31220                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
31221                 return "&#" + cc + ";";
31222                 
31223                 
31224             });
31225             
31226             
31227              
31228             if(this.owner.fireEvent('beforesync', this, html) !== false){
31229                 this.el.dom.value = html;
31230                 this.owner.fireEvent('sync', this, html);
31231             }
31232         }
31233     },
31234
31235     /**
31236      * TEXTAREA -> EDITABLE
31237      * Protected method that will not generally be called directly. Pushes the value of the textarea
31238      * into the iframe editor.
31239      */
31240     pushValue : function()
31241     {
31242         //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
31243         if(this.initialized){
31244             var v = this.el.dom.value.trim();
31245             
31246             
31247             if(this.owner.fireEvent('beforepush', this, v) !== false){
31248                 var d = (this.doc.body || this.doc.documentElement);
31249                 d.innerHTML = v;
31250                  
31251                 this.el.dom.value = d.innerHTML;
31252                 this.owner.fireEvent('push', this, v);
31253             }
31254             if (this.autoClean) {
31255                 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
31256                 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
31257             }
31258             if (this.enableBlocks) {
31259                 Roo.htmleditor.Block.initAll(this.doc.body);
31260             }
31261             
31262             this.updateLanguage();
31263             
31264             var lc = this.doc.body.lastChild;
31265             if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
31266                 // add an extra line at the end.
31267                 this.doc.body.appendChild(this.doc.createElement('br'));
31268             }
31269             
31270             
31271         }
31272     },
31273
31274     // private
31275     deferFocus : function(){
31276         this.focus.defer(10, this);
31277     },
31278
31279     // doc'ed in Field
31280     focus : function(){
31281         if(this.win && !this.sourceEditMode){
31282             this.win.focus();
31283         }else{
31284             this.el.focus();
31285         }
31286     },
31287     
31288     assignDocWin: function()
31289     {
31290         var iframe = this.iframe;
31291         
31292          if(Roo.isIE){
31293             this.doc = iframe.contentWindow.document;
31294             this.win = iframe.contentWindow;
31295         } else {
31296 //            if (!Roo.get(this.frameId)) {
31297 //                return;
31298 //            }
31299 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
31300 //            this.win = Roo.get(this.frameId).dom.contentWindow;
31301             
31302             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
31303                 return;
31304             }
31305             
31306             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
31307             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
31308         }
31309     },
31310     
31311     // private
31312     initEditor : function(){
31313         //console.log("INIT EDITOR");
31314         this.assignDocWin();
31315         
31316         
31317         
31318         this.doc.designMode="on";
31319         this.doc.open();
31320         this.doc.write(this.getDocMarkup());
31321         this.doc.close();
31322         
31323         var dbody = (this.doc.body || this.doc.documentElement);
31324         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
31325         // this copies styles from the containing element into thsi one..
31326         // not sure why we need all of this..
31327         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
31328         
31329         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
31330         //ss['background-attachment'] = 'fixed'; // w3c
31331         dbody.bgProperties = 'fixed'; // ie
31332         dbody.setAttribute("translate", "no");
31333         
31334         //Roo.DomHelper.applyStyles(dbody, ss);
31335         Roo.EventManager.on(this.doc, {
31336              
31337             'mouseup': this.onEditorEvent,
31338             'dblclick': this.onEditorEvent,
31339             'click': this.onEditorEvent,
31340             'keyup': this.onEditorEvent,
31341             
31342             buffer:100,
31343             scope: this
31344         });
31345         Roo.EventManager.on(this.doc, {
31346             'paste': this.onPasteEvent,
31347             scope : this
31348         });
31349         if(Roo.isGecko){
31350             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
31351         }
31352         //??? needed???
31353         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
31354             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
31355         }
31356         this.initialized = true;
31357
31358         
31359         // initialize special key events - enter
31360         new Roo.htmleditor.KeyEnter({core : this});
31361         
31362          
31363         
31364         this.owner.fireEvent('initialize', this);
31365         this.pushValue();
31366     },
31367     // this is to prevent a href clicks resulting in a redirect?
31368    
31369     onPasteEvent : function(e,v)
31370     {
31371         // I think we better assume paste is going to be a dirty load of rubish from word..
31372         
31373         // even pasting into a 'email version' of this widget will have to clean up that mess.
31374         var cd = (e.browserEvent.clipboardData || window.clipboardData);
31375         
31376         // check what type of paste - if it's an image, then handle it differently.
31377         if (cd.files && cd.files.length > 0) {
31378             // pasting images?
31379             var urlAPI = (window.createObjectURL && window) || 
31380                 (window.URL && URL.revokeObjectURL && URL) || 
31381                 (window.webkitURL && webkitURL);
31382             
31383             var r = new FileReader();
31384             var t = this;
31385             r.addEventListener('load',function()
31386             {
31387                 
31388                 var d = (new DOMParser().parseFromString('<img src="' + r.result+ '">', 'text/html')).body;
31389                 // is insert asycn?
31390                 if (t.enableBlocks) {
31391                     
31392                     Array.from(d.getElementsByTagName('img')).forEach(function(img) {
31393                         if (img.closest('figure')) { // assume!! that it's aready
31394                             return;
31395                         }
31396                         var fig  = new Roo.htmleditor.BlockFigure({
31397                             image_src  : img.src
31398                         });
31399                         fig.updateElement(img); // replace it..
31400                         
31401                     });
31402                 }
31403                 t.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
31404                 t.owner.fireEvent('paste', this);
31405             });
31406             r.readAsDataURL(cd.files[0]);
31407             
31408             e.preventDefault();
31409             
31410             return false;
31411         }
31412         if (cd.types.indexOf('text/html') < 0 ) {
31413             return false;
31414         }
31415         var images = [];
31416         var html = cd.getData('text/html'); // clipboard event
31417         if (cd.types.indexOf('text/rtf') > -1) {
31418             var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
31419             images = parser.doc ? parser.doc.getElementsByType('pict') : [];
31420         }
31421         //Roo.log(images);
31422         //Roo.log(imgs);
31423         // fixme..
31424         images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
31425                        .map(function(g) { return g.toDataURL(); })
31426                        .filter(function(g) { return g != 'about:blank'; });
31427         
31428         //Roo.log(html);
31429         html = this.cleanWordChars(html);
31430         
31431         var d = (new DOMParser().parseFromString(html, 'text/html')).body;
31432         
31433         
31434         var sn = this.getParentElement();
31435         // check if d contains a table, and prevent nesting??
31436         //Roo.log(d.getElementsByTagName('table'));
31437         //Roo.log(sn);
31438         //Roo.log(sn.closest('table'));
31439         if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
31440             e.preventDefault();
31441             this.insertAtCursor("You can not nest tables");
31442             //Roo.log("prevent?"); // fixme - 
31443             return false;
31444         }
31445         
31446         
31447         
31448         if (images.length > 0) {
31449             // replace all v:imagedata - with img.
31450             var ar = Array.from(d.getElementsByTagName('v:imagedata'));
31451             Roo.each(ar, function(node) {
31452                 node.parentNode.insertBefore(d.ownerDocument.createElement('img'), node );
31453                 node.parentNode.removeChild(node);
31454             });
31455             
31456             
31457             Roo.each(d.getElementsByTagName('img'), function(img, i) {
31458                 img.setAttribute('src', images[i]);
31459             });
31460         }
31461         if (this.autoClean) {
31462             new Roo.htmleditor.FilterWord({ node : d });
31463             
31464             new Roo.htmleditor.FilterStyleToTag({ node : d });
31465             new Roo.htmleditor.FilterAttributes({
31466                 node : d,
31467                 attrib_white : ['href', 'src', 'name', 'align', 'colspan', 'rowspan', 'data-display', 'data-width', 'start'],
31468                 attrib_clean : ['href', 'src' ] 
31469             });
31470             new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
31471             // should be fonts..
31472             new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', ':' ]} );
31473             new Roo.htmleditor.FilterParagraph({ node : d });
31474             new Roo.htmleditor.FilterSpan({ node : d });
31475             new Roo.htmleditor.FilterLongBr({ node : d });
31476             new Roo.htmleditor.FilterComment({ node : d });
31477             
31478             
31479         }
31480         if (this.enableBlocks) {
31481                 
31482             Array.from(d.getElementsByTagName('img')).forEach(function(img) {
31483                 if (img.closest('figure')) { // assume!! that it's aready
31484                     return;
31485                 }
31486                 var fig  = new Roo.htmleditor.BlockFigure({
31487                     image_src  : img.src
31488                 });
31489                 fig.updateElement(img); // replace it..
31490                 
31491             });
31492         }
31493         
31494         
31495         this.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
31496         if (this.enableBlocks) {
31497             Roo.htmleditor.Block.initAll(this.doc.body);
31498         }
31499          
31500         
31501         e.preventDefault();
31502         this.owner.fireEvent('paste', this);
31503         return false;
31504         // default behaveiour should be our local cleanup paste? (optional?)
31505         // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
31506         //this.owner.fireEvent('paste', e, v);
31507     },
31508     // private
31509     onDestroy : function(){
31510         
31511         
31512         
31513         if(this.rendered){
31514             
31515             //for (var i =0; i < this.toolbars.length;i++) {
31516             //    // fixme - ask toolbars for heights?
31517             //    this.toolbars[i].onDestroy();
31518            // }
31519             
31520             //this.wrap.dom.innerHTML = '';
31521             //this.wrap.remove();
31522         }
31523     },
31524
31525     // private
31526     onFirstFocus : function(){
31527         
31528         this.assignDocWin();
31529         this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
31530         
31531         this.activated = true;
31532          
31533     
31534         if(Roo.isGecko){ // prevent silly gecko errors
31535             this.win.focus();
31536             var s = this.win.getSelection();
31537             if(!s.focusNode || s.focusNode.nodeType != 3){
31538                 var r = s.getRangeAt(0);
31539                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
31540                 r.collapse(true);
31541                 this.deferFocus();
31542             }
31543             try{
31544                 this.execCmd('useCSS', true);
31545                 this.execCmd('styleWithCSS', false);
31546             }catch(e){}
31547         }
31548         this.owner.fireEvent('activate', this);
31549     },
31550
31551     // private
31552     adjustFont: function(btn){
31553         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
31554         //if(Roo.isSafari){ // safari
31555         //    adjust *= 2;
31556        // }
31557         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
31558         if(Roo.isSafari){ // safari
31559             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
31560             v =  (v < 10) ? 10 : v;
31561             v =  (v > 48) ? 48 : v;
31562             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
31563             
31564         }
31565         
31566         
31567         v = Math.max(1, v+adjust);
31568         
31569         this.execCmd('FontSize', v  );
31570     },
31571
31572     onEditorEvent : function(e)
31573     {
31574          
31575         
31576         if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
31577             return; // we do not handle this.. (undo manager does..)
31578         }
31579         // clicking a 'block'?
31580         
31581         // in theory this detects if the last element is not a br, then we try and do that.
31582         // its so clicking in space at bottom triggers adding a br and moving the cursor.
31583         if (e &&
31584             e.target.nodeName == 'BODY' &&
31585             e.type == "mouseup" &&
31586             this.doc.body.lastChild
31587            ) {
31588             var lc = this.doc.body.lastChild;
31589             // gtx-trans is google translate plugin adding crap.
31590             while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
31591                 lc = lc.previousSibling;
31592             }
31593             if (lc.nodeType == 1 && lc.nodeName != 'BR') {
31594             // if last element is <BR> - then dont do anything.
31595             
31596                 var ns = this.doc.createElement('br');
31597                 this.doc.body.appendChild(ns);
31598                 range = this.doc.createRange();
31599                 range.setStartAfter(ns);
31600                 range.collapse(true);
31601                 var sel = this.win.getSelection();
31602                 sel.removeAllRanges();
31603                 sel.addRange(range);
31604             }
31605         }
31606         
31607         
31608         
31609         this.fireEditorEvent(e);
31610       //  this.updateToolbar();
31611         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
31612     },
31613     
31614     fireEditorEvent: function(e)
31615     {
31616         this.owner.fireEvent('editorevent', this, e);
31617     },
31618
31619     insertTag : function(tg)
31620     {
31621         // could be a bit smarter... -> wrap the current selected tRoo..
31622         if (tg.toLowerCase() == 'span' ||
31623             tg.toLowerCase() == 'code' ||
31624             tg.toLowerCase() == 'sup' ||
31625             tg.toLowerCase() == 'sub' 
31626             ) {
31627             
31628             range = this.createRange(this.getSelection());
31629             var wrappingNode = this.doc.createElement(tg.toLowerCase());
31630             wrappingNode.appendChild(range.extractContents());
31631             range.insertNode(wrappingNode);
31632
31633             return;
31634             
31635             
31636             
31637         }
31638         this.execCmd("formatblock",   tg);
31639         this.undoManager.addEvent(); 
31640     },
31641     
31642     insertText : function(txt)
31643     {
31644         
31645         
31646         var range = this.createRange();
31647         range.deleteContents();
31648                //alert(Sender.getAttribute('label'));
31649                
31650         range.insertNode(this.doc.createTextNode(txt));
31651         this.undoManager.addEvent();
31652     } ,
31653     
31654      
31655
31656     /**
31657      * Executes a Midas editor command on the editor document and performs necessary focus and
31658      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
31659      * @param {String} cmd The Midas command
31660      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
31661      */
31662     relayCmd : function(cmd, value)
31663     {
31664         
31665         switch (cmd) {
31666             case 'justifyleft':
31667             case 'justifyright':
31668             case 'justifycenter':
31669                 // if we are in a cell, then we will adjust the
31670                 var n = this.getParentElement();
31671                 var td = n.closest('td');
31672                 if (td) {
31673                     var bl = Roo.htmleditor.Block.factory(td);
31674                     bl.textAlign = cmd.replace('justify','');
31675                     bl.updateElement();
31676                     this.owner.fireEvent('editorevent', this);
31677                     return;
31678                 }
31679                 this.execCmd('styleWithCSS', true); // 
31680                 break;
31681             case 'bold':
31682             case 'italic':
31683                 // if there is no selection, then we insert, and set the curson inside it..
31684                 this.execCmd('styleWithCSS', false); 
31685                 break;
31686                 
31687         
31688             default:
31689                 break;
31690         }
31691         
31692         
31693         this.win.focus();
31694         this.execCmd(cmd, value);
31695         this.owner.fireEvent('editorevent', this);
31696         //this.updateToolbar();
31697         this.owner.deferFocus();
31698     },
31699
31700     /**
31701      * Executes a Midas editor command directly on the editor document.
31702      * For visual commands, you should use {@link #relayCmd} instead.
31703      * <b>This should only be called after the editor is initialized.</b>
31704      * @param {String} cmd The Midas command
31705      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
31706      */
31707     execCmd : function(cmd, value){
31708         this.doc.execCommand(cmd, false, value === undefined ? null : value);
31709         this.syncValue();
31710     },
31711  
31712  
31713    
31714     /**
31715      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
31716      * to insert tRoo.
31717      * @param {String} text | dom node.. 
31718      */
31719     insertAtCursor : function(text)
31720     {
31721         
31722         if(!this.activated){
31723             return;
31724         }
31725          
31726         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
31727             this.win.focus();
31728             
31729             
31730             // from jquery ui (MIT licenced)
31731             var range, node;
31732             var win = this.win;
31733             
31734             if (win.getSelection && win.getSelection().getRangeAt) {
31735                 
31736                 // delete the existing?
31737                 
31738                 this.createRange(this.getSelection()).deleteContents();
31739                 range = win.getSelection().getRangeAt(0);
31740                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
31741                 range.insertNode(node);
31742                 range = range.cloneRange();
31743                 range.collapse(false);
31744                  
31745                 win.getSelection().removeAllRanges();
31746                 win.getSelection().addRange(range);
31747                 
31748                 
31749                 
31750             } else if (win.document.selection && win.document.selection.createRange) {
31751                 // no firefox support
31752                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
31753                 win.document.selection.createRange().pasteHTML(txt);
31754             
31755             } else {
31756                 // no firefox support
31757                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
31758                 this.execCmd('InsertHTML', txt);
31759             } 
31760             this.syncValue();
31761             
31762             this.deferFocus();
31763         }
31764     },
31765  // private
31766     mozKeyPress : function(e){
31767         if(e.ctrlKey){
31768             var c = e.getCharCode(), cmd;
31769           
31770             if(c > 0){
31771                 c = String.fromCharCode(c).toLowerCase();
31772                 switch(c){
31773                     case 'b':
31774                         cmd = 'bold';
31775                         break;
31776                     case 'i':
31777                         cmd = 'italic';
31778                         break;
31779                     
31780                     case 'u':
31781                         cmd = 'underline';
31782                         break;
31783                     
31784                     //case 'v':
31785                       //  this.cleanUpPaste.defer(100, this);
31786                       //  return;
31787                         
31788                 }
31789                 if(cmd){
31790                     
31791                     this.relayCmd(cmd);
31792                     //this.win.focus();
31793                     //this.execCmd(cmd);
31794                     //this.deferFocus();
31795                     e.preventDefault();
31796                 }
31797                 
31798             }
31799         }
31800     },
31801
31802     // private
31803     fixKeys : function(){ // load time branching for fastest keydown performance
31804         
31805         
31806         if(Roo.isIE){
31807             return function(e){
31808                 var k = e.getKey(), r;
31809                 if(k == e.TAB){
31810                     e.stopEvent();
31811                     r = this.doc.selection.createRange();
31812                     if(r){
31813                         r.collapse(true);
31814                         r.pasteHTML('&#160;&#160;&#160;&#160;');
31815                         this.deferFocus();
31816                     }
31817                     return;
31818                 }
31819                 /// this is handled by Roo.htmleditor.KeyEnter
31820                  /*
31821                 if(k == e.ENTER){
31822                     r = this.doc.selection.createRange();
31823                     if(r){
31824                         var target = r.parentElement();
31825                         if(!target || target.tagName.toLowerCase() != 'li'){
31826                             e.stopEvent();
31827                             r.pasteHTML('<br/>');
31828                             r.collapse(false);
31829                             r.select();
31830                         }
31831                     }
31832                 }
31833                 */
31834                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
31835                 //    this.cleanUpPaste.defer(100, this);
31836                 //    return;
31837                 //}
31838                 
31839                 
31840             };
31841         }else if(Roo.isOpera){
31842             return function(e){
31843                 var k = e.getKey();
31844                 if(k == e.TAB){
31845                     e.stopEvent();
31846                     this.win.focus();
31847                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
31848                     this.deferFocus();
31849                 }
31850                
31851                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
31852                 //    this.cleanUpPaste.defer(100, this);
31853                  //   return;
31854                 //}
31855                 
31856             };
31857         }else if(Roo.isSafari){
31858             return function(e){
31859                 var k = e.getKey();
31860                 
31861                 if(k == e.TAB){
31862                     e.stopEvent();
31863                     this.execCmd('InsertText','\t');
31864                     this.deferFocus();
31865                     return;
31866                 }
31867                  this.mozKeyPress(e);
31868                 
31869                //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
31870                  //   this.cleanUpPaste.defer(100, this);
31871                  //   return;
31872                // }
31873                 
31874              };
31875         }
31876     }(),
31877     
31878     getAllAncestors: function()
31879     {
31880         var p = this.getSelectedNode();
31881         var a = [];
31882         if (!p) {
31883             a.push(p); // push blank onto stack..
31884             p = this.getParentElement();
31885         }
31886         
31887         
31888         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
31889             a.push(p);
31890             p = p.parentNode;
31891         }
31892         a.push(this.doc.body);
31893         return a;
31894     },
31895     lastSel : false,
31896     lastSelNode : false,
31897     
31898     
31899     getSelection : function() 
31900     {
31901         this.assignDocWin();
31902         return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
31903     },
31904     /**
31905      * Select a dom node
31906      * @param {DomElement} node the node to select
31907      */
31908     selectNode : function(node, collapse)
31909     {
31910         var nodeRange = node.ownerDocument.createRange();
31911         try {
31912             nodeRange.selectNode(node);
31913         } catch (e) {
31914             nodeRange.selectNodeContents(node);
31915         }
31916         if (collapse === true) {
31917             nodeRange.collapse(true);
31918         }
31919         //
31920         var s = this.win.getSelection();
31921         s.removeAllRanges();
31922         s.addRange(nodeRange);
31923     },
31924     
31925     getSelectedNode: function() 
31926     {
31927         // this may only work on Gecko!!!
31928         
31929         // should we cache this!!!!
31930         
31931          
31932          
31933         var range = this.createRange(this.getSelection()).cloneRange();
31934         
31935         if (Roo.isIE) {
31936             var parent = range.parentElement();
31937             while (true) {
31938                 var testRange = range.duplicate();
31939                 testRange.moveToElementText(parent);
31940                 if (testRange.inRange(range)) {
31941                     break;
31942                 }
31943                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
31944                     break;
31945                 }
31946                 parent = parent.parentElement;
31947             }
31948             return parent;
31949         }
31950         
31951         // is ancestor a text element.
31952         var ac =  range.commonAncestorContainer;
31953         if (ac.nodeType == 3) {
31954             ac = ac.parentNode;
31955         }
31956         
31957         var ar = ac.childNodes;
31958          
31959         var nodes = [];
31960         var other_nodes = [];
31961         var has_other_nodes = false;
31962         for (var i=0;i<ar.length;i++) {
31963             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
31964                 continue;
31965             }
31966             // fullly contained node.
31967             
31968             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
31969                 nodes.push(ar[i]);
31970                 continue;
31971             }
31972             
31973             // probably selected..
31974             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
31975                 other_nodes.push(ar[i]);
31976                 continue;
31977             }
31978             // outer..
31979             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
31980                 continue;
31981             }
31982             
31983             
31984             has_other_nodes = true;
31985         }
31986         if (!nodes.length && other_nodes.length) {
31987             nodes= other_nodes;
31988         }
31989         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
31990             return false;
31991         }
31992         
31993         return nodes[0];
31994     },
31995     
31996     
31997     createRange: function(sel)
31998     {
31999         // this has strange effects when using with 
32000         // top toolbar - not sure if it's a great idea.
32001         //this.editor.contentWindow.focus();
32002         if (typeof sel != "undefined") {
32003             try {
32004                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
32005             } catch(e) {
32006                 return this.doc.createRange();
32007             }
32008         } else {
32009             return this.doc.createRange();
32010         }
32011     },
32012     getParentElement: function()
32013     {
32014         
32015         this.assignDocWin();
32016         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
32017         
32018         var range = this.createRange(sel);
32019          
32020         try {
32021             var p = range.commonAncestorContainer;
32022             while (p.nodeType == 3) { // text node
32023                 p = p.parentNode;
32024             }
32025             return p;
32026         } catch (e) {
32027             return null;
32028         }
32029     
32030     },
32031     /***
32032      *
32033      * Range intersection.. the hard stuff...
32034      *  '-1' = before
32035      *  '0' = hits..
32036      *  '1' = after.
32037      *         [ -- selected range --- ]
32038      *   [fail]                        [fail]
32039      *
32040      *    basically..
32041      *      if end is before start or  hits it. fail.
32042      *      if start is after end or hits it fail.
32043      *
32044      *   if either hits (but other is outside. - then it's not 
32045      *   
32046      *    
32047      **/
32048     
32049     
32050     // @see http://www.thismuchiknow.co.uk/?p=64.
32051     rangeIntersectsNode : function(range, node)
32052     {
32053         var nodeRange = node.ownerDocument.createRange();
32054         try {
32055             nodeRange.selectNode(node);
32056         } catch (e) {
32057             nodeRange.selectNodeContents(node);
32058         }
32059     
32060         var rangeStartRange = range.cloneRange();
32061         rangeStartRange.collapse(true);
32062     
32063         var rangeEndRange = range.cloneRange();
32064         rangeEndRange.collapse(false);
32065     
32066         var nodeStartRange = nodeRange.cloneRange();
32067         nodeStartRange.collapse(true);
32068     
32069         var nodeEndRange = nodeRange.cloneRange();
32070         nodeEndRange.collapse(false);
32071     
32072         return rangeStartRange.compareBoundaryPoints(
32073                  Range.START_TO_START, nodeEndRange) == -1 &&
32074                rangeEndRange.compareBoundaryPoints(
32075                  Range.START_TO_START, nodeStartRange) == 1;
32076         
32077          
32078     },
32079     rangeCompareNode : function(range, node)
32080     {
32081         var nodeRange = node.ownerDocument.createRange();
32082         try {
32083             nodeRange.selectNode(node);
32084         } catch (e) {
32085             nodeRange.selectNodeContents(node);
32086         }
32087         
32088         
32089         range.collapse(true);
32090     
32091         nodeRange.collapse(true);
32092      
32093         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
32094         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
32095          
32096         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
32097         
32098         var nodeIsBefore   =  ss == 1;
32099         var nodeIsAfter    = ee == -1;
32100         
32101         if (nodeIsBefore && nodeIsAfter) {
32102             return 0; // outer
32103         }
32104         if (!nodeIsBefore && nodeIsAfter) {
32105             return 1; //right trailed.
32106         }
32107         
32108         if (nodeIsBefore && !nodeIsAfter) {
32109             return 2;  // left trailed.
32110         }
32111         // fully contined.
32112         return 3;
32113     },
32114  
32115     cleanWordChars : function(input) {// change the chars to hex code
32116         
32117        var swapCodes  = [ 
32118             [    8211, "&#8211;" ], 
32119             [    8212, "&#8212;" ], 
32120             [    8216,  "'" ],  
32121             [    8217, "'" ],  
32122             [    8220, '"' ],  
32123             [    8221, '"' ],  
32124             [    8226, "*" ],  
32125             [    8230, "..." ]
32126         ]; 
32127         var output = input;
32128         Roo.each(swapCodes, function(sw) { 
32129             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
32130             
32131             output = output.replace(swapper, sw[1]);
32132         });
32133         
32134         return output;
32135     },
32136     
32137      
32138     
32139         
32140     
32141     cleanUpChild : function (node)
32142     {
32143         
32144         new Roo.htmleditor.FilterComment({node : node});
32145         new Roo.htmleditor.FilterAttributes({
32146                 node : node,
32147                 attrib_black : this.ablack,
32148                 attrib_clean : this.aclean,
32149                 style_white : this.cwhite,
32150                 style_black : this.cblack
32151         });
32152         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
32153         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
32154          
32155         
32156     },
32157     
32158     /**
32159      * Clean up MS wordisms...
32160      * @deprecated - use filter directly
32161      */
32162     cleanWord : function(node)
32163     {
32164         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
32165         new Roo.htmleditor.FilterKeepChildren({node : node ? node : this.doc.body, tag : [ 'FONT', ':' ]} );
32166         
32167     },
32168    
32169     
32170     /**
32171
32172      * @deprecated - use filters
32173      */
32174     cleanTableWidths : function(node)
32175     {
32176         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
32177         
32178  
32179     },
32180     
32181      
32182         
32183     applyBlacklists : function()
32184     {
32185         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
32186         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
32187         
32188         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
32189         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
32190         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
32191         
32192         this.white = [];
32193         this.black = [];
32194         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
32195             if (b.indexOf(tag) > -1) {
32196                 return;
32197             }
32198             this.white.push(tag);
32199             
32200         }, this);
32201         
32202         Roo.each(w, function(tag) {
32203             if (b.indexOf(tag) > -1) {
32204                 return;
32205             }
32206             if (this.white.indexOf(tag) > -1) {
32207                 return;
32208             }
32209             this.white.push(tag);
32210             
32211         }, this);
32212         
32213         
32214         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
32215             if (w.indexOf(tag) > -1) {
32216                 return;
32217             }
32218             this.black.push(tag);
32219             
32220         }, this);
32221         
32222         Roo.each(b, function(tag) {
32223             if (w.indexOf(tag) > -1) {
32224                 return;
32225             }
32226             if (this.black.indexOf(tag) > -1) {
32227                 return;
32228             }
32229             this.black.push(tag);
32230             
32231         }, this);
32232         
32233         
32234         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
32235         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
32236         
32237         this.cwhite = [];
32238         this.cblack = [];
32239         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
32240             if (b.indexOf(tag) > -1) {
32241                 return;
32242             }
32243             this.cwhite.push(tag);
32244             
32245         }, this);
32246         
32247         Roo.each(w, function(tag) {
32248             if (b.indexOf(tag) > -1) {
32249                 return;
32250             }
32251             if (this.cwhite.indexOf(tag) > -1) {
32252                 return;
32253             }
32254             this.cwhite.push(tag);
32255             
32256         }, this);
32257         
32258         
32259         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
32260             if (w.indexOf(tag) > -1) {
32261                 return;
32262             }
32263             this.cblack.push(tag);
32264             
32265         }, this);
32266         
32267         Roo.each(b, function(tag) {
32268             if (w.indexOf(tag) > -1) {
32269                 return;
32270             }
32271             if (this.cblack.indexOf(tag) > -1) {
32272                 return;
32273             }
32274             this.cblack.push(tag);
32275             
32276         }, this);
32277     },
32278     
32279     setStylesheets : function(stylesheets)
32280     {
32281         if(typeof(stylesheets) == 'string'){
32282             Roo.get(this.iframe.contentDocument.head).createChild({
32283                 tag : 'link',
32284                 rel : 'stylesheet',
32285                 type : 'text/css',
32286                 href : stylesheets
32287             });
32288             
32289             return;
32290         }
32291         var _this = this;
32292      
32293         Roo.each(stylesheets, function(s) {
32294             if(!s.length){
32295                 return;
32296             }
32297             
32298             Roo.get(_this.iframe.contentDocument.head).createChild({
32299                 tag : 'link',
32300                 rel : 'stylesheet',
32301                 type : 'text/css',
32302                 href : s
32303             });
32304         });
32305
32306         
32307     },
32308     
32309     
32310     updateLanguage : function()
32311     {
32312         if (!this.iframe || !this.iframe.contentDocument) {
32313             return;
32314         }
32315         Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
32316     },
32317     
32318     
32319     removeStylesheets : function()
32320     {
32321         var _this = this;
32322         
32323         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
32324             s.remove();
32325         });
32326     },
32327     
32328     setStyle : function(style)
32329     {
32330         Roo.get(this.iframe.contentDocument.head).createChild({
32331             tag : 'style',
32332             type : 'text/css',
32333             html : style
32334         });
32335
32336         return;
32337     }
32338     
32339     // hide stuff that is not compatible
32340     /**
32341      * @event blur
32342      * @hide
32343      */
32344     /**
32345      * @event change
32346      * @hide
32347      */
32348     /**
32349      * @event focus
32350      * @hide
32351      */
32352     /**
32353      * @event specialkey
32354      * @hide
32355      */
32356     /**
32357      * @cfg {String} fieldClass @hide
32358      */
32359     /**
32360      * @cfg {String} focusClass @hide
32361      */
32362     /**
32363      * @cfg {String} autoCreate @hide
32364      */
32365     /**
32366      * @cfg {String} inputType @hide
32367      */
32368     /**
32369      * @cfg {String} invalidClass @hide
32370      */
32371     /**
32372      * @cfg {String} invalidText @hide
32373      */
32374     /**
32375      * @cfg {String} msgFx @hide
32376      */
32377     /**
32378      * @cfg {String} validateOnBlur @hide
32379      */
32380 });
32381
32382 Roo.HtmlEditorCore.white = [
32383         'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
32384         
32385        'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD',      'DIR',       'DIV', 
32386        'DL',      'DT',         'H1',     'H2',      'H3',        'H4', 
32387        'H5',      'H6',         'HR',     'ISINDEX', 'LISTING',   'MARQUEE', 
32388        'MENU',    'MULTICOL',   'OL',     'P',       'PLAINTEXT', 'PRE', 
32389        'TABLE',   'UL',         'XMP', 
32390        
32391        'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH', 
32392       'THEAD',   'TR', 
32393      
32394       'DIR', 'MENU', 'OL', 'UL', 'DL',
32395        
32396       'EMBED',  'OBJECT'
32397 ];
32398
32399
32400 Roo.HtmlEditorCore.black = [
32401     //    'embed',  'object', // enable - backend responsiblity to clean thiese
32402         'APPLET', // 
32403         'BASE',   'BASEFONT', 'BGSOUND', 'BLINK',  'BODY', 
32404         'FRAME',  'FRAMESET', 'HEAD',    'HTML',   'ILAYER', 
32405         'IFRAME', 'LAYER',  'LINK',     'META',    'OBJECT',   
32406         'SCRIPT', 'STYLE' ,'TITLE',  'XML',
32407         //'FONT' // CLEAN LATER..
32408         'COLGROUP', 'COL'   // messy tables.
32409         
32410         
32411 ];
32412 Roo.HtmlEditorCore.clean = [ // ?? needed???
32413      'SCRIPT', 'STYLE', 'TITLE', 'XML'
32414 ];
32415 Roo.HtmlEditorCore.tag_remove = [
32416     'FONT', 'TBODY'  
32417 ];
32418 // attributes..
32419
32420 Roo.HtmlEditorCore.ablack = [
32421     'on'
32422 ];
32423     
32424 Roo.HtmlEditorCore.aclean = [ 
32425     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
32426 ];
32427
32428 // protocols..
32429 Roo.HtmlEditorCore.pwhite= [
32430         'http',  'https',  'mailto'
32431 ];
32432
32433 // white listed style attributes.
32434 Roo.HtmlEditorCore.cwhite= [
32435       //  'text-align', /// default is to allow most things..
32436       
32437          
32438 //        'font-size'//??
32439 ];
32440
32441 // black listed style attributes.
32442 Roo.HtmlEditorCore.cblack= [
32443       //  'font-size' -- this can be set by the project 
32444 ];
32445
32446
32447
32448
32449     /*
32450  * - LGPL
32451  *
32452  * HtmlEditor
32453  * 
32454  */
32455
32456 /**
32457  * @class Roo.bootstrap.form.HtmlEditor
32458  * @extends Roo.bootstrap.form.TextArea
32459  * Bootstrap HtmlEditor class
32460
32461  * @constructor
32462  * Create a new HtmlEditor
32463  * @param {Object} config The config object
32464  */
32465
32466 Roo.bootstrap.form.HtmlEditor = function(config){
32467     Roo.bootstrap.form.HtmlEditor.superclass.constructor.call(this, config);
32468     if (!this.toolbars) {
32469         this.toolbars = [];
32470     }
32471     
32472     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
32473     this.addEvents({
32474             /**
32475              * @event initialize
32476              * Fires when the editor is fully initialized (including the iframe)
32477              * @param {HtmlEditor} this
32478              */
32479             initialize: true,
32480             /**
32481              * @event activate
32482              * Fires when the editor is first receives the focus. Any insertion must wait
32483              * until after this event.
32484              * @param {HtmlEditor} this
32485              */
32486             activate: true,
32487              /**
32488              * @event beforesync
32489              * Fires before the textarea is updated with content from the editor iframe. Return false
32490              * to cancel the sync.
32491              * @param {HtmlEditor} this
32492              * @param {String} html
32493              */
32494             beforesync: true,
32495              /**
32496              * @event beforepush
32497              * Fires before the iframe editor is updated with content from the textarea. Return false
32498              * to cancel the push.
32499              * @param {HtmlEditor} this
32500              * @param {String} html
32501              */
32502             beforepush: true,
32503              /**
32504              * @event sync
32505              * Fires when the textarea is updated with content from the editor iframe.
32506              * @param {HtmlEditor} this
32507              * @param {String} html
32508              */
32509             sync: true,
32510              /**
32511              * @event push
32512              * Fires when the iframe editor is updated with content from the textarea.
32513              * @param {HtmlEditor} this
32514              * @param {String} html
32515              */
32516             push: true,
32517              /**
32518              * @event editmodechange
32519              * Fires when the editor switches edit modes
32520              * @param {HtmlEditor} this
32521              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
32522              */
32523             editmodechange: true,
32524             /**
32525              * @event editorevent
32526              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
32527              * @param {HtmlEditor} this
32528              */
32529             editorevent: true,
32530             /**
32531              * @event firstfocus
32532              * Fires when on first focus - needed by toolbars..
32533              * @param {HtmlEditor} this
32534              */
32535             firstfocus: true,
32536             /**
32537              * @event autosave
32538              * Auto save the htmlEditor value as a file into Events
32539              * @param {HtmlEditor} this
32540              */
32541             autosave: true,
32542             /**
32543              * @event savedpreview
32544              * preview the saved version of htmlEditor
32545              * @param {HtmlEditor} this
32546              */
32547             savedpreview: true
32548         });
32549 };
32550
32551
32552 Roo.extend(Roo.bootstrap.form.HtmlEditor, Roo.bootstrap.form.TextArea,  {
32553     
32554     
32555       /**
32556      * @cfg {Array|boolean} toolbars Array of toolbars, or names of toolbars. - true for standard, and false for none.
32557      */
32558     toolbars : true,
32559     
32560      /**
32561     * @cfg {Array} buttons Array of toolbar's buttons. - defaults to empty
32562     */
32563     btns : [],
32564    
32565      /**
32566      * @cfg {String} resize  (none|both|horizontal|vertical) - css resize of element
32567      */
32568     resize : false,
32569      /**
32570      * @cfg {Number} height (in pixels)
32571      */   
32572     height: 300,
32573    /**
32574      * @cfg {Number} width (in pixels)
32575      */   
32576     width: false,
32577     
32578     /**
32579      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
32580      * 
32581      */
32582     stylesheets: false,
32583     
32584     // id of frame..
32585     frameId: false,
32586     
32587     // private properties
32588     validationEvent : false,
32589     deferHeight: true,
32590     initialized : false,
32591     activated : false,
32592     
32593     onFocus : Roo.emptyFn,
32594     iframePad:3,
32595     hideMode:'offsets',
32596     
32597     tbContainer : false,
32598     
32599     bodyCls : '',
32600     
32601     toolbarContainer :function() {
32602         return this.wrap.select('.x-html-editor-tb',true).first();
32603     },
32604
32605     /**
32606      * Protected method that will not generally be called directly. It
32607      * is called when the editor creates its toolbar. Override this method if you need to
32608      * add custom toolbar buttons.
32609      * @param {HtmlEditor} editor
32610      */
32611     createToolbar : function()
32612     {
32613         //Roo.log('renewing');
32614         //Roo.log("create toolbars");
32615         if (this.toolbars === false) {
32616             return;
32617         }
32618         if (this.toolbars === true) {
32619             this.toolbars = [ 'Standard' ];
32620         }
32621         
32622         var ar = Array.from(this.toolbars);
32623         this.toolbars = [];
32624         ar.forEach(function(t,i) {
32625             if (typeof(t) == 'string') {
32626                 t = {
32627                     xtype : t
32628                 };
32629             }
32630             if (typeof(t) == 'object' && typeof(t.xtype) == 'string') {
32631                 t.editor = this;
32632                 t.xns = t.xns || Roo.bootstrap.form.HtmlEditorToolbar;
32633                 t = Roo.factory(t);
32634             }
32635             this.toolbars[i] = t;
32636             this.toolbars[i].render(this.toolbarContainer());
32637         }, this);
32638         
32639         
32640     },
32641
32642      
32643     // private
32644     onRender : function(ct, position)
32645     {
32646        // Roo.log("Call onRender: " + this.xtype);
32647         var _t = this;
32648         Roo.bootstrap.form.HtmlEditor.superclass.onRender.call(this, ct, position);
32649       
32650         this.wrap = this.inputEl().wrap({
32651             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
32652         });
32653         
32654         this.editorcore.onRender(ct, position);
32655          
32656          
32657         this.createToolbar(this);
32658        
32659         
32660           
32661         
32662     },
32663
32664     // private
32665     onResize : function(w, h)
32666     {
32667         Roo.log('resize: ' +w + ',' + h );
32668         Roo.bootstrap.form.HtmlEditor.superclass.onResize.apply(this, arguments);
32669         var ew = false;
32670         var eh = false;
32671         
32672         if(this.inputEl() ){
32673             if(typeof w == 'number'){
32674                 var aw = w - this.wrap.getFrameWidth('lr');
32675                 this.inputEl().setWidth(this.adjustWidth('textarea', aw));
32676                 ew = aw;
32677             }
32678             if(typeof h == 'number'){
32679                  var tbh = -11;  // fixme it needs to tool bar size!
32680                 for (var i =0; i < this.toolbars.length;i++) {
32681                     // fixme - ask toolbars for heights?
32682                     tbh += this.toolbars[i].el.getHeight();
32683                     //if (this.toolbars[i].footer) {
32684                     //    tbh += this.toolbars[i].footer.el.getHeight();
32685                     //}
32686                 }
32687               
32688                 
32689                 
32690                 
32691                 
32692                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
32693                 ah -= 5; // knock a few pixes off for look..
32694                 this.inputEl().setHeight(this.adjustWidth('textarea', ah));
32695                 var eh = ah;
32696             }
32697         }
32698         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
32699         this.editorcore.onResize(ew,eh);
32700         
32701     },
32702
32703     /**
32704      * Toggles the editor between standard and source edit mode.
32705      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
32706      */
32707     toggleSourceEdit : function(sourceEditMode)
32708     {
32709         this.editorcore.toggleSourceEdit(sourceEditMode);
32710         
32711         if(this.editorcore.sourceEditMode){
32712             Roo.log('editor - showing textarea');
32713             
32714 //            Roo.log('in');
32715 //            Roo.log(this.syncValue());
32716             this.syncValue();
32717             this.inputEl().removeClass(['hide', 'x-hidden']);
32718             this.inputEl().dom.removeAttribute('tabIndex');
32719             this.inputEl().focus();
32720         }else{
32721             Roo.log('editor - hiding textarea');
32722 //            Roo.log('out')
32723 //            Roo.log(this.pushValue()); 
32724             this.pushValue();
32725             
32726             this.inputEl().addClass(['hide', 'x-hidden']);
32727             this.inputEl().dom.setAttribute('tabIndex', -1);
32728             //this.deferFocus();
32729         }
32730          
32731         //if(this.resizable){
32732         //    this.setSize(this.wrap.getSize());
32733         //}
32734         
32735         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
32736     },
32737  
32738     // private (for BoxComponent)
32739     adjustSize : Roo.BoxComponent.prototype.adjustSize,
32740
32741     // private (for BoxComponent)
32742     getResizeEl : function(){
32743         return this.wrap;
32744     },
32745
32746     // private (for BoxComponent)
32747     getPositionEl : function(){
32748         return this.wrap;
32749     },
32750
32751     // private
32752     initEvents : function(){
32753         this.originalValue = this.getValue();
32754     },
32755
32756 //    /**
32757 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
32758 //     * @method
32759 //     */
32760 //    markInvalid : Roo.emptyFn,
32761 //    /**
32762 //     * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
32763 //     * @method
32764 //     */
32765 //    clearInvalid : Roo.emptyFn,
32766
32767     setValue : function(v){
32768         Roo.bootstrap.form.HtmlEditor.superclass.setValue.call(this, v);
32769         this.editorcore.pushValue();
32770     },
32771
32772      
32773     // private
32774     deferFocus : function(){
32775         this.focus.defer(10, this);
32776     },
32777
32778     // doc'ed in Field
32779     focus : function(){
32780         this.editorcore.focus();
32781         
32782     },
32783       
32784
32785     // private
32786     onDestroy : function(){
32787         
32788         
32789         
32790         if(this.rendered){
32791             
32792             for (var i =0; i < this.toolbars.length;i++) {
32793                 // fixme - ask toolbars for heights?
32794                 this.toolbars[i].onDestroy();
32795             }
32796             
32797             this.wrap.dom.innerHTML = '';
32798             this.wrap.remove();
32799         }
32800     },
32801
32802     // private
32803     onFirstFocus : function(){
32804         //Roo.log("onFirstFocus");
32805         this.editorcore.onFirstFocus();
32806          for (var i =0; i < this.toolbars.length;i++) {
32807             this.toolbars[i].onFirstFocus();
32808         }
32809         
32810     },
32811     
32812     // private
32813     syncValue : function()
32814     {   
32815         this.editorcore.syncValue();
32816     },
32817     
32818     pushValue : function()
32819     {   
32820         this.editorcore.pushValue();
32821     }
32822      
32823     
32824     // hide stuff that is not compatible
32825     /**
32826      * @event blur
32827      * @hide
32828      */
32829     /**
32830      * @event change
32831      * @hide
32832      */
32833     /**
32834      * @event focus
32835      * @hide
32836      */
32837     /**
32838      * @event specialkey
32839      * @hide
32840      */
32841     /**
32842      * @cfg {String} fieldClass @hide
32843      */
32844     /**
32845      * @cfg {String} focusClass @hide
32846      */
32847     /**
32848      * @cfg {String} autoCreate @hide
32849      */
32850     /**
32851      * @cfg {String} inputType @hide
32852      */
32853      
32854     /**
32855      * @cfg {String} invalidText @hide
32856      */
32857     /**
32858      * @cfg {String} msgFx @hide
32859      */
32860     /**
32861      * @cfg {String} validateOnBlur @hide
32862      */
32863 });
32864  
32865     
32866    
32867    
32868    
32869       
32870 /**
32871  * @class Roo.bootstrap.form.HtmlEditorToolbar.Standard
32872  * @parent Roo.bootstrap.form.HtmlEditor
32873  * @extends Roo.bootstrap.nav.Simplebar
32874  * Basic Toolbar
32875  * 
32876  * @example
32877  * Usage:
32878  *
32879  new Roo.bootstrap.form.HtmlEditor({
32880     ....
32881     toolbars : [
32882         new Roo.bootstrap.form.HtmlEditorToolbar.Standard({
32883             disable : { fonts: 1 , format: 1, ..., ... , ...],
32884             btns : [ .... ]
32885         })
32886     }
32887      
32888  * 
32889  * @cfg {Object} disable List of elements to disable..
32890  * @cfg {Array} btns List of additional buttons.
32891  * 
32892  * 
32893  * NEEDS Extra CSS? 
32894  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
32895  */
32896  
32897 Roo.bootstrap.form.HtmlEditorToolbar.Standard = function(config)
32898 {
32899     
32900     Roo.apply(this, config);
32901     
32902     // default disabled, based on 'good practice'..
32903     this.disable = this.disable || {};
32904     Roo.applyIf(this.disable, {
32905         fontSize : true,
32906         colors : true,
32907         specialElements : true
32908     });
32909     Roo.bootstrap.form.HtmlEditorToolbar.Standard.superclass.constructor.call(this, config);
32910     
32911     this.editor = config.editor;
32912     this.editorcore = config.editor.editorcore;
32913     
32914     this.buttons   = new Roo.util.MixedCollection(false, function(o) { return o.btnid; });
32915     
32916     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
32917     // dont call parent... till later.
32918 }
32919 Roo.extend(Roo.bootstrap.form.HtmlEditorToolbar.Standard, Roo.bootstrap.nav.Simplebar,  {
32920      
32921     bar : true,
32922     
32923     editor : false,
32924     editorcore : false,
32925     
32926     
32927     formats : [
32928         "p" ,  
32929         "h1","h2","h3","h4","h5","h6", 
32930         "pre", "code", 
32931         "abbr", "acronym", "address", "cite", "samp", "var",
32932         'div','span'
32933     ],
32934     
32935     
32936     deleteBtn: false,
32937     
32938     onRender : function(ct, position)
32939     {
32940        // Roo.log("Call onRender: " + this.xtype);
32941         
32942        Roo.bootstrap.form.HtmlEditorToolbar.Standard.superclass.onRender.call(this, ct, position);
32943        Roo.log(this.el);
32944        this.el.dom.style.marginBottom = '0';
32945        var _this = this;
32946        var editorcore = this.editorcore;
32947        var editor= this.editor;
32948        
32949        var children = [];
32950        var btn = function(id, cmd , toggle, handler, html){
32951        
32952             var  event = toggle ? 'toggle' : 'click';
32953        
32954             var a = {
32955                 size : 'sm',
32956                 xtype: 'Button',
32957                 xns: Roo.bootstrap,
32958                 //glyphicon : id,
32959                 btnid : id,
32960                 fa: id,
32961                 cmd : cmd, // why id || cmd
32962                 enableToggle: toggle !== false,
32963                 html : html || '',
32964                 pressed : toggle ? false : null,
32965                 listeners : {}
32966             };
32967             a.listeners[toggle ? 'toggle' : 'click'] = function() {
32968                 handler ? handler.call(_this,this) :_this.onBtnClick.call(_this, cmd ||  id);
32969             };
32970             children.push(a);
32971             return a;
32972        }
32973        
32974     //    var cb_box = function...
32975         
32976         var style = {
32977                 xtype: 'Button',
32978                 size : 'sm',
32979                 xns: Roo.bootstrap,
32980                 fa : 'font',
32981                 //html : 'submit'
32982                 menu : {
32983                     xtype: 'Menu',
32984                     xns: Roo.bootstrap,
32985                     items:  []
32986                 }
32987         };
32988         Roo.each(this.formats, function(f) {
32989             style.menu.items.push({
32990                 xtype :'MenuItem',
32991                 xns: Roo.bootstrap,
32992                 html : '<'+ f+' style="margin:2px">'+f +'</'+ f+'>',
32993                 tagname : f,
32994                 listeners : {
32995                     click : function()
32996                     {
32997                         editorcore.insertTag(this.tagname);
32998                         editor.focus();
32999                     }
33000                 }
33001                 
33002             });
33003         });
33004         children.push(style);   
33005         
33006         btn('bold',         false,true);
33007         btn('italic',       false,true);
33008         btn('align-left',   'justifyleft',true);
33009         btn('align-center', 'justifycenter',true);
33010         btn('align-right' , 'justifyright',true);
33011         btn('link', false, true, function(btn) {
33012             var url = this.selectedNode && this.selectedNode.tagName.toUpperCase() == 'A' ?
33013                     this.selectedNode.getAttribute('href') : '';
33014                 
33015             Roo.bootstrap.MessageBox.show({
33016                 title : "Add / Edit Link URL",
33017                 msg : "Enter the URL for the link",
33018                 buttons: Roo.bootstrap.MessageBox.OKCANCEL,
33019                 minWidth: 250,
33020                 scope : this,
33021                 prompt:true,
33022                 multiline: false,
33023                 modal : true,
33024                 value : url,
33025                 fn:  function(pressed, newurl) {
33026                     if (pressed != 'ok') {
33027                         return;
33028                     }
33029                     if (url != '') {
33030                         this.selectedNode.setAttribute('href', newurl);
33031                         return;
33032                     }
33033                     if(newurl && newurl .match(/http(s):\/\/.+/)) {
33034                         this.editorcore.relayCmd('createlink', newurl);
33035                     }
33036                 }
33037             });
33038         });
33039         btn('image', false, true, function() {
33040             
33041         });
33042         btn('list','insertunorderedlist',true);
33043         btn('list-ol','insertorderedlist',true);
33044
33045         btn('pencil', false,true, function(btn){
33046                 Roo.log(this);
33047                 this.toggleSourceEdit(btn.pressed);
33048         });
33049         
33050         if (this.editor.btns.length > 0) {
33051             for (var i = 0; i<this.editor.btns.length; i++) {
33052                 children.push(this.editor.btns[i]);
33053             }
33054         }
33055         
33056         
33057          
33058         this.xtype = 'NavSimplebar'; // why?
33059         
33060         for(var i=0;i< children.length;i++) {
33061             
33062             this.buttons.add(this.addxtypeChild(children[i]));
33063             
33064         }
33065         this.buildToolbarDelete();
33066
33067         editor.on('editorevent', this.updateToolbar, this);
33068     },
33069     
33070     buildToolbarDelete : function()
33071     {
33072         
33073        /* this.addxtypeChild({
33074             xtype : 'Element',
33075             xns : Roo.bootstrap,
33076             cls : 'roo-htmleditor-fill'
33077         });
33078         */
33079         this.deleteBtn = this.addxtypeChild({
33080             size : 'sm',
33081             xtype: 'Button',
33082             xns: Roo.bootstrap,
33083             fa: 'trash',
33084             listeners : {
33085                 click : this.onDelete.createDelegate(this)
33086             }
33087         });
33088         this.deleteBtn.hide();     
33089         
33090     },
33091     
33092     
33093     onBtnClick : function(id)
33094     {
33095        this.editorcore.relayCmd(id);
33096        this.editorcore.focus();
33097     },
33098     
33099     /**
33100      * Protected method that will not generally be called directly. It triggers
33101      * a toolbar update by reading the markup state of the current selection in the editor.
33102      */
33103     updateToolbar: function(editor ,ev, sel){
33104
33105         if(!this.editorcore.activated){
33106             this.editor.onFirstFocus(); // is this neeed?
33107             return;
33108         }
33109
33110         var btns = this.buttons; 
33111         var doc = this.editorcore.doc;
33112         var hasToggle  = false;
33113         btns.each(function(e) {
33114             if (e.enableToggle && e.cmd) {
33115                 hasToggle = hasToggle  || (['align-left', 'align-right', 'align-center'].indexOf(e.btnid) < 0 && doc.queryCommandState(e.cmd));
33116                 e.setActive(doc.queryCommandState(e.cmd));
33117             }
33118         }, this);
33119         
33120         
33121         if (ev &&
33122             (ev.type == 'mouseup' || ev.type == 'click' ) &&
33123             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
33124             // they have click on an image...
33125             // let's see if we can change the selection...
33126             sel = ev.target;
33127             
33128         }
33129         
33130         var ans = this.editorcore.getAllAncestors();
33131         if (!sel) { 
33132             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
33133             sel = sel ? sel : this.editorcore.doc.body;
33134             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
33135             
33136         }
33137         
33138         var lastSel = this.selectedNode;
33139         this.selectedNode = sel;
33140          
33141         // ok see if we are editing a block?
33142         
33143         var db = false;
33144         // you are not actually selecting the block.
33145         if (sel && sel.hasAttribute('data-block')) {
33146             db = sel;
33147         } else if (sel && sel.closest('[data-block]')) {
33148             db = sel.closest('[data-block]');
33149         }
33150         
33151         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
33152             e.classList.remove('roo-ed-selection');
33153         });
33154         
33155         var block = false;
33156         if (db && this.editorcore.enableBlocks) {
33157             block = Roo.htmleditor.Block.factory(db);
33158             
33159             if (block) {
33160                 db.className =  (db.classList.length > 0  ? db.className + ' ' : '') +
33161                     ' roo-ed-selection';
33162                 sel = this.selectedNode = db;
33163             }
33164         }
33165         
33166         // highlight the 'a'..
33167         var tn = sel && sel.tagName.toUpperCase() || '';
33168         if (!block && sel && tn != 'A') {
33169             var asel = sel.closest('A');
33170             if (asel) {
33171                 sel = asel;
33172             }
33173         }
33174        
33175         btns.get('link').setActive(tn == 'A' && this.selectedNode.hasAttribute('href'));
33176         
33177         Roo.bootstrap.menu.Manager.hideAll();
33178          
33179         
33180         
33181         
33182         
33183         // handle delete button..
33184         if (hasToggle || (tn.length && tn == 'BODY')) {
33185             this.deleteBtn.hide();
33186             return;
33187             
33188         }
33189         this.deleteBtn.show();
33190         
33191         
33192         
33193         //this.editorsyncValue();
33194     },
33195     onFirstFocus: function() {
33196         this.buttons.each(function(item){
33197            item.enable();
33198         });
33199     },
33200     
33201     onDelete : function()
33202     {
33203         var range = this.editorcore.createRange();
33204         var selection = this.editorcore.getSelection();
33205         var sn = this.selectedNode;
33206         range.setStart(sn,0);
33207         range.setEnd(sn,0); 
33208         
33209         
33210         if (sn.hasAttribute('data-block')) {
33211             var block = Roo.htmleditor.Block.factory(this.selectedNode);
33212             if (block) {
33213                 sn = block.removeNode();
33214                 sn.parentNode.removeChild(sn);
33215                 selection.removeAllRanges();
33216                 selection.addRange(range);
33217                 this.updateToolbar(null, null, null);
33218                 this.editorcore.fireEditorEvent(false);
33219                 return;
33220             }   
33221              
33222         }
33223         if (!sn) {
33224             return; // should not really happen..
33225         }
33226         if (sn && sn.tagName == 'BODY') {
33227             return;
33228         }
33229         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
33230         
33231         // remove and keep parents.
33232         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
33233         a.replaceTag(sn);
33234         
33235         selection.removeAllRanges();
33236         selection.addRange(range);
33237         this.editorcore.fireEditorEvent(false);
33238         
33239         
33240     },
33241     
33242     
33243     toggleSourceEdit : function(sourceEditMode){
33244         
33245           
33246         if(sourceEditMode){
33247             Roo.log("disabling buttons");
33248            this.buttons.each( function(item){
33249                 if(item.cmd != 'pencil'){
33250                     item.disable();
33251                 }
33252             });
33253           
33254         }else{
33255             Roo.log("enabling buttons");
33256             if(this.editorcore.initialized){
33257                 this.buttons.each( function(item){
33258                     item.enable();
33259                 });
33260             }
33261             
33262         }
33263         Roo.log("calling toggole on editor");
33264         // tell the editor that it's been pressed..
33265         this.editor.toggleSourceEdit(sourceEditMode);
33266        
33267     }
33268 });
33269
33270
33271
33272
33273   
33274 /**
33275  * @class Roo.bootstrap.form.HtmlEditorToolbar.Context
33276  * @parent Roo.bootstrap.form.HtmlEditor
33277  * @extends Roo.bootstrap.nav.Simplebar
33278  * Basic Toolbar
33279  * 
33280  * @example
33281  * Usage:
33282  *
33283  new Roo.bootstrap.form.HtmlEditor({
33284     ....
33285     toolbars : [
33286         {
33287             xtyle: 'Standard',
33288             disable : { fonts: 1 , format: 1, ..., ... , ...],
33289             btns : [ .... ]
33290         },
33291         {
33292             xtyle : 'Context',
33293             ....
33294         }
33295     }
33296      
33297  * 
33298  * 
33299  */
33300  
33301 Roo.bootstrap.form.HtmlEditorToolbar.Context = function(config)
33302 {
33303     
33304     Roo.apply(this, config);
33305     
33306     
33307     Roo.bootstrap.form.HtmlEditorToolbar.Context.superclass.constructor.call(this, config);
33308     
33309     this.editor = config.editor;
33310     this.editorcore = config.editor.editorcore;
33311     
33312     this.buttons   = new Roo.util.MixedCollection(false, function(o) { return o.cmd; });
33313     
33314 }
33315
33316 Roo.bootstrap.form.HtmlEditorToolbar.Context.types = {
33317     'IMG' : [
33318         {
33319             name : 'width',
33320             title: "Width",
33321             width: 40
33322         },
33323         {
33324             name : 'height',
33325             title: "Height",
33326             width: 40
33327         },
33328         {
33329             name : 'align',
33330             title: "Align",
33331             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
33332             width : 80
33333             
33334         },
33335         {
33336             name : 'border',
33337             title: "Border",
33338             width: 40
33339         },
33340         {
33341             name : 'alt',
33342             title: "Alt",
33343             width: 120
33344         },
33345         {
33346             name : 'src',
33347             title: "Src",
33348             width: 220
33349         }
33350         
33351     ],
33352     
33353     /*
33354     'A' : [
33355         {
33356             name : 'name',
33357             title: "Name",
33358             width: 50
33359         },
33360         {
33361             name : 'target',
33362             title: "Target",
33363             width: 120
33364         },
33365         {
33366             name : 'href',
33367             title: "Href",
33368             width: 220
33369         } // border?
33370         
33371     ],
33372     */
33373     /*
33374     'INPUT' : [
33375         {
33376             name : 'name',
33377             title: "name",
33378             width: 120
33379         },
33380         {
33381             name : 'value',
33382             title: "Value",
33383             width: 120
33384         },
33385         {
33386             name : 'width',
33387             title: "Width",
33388             width: 40
33389         }
33390     ],
33391     'LABEL' : [
33392          {
33393             name : 'for',
33394             title: "For",
33395             width: 120
33396         }
33397     ],
33398     'TEXTAREA' : [
33399         {
33400             name : 'name',
33401             title: "name",
33402             width: 120
33403         },
33404         {
33405             name : 'rows',
33406             title: "Rows",
33407             width: 20
33408         },
33409         {
33410             name : 'cols',
33411             title: "Cols",
33412             width: 20
33413         }
33414     ],
33415     'SELECT' : [
33416         {
33417             name : 'name',
33418             title: "name",
33419             width: 120
33420         },
33421         {
33422             name : 'selectoptions',
33423             title: "Options",
33424             width: 200
33425         }
33426     ],
33427     
33428     // should we really allow this??
33429     // should this just be 
33430     'BODY' : [
33431         
33432         {
33433             name : 'title',
33434             title: "Title",
33435             width: 200,
33436             disabled : true
33437         }
33438     ],
33439     */
33440     '*' : [
33441         // empty.
33442     ]
33443
33444 };
33445
33446 Roo.extend(Roo.bootstrap.form.HtmlEditorToolbar.Context, Roo.bootstrap.nav.Simplebar,  {
33447     
33448     editor : false,
33449     editorcore : false,
33450     buttons : false,
33451     
33452     button_groups : false, // subtoolbars...  - buttson?
33453     active_group : false,
33454     
33455     selectedNode : false,
33456     
33457     onRender : function(ct, position)
33458     {
33459        // Roo.log("Call onRender: " + this.xtype);
33460         
33461         this.constructor.superclass.onRender.call(this, ct, position);
33462        
33463         
33464          
33465         
33466           
33467         // disable everything...
33468         var ty = this.constructor.types;
33469         this.button_groups = {};
33470         // block toolbars are built in updateToolbar when needed.
33471         for (var i in  ty) {
33472             this.button_groups[i] = this.buildToolbarGroup(ty[i],i);
33473         }
33474         this.buildToolbarDelete();
33475           this.hide();
33476         // the all the btns;
33477         this.editor.on('editorevent', this.updateToolbar, this);
33478         
33479     },
33480     onFirstFocus: function() {
33481        
33482     },
33483     
33484     
33485     buildToolbarGroup: function(tlist, key )
33486     {
33487         var editor = this.editor;
33488         var editorcore = this.editorcore;
33489         var tb = this;
33490        
33491         var ret = [];
33492          
33493         for (var i = 0; i < tlist.length; i++) {
33494             
33495             // newer versions will use xtype cfg to create menus.
33496             if (typeof(tlist[i].xtype) != 'undefined') {
33497                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
33498                 continue;
33499             }
33500             
33501             var item = tlist[i];
33502             ret.push(
33503                 this.addxtypeChild({
33504                     xtype : 'Element',
33505                     xns : Roo.bootstrap,
33506                     cls : 'roo-htmleditor-context-label-' + key + '-' + item.name,
33507                     html : item.title
33508                 })  
33509             );
33510             
33511             // add a text entry!?
33512             ret.push(
33513                 this.addxtypeChild({
33514                     xtype : 'Input',
33515                     xns : Roo.bootstrap.form,
33516                     cls : 'roo-htmleditor-context-entry-' + key + '-' + item.name,
33517                     name: '-roo-edit-' + item.name,
33518                     attrname : item.name,
33519                     width: item.width,
33520                     //allowBlank:true,
33521                     value: '',
33522                     listeners: {
33523                         'change' : function(f, nv, ov) {
33524                             tb.selectedNode.setAttribute(f.attrname, nv);
33525                             editorcore.syncValue();
33526                         }
33527                     }
33528                 })
33529             );
33530                 
33531         }
33532         // hide them all..
33533         ret.forEach(function(e) {
33534             e.hide();
33535         });
33536         ret.name = key;
33537         
33538         return ret;
33539     },
33540     buildToolbarDelete : function()
33541     {
33542         
33543         this.addxtypeChild({
33544             xtype : 'Element',
33545             xns : Roo.bootstrap,
33546             cls : 'roo-htmleditor-fill'
33547         });
33548         
33549         this.deleteBtn = this.addxtypeChild({
33550             size : 'sm',
33551             xtype: 'Button',
33552             xns: Roo.bootstrap,
33553             fa: 'trash',
33554             listeners : {
33555                 click : this.onDelete.createDelegate(this)
33556             }
33557         });
33558         this.deleteBtn.hide();     
33559         
33560     },
33561     
33562     
33563     onDelete : function()
33564     {
33565         var range = this.editorcore.createRange();
33566         var selection = this.editorcore.getSelection();
33567         var sn = this.selectedNode;
33568         range.setStart(sn,0);
33569         range.setEnd(sn,0); 
33570         
33571         
33572         if (sn.hasAttribute('data-block')) {
33573             var block = Roo.htmleditor.Block.factory(tb.selectedNode);
33574             if (block) {
33575                 block.removeNode();
33576                 selection.removeAllRanges();
33577                 selection.addRange(range);
33578                 this.updateToolbar(null, null, null);
33579             }   
33580              
33581         }
33582         if (!sn) {
33583             return; // should not really happen..
33584         }
33585         if (sn && sn.tagName == 'BODY') {
33586             return;
33587         }
33588         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
33589         
33590         // remove and keep parents.
33591         a = new Roo.htmleditor.FilterKeepChildren({tag : false});
33592         a.replaceTag(sn);
33593         
33594         selection.removeAllRanges();
33595         selection.addRange(range);
33596         this.editorcore.fireEditorEvent(false);
33597         
33598         
33599     },
33600     /**
33601      * Protected method that will not generally be called directly. It triggers
33602      * a toolbar update by reading the markup state of the current selection in the editor.
33603      *
33604      * Note you can force an update by calling on('editorevent', scope, false)
33605      */
33606     updateToolbar: function(editor ,ev, sel)
33607     {
33608         var ty = this.constructor.types;
33609         
33610         
33611         if (ev) {
33612             ev.stopEvent(); // se if we can stop this looping with mutiple events.
33613         }
33614         
33615          
33616         // capture mouse up - this is handy for selecting images..
33617         // perhaps should go somewhere else...
33618         if(!this.editorcore.activated){
33619             this.editor.onFirstFocus();
33620             return;
33621         }
33622         //Roo.log(ev ? ev.target : 'NOTARGET');
33623         
33624         
33625         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
33626         // selectNode - might want to handle IE?
33627          
33628         if (ev &&
33629             (ev.type == 'mouseup' || ev.type == 'click' ) &&
33630             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
33631             // they have click on an image...
33632             // let's see if we can change the selection...
33633             sel = ev.target;
33634            
33635              
33636         }
33637         
33638         // this forces an id..
33639         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
33640             e.classList.remove('roo-ed-selection');
33641         });
33642           
33643         var ans = this.editorcore.getAllAncestors();
33644         
33645                
33646         if (!sel) { 
33647             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
33648             sel = sel ? sel : this.editorcore.doc.body;
33649             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
33650             
33651         }
33652         
33653         var tn = sel.tagName.toUpperCase();
33654         var lastSel = this.selectedNode;
33655         this.selectedNode = sel;
33656         var left_label = tn;
33657         
33658         // ok see if we are editing a block?
33659         
33660         var db = false;
33661         // you are not actually selecting the block.
33662         if (sel && sel.hasAttribute('data-block')) {
33663             db = sel;
33664         } else if (sel && sel.closest('[data-block]')) {
33665             
33666             db = sel.closest('[data-block]');
33667              
33668         }
33669         
33670         
33671         var block = false;
33672         if (db && this.editorcore.enableBlocks) {
33673             block = Roo.htmleditor.Block.factory(db);
33674             
33675             
33676             if (block) {
33677                 db.className = (
33678                         db.classList.length > 0  ? db.className + ' ' : ''
33679                     )  + 'roo-ed-selection';
33680                  
33681                  // since we removed it earlier... its not there..
33682                 tn = 'BLOCK.' + db.getAttribute('data-block');
33683                 
33684                 //this.editorcore.selectNode(db);
33685                 if (typeof(this.button_groups[tn]) == 'undefined') {
33686                    this.button_groups[tn] = this.buildBlockToolbar( block );
33687                 }
33688                 this.selectedNode = db;
33689                 left_label = block.friendly_name;
33690                  
33691             }
33692               
33693             
33694         }
33695         
33696         
33697         if ( this.active_group !== false && this.active_group.name == tn && lastSel == this.selectedNode && ev !== false) {
33698             return; // no change?
33699         }
33700         
33701         if (tn == 'BODY') {
33702             this.deleteBtn.hide();
33703             this.hide();
33704             this.hideActiveGroup();
33705             return;
33706             
33707         }
33708         
33709         
33710         if (this.active_group) {
33711             this.hideActiveGroup();
33712         }
33713         this.showActiveGroup(tn);
33714         this.show();
33715         this.deleteBtn.show();
33716         
33717     },
33718     hideActiveGroup : function()
33719     {
33720         this.hide();
33721         if (this.active_group === false) {
33722             return;
33723         }
33724         this.active_group.forEach(function(e) {
33725             e.hide();
33726         });
33727         this.active_group = false;
33728     },
33729     showActiveGroup : function(tn)
33730     {
33731         
33732         if (typeof(this.button_groups[tn]) == 'undefined') {
33733             
33734             return;
33735         }
33736         
33737         this.active_group = this.button_groups[tn];
33738         
33739         this.active_group.forEach(function(e) {
33740             e.show();
33741         });
33742         
33743         // update attributes
33744         if (this.selectedNode.hasAttribute('data-block') ) {
33745             var block = Roo.htmleditor.Block.factory(this.selectedNode);
33746             this.active_group.forEach(function(e) {
33747                 e.setValue(this.selectedNode.getAttribute(block[e.name]));
33748             }, this);
33749                 
33750             return;
33751             
33752         }
33753         // based on attributes...
33754         this.active_group.forEach(function(e) {
33755             if (typeof(e.attrname) == 'undefined') {
33756                 return;
33757             }
33758              e.setValue(this.selectedNode.getAttribute(e.attrname));
33759         }, this);
33760         
33761             
33762     }
33763     
33764 }); 
33765 /*
33766  * - LGPL
33767  */
33768
33769 /**
33770  * @class Roo.bootstrap.form.Markdown
33771  * @extends Roo.bootstrap.form.TextArea
33772  * Bootstrap Showdown editable area
33773  * @cfg {string} content
33774  * 
33775  * @constructor
33776  * Create a new Showdown
33777  */
33778
33779 Roo.bootstrap.form.Markdown = function(config){
33780     Roo.bootstrap.form.Markdown.superclass.constructor.call(this, config);
33781    
33782 };
33783
33784 Roo.extend(Roo.bootstrap.form.Markdown, Roo.bootstrap.form.TextArea,  {
33785     
33786     editing :false,
33787     
33788     initEvents : function()
33789     {
33790         
33791         Roo.bootstrap.form.TextArea.prototype.initEvents.call(this);
33792         this.markdownEl = this.el.createChild({
33793             cls : 'roo-markdown-area'
33794         });
33795         this.inputEl().addClass('d-none');
33796         if (this.getValue() == '') {
33797             this.markdownEl.dom.innerHTML = String.format('<span class="roo-placeholder">{0}</span>', this.placeholder || '');
33798             
33799         } else {
33800             this.markdownEl.dom.innerHTML = Roo.Markdown.toHtml(Roo.util.Format.htmlEncode(this.getValue()));
33801         }
33802         this.markdownEl.on('click', this.toggleTextEdit, this);
33803         this.on('blur', this.toggleTextEdit, this);
33804         this.on('specialkey', this.resizeTextArea, this);
33805     },
33806     
33807     toggleTextEdit : function()
33808     {
33809         var sh = this.markdownEl.getHeight();
33810         this.inputEl().addClass('d-none');
33811         this.markdownEl.addClass('d-none');
33812         if (!this.editing) {
33813             // show editor?
33814             this.inputEl().setHeight(Math.min(500, Math.max(sh,(this.getValue().split("\n").length+1) * 30)));
33815             this.inputEl().removeClass('d-none');
33816             this.inputEl().focus();
33817             this.editing = true;
33818             return;
33819         }
33820         // show showdown...
33821         this.updateMarkdown();
33822         this.markdownEl.removeClass('d-none');
33823         this.editing = false;
33824         return;
33825     },
33826     updateMarkdown : function()
33827     {
33828         if (this.getValue() == '') {
33829             this.markdownEl.dom.innerHTML = String.format('<span class="roo-placeholder">{0}</span>', this.placeholder || '');
33830             return;
33831         }
33832  
33833         this.markdownEl.dom.innerHTML = Roo.Markdown.toHtml(Roo.util.Format.htmlEncode(this.getValue()));
33834     },
33835     
33836     resizeTextArea: function () {
33837         
33838         var sh = 100;
33839         Roo.log([sh, this.getValue().split("\n").length * 30]);
33840         this.inputEl().setHeight(Math.min(500, Math.max(sh, (this.getValue().split("\n").length +1) * 30)));
33841     },
33842     setValue : function(val)
33843     {
33844         Roo.bootstrap.form.TextArea.prototype.setValue.call(this,val);
33845         if (!this.editing) {
33846             this.updateMarkdown();
33847         }
33848         
33849     },
33850     focus : function()
33851     {
33852         if (!this.editing) {
33853             this.toggleTextEdit();
33854         }
33855         
33856     }
33857
33858
33859 });/*
33860  * Based on:
33861  * Ext JS Library 1.1.1
33862  * Copyright(c) 2006-2007, Ext JS, LLC.
33863  *
33864  * Originally Released Under LGPL - original licence link has changed is not relivant.
33865  *
33866  * Fork - LGPL
33867  * <script type="text/javascript">
33868  */
33869  
33870 /**
33871  * @class Roo.bootstrap.PagingToolbar
33872  * @extends Roo.bootstrap.nav.Simplebar
33873  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
33874  * @constructor
33875  * Create a new PagingToolbar
33876  * @param {Object} config The config object
33877  * @param {Roo.data.Store} store
33878  */
33879 Roo.bootstrap.PagingToolbar = function(config)
33880 {
33881     // old args format still supported... - xtype is prefered..
33882         // created from xtype...
33883     
33884     this.ds = config.dataSource;
33885     
33886     if (config.store && !this.ds) {
33887         this.store= Roo.factory(config.store, Roo.data);
33888         this.ds = this.store;
33889         this.ds.xmodule = this.xmodule || false;
33890     }
33891     
33892     this.toolbarItems = [];
33893     if (config.items) {
33894         this.toolbarItems = config.items;
33895     }
33896     
33897     Roo.bootstrap.PagingToolbar.superclass.constructor.call(this, config);
33898     
33899     this.cursor = 0;
33900     
33901     if (this.ds) { 
33902         this.bind(this.ds);
33903     }
33904     
33905     if (Roo.bootstrap.version == 4) {
33906         this.navgroup = new Roo.bootstrap.ButtonGroup({ cls: 'pagination' });
33907     } else {
33908         this.navgroup = new Roo.bootstrap.nav.Group({ cls: 'pagination' });
33909     }
33910     
33911 };
33912
33913 Roo.extend(Roo.bootstrap.PagingToolbar, Roo.bootstrap.nav.Simplebar, {
33914     /**
33915      * @cfg {Roo.bootstrap.Button} buttons[]
33916      * Buttons for the toolbar
33917      */
33918      /**
33919      * @cfg {Roo.data.Store} store
33920      * The underlying data store providing the paged data
33921      */
33922     /**
33923      * @cfg {String/HTMLElement/Element} container
33924      * container The id or element that will contain the toolbar
33925      */
33926     /**
33927      * @cfg {Boolean} displayInfo
33928      * True to display the displayMsg (defaults to false)
33929      */
33930     /**
33931      * @cfg {Number} pageSize
33932      * The number of records to display per page (defaults to 20)
33933      */
33934     pageSize: 20,
33935     /**
33936      * @cfg {String} displayMsg
33937      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
33938      */
33939     displayMsg : 'Displaying {0} - {1} of {2}',
33940     /**
33941      * @cfg {String} emptyMsg
33942      * The message to display when no records are found (defaults to "No data to display")
33943      */
33944     emptyMsg : 'No data to display',
33945     /**
33946      * Customizable piece of the default paging text (defaults to "Page")
33947      * @type String
33948      */
33949     beforePageText : "Page",
33950     /**
33951      * Customizable piece of the default paging text (defaults to "of %0")
33952      * @type String
33953      */
33954     afterPageText : "of {0}",
33955     /**
33956      * Customizable piece of the default paging text (defaults to "First Page")
33957      * @type String
33958      */
33959     firstText : "First Page",
33960     /**
33961      * Customizable piece of the default paging text (defaults to "Previous Page")
33962      * @type String
33963      */
33964     prevText : "Previous Page",
33965     /**
33966      * Customizable piece of the default paging text (defaults to "Next Page")
33967      * @type String
33968      */
33969     nextText : "Next Page",
33970     /**
33971      * Customizable piece of the default paging text (defaults to "Last Page")
33972      * @type String
33973      */
33974     lastText : "Last Page",
33975     /**
33976      * Customizable piece of the default paging text (defaults to "Refresh")
33977      * @type String
33978      */
33979     refreshText : "Refresh",
33980
33981     buttons : false,
33982     // private
33983     onRender : function(ct, position) 
33984     {
33985         Roo.bootstrap.PagingToolbar.superclass.onRender.call(this, ct, position);
33986         this.navgroup.parentId = this.id;
33987         this.navgroup.onRender(this.el, null);
33988         // add the buttons to the navgroup
33989         
33990         if(this.displayInfo){
33991             this.el.select('ul.navbar-nav',true).first().createChild({cls:'x-paging-info'});
33992             this.displayEl = this.el.select('.x-paging-info', true).first();
33993 //            var navel = this.navgroup.addItem( { tagtype : 'span', html : '', cls : 'x-paging-info', preventDefault : true } );
33994 //            this.displayEl = navel.el.select('span',true).first();
33995         }
33996         
33997         var _this = this;
33998         
33999         if(this.buttons){
34000             Roo.each(_this.buttons, function(e){ // this might need to use render????
34001                Roo.factory(e).render(_this.el);
34002             });
34003         }
34004             
34005         Roo.each(_this.toolbarItems, function(e) {
34006             _this.navgroup.addItem(e);
34007         });
34008         
34009         
34010         this.first = this.navgroup.addItem({
34011             tooltip: this.firstText,
34012             cls: "prev btn-outline-secondary",
34013             html : ' <i class="fa fa-step-backward"></i>',
34014             disabled: true,
34015             preventDefault: true,
34016             listeners : { click : this.onClick.createDelegate(this, ["first"]) }
34017         });
34018         
34019         this.prev =  this.navgroup.addItem({
34020             tooltip: this.prevText,
34021             cls: "prev btn-outline-secondary",
34022             html : ' <i class="fa fa-backward"></i>',
34023             disabled: true,
34024             preventDefault: true,
34025             listeners : { click :  this.onClick.createDelegate(this, ["prev"]) }
34026         });
34027     //this.addSeparator();
34028         
34029         
34030         var field = this.navgroup.addItem( {
34031             tagtype : 'span',
34032             cls : 'x-paging-position  btn-outline-secondary',
34033              disabled: true,
34034             html : this.beforePageText  +
34035                 '<input type="text" size="3" value="1" class="x-grid-page-number">' +
34036                 '<span class="x-paging-after">' +  String.format(this.afterPageText, 1) + '</span>'
34037          } ); //?? escaped?
34038         
34039         this.field = field.el.select('input', true).first();
34040         this.field.on("keydown", this.onPagingKeydown, this);
34041         this.field.on("focus", function(){this.dom.select();});
34042     
34043     
34044         this.afterTextEl =  field.el.select('.x-paging-after',true).first();
34045         //this.field.setHeight(18);
34046         //this.addSeparator();
34047         this.next = this.navgroup.addItem({
34048             tooltip: this.nextText,
34049             cls: "next btn-outline-secondary",
34050             html : ' <i class="fa fa-forward"></i>',
34051             disabled: true,
34052             preventDefault: true,
34053             listeners : { click :  this.onClick.createDelegate(this, ["next"]) }
34054         });
34055         this.last = this.navgroup.addItem({
34056             tooltip: this.lastText,
34057             html : ' <i class="fa fa-step-forward"></i>',
34058             cls: "next btn-outline-secondary",
34059             disabled: true,
34060             preventDefault: true,
34061             listeners : { click :  this.onClick.createDelegate(this, ["last"]) }
34062         });
34063     //this.addSeparator();
34064         this.loading = this.navgroup.addItem({
34065             tooltip: this.refreshText,
34066             cls: "btn-outline-secondary",
34067             html : ' <i class="fa fa-refresh"></i>',
34068             preventDefault: true,
34069             listeners : { click : this.onClick.createDelegate(this, ["refresh"]) }
34070         });
34071         
34072     },
34073
34074     // private
34075     updateInfo : function(){
34076         if(this.displayEl){
34077             var count = (typeof(this.getCount) == 'undefined') ? this.ds.getCount() : this.getCount();
34078             var msg = count == 0 ?
34079                 this.emptyMsg :
34080                 String.format(
34081                     this.displayMsg,
34082                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
34083                 );
34084             this.displayEl.update(msg);
34085         }
34086     },
34087
34088     // private
34089     onLoad : function(ds, r, o)
34090     {
34091         this.cursor = o.params && o.params.start ? o.params.start : 0;
34092         
34093         var d = this.getPageData(),
34094             ap = d.activePage,
34095             ps = d.pages;
34096         
34097         
34098         this.afterTextEl.dom.innerHTML = String.format(this.afterPageText, d.pages);
34099         this.field.dom.value = ap;
34100         this.first.setDisabled(ap == 1);
34101         this.prev.setDisabled(ap == 1);
34102         this.next.setDisabled(ap == ps);
34103         this.last.setDisabled(ap == ps);
34104         this.loading.enable();
34105         this.updateInfo();
34106     },
34107
34108     // private
34109     getPageData : function(){
34110         var total = this.ds.getTotalCount();
34111         return {
34112             total : total,
34113             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
34114             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
34115         };
34116     },
34117
34118     // private
34119     onLoadError : function(proxy, o){
34120         this.loading.enable();
34121         if (this.ds.events.loadexception.listeners.length  < 2) {
34122             // nothing has been assigned to loadexception except this...
34123             // so 
34124             Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
34125
34126         }
34127     },
34128
34129     // private
34130     onPagingKeydown : function(e){
34131         var k = e.getKey();
34132         var d = this.getPageData();
34133         if(k == e.RETURN){
34134             var v = this.field.dom.value, pageNum;
34135             if(!v || isNaN(pageNum = parseInt(v, 10))){
34136                 this.field.dom.value = d.activePage;
34137                 return;
34138             }
34139             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
34140             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
34141             e.stopEvent();
34142         }
34143         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))
34144         {
34145           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
34146           this.field.dom.value = pageNum;
34147           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
34148           e.stopEvent();
34149         }
34150         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
34151         {
34152           var v = this.field.dom.value, pageNum; 
34153           var increment = (e.shiftKey) ? 10 : 1;
34154           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
34155                 increment *= -1;
34156           }
34157           if(!v || isNaN(pageNum = parseInt(v, 10))) {
34158             this.field.dom.value = d.activePage;
34159             return;
34160           }
34161           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
34162           {
34163             this.field.dom.value = parseInt(v, 10) + increment;
34164             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
34165             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
34166           }
34167           e.stopEvent();
34168         }
34169     },
34170
34171     // private
34172     beforeLoad : function(){
34173         if(this.loading){
34174             this.loading.disable();
34175         }
34176     },
34177
34178     // private
34179     onClick : function(which){
34180         
34181         var ds = this.ds;
34182         if (!ds) {
34183             return;
34184         }
34185         
34186         switch(which){
34187             case "first":
34188                 ds.load({params:{start: 0, limit: this.pageSize}});
34189             break;
34190             case "prev":
34191                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
34192             break;
34193             case "next":
34194                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
34195             break;
34196             case "last":
34197                 var total = ds.getTotalCount();
34198                 var extra = total % this.pageSize;
34199                 var lastStart = extra ? (total - extra) : total-this.pageSize;
34200                 ds.load({params:{start: lastStart, limit: this.pageSize}});
34201             break;
34202             case "refresh":
34203                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
34204             break;
34205         }
34206     },
34207
34208     /**
34209      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
34210      * @param {Roo.data.Store} store The data store to unbind
34211      */
34212     unbind : function(ds){
34213         ds.un("beforeload", this.beforeLoad, this);
34214         ds.un("load", this.onLoad, this);
34215         ds.un("loadexception", this.onLoadError, this);
34216         ds.un("remove", this.updateInfo, this);
34217         ds.un("add", this.updateInfo, this);
34218         this.ds = undefined;
34219     },
34220
34221     /**
34222      * Binds the paging toolbar to the specified {@link Roo.data.Store}
34223      * @param {Roo.data.Store} store The data store to bind
34224      */
34225     bind : function(ds){
34226         ds.on("beforeload", this.beforeLoad, this);
34227         ds.on("load", this.onLoad, this);
34228         ds.on("loadexception", this.onLoadError, this);
34229         ds.on("remove", this.updateInfo, this);
34230         ds.on("add", this.updateInfo, this);
34231         this.ds = ds;
34232     }
34233 });/*
34234  * - LGPL
34235  *
34236  * element
34237  * 
34238  */
34239
34240 /**
34241  * @class Roo.bootstrap.MessageBar
34242  * @extends Roo.bootstrap.Component
34243  * Bootstrap MessageBar class
34244  * @cfg {String} html contents of the MessageBar
34245  * @cfg {String} weight (info | success | warning | danger) default info
34246  * @cfg {String} beforeClass insert the bar before the given class
34247  * @cfg {Boolean} closable (true | false) default false
34248  * @cfg {Boolean} fixed (true | false) default false, fix the bar at the top
34249  * 
34250  * @constructor
34251  * Create a new Element
34252  * @param {Object} config The config object
34253  */
34254
34255 Roo.bootstrap.MessageBar = function(config){
34256     Roo.bootstrap.MessageBar.superclass.constructor.call(this, config);
34257 };
34258
34259 Roo.extend(Roo.bootstrap.MessageBar, Roo.bootstrap.Component,  {
34260     
34261     html: '',
34262     weight: 'info',
34263     closable: false,
34264     fixed: false,
34265     beforeClass: 'bootstrap-sticky-wrap',
34266     
34267     getAutoCreate : function(){
34268         
34269         var cfg = {
34270             tag: 'div',
34271             cls: 'alert alert-dismissable alert-' + this.weight,
34272             cn: [
34273                 {
34274                     tag: 'span',
34275                     cls: 'message',
34276                     html: this.html || ''
34277                 }
34278             ]
34279         };
34280         
34281         if(this.fixed){
34282             cfg.cls += ' alert-messages-fixed';
34283         }
34284         
34285         if(this.closable){
34286             cfg.cn.push({
34287                 tag: 'button',
34288                 cls: 'close',
34289                 html: 'x'
34290             });
34291         }
34292         
34293         return cfg;
34294     },
34295     
34296     onRender : function(ct, position)
34297     {
34298         Roo.bootstrap.Component.superclass.onRender.call(this, ct, position);
34299         
34300         if(!this.el){
34301             var cfg = Roo.apply({},  this.getAutoCreate());
34302             cfg.id = Roo.id();
34303             
34304             if (this.cls) {
34305                 cfg.cls += ' ' + this.cls;
34306             }
34307             if (this.style) {
34308                 cfg.style = this.style;
34309             }
34310             this.el = Roo.get(document.body).createChild(cfg, Roo.select('.'+this.beforeClass, true).first());
34311             
34312             this.el.setVisibilityMode(Roo.Element.DISPLAY);
34313         }
34314         
34315         this.el.select('>button.close').on('click', this.hide, this);
34316         
34317     },
34318     
34319     show : function()
34320     {
34321         if (!this.rendered) {
34322             this.render();
34323         }
34324         
34325         this.el.show();
34326         
34327         this.fireEvent('show', this);
34328         
34329     },
34330     
34331     hide : function()
34332     {
34333         if (!this.rendered) {
34334             this.render();
34335         }
34336         
34337         this.el.hide();
34338         
34339         this.fireEvent('hide', this);
34340     },
34341     
34342     update : function()
34343     {
34344 //        var e = this.el.dom.firstChild;
34345 //        
34346 //        if(this.closable){
34347 //            e = e.nextSibling;
34348 //        }
34349 //        
34350 //        e.data = this.html || '';
34351
34352         this.el.select('>.message', true).first().dom.innerHTML = this.html || '';
34353     }
34354    
34355 });
34356
34357  
34358
34359      /*
34360  * - LGPL
34361  *
34362  * Graph
34363  * 
34364  */
34365
34366
34367 /**
34368  * @class Roo.bootstrap.Graph
34369  * @extends Roo.bootstrap.Component
34370  * Bootstrap Graph class
34371 > Prameters
34372  -sm {number} sm 4
34373  -md {number} md 5
34374  @cfg {String} graphtype  bar | vbar | pie
34375  @cfg {number} g_x coodinator | centre x (pie)
34376  @cfg {number} g_y coodinator | centre y (pie)
34377  @cfg {number} g_r radius (pie)
34378  @cfg {number} g_height height of the chart (respected by all elements in the set)
34379  @cfg {number} g_width width of the chart (respected by all elements in the set)
34380  @cfg {Object} title The title of the chart
34381     
34382  -{Array}  values
34383  -opts (object) options for the chart 
34384      o {
34385      o type (string) type of endings of the bar. Default: 'square'. Other options are: 'round', 'sharp', 'soft'.
34386      o gutter (number)(string) default '20%' (WHAT DOES IT DO?)
34387      o vgutter (number)
34388      o colors (array) colors be used repeatedly to plot the bars. If multicolumn bar is used each sequence of bars with use a different color.
34389      o stacked (boolean) whether or not to tread values as in a stacked bar chart
34390      o to
34391      o stretch (boolean)
34392      o }
34393  -opts (object) options for the pie
34394      o{
34395      o cut
34396      o startAngle (number)
34397      o endAngle (number)
34398      } 
34399  *
34400  * @constructor
34401  * Create a new Input
34402  * @param {Object} config The config object
34403  */
34404
34405 Roo.bootstrap.Graph = function(config){
34406     Roo.bootstrap.Graph.superclass.constructor.call(this, config);
34407     
34408     this.addEvents({
34409         // img events
34410         /**
34411          * @event click
34412          * The img click event for the img.
34413          * @param {Roo.EventObject} e
34414          */
34415         "click" : true
34416     });
34417 };
34418
34419 Roo.extend(Roo.bootstrap.Graph, Roo.bootstrap.Component,  {
34420     
34421     sm: 4,
34422     md: 5,
34423     graphtype: 'bar',
34424     g_height: 250,
34425     g_width: 400,
34426     g_x: 50,
34427     g_y: 50,
34428     g_r: 30,
34429     opts:{
34430         //g_colors: this.colors,
34431         g_type: 'soft',
34432         g_gutter: '20%'
34433
34434     },
34435     title : false,
34436
34437     getAutoCreate : function(){
34438         
34439         var cfg = {
34440             tag: 'div',
34441             html : null
34442         };
34443         
34444         
34445         return  cfg;
34446     },
34447
34448     onRender : function(ct,position){
34449         
34450         
34451         Roo.bootstrap.Graph.superclass.onRender.call(this,ct,position);
34452         
34453         if (typeof(Raphael) == 'undefined') {
34454             Roo.bootstrap.MessageBox.alert("Error","Raphael is not availabe");
34455             return;
34456         }
34457         
34458         this.raphael = Raphael(this.el.dom);
34459         
34460                     // data1 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
34461                     // data2 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
34462                     // data3 = [[55, 20, 13, 32, 5, 1, 2, 10], [10, 2, 1, 5, 32, 13, 20, 55], [12, 20, 30]],
34463                     // txtattr = { font: "12px 'Fontin Sans', Fontin-Sans, sans-serif" };
34464                 /*
34465                 r.text(160, 10, "Single Series Chart").attr(txtattr);
34466                 r.text(480, 10, "Multiline Series Chart").attr(txtattr);
34467                 r.text(160, 250, "Multiple Series Stacked Chart").attr(txtattr);
34468                 r.text(480, 250, 'Multiline Series Stacked Vertical Chart. Type "round"').attr(txtattr);
34469                 
34470                 r.barchart(10, 10, 300, 220, [[55, 20, 13, 32, 5, 1, 2, 10]], 0, {type: "sharp"});
34471                 r.barchart(330, 10, 300, 220, data1);
34472                 r.barchart(10, 250, 300, 220, data2, {stacked: true});
34473                 r.barchart(330, 250, 300, 220, data3, {stacked: true, type: "round"});
34474                 */
34475                 
34476                 // var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
34477                 // r.barchart(30, 30, 560, 250,  xdata, {
34478                 //    labels : [55, 20, 13, 32, 5, 1, 2, 10,5 , 10],
34479                 //     axis : "0 0 1 1",
34480                 //     axisxlabels :  xdata
34481                 //     //yvalues : cols,
34482                    
34483                 // });
34484 //        var xdata = [55, 20, 13, 32, 5, 1, 2, 10,5 , 10];
34485 //        
34486 //        this.load(null,xdata,{
34487 //                axis : "0 0 1 1",
34488 //                axisxlabels :  xdata
34489 //                });
34490
34491     },
34492
34493     load : function(graphtype,xdata,opts)
34494     {
34495         this.raphael.clear();
34496         if(!graphtype) {
34497             graphtype = this.graphtype;
34498         }
34499         if(!opts){
34500             opts = this.opts;
34501         }
34502         var r = this.raphael,
34503             fin = function () {
34504                 this.flag = r.popup(this.bar.x, this.bar.y, this.bar.value || "0").insertBefore(this);
34505             },
34506             fout = function () {
34507                 this.flag.animate({opacity: 0}, 300, function () {this.remove();});
34508             },
34509             pfin = function() {
34510                 this.sector.stop();
34511                 this.sector.scale(1.1, 1.1, this.cx, this.cy);
34512
34513                 if (this.label) {
34514                     this.label[0].stop();
34515                     this.label[0].attr({ r: 7.5 });
34516                     this.label[1].attr({ "font-weight": 800 });
34517                 }
34518             },
34519             pfout = function() {
34520                 this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce");
34521
34522                 if (this.label) {
34523                     this.label[0].animate({ r: 5 }, 500, "bounce");
34524                     this.label[1].attr({ "font-weight": 400 });
34525                 }
34526             };
34527
34528         switch(graphtype){
34529             case 'bar':
34530                 this.raphael.barchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
34531                 break;
34532             case 'hbar':
34533                 this.raphael.hbarchart(this.g_x,this.g_y,this.g_width,this.g_height,xdata,opts).hover(fin,fout);
34534                 break;
34535             case 'pie':
34536 //                opts = { legend: ["%% - Enterprise Users", "% - ddd","Chrome Users"], legendpos: "west", 
34537 //                href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]};
34538 //            
34539                 this.raphael.piechart(this.g_x,this.g_y,this.g_r,xdata,opts).hover(pfin, pfout);
34540                 
34541                 break;
34542
34543         }
34544         
34545         if(this.title){
34546             this.raphael.text(this.title.x, this.title.y, this.title.text).attr(this.title.attr);
34547         }
34548         
34549     },
34550     
34551     setTitle: function(o)
34552     {
34553         this.title = o;
34554     },
34555     
34556     initEvents: function() {
34557         
34558         if(!this.href){
34559             this.el.on('click', this.onClick, this);
34560         }
34561     },
34562     
34563     onClick : function(e)
34564     {
34565         Roo.log('img onclick');
34566         this.fireEvent('click', this, e);
34567     }
34568    
34569 });
34570
34571  
34572 Roo.bootstrap.dash = {};/*
34573  * - LGPL
34574  *
34575  * numberBox
34576  * 
34577  */
34578 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
34579
34580 /**
34581  * @class Roo.bootstrap.dash.NumberBox
34582  * @extends Roo.bootstrap.Component
34583  * Bootstrap NumberBox class
34584  * @cfg {String} headline Box headline
34585  * @cfg {String} content Box content
34586  * @cfg {String} icon Box icon
34587  * @cfg {String} footer Footer text
34588  * @cfg {String} fhref Footer href
34589  * 
34590  * @constructor
34591  * Create a new NumberBox
34592  * @param {Object} config The config object
34593  */
34594
34595
34596 Roo.bootstrap.dash.NumberBox = function(config){
34597     Roo.bootstrap.dash.NumberBox.superclass.constructor.call(this, config);
34598     
34599 };
34600
34601 Roo.extend(Roo.bootstrap.dash.NumberBox, Roo.bootstrap.Component,  {
34602     
34603     headline : '',
34604     content : '',
34605     icon : '',
34606     footer : '',
34607     fhref : '',
34608     ficon : '',
34609     
34610     getAutoCreate : function(){
34611         
34612         var cfg = {
34613             tag : 'div',
34614             cls : 'small-box ',
34615             cn : [
34616                 {
34617                     tag : 'div',
34618                     cls : 'inner',
34619                     cn :[
34620                         {
34621                             tag : 'h3',
34622                             cls : 'roo-headline',
34623                             html : this.headline
34624                         },
34625                         {
34626                             tag : 'p',
34627                             cls : 'roo-content',
34628                             html : this.content
34629                         }
34630                     ]
34631                 }
34632             ]
34633         };
34634         
34635         if(this.icon){
34636             cfg.cn.push({
34637                 tag : 'div',
34638                 cls : 'icon',
34639                 cn :[
34640                     {
34641                         tag : 'i',
34642                         cls : 'ion ' + this.icon
34643                     }
34644                 ]
34645             });
34646         }
34647         
34648         if(this.footer){
34649             var footer = {
34650                 tag : 'a',
34651                 cls : 'small-box-footer',
34652                 href : this.fhref || '#',
34653                 html : this.footer
34654             };
34655             
34656             cfg.cn.push(footer);
34657             
34658         }
34659         
34660         return  cfg;
34661     },
34662
34663     onRender : function(ct,position){
34664         Roo.bootstrap.dash.NumberBox.superclass.onRender.call(this,ct,position);
34665
34666
34667        
34668                 
34669     },
34670
34671     setHeadline: function (value)
34672     {
34673         this.el.select('.roo-headline',true).first().dom.innerHTML = value;
34674     },
34675     
34676     setFooter: function (value, href)
34677     {
34678         this.el.select('a.small-box-footer',true).first().dom.innerHTML = value;
34679         
34680         if(href){
34681             this.el.select('a.small-box-footer',true).first().attr('href', href);
34682         }
34683         
34684     },
34685
34686     setContent: function (value)
34687     {
34688         this.el.select('.roo-content',true).first().dom.innerHTML = value;
34689     },
34690
34691     initEvents: function() 
34692     {   
34693         
34694     }
34695     
34696 });
34697
34698  
34699 /*
34700  * - LGPL
34701  *
34702  * TabBox
34703  * 
34704  */
34705 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
34706
34707 /**
34708  * @class Roo.bootstrap.dash.TabBox
34709  * @extends Roo.bootstrap.Component
34710  * @children Roo.bootstrap.dash.TabPane
34711  * Bootstrap TabBox class
34712  * @cfg {String} title Title of the TabBox
34713  * @cfg {String} icon Icon of the TabBox
34714  * @cfg {Boolean} showtabs (true|false) show the tabs default true
34715  * @cfg {Boolean} tabScrollable (true|false) tab scrollable when mobile view default false
34716  * 
34717  * @constructor
34718  * Create a new TabBox
34719  * @param {Object} config The config object
34720  */
34721
34722
34723 Roo.bootstrap.dash.TabBox = function(config){
34724     Roo.bootstrap.dash.TabBox.superclass.constructor.call(this, config);
34725     this.addEvents({
34726         // raw events
34727         /**
34728          * @event addpane
34729          * When a pane is added
34730          * @param {Roo.bootstrap.dash.TabPane} pane
34731          */
34732         "addpane" : true,
34733         /**
34734          * @event activatepane
34735          * When a pane is activated
34736          * @param {Roo.bootstrap.dash.TabPane} pane
34737          */
34738         "activatepane" : true
34739         
34740          
34741     });
34742     
34743     this.panes = [];
34744 };
34745
34746 Roo.extend(Roo.bootstrap.dash.TabBox, Roo.bootstrap.Component,  {
34747
34748     title : '',
34749     icon : false,
34750     showtabs : true,
34751     tabScrollable : false,
34752     
34753     getChildContainer : function()
34754     {
34755         return this.el.select('.tab-content', true).first();
34756     },
34757     
34758     getAutoCreate : function(){
34759         
34760         var header = {
34761             tag: 'li',
34762             cls: 'pull-left header',
34763             html: this.title,
34764             cn : []
34765         };
34766         
34767         if(this.icon){
34768             header.cn.push({
34769                 tag: 'i',
34770                 cls: 'fa ' + this.icon
34771             });
34772         }
34773         
34774         var h = {
34775             tag: 'ul',
34776             cls: 'nav nav-tabs pull-right',
34777             cn: [
34778                 header
34779             ]
34780         };
34781         
34782         if(this.tabScrollable){
34783             h = {
34784                 tag: 'div',
34785                 cls: 'tab-header',
34786                 cn: [
34787                     {
34788                         tag: 'ul',
34789                         cls: 'nav nav-tabs pull-right',
34790                         cn: [
34791                             header
34792                         ]
34793                     }
34794                 ]
34795             };
34796         }
34797         
34798         var cfg = {
34799             tag: 'div',
34800             cls: 'nav-tabs-custom',
34801             cn: [
34802                 h,
34803                 {
34804                     tag: 'div',
34805                     cls: 'tab-content no-padding',
34806                     cn: []
34807                 }
34808             ]
34809         };
34810
34811         return  cfg;
34812     },
34813     initEvents : function()
34814     {
34815         //Roo.log('add add pane handler');
34816         this.on('addpane', this.onAddPane, this);
34817     },
34818      /**
34819      * Updates the box title
34820      * @param {String} html to set the title to.
34821      */
34822     setTitle : function(value)
34823     {
34824         this.el.select('.nav-tabs .header', true).first().dom.innerHTML = value;
34825     },
34826     onAddPane : function(pane)
34827     {
34828         this.panes.push(pane);
34829         //Roo.log('addpane');
34830         //Roo.log(pane);
34831         // tabs are rendere left to right..
34832         if(!this.showtabs){
34833             return;
34834         }
34835         
34836         var ctr = this.el.select('.nav-tabs', true).first();
34837          
34838          
34839         var existing = ctr.select('.nav-tab',true);
34840         var qty = existing.getCount();;
34841         
34842         
34843         var tab = ctr.createChild({
34844             tag : 'li',
34845             cls : 'nav-tab' + (qty ? '' : ' active'),
34846             cn : [
34847                 {
34848                     tag : 'a',
34849                     href:'#',
34850                     html : pane.title
34851                 }
34852             ]
34853         }, qty ? existing.first().dom : ctr.select('.header', true).first().dom );
34854         pane.tab = tab;
34855         
34856         tab.on('click', this.onTabClick.createDelegate(this, [pane], true));
34857         if (!qty) {
34858             pane.el.addClass('active');
34859         }
34860         
34861                 
34862     },
34863     onTabClick : function(ev,un,ob,pane)
34864     {
34865         //Roo.log('tab - prev default');
34866         ev.preventDefault();
34867         
34868         
34869         this.el.select('.nav-tabs li.nav-tab', true).removeClass('active');
34870         pane.tab.addClass('active');
34871         //Roo.log(pane.title);
34872         this.getChildContainer().select('.tab-pane',true).removeClass('active');
34873         // technically we should have a deactivate event.. but maybe add later.
34874         // and it should not de-activate the selected tab...
34875         this.fireEvent('activatepane', pane);
34876         pane.el.addClass('active');
34877         pane.fireEvent('activate');
34878         
34879         
34880     },
34881     
34882     getActivePane : function()
34883     {
34884         var r = false;
34885         Roo.each(this.panes, function(p) {
34886             if(p.el.hasClass('active')){
34887                 r = p;
34888                 return false;
34889             }
34890             
34891             return;
34892         });
34893         
34894         return r;
34895     }
34896     
34897     
34898 });
34899
34900  
34901 /*
34902  * - LGPL
34903  *
34904  * Tab pane
34905  * 
34906  */
34907 Roo.bootstrap.dash = Roo.bootstrap.dash || {};
34908 /**
34909  * @class Roo.bootstrap.TabPane
34910  * @extends Roo.bootstrap.Component
34911  * @children  Roo.bootstrap.Graph Roo.bootstrap.Column
34912  * Bootstrap TabPane class
34913  * @cfg {Boolean} active (false | true) Default false
34914  * @cfg {String} title title of panel
34915
34916  * 
34917  * @constructor
34918  * Create a new TabPane
34919  * @param {Object} config The config object
34920  */
34921
34922 Roo.bootstrap.dash.TabPane = function(config){
34923     Roo.bootstrap.dash.TabPane.superclass.constructor.call(this, config);
34924     
34925     this.addEvents({
34926         // raw events
34927         /**
34928          * @event activate
34929          * When a pane is activated
34930          * @param {Roo.bootstrap.dash.TabPane} pane
34931          */
34932         "activate" : true
34933          
34934     });
34935 };
34936
34937 Roo.extend(Roo.bootstrap.dash.TabPane, Roo.bootstrap.Component,  {
34938     
34939     active : false,
34940     title : '',
34941     
34942     // the tabBox that this is attached to.
34943     tab : false,
34944      
34945     getAutoCreate : function() 
34946     {
34947         var cfg = {
34948             tag: 'div',
34949             cls: 'tab-pane'
34950         };
34951         
34952         if(this.active){
34953             cfg.cls += ' active';
34954         }
34955         
34956         return cfg;
34957     },
34958     initEvents  : function()
34959     {
34960         //Roo.log('trigger add pane handler');
34961         this.parent().fireEvent('addpane', this)
34962     },
34963     
34964      /**
34965      * Updates the tab title 
34966      * @param {String} html to set the title to.
34967      */
34968     setTitle: function(str)
34969     {
34970         if (!this.tab) {
34971             return;
34972         }
34973         this.title = str;
34974         this.tab.select('a', true).first().dom.innerHTML = str;
34975         
34976     }
34977     
34978     
34979     
34980 });
34981
34982  
34983
34984
34985  /*
34986  * - LGPL
34987  *
34988  * Tooltip
34989  * 
34990  */
34991
34992 /**
34993  * @class Roo.bootstrap.Tooltip
34994  * Bootstrap Tooltip class
34995  * This is basic at present - all componets support it by default, however they should add tooltipEl() method
34996  * to determine which dom element triggers the tooltip.
34997  * 
34998  * It needs to add support for additional attributes like tooltip-position
34999  * 
35000  * @constructor
35001  * Create a new Toolti
35002  * @param {Object} config The config object
35003  */
35004
35005 Roo.bootstrap.Tooltip = function(config){
35006     Roo.bootstrap.Tooltip.superclass.constructor.call(this, config);
35007     
35008     this.alignment = Roo.bootstrap.Tooltip.alignment;
35009     
35010     if(typeof(config) != 'undefined' && typeof(config.alignment) != 'undefined'){
35011         this.alignment = config.alignment;
35012     }
35013     
35014 };
35015
35016 Roo.apply(Roo.bootstrap.Tooltip, {
35017     /**
35018      * @function init initialize tooltip monitoring.
35019      * @static
35020      */
35021     currentEl : false,
35022     currentTip : false,
35023     currentRegion : false,
35024     
35025     //  init : delay?
35026     
35027     init : function()
35028     {
35029         Roo.get(document).on('mouseover', this.enter ,this);
35030         Roo.get(document).on('mouseout', this.leave, this);
35031          
35032         
35033         this.currentTip = new Roo.bootstrap.Tooltip();
35034     },
35035     
35036     enter : function(ev)
35037     {
35038         var dom = ev.getTarget();
35039         
35040         //Roo.log(['enter',dom]);
35041         var el = Roo.fly(dom);
35042         if (this.currentEl) {
35043             //Roo.log(dom);
35044             //Roo.log(this.currentEl);
35045             //Roo.log(this.currentEl.contains(dom));
35046             if (this.currentEl == el) {
35047                 return;
35048             }
35049             if (dom != this.currentEl.dom && this.currentEl.contains(dom)) {
35050                 return;
35051             }
35052
35053         }
35054         
35055         if (this.currentTip.el) {
35056             this.currentTip.el.setVisibilityMode(Roo.Element.DISPLAY).hide(); // force hiding...
35057         }    
35058         //Roo.log(ev);
35059         
35060         if(!el || el.dom == document){
35061             return;
35062         }
35063         
35064         var bindEl = el; 
35065         var pel = false;
35066         if (!el.attr('tooltip')) {
35067             pel = el.findParent("[tooltip]");
35068             if (pel) {
35069                 bindEl = Roo.get(pel);
35070             }
35071         }
35072         
35073        
35074         
35075         // you can not look for children, as if el is the body.. then everythign is the child..
35076         if (!pel && !el.attr('tooltip')) { //
35077             if (!el.select("[tooltip]").elements.length) {
35078                 return;
35079             }
35080             // is the mouse over this child...?
35081             bindEl = el.select("[tooltip]").first();
35082             var xy = ev.getXY();
35083             if (!bindEl.getRegion().contains( { top : xy[1] ,right : xy[0] , bottom : xy[1], left : xy[0]})) {
35084                 //Roo.log("not in region.");
35085                 return;
35086             }
35087             //Roo.log("child element over..");
35088             
35089         }
35090         this.currentEl = el;
35091         this.currentTip.bind(bindEl);
35092         this.currentRegion = Roo.lib.Region.getRegion(dom);
35093         this.currentTip.enter();
35094         
35095     },
35096     leave : function(ev)
35097     {
35098         var dom = ev.getTarget();
35099         //Roo.log(['leave',dom]);
35100         if (!this.currentEl) {
35101             return;
35102         }
35103         
35104         
35105         if (dom != this.currentEl.dom) {
35106             return;
35107         }
35108         var xy = ev.getXY();
35109         if (this.currentRegion.contains( new Roo.lib.Region( xy[1], xy[0] ,xy[1], xy[0]  ))) {
35110             return;
35111         }
35112         // only activate leave if mouse cursor is outside... bounding box..
35113         
35114         
35115         
35116         
35117         if (this.currentTip) {
35118             this.currentTip.leave();
35119         }
35120         //Roo.log('clear currentEl');
35121         this.currentEl = false;
35122         
35123         
35124     },
35125     alignment : {
35126         'left' : ['r-l', [-2,0], 'right'],
35127         'right' : ['l-r', [2,0], 'left'],
35128         'bottom' : ['t-b', [0,2], 'top'],
35129         'top' : [ 'b-t', [0,-2], 'bottom']
35130     }
35131     
35132 });
35133
35134
35135 Roo.extend(Roo.bootstrap.Tooltip, Roo.bootstrap.Component,  {
35136     
35137     
35138     bindEl : false,
35139     
35140     delay : null, // can be { show : 300 , hide: 500}
35141     
35142     timeout : null,
35143     
35144     hoverState : null, //???
35145     
35146     placement : 'bottom', 
35147     
35148     alignment : false,
35149     
35150     getAutoCreate : function(){
35151     
35152         var cfg = {
35153            cls : 'tooltip',   
35154            role : 'tooltip',
35155            cn : [
35156                 {
35157                     cls : 'tooltip-arrow arrow'
35158                 },
35159                 {
35160                     cls : 'tooltip-inner'
35161                 }
35162            ]
35163         };
35164         
35165         return cfg;
35166     },
35167     bind : function(el)
35168     {
35169         this.bindEl = el;
35170     },
35171     
35172     initEvents : function()
35173     {
35174         this.arrowEl = this.el.select('.arrow', true).first();
35175         this.innerEl = this.el.select('.tooltip-inner', true).first();
35176     },
35177     
35178     enter : function () {
35179        
35180         if (this.timeout != null) {
35181             clearTimeout(this.timeout);
35182         }
35183         
35184         this.hoverState = 'in';
35185          //Roo.log("enter - show");
35186         if (!this.delay || !this.delay.show) {
35187             this.show();
35188             return;
35189         }
35190         var _t = this;
35191         this.timeout = setTimeout(function () {
35192             if (_t.hoverState == 'in') {
35193                 _t.show();
35194             }
35195         }, this.delay.show);
35196     },
35197     leave : function()
35198     {
35199         clearTimeout(this.timeout);
35200     
35201         this.hoverState = 'out';
35202          if (!this.delay || !this.delay.hide) {
35203             this.hide();
35204             return;
35205         }
35206        
35207         var _t = this;
35208         this.timeout = setTimeout(function () {
35209             //Roo.log("leave - timeout");
35210             
35211             if (_t.hoverState == 'out') {
35212                 _t.hide();
35213                 Roo.bootstrap.Tooltip.currentEl = false;
35214             }
35215         }, delay);
35216     },
35217     
35218     show : function (msg)
35219     {
35220         if (!this.el) {
35221             this.render(document.body);
35222         }
35223         // set content.
35224         //Roo.log([this.bindEl, this.bindEl.attr('tooltip')]);
35225         
35226         var tip = msg || this.bindEl.attr('tooltip') || this.bindEl.select("[tooltip]").first().attr('tooltip');
35227         
35228         this.el.select('.tooltip-inner',true).first().dom.innerHTML = tip;
35229         
35230         this.el.removeClass(['fade','top','bottom', 'left', 'right','in',
35231                              'bs-tooltip-top','bs-tooltip-bottom', 'bs-tooltip-left', 'bs-tooltip-right']);
35232
35233         if(this.bindEl.attr('tooltip-class')) {
35234             this.el.addClass(this.bindEl.attr('tooltip-class'));
35235         }
35236         
35237         var placement = typeof this.placement == 'function' ?
35238             this.placement.call(this, this.el, on_el) :
35239             this.placement;
35240         
35241         if(this.bindEl.attr('tooltip-placement')) {
35242             placement = this.bindEl.attr('tooltip-placement');
35243         }
35244             
35245         var autoToken = /\s?auto?\s?/i;
35246         var autoPlace = autoToken.test(placement);
35247         if (autoPlace) {
35248             placement = placement.replace(autoToken, '') || 'top';
35249         }
35250         
35251         //this.el.detach()
35252         //this.el.setXY([0,0]);
35253         this.el.show();
35254         //this.el.dom.style.display='block';
35255         
35256         //this.el.appendTo(on_el);
35257         
35258         var p = this.getPosition();
35259         var box = this.el.getBox();
35260         
35261         if (autoPlace) {
35262             // fixme..
35263         }
35264         
35265         var align = this.alignment[placement];
35266         
35267         var xy = this.el.getAlignToXY(this.bindEl, align[0], align[1]);
35268         
35269         if(placement == 'top' || placement == 'bottom'){
35270             if(xy[0] < 0){
35271                 placement = 'right';
35272             }
35273             
35274             if(xy[0] + this.el.getWidth() > Roo.lib.Dom.getViewWidth()){
35275                 placement = 'left';
35276             }
35277             
35278             var scroll = Roo.select('body', true).first().getScroll();
35279             
35280             if(xy[1] > Roo.lib.Dom.getViewHeight() + scroll.top - this.el.getHeight()){
35281                 placement = 'top';
35282             }
35283             
35284             align = this.alignment[placement];
35285             
35286             this.arrowEl.setLeft((this.innerEl.getWidth()/2) - 5);
35287             
35288         }
35289         
35290         var elems = document.getElementsByTagName('div');
35291         var highest = Number.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);
35292         for (var i = 0; i < elems.length; i++) {
35293           var zindex = Number.parseInt(
35294                 document.defaultView.getComputedStyle(elems[i], null).getPropertyValue("z-index"),
35295                 10
35296           );
35297           if (zindex > highest) {
35298             highest = zindex;
35299           }
35300         }
35301         
35302         
35303         
35304         this.el.dom.style.zIndex = highest;
35305         
35306         this.el.alignTo(this.bindEl, align[0],align[1]);
35307         //var arrow = this.el.select('.arrow',true).first();
35308         //arrow.set(align[2], 
35309         
35310         this.el.addClass(placement);
35311         this.el.addClass("bs-tooltip-"+ placement);
35312         
35313         this.el.addClass('in fade show');
35314         
35315         this.hoverState = null;
35316         
35317         if (this.el.hasClass('fade')) {
35318             // fade it?
35319         }
35320         
35321         
35322         
35323         
35324         
35325     },
35326     hide : function()
35327     {
35328          
35329         if (!this.el) {
35330             return;
35331         }
35332         //this.el.setXY([0,0]);
35333         if(this.bindEl.attr('tooltip-class')) {
35334             this.el.removeClass(this.bindEl.attr('tooltip-class'));
35335         }
35336         this.el.removeClass(['show', 'in']);
35337         //this.el.hide();
35338         
35339     }
35340     
35341 });
35342  
35343
35344  /*
35345  * - LGPL
35346  *
35347  * Location Picker
35348  * 
35349  */
35350
35351 /**
35352  * @class Roo.bootstrap.LocationPicker
35353  * @extends Roo.bootstrap.Component
35354  * Bootstrap LocationPicker class
35355  * @cfg {Number} latitude Position when init default 0
35356  * @cfg {Number} longitude Position when init default 0
35357  * @cfg {Number} zoom default 15
35358  * @cfg {String} mapTypeId default google.maps.MapTypeId.ROADMAP
35359  * @cfg {Boolean} mapTypeControl default false
35360  * @cfg {Boolean} disableDoubleClickZoom default false
35361  * @cfg {Boolean} scrollwheel default true
35362  * @cfg {Boolean} streetViewControl default false
35363  * @cfg {Number} radius default 0
35364  * @cfg {String} locationName
35365  * @cfg {Boolean} draggable default true
35366  * @cfg {Boolean} enableAutocomplete default false
35367  * @cfg {Boolean} enableReverseGeocode default true
35368  * @cfg {String} markerTitle
35369  * 
35370  * @constructor
35371  * Create a new LocationPicker
35372  * @param {Object} config The config object
35373  */
35374
35375
35376 Roo.bootstrap.LocationPicker = function(config){
35377     
35378     Roo.bootstrap.LocationPicker.superclass.constructor.call(this, config);
35379     
35380     this.addEvents({
35381         /**
35382          * @event initial
35383          * Fires when the picker initialized.
35384          * @param {Roo.bootstrap.LocationPicker} this
35385          * @param {Google Location} location
35386          */
35387         initial : true,
35388         /**
35389          * @event positionchanged
35390          * Fires when the picker position changed.
35391          * @param {Roo.bootstrap.LocationPicker} this
35392          * @param {Google Location} location
35393          */
35394         positionchanged : true,
35395         /**
35396          * @event resize
35397          * Fires when the map resize.
35398          * @param {Roo.bootstrap.LocationPicker} this
35399          */
35400         resize : true,
35401         /**
35402          * @event show
35403          * Fires when the map show.
35404          * @param {Roo.bootstrap.LocationPicker} this
35405          */
35406         show : true,
35407         /**
35408          * @event hide
35409          * Fires when the map hide.
35410          * @param {Roo.bootstrap.LocationPicker} this
35411          */
35412         hide : true,
35413         /**
35414          * @event mapClick
35415          * Fires when click the map.
35416          * @param {Roo.bootstrap.LocationPicker} this
35417          * @param {Map event} e
35418          */
35419         mapClick : true,
35420         /**
35421          * @event mapRightClick
35422          * Fires when right click the map.
35423          * @param {Roo.bootstrap.LocationPicker} this
35424          * @param {Map event} e
35425          */
35426         mapRightClick : true,
35427         /**
35428          * @event markerClick
35429          * Fires when click the marker.
35430          * @param {Roo.bootstrap.LocationPicker} this
35431          * @param {Map event} e
35432          */
35433         markerClick : true,
35434         /**
35435          * @event markerRightClick
35436          * Fires when right click the marker.
35437          * @param {Roo.bootstrap.LocationPicker} this
35438          * @param {Map event} e
35439          */
35440         markerRightClick : true,
35441         /**
35442          * @event OverlayViewDraw
35443          * Fires when OverlayView Draw
35444          * @param {Roo.bootstrap.LocationPicker} this
35445          */
35446         OverlayViewDraw : true,
35447         /**
35448          * @event OverlayViewOnAdd
35449          * Fires when OverlayView Draw
35450          * @param {Roo.bootstrap.LocationPicker} this
35451          */
35452         OverlayViewOnAdd : true,
35453         /**
35454          * @event OverlayViewOnRemove
35455          * Fires when OverlayView Draw
35456          * @param {Roo.bootstrap.LocationPicker} this
35457          */
35458         OverlayViewOnRemove : true,
35459         /**
35460          * @event OverlayViewShow
35461          * Fires when OverlayView Draw
35462          * @param {Roo.bootstrap.LocationPicker} this
35463          * @param {Pixel} cpx
35464          */
35465         OverlayViewShow : true,
35466         /**
35467          * @event OverlayViewHide
35468          * Fires when OverlayView Draw
35469          * @param {Roo.bootstrap.LocationPicker} this
35470          */
35471         OverlayViewHide : true,
35472         /**
35473          * @event loadexception
35474          * Fires when load google lib failed.
35475          * @param {Roo.bootstrap.LocationPicker} this
35476          */
35477         loadexception : true
35478     });
35479         
35480 };
35481
35482 Roo.extend(Roo.bootstrap.LocationPicker, Roo.bootstrap.Component,  {
35483     
35484     gMapContext: false,
35485     
35486     latitude: 0,
35487     longitude: 0,
35488     zoom: 15,
35489     mapTypeId: false,
35490     mapTypeControl: false,
35491     disableDoubleClickZoom: false,
35492     scrollwheel: true,
35493     streetViewControl: false,
35494     radius: 0,
35495     locationName: '',
35496     draggable: true,
35497     enableAutocomplete: false,
35498     enableReverseGeocode: true,
35499     markerTitle: '',
35500     
35501     getAutoCreate: function()
35502     {
35503
35504         var cfg = {
35505             tag: 'div',
35506             cls: 'roo-location-picker'
35507         };
35508         
35509         return cfg
35510     },
35511     
35512     initEvents: function(ct, position)
35513     {       
35514         if(!this.el.getWidth() || this.isApplied()){
35515             return;
35516         }
35517         
35518         this.el.setVisibilityMode(Roo.Element.DISPLAY);
35519         
35520         this.initial();
35521     },
35522     
35523     initial: function()
35524     {
35525         if(typeof(google) == 'undefined' || typeof(google.maps) == 'undefined'){
35526             this.fireEvent('loadexception', this);
35527             return;
35528         }
35529         
35530         if(!this.mapTypeId){
35531             this.mapTypeId = google.maps.MapTypeId.ROADMAP;
35532         }
35533         
35534         this.gMapContext = this.GMapContext();
35535         
35536         this.initOverlayView();
35537         
35538         this.OverlayView = new Roo.bootstrap.LocationPicker.OverlayView(this.gMapContext.map);
35539         
35540         var _this = this;
35541                 
35542         google.maps.event.addListener(this.gMapContext.marker, "dragend", function(event) {
35543             _this.setPosition(_this.gMapContext.marker.position);
35544         });
35545         
35546         google.maps.event.addListener(this.gMapContext.map, 'click', function(event){
35547             _this.fireEvent('mapClick', this, event);
35548             
35549         });
35550
35551         google.maps.event.addListener(this.gMapContext.map, 'rightclick', function(event){
35552             _this.fireEvent('mapRightClick', this, event);
35553             
35554         });
35555         
35556         google.maps.event.addListener(this.gMapContext.marker, 'click', function(event){
35557             _this.fireEvent('markerClick', this, event);
35558             
35559         });
35560
35561         google.maps.event.addListener(this.gMapContext.marker, 'rightclick', function(event){
35562             _this.fireEvent('markerRightClick', this, event);
35563             
35564         });
35565         
35566         this.setPosition(this.gMapContext.location);
35567         
35568         this.fireEvent('initial', this, this.gMapContext.location);
35569     },
35570     
35571     initOverlayView: function()
35572     {
35573         var _this = this;
35574         
35575         Roo.bootstrap.LocationPicker.OverlayView.prototype = Roo.apply(new google.maps.OverlayView(), {
35576             
35577             draw: function()
35578             {
35579                 _this.fireEvent('OverlayViewDraw', _this);
35580             },
35581             
35582             onAdd: function()
35583             {
35584                 _this.fireEvent('OverlayViewOnAdd', _this);
35585             },
35586             
35587             onRemove: function()
35588             {
35589                 _this.fireEvent('OverlayViewOnRemove', _this);
35590             },
35591             
35592             show: function(cpx)
35593             {
35594                 _this.fireEvent('OverlayViewShow', _this, cpx);
35595             },
35596             
35597             hide: function()
35598             {
35599                 _this.fireEvent('OverlayViewHide', _this);
35600             }
35601             
35602         });
35603     },
35604     
35605     fromLatLngToContainerPixel: function(event)
35606     {
35607         return this.OverlayView.getProjection().fromLatLngToContainerPixel(event.latLng);
35608     },
35609     
35610     isApplied: function() 
35611     {
35612         return this.getGmapContext() == false ? false : true;
35613     },
35614     
35615     getGmapContext: function() 
35616     {
35617         return (typeof(this.gMapContext) == 'undefined') ? false : this.gMapContext;
35618     },
35619     
35620     GMapContext: function() 
35621     {
35622         var position = new google.maps.LatLng(this.latitude, this.longitude);
35623         
35624         var _map = new google.maps.Map(this.el.dom, {
35625             center: position,
35626             zoom: this.zoom,
35627             mapTypeId: this.mapTypeId,
35628             mapTypeControl: this.mapTypeControl,
35629             disableDoubleClickZoom: this.disableDoubleClickZoom,
35630             scrollwheel: this.scrollwheel,
35631             streetViewControl: this.streetViewControl,
35632             locationName: this.locationName,
35633             draggable: this.draggable,
35634             enableAutocomplete: this.enableAutocomplete,
35635             enableReverseGeocode: this.enableReverseGeocode
35636         });
35637         
35638         var _marker = new google.maps.Marker({
35639             position: position,
35640             map: _map,
35641             title: this.markerTitle,
35642             draggable: this.draggable
35643         });
35644         
35645         return {
35646             map: _map,
35647             marker: _marker,
35648             circle: null,
35649             location: position,
35650             radius: this.radius,
35651             locationName: this.locationName,
35652             addressComponents: {
35653                 formatted_address: null,
35654                 addressLine1: null,
35655                 addressLine2: null,
35656                 streetName: null,
35657                 streetNumber: null,
35658                 city: null,
35659                 district: null,
35660                 state: null,
35661                 stateOrProvince: null
35662             },
35663             settings: this,
35664             domContainer: this.el.dom,
35665             geodecoder: new google.maps.Geocoder()
35666         };
35667     },
35668     
35669     drawCircle: function(center, radius, options) 
35670     {
35671         if (this.gMapContext.circle != null) {
35672             this.gMapContext.circle.setMap(null);
35673         }
35674         if (radius > 0) {
35675             radius *= 1;
35676             options = Roo.apply({}, options, {
35677                 strokeColor: "#0000FF",
35678                 strokeOpacity: .35,
35679                 strokeWeight: 2,
35680                 fillColor: "#0000FF",
35681                 fillOpacity: .2
35682             });
35683             
35684             options.map = this.gMapContext.map;
35685             options.radius = radius;
35686             options.center = center;
35687             this.gMapContext.circle = new google.maps.Circle(options);
35688             return this.gMapContext.circle;
35689         }
35690         
35691         return null;
35692     },
35693     
35694     setPosition: function(location) 
35695     {
35696         this.gMapContext.location = location;
35697         this.gMapContext.marker.setPosition(location);
35698         this.gMapContext.map.panTo(location);
35699         this.drawCircle(location, this.gMapContext.radius, {});
35700         
35701         var _this = this;
35702         
35703         if (this.gMapContext.settings.enableReverseGeocode) {
35704             this.gMapContext.geodecoder.geocode({
35705                 latLng: this.gMapContext.location
35706             }, function(results, status) {
35707                 
35708                 if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
35709                     _this.gMapContext.locationName = results[0].formatted_address;
35710                     _this.gMapContext.addressComponents = _this.address_component_from_google_geocode(results[0].address_components);
35711                     
35712                     _this.fireEvent('positionchanged', this, location);
35713                 }
35714             });
35715             
35716             return;
35717         }
35718         
35719         this.fireEvent('positionchanged', this, location);
35720     },
35721     
35722     resize: function()
35723     {
35724         google.maps.event.trigger(this.gMapContext.map, "resize");
35725         
35726         this.gMapContext.map.setCenter(this.gMapContext.marker.position);
35727         
35728         this.fireEvent('resize', this);
35729     },
35730     
35731     setPositionByLatLng: function(latitude, longitude)
35732     {
35733         this.setPosition(new google.maps.LatLng(latitude, longitude));
35734     },
35735     
35736     getCurrentPosition: function() 
35737     {
35738         return {
35739             latitude: this.gMapContext.location.lat(),
35740             longitude: this.gMapContext.location.lng()
35741         };
35742     },
35743     
35744     getAddressName: function() 
35745     {
35746         return this.gMapContext.locationName;
35747     },
35748     
35749     getAddressComponents: function() 
35750     {
35751         return this.gMapContext.addressComponents;
35752     },
35753     
35754     address_component_from_google_geocode: function(address_components) 
35755     {
35756         var result = {};
35757         
35758         for (var i = 0; i < address_components.length; i++) {
35759             var component = address_components[i];
35760             if (component.types.indexOf("postal_code") >= 0) {
35761                 result.postalCode = component.short_name;
35762             } else if (component.types.indexOf("street_number") >= 0) {
35763                 result.streetNumber = component.short_name;
35764             } else if (component.types.indexOf("route") >= 0) {
35765                 result.streetName = component.short_name;
35766             } else if (component.types.indexOf("neighborhood") >= 0) {
35767                 result.city = component.short_name;
35768             } else if (component.types.indexOf("locality") >= 0) {
35769                 result.city = component.short_name;
35770             } else if (component.types.indexOf("sublocality") >= 0) {
35771                 result.district = component.short_name;
35772             } else if (component.types.indexOf("administrative_area_level_1") >= 0) {
35773                 result.stateOrProvince = component.short_name;
35774             } else if (component.types.indexOf("country") >= 0) {
35775                 result.country = component.short_name;
35776             }
35777         }
35778         
35779         result.addressLine1 = [ result.streetNumber, result.streetName ].join(" ").trim();
35780         result.addressLine2 = "";
35781         return result;
35782     },
35783     
35784     setZoomLevel: function(zoom)
35785     {
35786         this.gMapContext.map.setZoom(zoom);
35787     },
35788     
35789     show: function()
35790     {
35791         if(!this.el){
35792             return;
35793         }
35794         
35795         this.el.show();
35796         
35797         this.resize();
35798         
35799         this.fireEvent('show', this);
35800     },
35801     
35802     hide: function()
35803     {
35804         if(!this.el){
35805             return;
35806         }
35807         
35808         this.el.hide();
35809         
35810         this.fireEvent('hide', this);
35811     }
35812     
35813 });
35814
35815 Roo.apply(Roo.bootstrap.LocationPicker, {
35816     
35817     OverlayView : function(map, options)
35818     {
35819         options = options || {};
35820         
35821         this.setMap(map);
35822     }
35823     
35824     
35825 });/**
35826  * @class Roo.bootstrap.Alert
35827  * @extends Roo.bootstrap.Component
35828  * Bootstrap Alert class - shows an alert area box
35829  * eg
35830  * <div class="alert alert-danger" role="alert"><span class="fa fa-exclamation-triangle"></span><span class="sr-only">Error:</span>
35831   Enter a valid email address
35832 </div>
35833  * @licence LGPL
35834  * @cfg {String} title The title of alert
35835  * @cfg {String} html The content of alert
35836  * @cfg {String} weight (success|info|warning|danger) Weight of the message
35837  * @cfg {String} fa font-awesomeicon
35838  * @cfg {Number} seconds default:-1 Number of seconds until it disapears (-1 means never.)
35839  * @cfg {Boolean} close true to show a x closer
35840  * 
35841  * 
35842  * @constructor
35843  * Create a new alert
35844  * @param {Object} config The config object
35845  */
35846
35847
35848 Roo.bootstrap.Alert = function(config){
35849     Roo.bootstrap.Alert.superclass.constructor.call(this, config);
35850     
35851 };
35852
35853 Roo.extend(Roo.bootstrap.Alert, Roo.bootstrap.Component,  {
35854     
35855     title: '',
35856     html: '',
35857     weight: false,
35858     fa: false,
35859     faicon: false, // BC
35860     close : false,
35861     
35862     
35863     getAutoCreate : function()
35864     {
35865         
35866         var cfg = {
35867             tag : 'div',
35868             cls : 'alert',
35869             cn : [
35870                 {
35871                     tag: 'button',
35872                     type :  "button",
35873                     cls: "close",
35874                     html : '×',
35875                     style : this.close ? '' : 'display:none'
35876                 },
35877                 {
35878                     tag : 'i',
35879                     cls : 'roo-alert-icon'
35880                     
35881                 },
35882                 {
35883                     tag : 'b',
35884                     cls : 'roo-alert-title',
35885                     html : this.title
35886                 },
35887                 {
35888                     tag : 'span',
35889                     cls : 'roo-alert-text',
35890                     html : this.html
35891                 }
35892             ]
35893         };
35894         
35895         if(this.faicon){
35896             cfg.cn[0].cls += ' fa ' + this.faicon;
35897         }
35898         if(this.fa){
35899             cfg.cn[0].cls += ' fa ' + this.fa;
35900         }
35901         
35902         if(this.weight){
35903             cfg.cls += ' alert-' + this.weight;
35904         }
35905         
35906         return cfg;
35907     },
35908     
35909     initEvents: function() 
35910     {
35911         this.el.setVisibilityMode(Roo.Element.DISPLAY);
35912         this.titleEl =  this.el.select('.roo-alert-title',true).first();
35913         this.iconEl = this.el.select('.roo-alert-icon',true).first();
35914         this.htmlEl = this.el.select('.roo-alert-text',true).first();
35915         if (this.seconds > 0) {
35916             this.hide.defer(this.seconds, this);
35917         }
35918     },
35919     /**
35920      * Set the Title Message HTML
35921      * @param {String} html
35922      */
35923     setTitle : function(str)
35924     {
35925         this.titleEl.dom.innerHTML = str;
35926     },
35927      
35928      /**
35929      * Set the Body Message HTML
35930      * @param {String} html
35931      */
35932     setHtml : function(str)
35933     {
35934         this.htmlEl.dom.innerHTML = str;
35935     },
35936     /**
35937      * Set the Weight of the alert
35938      * @param {String} (success|info|warning|danger) weight
35939      */
35940     
35941     setWeight : function(weight)
35942     {
35943         if(this.weight){
35944             this.el.removeClass('alert-' + this.weight);
35945         }
35946         
35947         this.weight = weight;
35948         
35949         this.el.addClass('alert-' + this.weight);
35950     },
35951       /**
35952      * Set the Icon of the alert
35953      * @param {String} see fontawsome names (name without the 'fa-' bit)
35954      */
35955     setIcon : function(icon)
35956     {
35957         if(this.faicon){
35958             this.alertEl.removeClass(['fa', 'fa-' + this.faicon]);
35959         }
35960         
35961         this.faicon = icon;
35962         
35963         this.alertEl.addClass(['fa', 'fa-' + this.faicon]);
35964     },
35965     /**
35966      * Hide the Alert
35967      */
35968     hide: function() 
35969     {
35970         this.el.hide();   
35971     },
35972     /**
35973      * Show the Alert
35974      */
35975     show: function() 
35976     {  
35977         this.el.show();   
35978     }
35979     
35980 });
35981
35982  
35983 /*
35984 * Licence: LGPL
35985 */
35986
35987 /**
35988  * @class Roo.bootstrap.UploadCropbox
35989  * @extends Roo.bootstrap.Component
35990  * Bootstrap UploadCropbox class
35991  * @cfg {String} emptyText show when image has been loaded
35992  * @cfg {String} rotateNotify show when image too small to rotate
35993  * @cfg {Number} errorTimeout default 3000
35994  * @cfg {Number} minWidth default 300
35995  * @cfg {Number} minHeight default 300
35996  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
35997  * @cfg {Boolean} isDocument (true|false) default false
35998  * @cfg {String} url action url
35999  * @cfg {String} paramName default 'imageUpload'
36000  * @cfg {String} method default POST
36001  * @cfg {Boolean} loadMask (true|false) default true
36002  * @cfg {Boolean} loadingText default 'Loading...'
36003  * 
36004  * @constructor
36005  * Create a new UploadCropbox
36006  * @param {Object} config The config object
36007  */
36008
36009 Roo.bootstrap.UploadCropbox = function(config){
36010     Roo.bootstrap.UploadCropbox.superclass.constructor.call(this, config);
36011     
36012     this.addEvents({
36013         /**
36014          * @event beforeselectfile
36015          * Fire before select file
36016          * @param {Roo.bootstrap.UploadCropbox} this
36017          */
36018         "beforeselectfile" : true,
36019         /**
36020          * @event initial
36021          * Fire after initEvent
36022          * @param {Roo.bootstrap.UploadCropbox} this
36023          */
36024         "initial" : true,
36025         /**
36026          * @event crop
36027          * Fire after initEvent
36028          * @param {Roo.bootstrap.UploadCropbox} this
36029          * @param {String} data
36030          */
36031         "crop" : true,
36032         /**
36033          * @event prepare
36034          * Fire when preparing the file data
36035          * @param {Roo.bootstrap.UploadCropbox} this
36036          * @param {Object} file
36037          */
36038         "prepare" : true,
36039         /**
36040          * @event exception
36041          * Fire when get exception
36042          * @param {Roo.bootstrap.UploadCropbox} this
36043          * @param {XMLHttpRequest} xhr
36044          */
36045         "exception" : true,
36046         /**
36047          * @event beforeloadcanvas
36048          * Fire before load the canvas
36049          * @param {Roo.bootstrap.UploadCropbox} this
36050          * @param {String} src
36051          */
36052         "beforeloadcanvas" : true,
36053         /**
36054          * @event trash
36055          * Fire when trash image
36056          * @param {Roo.bootstrap.UploadCropbox} this
36057          */
36058         "trash" : true,
36059         /**
36060          * @event download
36061          * Fire when download the image
36062          * @param {Roo.bootstrap.UploadCropbox} this
36063          */
36064         "download" : true,
36065         /**
36066          * @event footerbuttonclick
36067          * Fire when footerbuttonclick
36068          * @param {Roo.bootstrap.UploadCropbox} this
36069          * @param {String} type
36070          */
36071         "footerbuttonclick" : true,
36072         /**
36073          * @event resize
36074          * Fire when resize
36075          * @param {Roo.bootstrap.UploadCropbox} this
36076          */
36077         "resize" : true,
36078         /**
36079          * @event rotate
36080          * Fire when rotate the image
36081          * @param {Roo.bootstrap.UploadCropbox} this
36082          * @param {String} pos
36083          */
36084         "rotate" : true,
36085         /**
36086          * @event inspect
36087          * Fire when inspect the file
36088          * @param {Roo.bootstrap.UploadCropbox} this
36089          * @param {Object} file
36090          */
36091         "inspect" : true,
36092         /**
36093          * @event upload
36094          * Fire when xhr upload the file
36095          * @param {Roo.bootstrap.UploadCropbox} this
36096          * @param {Object} data
36097          */
36098         "upload" : true,
36099         /**
36100          * @event arrange
36101          * Fire when arrange the file data
36102          * @param {Roo.bootstrap.UploadCropbox} this
36103          * @param {Object} formData
36104          */
36105         "arrange" : true
36106     });
36107     
36108     this.buttons = this.buttons || Roo.bootstrap.UploadCropbox.footer.STANDARD;
36109 };
36110
36111 Roo.extend(Roo.bootstrap.UploadCropbox, Roo.bootstrap.Component,  {
36112     
36113     emptyText : 'Click to upload image',
36114     rotateNotify : 'Image is too small to rotate',
36115     errorTimeout : 3000,
36116     scale : 0,
36117     baseScale : 1,
36118     rotate : 0,
36119     dragable : false,
36120     pinching : false,
36121     mouseX : 0,
36122     mouseY : 0,
36123     cropData : false,
36124     minWidth : 300,
36125     minHeight : 300,
36126     file : false,
36127     exif : {},
36128     baseRotate : 1,
36129     cropType : 'image/jpeg',
36130     buttons : false,
36131     canvasLoaded : false,
36132     isDocument : false,
36133     method : 'POST',
36134     paramName : 'imageUpload',
36135     loadMask : true,
36136     loadingText : 'Loading...',
36137     maskEl : false,
36138     
36139     getAutoCreate : function()
36140     {
36141         var cfg = {
36142             tag : 'div',
36143             cls : 'roo-upload-cropbox',
36144             cn : [
36145                 {
36146                     tag : 'input',
36147                     cls : 'roo-upload-cropbox-selector',
36148                     type : 'file'
36149                 },
36150                 {
36151                     tag : 'div',
36152                     cls : 'roo-upload-cropbox-body',
36153                     style : 'cursor:pointer',
36154                     cn : [
36155                         {
36156                             tag : 'div',
36157                             cls : 'roo-upload-cropbox-preview'
36158                         },
36159                         {
36160                             tag : 'div',
36161                             cls : 'roo-upload-cropbox-thumb'
36162                         },
36163                         {
36164                             tag : 'div',
36165                             cls : 'roo-upload-cropbox-empty-notify',
36166                             html : this.emptyText
36167                         },
36168                         {
36169                             tag : 'div',
36170                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
36171                             html : this.rotateNotify
36172                         }
36173                     ]
36174                 },
36175                 {
36176                     tag : 'div',
36177                     cls : 'roo-upload-cropbox-footer',
36178                     cn : {
36179                         tag : 'div',
36180                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
36181                         cn : []
36182                     }
36183                 }
36184             ]
36185         };
36186         
36187         return cfg;
36188     },
36189     
36190     onRender : function(ct, position)
36191     {
36192         Roo.bootstrap.UploadCropbox.superclass.onRender.call(this, ct, position);
36193         
36194         if (this.buttons.length) {
36195             
36196             Roo.each(this.buttons, function(bb) {
36197                 
36198                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
36199                 
36200                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
36201                 
36202             }, this);
36203         }
36204         
36205         if(this.loadMask){
36206             this.maskEl = this.el;
36207         }
36208     },
36209     
36210     initEvents : function()
36211     {
36212         this.urlAPI = (window.createObjectURL && window) || 
36213                                 (window.URL && URL.revokeObjectURL && URL) || 
36214                                 (window.webkitURL && webkitURL);
36215                         
36216         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
36217         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36218         
36219         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
36220         this.selectorEl.hide();
36221         
36222         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
36223         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36224         
36225         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
36226         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36227         this.thumbEl.hide();
36228         
36229         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
36230         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36231         
36232         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
36233         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36234         this.errorEl.hide();
36235         
36236         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
36237         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
36238         this.footerEl.hide();
36239         
36240         this.setThumbBoxSize();
36241         
36242         this.bind();
36243         
36244         this.resize();
36245         
36246         this.fireEvent('initial', this);
36247     },
36248
36249     bind : function()
36250     {
36251         var _this = this;
36252         
36253         window.addEventListener("resize", function() { _this.resize(); } );
36254         
36255         this.bodyEl.on('click', this.beforeSelectFile, this);
36256         
36257         if(Roo.isTouch){
36258             this.bodyEl.on('touchstart', this.onTouchStart, this);
36259             this.bodyEl.on('touchmove', this.onTouchMove, this);
36260             this.bodyEl.on('touchend', this.onTouchEnd, this);
36261         }
36262         
36263         if(!Roo.isTouch){
36264             this.bodyEl.on('mousedown', this.onMouseDown, this);
36265             this.bodyEl.on('mousemove', this.onMouseMove, this);
36266             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
36267             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
36268             Roo.get(document).on('mouseup', this.onMouseUp, this);
36269         }
36270         
36271         this.selectorEl.on('change', this.onFileSelected, this);
36272     },
36273     
36274     reset : function()
36275     {    
36276         this.scale = 0;
36277         this.baseScale = 1;
36278         this.rotate = 0;
36279         this.baseRotate = 1;
36280         this.dragable = false;
36281         this.pinching = false;
36282         this.mouseX = 0;
36283         this.mouseY = 0;
36284         this.cropData = false;
36285         this.notifyEl.dom.innerHTML = this.emptyText;
36286         
36287         this.selectorEl.dom.value = '';
36288         
36289     },
36290     
36291     resize : function()
36292     {
36293         if(this.fireEvent('resize', this) != false){
36294             this.setThumbBoxPosition();
36295             this.setCanvasPosition();
36296         }
36297     },
36298     
36299     onFooterButtonClick : function(e, el, o, type)
36300     {
36301         switch (type) {
36302             case 'rotate-left' :
36303                 this.onRotateLeft(e);
36304                 break;
36305             case 'rotate-right' :
36306                 this.onRotateRight(e);
36307                 break;
36308             case 'picture' :
36309                 this.beforeSelectFile(e);
36310                 break;
36311             case 'trash' :
36312                 this.trash(e);
36313                 break;
36314             case 'crop' :
36315                 this.crop(e);
36316                 break;
36317             case 'download' :
36318                 this.download(e);
36319                 break;
36320             default :
36321                 break;
36322         }
36323         
36324         this.fireEvent('footerbuttonclick', this, type);
36325     },
36326     
36327     beforeSelectFile : function(e)
36328     {
36329         e.preventDefault();
36330         
36331         if(this.fireEvent('beforeselectfile', this) != false){
36332             this.selectorEl.dom.click();
36333         }
36334     },
36335     
36336     onFileSelected : function(e)
36337     {
36338         e.preventDefault();
36339         
36340         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
36341             return;
36342         }
36343         
36344         var file = this.selectorEl.dom.files[0];
36345         
36346         if(this.fireEvent('inspect', this, file) != false){
36347             this.prepare(file);
36348         }
36349         
36350     },
36351     
36352     trash : function(e)
36353     {
36354         this.fireEvent('trash', this);
36355     },
36356     
36357     download : function(e)
36358     {
36359         this.fireEvent('download', this);
36360     },
36361     
36362     loadCanvas : function(src)
36363     {   
36364         if(this.fireEvent('beforeloadcanvas', this, src) != false){
36365             
36366             this.reset();
36367             
36368             this.imageEl = document.createElement('img');
36369             
36370             var _this = this;
36371             
36372             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
36373             
36374             this.imageEl.src = src;
36375         }
36376     },
36377     
36378     onLoadCanvas : function()
36379     {   
36380         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
36381         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
36382         
36383         this.bodyEl.un('click', this.beforeSelectFile, this);
36384         
36385         this.notifyEl.hide();
36386         this.thumbEl.show();
36387         this.footerEl.show();
36388         
36389         this.baseRotateLevel();
36390         
36391         if(this.isDocument){
36392             this.setThumbBoxSize();
36393         }
36394         
36395         this.setThumbBoxPosition();
36396         
36397         this.baseScaleLevel();
36398         
36399         this.draw();
36400         
36401         this.resize();
36402         
36403         this.canvasLoaded = true;
36404         
36405         if(this.loadMask){
36406             this.maskEl.unmask();
36407         }
36408         
36409     },
36410     
36411     setCanvasPosition : function()
36412     {   
36413         if(!this.canvasEl){
36414             return;
36415         }
36416         
36417         var pw = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
36418         var ph = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
36419         
36420         this.previewEl.setLeft(pw);
36421         this.previewEl.setTop(ph);
36422         
36423     },
36424     
36425     onMouseDown : function(e)
36426     {   
36427         e.stopEvent();
36428         
36429         this.dragable = true;
36430         this.pinching = false;
36431         
36432         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
36433             this.dragable = false;
36434             return;
36435         }
36436         
36437         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
36438         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
36439         
36440     },
36441     
36442     onMouseMove : function(e)
36443     {   
36444         e.stopEvent();
36445         
36446         if(!this.canvasLoaded){
36447             return;
36448         }
36449         
36450         if (!this.dragable){
36451             return;
36452         }
36453         
36454         var minX = Math.ceil(this.thumbEl.getLeft(true));
36455         var minY = Math.ceil(this.thumbEl.getTop(true));
36456         
36457         var maxX = Math.ceil(minX + this.thumbEl.getWidth() - this.canvasEl.width);
36458         var maxY = Math.ceil(minY + this.thumbEl.getHeight() - this.canvasEl.height);
36459         
36460         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
36461         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
36462         
36463         x = x - this.mouseX;
36464         y = y - this.mouseY;
36465         
36466         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
36467         var bgY = Math.ceil(y + this.previewEl.getTop(true));
36468         
36469         bgX = (minX < bgX) ? minX : ((maxX > bgX) ? maxX : bgX);
36470         bgY = (minY < bgY) ? minY : ((maxY > bgY) ? maxY : bgY);
36471         
36472         this.previewEl.setLeft(bgX);
36473         this.previewEl.setTop(bgY);
36474         
36475         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
36476         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
36477     },
36478     
36479     onMouseUp : function(e)
36480     {   
36481         e.stopEvent();
36482         
36483         this.dragable = false;
36484     },
36485     
36486     onMouseWheel : function(e)
36487     {   
36488         e.stopEvent();
36489         
36490         this.startScale = this.scale;
36491         
36492         this.scale = (e.getWheelDelta() == 1) ? (this.scale + 1) : (this.scale - 1);
36493         
36494         if(!this.zoomable()){
36495             this.scale = this.startScale;
36496             return;
36497         }
36498         
36499         this.draw();
36500         
36501         return;
36502     },
36503     
36504     zoomable : function()
36505     {
36506         var minScale = this.thumbEl.getWidth() / this.minWidth;
36507         
36508         if(this.minWidth < this.minHeight){
36509             minScale = this.thumbEl.getHeight() / this.minHeight;
36510         }
36511         
36512         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
36513         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
36514         
36515         if(
36516                 this.isDocument &&
36517                 (this.rotate == 0 || this.rotate == 180) && 
36518                 (
36519                     width > this.imageEl.OriginWidth || 
36520                     height > this.imageEl.OriginHeight ||
36521                     (width < this.minWidth && height < this.minHeight)
36522                 )
36523         ){
36524             return false;
36525         }
36526         
36527         if(
36528                 this.isDocument &&
36529                 (this.rotate == 90 || this.rotate == 270) && 
36530                 (
36531                     width > this.imageEl.OriginWidth || 
36532                     height > this.imageEl.OriginHeight ||
36533                     (width < this.minHeight && height < this.minWidth)
36534                 )
36535         ){
36536             return false;
36537         }
36538         
36539         if(
36540                 !this.isDocument &&
36541                 (this.rotate == 0 || this.rotate == 180) && 
36542                 (
36543                     width < this.minWidth || 
36544                     width > this.imageEl.OriginWidth || 
36545                     height < this.minHeight || 
36546                     height > this.imageEl.OriginHeight
36547                 )
36548         ){
36549             return false;
36550         }
36551         
36552         if(
36553                 !this.isDocument &&
36554                 (this.rotate == 90 || this.rotate == 270) && 
36555                 (
36556                     width < this.minHeight || 
36557                     width > this.imageEl.OriginWidth || 
36558                     height < this.minWidth || 
36559                     height > this.imageEl.OriginHeight
36560                 )
36561         ){
36562             return false;
36563         }
36564         
36565         return true;
36566         
36567     },
36568     
36569     onRotateLeft : function(e)
36570     {   
36571         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
36572             
36573             var minScale = this.thumbEl.getWidth() / this.minWidth;
36574             
36575             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
36576             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
36577             
36578             this.startScale = this.scale;
36579             
36580             while (this.getScaleLevel() < minScale){
36581             
36582                 this.scale = this.scale + 1;
36583                 
36584                 if(!this.zoomable()){
36585                     break;
36586                 }
36587                 
36588                 if(
36589                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
36590                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
36591                 ){
36592                     continue;
36593                 }
36594                 
36595                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
36596
36597                 this.draw();
36598                 
36599                 return;
36600             }
36601             
36602             this.scale = this.startScale;
36603             
36604             this.onRotateFail();
36605             
36606             return false;
36607         }
36608         
36609         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
36610
36611         if(this.isDocument){
36612             this.setThumbBoxSize();
36613             this.setThumbBoxPosition();
36614             this.setCanvasPosition();
36615         }
36616         
36617         this.draw();
36618         
36619         this.fireEvent('rotate', this, 'left');
36620         
36621     },
36622     
36623     onRotateRight : function(e)
36624     {
36625         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
36626             
36627             var minScale = this.thumbEl.getWidth() / this.minWidth;
36628         
36629             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
36630             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
36631             
36632             this.startScale = this.scale;
36633             
36634             while (this.getScaleLevel() < minScale){
36635             
36636                 this.scale = this.scale + 1;
36637                 
36638                 if(!this.zoomable()){
36639                     break;
36640                 }
36641                 
36642                 if(
36643                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
36644                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
36645                 ){
36646                     continue;
36647                 }
36648                 
36649                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
36650
36651                 this.draw();
36652                 
36653                 return;
36654             }
36655             
36656             this.scale = this.startScale;
36657             
36658             this.onRotateFail();
36659             
36660             return false;
36661         }
36662         
36663         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
36664
36665         if(this.isDocument){
36666             this.setThumbBoxSize();
36667             this.setThumbBoxPosition();
36668             this.setCanvasPosition();
36669         }
36670         
36671         this.draw();
36672         
36673         this.fireEvent('rotate', this, 'right');
36674     },
36675     
36676     onRotateFail : function()
36677     {
36678         this.errorEl.show(true);
36679         
36680         var _this = this;
36681         
36682         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
36683     },
36684     
36685     draw : function()
36686     {
36687         this.previewEl.dom.innerHTML = '';
36688         
36689         var canvasEl = document.createElement("canvas");
36690         
36691         var contextEl = canvasEl.getContext("2d");
36692         
36693         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
36694         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
36695         var center = this.imageEl.OriginWidth / 2;
36696         
36697         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
36698             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
36699             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
36700             center = this.imageEl.OriginHeight / 2;
36701         }
36702         
36703         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
36704         
36705         contextEl.translate(center, center);
36706         contextEl.rotate(this.rotate * Math.PI / 180);
36707
36708         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
36709         
36710         this.canvasEl = document.createElement("canvas");
36711         
36712         this.contextEl = this.canvasEl.getContext("2d");
36713         
36714         switch (this.rotate) {
36715             case 0 :
36716                 
36717                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
36718                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
36719                 
36720                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36721                 
36722                 break;
36723             case 90 : 
36724                 
36725                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
36726                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
36727                 
36728                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
36729                     this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36730                     break;
36731                 }
36732                 
36733                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36734                 
36735                 break;
36736             case 180 :
36737                 
36738                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
36739                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
36740                 
36741                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
36742                     this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36743                     break;
36744                 }
36745                 
36746                 this.contextEl.drawImage(canvasEl, Math.abs(this.canvasEl.width - this.canvasEl.height), 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36747                 
36748                 break;
36749             case 270 :
36750                 
36751                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
36752                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
36753         
36754                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
36755                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36756                     break;
36757                 }
36758                 
36759                 this.contextEl.drawImage(canvasEl, 0, Math.abs(this.canvasEl.width - this.canvasEl.height), this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
36760                 
36761                 break;
36762             default : 
36763                 break;
36764         }
36765         
36766         this.previewEl.appendChild(this.canvasEl);
36767         
36768         this.setCanvasPosition();
36769     },
36770     
36771     crop : function()
36772     {
36773         if(!this.canvasLoaded){
36774             return;
36775         }
36776         
36777         var imageCanvas = document.createElement("canvas");
36778         
36779         var imageContext = imageCanvas.getContext("2d");
36780         
36781         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
36782         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
36783         
36784         var center = imageCanvas.width / 2;
36785         
36786         imageContext.translate(center, center);
36787         
36788         imageContext.rotate(this.rotate * Math.PI / 180);
36789         
36790         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
36791         
36792         var canvas = document.createElement("canvas");
36793         
36794         var context = canvas.getContext("2d");
36795                 
36796         canvas.width = this.minWidth;
36797         canvas.height = this.minHeight;
36798
36799         switch (this.rotate) {
36800             case 0 :
36801                 
36802                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
36803                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
36804                 
36805                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
36806                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
36807                 
36808                 var targetWidth = this.minWidth - 2 * x;
36809                 var targetHeight = this.minHeight - 2 * y;
36810                 
36811                 var scale = 1;
36812                 
36813                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
36814                     scale = targetWidth / width;
36815                 }
36816                 
36817                 if(x > 0 && y == 0){
36818                     scale = targetHeight / height;
36819                 }
36820                 
36821                 if(x > 0 && y > 0){
36822                     scale = targetWidth / width;
36823                     
36824                     if(width < height){
36825                         scale = targetHeight / height;
36826                     }
36827                 }
36828                 
36829                 context.scale(scale, scale);
36830                 
36831                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
36832                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
36833
36834                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
36835                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
36836
36837                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
36838                 
36839                 break;
36840             case 90 : 
36841                 
36842                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
36843                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
36844                 
36845                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
36846                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
36847                 
36848                 var targetWidth = this.minWidth - 2 * x;
36849                 var targetHeight = this.minHeight - 2 * y;
36850                 
36851                 var scale = 1;
36852                 
36853                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
36854                     scale = targetWidth / width;
36855                 }
36856                 
36857                 if(x > 0 && y == 0){
36858                     scale = targetHeight / height;
36859                 }
36860                 
36861                 if(x > 0 && y > 0){
36862                     scale = targetWidth / width;
36863                     
36864                     if(width < height){
36865                         scale = targetHeight / height;
36866                     }
36867                 }
36868                 
36869                 context.scale(scale, scale);
36870                 
36871                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
36872                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
36873
36874                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
36875                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
36876                 
36877                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
36878                 
36879                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
36880                 
36881                 break;
36882             case 180 :
36883                 
36884                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
36885                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
36886                 
36887                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
36888                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
36889                 
36890                 var targetWidth = this.minWidth - 2 * x;
36891                 var targetHeight = this.minHeight - 2 * y;
36892                 
36893                 var scale = 1;
36894                 
36895                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
36896                     scale = targetWidth / width;
36897                 }
36898                 
36899                 if(x > 0 && y == 0){
36900                     scale = targetHeight / height;
36901                 }
36902                 
36903                 if(x > 0 && y > 0){
36904                     scale = targetWidth / width;
36905                     
36906                     if(width < height){
36907                         scale = targetHeight / height;
36908                     }
36909                 }
36910                 
36911                 context.scale(scale, scale);
36912                 
36913                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
36914                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
36915
36916                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
36917                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
36918
36919                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
36920                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
36921                 
36922                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
36923                 
36924                 break;
36925             case 270 :
36926                 
36927                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
36928                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
36929                 
36930                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
36931                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
36932                 
36933                 var targetWidth = this.minWidth - 2 * x;
36934                 var targetHeight = this.minHeight - 2 * y;
36935                 
36936                 var scale = 1;
36937                 
36938                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
36939                     scale = targetWidth / width;
36940                 }
36941                 
36942                 if(x > 0 && y == 0){
36943                     scale = targetHeight / height;
36944                 }
36945                 
36946                 if(x > 0 && y > 0){
36947                     scale = targetWidth / width;
36948                     
36949                     if(width < height){
36950                         scale = targetHeight / height;
36951                     }
36952                 }
36953                 
36954                 context.scale(scale, scale);
36955                 
36956                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
36957                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
36958
36959                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
36960                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
36961                 
36962                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
36963                 
36964                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
36965                 
36966                 break;
36967             default : 
36968                 break;
36969         }
36970         
36971         this.cropData = canvas.toDataURL(this.cropType);
36972         
36973         if(this.fireEvent('crop', this, this.cropData) !== false){
36974             this.process(this.file, this.cropData);
36975         }
36976         
36977         return;
36978         
36979     },
36980     
36981     setThumbBoxSize : function()
36982     {
36983         var width, height;
36984         
36985         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
36986             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
36987             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
36988             
36989             this.minWidth = width;
36990             this.minHeight = height;
36991             
36992             if(this.rotate == 90 || this.rotate == 270){
36993                 this.minWidth = height;
36994                 this.minHeight = width;
36995             }
36996         }
36997         
36998         height = 300;
36999         width = Math.ceil(this.minWidth * height / this.minHeight);
37000         
37001         if(this.minWidth > this.minHeight){
37002             width = 300;
37003             height = Math.ceil(this.minHeight * width / this.minWidth);
37004         }
37005         
37006         this.thumbEl.setStyle({
37007             width : width + 'px',
37008             height : height + 'px'
37009         });
37010
37011         return;
37012             
37013     },
37014     
37015     setThumbBoxPosition : function()
37016     {
37017         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
37018         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
37019         
37020         this.thumbEl.setLeft(x);
37021         this.thumbEl.setTop(y);
37022         
37023     },
37024     
37025     baseRotateLevel : function()
37026     {
37027         this.baseRotate = 1;
37028         
37029         if(
37030                 typeof(this.exif) != 'undefined' &&
37031                 typeof(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
37032                 [1, 3, 6, 8].indexOf(this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']]) != -1
37033         ){
37034             this.baseRotate = this.exif[Roo.bootstrap.UploadCropbox['tags']['Orientation']];
37035         }
37036         
37037         this.rotate = Roo.bootstrap.UploadCropbox['Orientation'][this.baseRotate];
37038         
37039     },
37040     
37041     baseScaleLevel : function()
37042     {
37043         var width, height;
37044         
37045         if(this.isDocument){
37046             
37047             if(this.baseRotate == 6 || this.baseRotate == 8){
37048             
37049                 height = this.thumbEl.getHeight();
37050                 this.baseScale = height / this.imageEl.OriginWidth;
37051
37052                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
37053                     width = this.thumbEl.getWidth();
37054                     this.baseScale = width / this.imageEl.OriginHeight;
37055                 }
37056
37057                 return;
37058             }
37059
37060             height = this.thumbEl.getHeight();
37061             this.baseScale = height / this.imageEl.OriginHeight;
37062
37063             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
37064                 width = this.thumbEl.getWidth();
37065                 this.baseScale = width / this.imageEl.OriginWidth;
37066             }
37067
37068             return;
37069         }
37070         
37071         if(this.baseRotate == 6 || this.baseRotate == 8){
37072             
37073             width = this.thumbEl.getHeight();
37074             this.baseScale = width / this.imageEl.OriginHeight;
37075             
37076             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
37077                 height = this.thumbEl.getWidth();
37078                 this.baseScale = height / this.imageEl.OriginHeight;
37079             }
37080             
37081             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
37082                 height = this.thumbEl.getWidth();
37083                 this.baseScale = height / this.imageEl.OriginHeight;
37084                 
37085                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
37086                     width = this.thumbEl.getHeight();
37087                     this.baseScale = width / this.imageEl.OriginWidth;
37088                 }
37089             }
37090             
37091             return;
37092         }
37093         
37094         width = this.thumbEl.getWidth();
37095         this.baseScale = width / this.imageEl.OriginWidth;
37096         
37097         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
37098             height = this.thumbEl.getHeight();
37099             this.baseScale = height / this.imageEl.OriginHeight;
37100         }
37101         
37102         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
37103             
37104             height = this.thumbEl.getHeight();
37105             this.baseScale = height / this.imageEl.OriginHeight;
37106             
37107             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
37108                 width = this.thumbEl.getWidth();
37109                 this.baseScale = width / this.imageEl.OriginWidth;
37110             }
37111             
37112         }
37113         
37114         return;
37115     },
37116     
37117     getScaleLevel : function()
37118     {
37119         return this.baseScale * Math.pow(1.1, this.scale);
37120     },
37121     
37122     onTouchStart : function(e)
37123     {
37124         if(!this.canvasLoaded){
37125             this.beforeSelectFile(e);
37126             return;
37127         }
37128         
37129         var touches = e.browserEvent.touches;
37130         
37131         if(!touches){
37132             return;
37133         }
37134         
37135         if(touches.length == 1){
37136             this.onMouseDown(e);
37137             return;
37138         }
37139         
37140         if(touches.length != 2){
37141             return;
37142         }
37143         
37144         var coords = [];
37145         
37146         for(var i = 0, finger; finger = touches[i]; i++){
37147             coords.push(finger.pageX, finger.pageY);
37148         }
37149         
37150         var x = Math.pow(coords[0] - coords[2], 2);
37151         var y = Math.pow(coords[1] - coords[3], 2);
37152         
37153         this.startDistance = Math.sqrt(x + y);
37154         
37155         this.startScale = this.scale;
37156         
37157         this.pinching = true;
37158         this.dragable = false;
37159         
37160     },
37161     
37162     onTouchMove : function(e)
37163     {
37164         if(!this.pinching && !this.dragable){
37165             return;
37166         }
37167         
37168         var touches = e.browserEvent.touches;
37169         
37170         if(!touches){
37171             return;
37172         }
37173         
37174         if(this.dragable){
37175             this.onMouseMove(e);
37176             return;
37177         }
37178         
37179         var coords = [];
37180         
37181         for(var i = 0, finger; finger = touches[i]; i++){
37182             coords.push(finger.pageX, finger.pageY);
37183         }
37184         
37185         var x = Math.pow(coords[0] - coords[2], 2);
37186         var y = Math.pow(coords[1] - coords[3], 2);
37187         
37188         this.endDistance = Math.sqrt(x + y);
37189         
37190         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
37191         
37192         if(!this.zoomable()){
37193             this.scale = this.startScale;
37194             return;
37195         }
37196         
37197         this.draw();
37198         
37199     },
37200     
37201     onTouchEnd : function(e)
37202     {
37203         this.pinching = false;
37204         this.dragable = false;
37205         
37206     },
37207     
37208     process : function(file, crop)
37209     {
37210         if(this.loadMask){
37211             this.maskEl.mask(this.loadingText);
37212         }
37213         
37214         this.xhr = new XMLHttpRequest();
37215         
37216         file.xhr = this.xhr;
37217
37218         this.xhr.open(this.method, this.url, true);
37219         
37220         var headers = {
37221             "Accept": "application/json",
37222             "Cache-Control": "no-cache",
37223             "X-Requested-With": "XMLHttpRequest"
37224         };
37225         
37226         for (var headerName in headers) {
37227             var headerValue = headers[headerName];
37228             if (headerValue) {
37229                 this.xhr.setRequestHeader(headerName, headerValue);
37230             }
37231         }
37232         
37233         var _this = this;
37234         
37235         this.xhr.onload = function()
37236         {
37237             _this.xhrOnLoad(_this.xhr);
37238         }
37239         
37240         this.xhr.onerror = function()
37241         {
37242             _this.xhrOnError(_this.xhr);
37243         }
37244         
37245         var formData = new FormData();
37246
37247         formData.append('returnHTML', 'NO');
37248         
37249         if(crop){
37250             formData.append('crop', crop);
37251         }
37252         
37253         if(typeof(file) != 'undefined' && (typeof(file.id) == 'undefined' || file.id * 1 < 1)){
37254             formData.append(this.paramName, file, file.name);
37255         }
37256         
37257         if(typeof(file.filename) != 'undefined'){
37258             formData.append('filename', file.filename);
37259         }
37260         
37261         if(typeof(file.mimetype) != 'undefined'){
37262             formData.append('mimetype', file.mimetype);
37263         }
37264         
37265         if(this.fireEvent('arrange', this, formData) != false){
37266             this.xhr.send(formData);
37267         };
37268     },
37269     
37270     xhrOnLoad : function(xhr)
37271     {
37272         if(this.loadMask){
37273             this.maskEl.unmask();
37274         }
37275         
37276         if (xhr.readyState !== 4) {
37277             this.fireEvent('exception', this, xhr);
37278             return;
37279         }
37280
37281         var response = Roo.decode(xhr.responseText);
37282         
37283         if(!response.success){
37284             this.fireEvent('exception', this, xhr);
37285             return;
37286         }
37287         
37288         var response = Roo.decode(xhr.responseText);
37289         
37290         this.fireEvent('upload', this, response);
37291         
37292     },
37293     
37294     xhrOnError : function()
37295     {
37296         if(this.loadMask){
37297             this.maskEl.unmask();
37298         }
37299         
37300         Roo.log('xhr on error');
37301         
37302         var response = Roo.decode(xhr.responseText);
37303           
37304         Roo.log(response);
37305         
37306     },
37307     
37308     prepare : function(file)
37309     {   
37310         if(this.loadMask){
37311             this.maskEl.mask(this.loadingText);
37312         }
37313         
37314         this.file = false;
37315         this.exif = {};
37316         
37317         if(typeof(file) === 'string'){
37318             this.loadCanvas(file);
37319             return;
37320         }
37321         
37322         if(!file || !this.urlAPI){
37323             return;
37324         }
37325         
37326         this.file = file;
37327         this.cropType = file.type;
37328         
37329         var _this = this;
37330         
37331         if(this.fireEvent('prepare', this, this.file) != false){
37332             
37333             var reader = new FileReader();
37334             
37335             reader.onload = function (e) {
37336                 if (e.target.error) {
37337                     Roo.log(e.target.error);
37338                     return;
37339                 }
37340                 
37341                 var buffer = e.target.result,
37342                     dataView = new DataView(buffer),
37343                     offset = 2,
37344                     maxOffset = dataView.byteLength - 4,
37345                     markerBytes,
37346                     markerLength;
37347                 
37348                 if (dataView.getUint16(0) === 0xffd8) {
37349                     while (offset < maxOffset) {
37350                         markerBytes = dataView.getUint16(offset);
37351                         
37352                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
37353                             markerLength = dataView.getUint16(offset + 2) + 2;
37354                             if (offset + markerLength > dataView.byteLength) {
37355                                 Roo.log('Invalid meta data: Invalid segment size.');
37356                                 break;
37357                             }
37358                             
37359                             if(markerBytes == 0xffe1){
37360                                 _this.parseExifData(
37361                                     dataView,
37362                                     offset,
37363                                     markerLength
37364                                 );
37365                             }
37366                             
37367                             offset += markerLength;
37368                             
37369                             continue;
37370                         }
37371                         
37372                         break;
37373                     }
37374                     
37375                 }
37376                 
37377                 var url = _this.urlAPI.createObjectURL(_this.file);
37378                 
37379                 _this.loadCanvas(url);
37380                 
37381                 return;
37382             }
37383             
37384             reader.readAsArrayBuffer(this.file);
37385             
37386         }
37387         
37388     },
37389     
37390     parseExifData : function(dataView, offset, length)
37391     {
37392         var tiffOffset = offset + 10,
37393             littleEndian,
37394             dirOffset;
37395     
37396         if (dataView.getUint32(offset + 4) !== 0x45786966) {
37397             // No Exif data, might be XMP data instead
37398             return;
37399         }
37400         
37401         // Check for the ASCII code for "Exif" (0x45786966):
37402         if (dataView.getUint32(offset + 4) !== 0x45786966) {
37403             // No Exif data, might be XMP data instead
37404             return;
37405         }
37406         if (tiffOffset + 8 > dataView.byteLength) {
37407             Roo.log('Invalid Exif data: Invalid segment size.');
37408             return;
37409         }
37410         // Check for the two null bytes:
37411         if (dataView.getUint16(offset + 8) !== 0x0000) {
37412             Roo.log('Invalid Exif data: Missing byte alignment offset.');
37413             return;
37414         }
37415         // Check the byte alignment:
37416         switch (dataView.getUint16(tiffOffset)) {
37417         case 0x4949:
37418             littleEndian = true;
37419             break;
37420         case 0x4D4D:
37421             littleEndian = false;
37422             break;
37423         default:
37424             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
37425             return;
37426         }
37427         // Check for the TIFF tag marker (0x002A):
37428         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
37429             Roo.log('Invalid Exif data: Missing TIFF marker.');
37430             return;
37431         }
37432         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
37433         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
37434         
37435         this.parseExifTags(
37436             dataView,
37437             tiffOffset,
37438             tiffOffset + dirOffset,
37439             littleEndian
37440         );
37441     },
37442     
37443     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
37444     {
37445         var tagsNumber,
37446             dirEndOffset,
37447             i;
37448         if (dirOffset + 6 > dataView.byteLength) {
37449             Roo.log('Invalid Exif data: Invalid directory offset.');
37450             return;
37451         }
37452         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
37453         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
37454         if (dirEndOffset + 4 > dataView.byteLength) {
37455             Roo.log('Invalid Exif data: Invalid directory size.');
37456             return;
37457         }
37458         for (i = 0; i < tagsNumber; i += 1) {
37459             this.parseExifTag(
37460                 dataView,
37461                 tiffOffset,
37462                 dirOffset + 2 + 12 * i, // tag offset
37463                 littleEndian
37464             );
37465         }
37466         // Return the offset to the next directory:
37467         return dataView.getUint32(dirEndOffset, littleEndian);
37468     },
37469     
37470     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
37471     {
37472         var tag = dataView.getUint16(offset, littleEndian);
37473         
37474         this.exif[tag] = this.getExifValue(
37475             dataView,
37476             tiffOffset,
37477             offset,
37478             dataView.getUint16(offset + 2, littleEndian), // tag type
37479             dataView.getUint32(offset + 4, littleEndian), // tag length
37480             littleEndian
37481         );
37482     },
37483     
37484     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
37485     {
37486         var tagType = Roo.bootstrap.UploadCropbox.exifTagTypes[type],
37487             tagSize,
37488             dataOffset,
37489             values,
37490             i,
37491             str,
37492             c;
37493     
37494         if (!tagType) {
37495             Roo.log('Invalid Exif data: Invalid tag type.');
37496             return;
37497         }
37498         
37499         tagSize = tagType.size * length;
37500         // Determine if the value is contained in the dataOffset bytes,
37501         // or if the value at the dataOffset is a pointer to the actual data:
37502         dataOffset = tagSize > 4 ?
37503                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
37504         if (dataOffset + tagSize > dataView.byteLength) {
37505             Roo.log('Invalid Exif data: Invalid data offset.');
37506             return;
37507         }
37508         if (length === 1) {
37509             return tagType.getValue(dataView, dataOffset, littleEndian);
37510         }
37511         values = [];
37512         for (i = 0; i < length; i += 1) {
37513             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
37514         }
37515         
37516         if (tagType.ascii) {
37517             str = '';
37518             // Concatenate the chars:
37519             for (i = 0; i < values.length; i += 1) {
37520                 c = values[i];
37521                 // Ignore the terminating NULL byte(s):
37522                 if (c === '\u0000') {
37523                     break;
37524                 }
37525                 str += c;
37526             }
37527             return str;
37528         }
37529         return values;
37530     }
37531     
37532 });
37533
37534 Roo.apply(Roo.bootstrap.UploadCropbox, {
37535     tags : {
37536         'Orientation': 0x0112
37537     },
37538     
37539     Orientation: {
37540             1: 0, //'top-left',
37541 //            2: 'top-right',
37542             3: 180, //'bottom-right',
37543 //            4: 'bottom-left',
37544 //            5: 'left-top',
37545             6: 90, //'right-top',
37546 //            7: 'right-bottom',
37547             8: 270 //'left-bottom'
37548     },
37549     
37550     exifTagTypes : {
37551         // byte, 8-bit unsigned int:
37552         1: {
37553             getValue: function (dataView, dataOffset) {
37554                 return dataView.getUint8(dataOffset);
37555             },
37556             size: 1
37557         },
37558         // ascii, 8-bit byte:
37559         2: {
37560             getValue: function (dataView, dataOffset) {
37561                 return String.fromCharCode(dataView.getUint8(dataOffset));
37562             },
37563             size: 1,
37564             ascii: true
37565         },
37566         // short, 16 bit int:
37567         3: {
37568             getValue: function (dataView, dataOffset, littleEndian) {
37569                 return dataView.getUint16(dataOffset, littleEndian);
37570             },
37571             size: 2
37572         },
37573         // long, 32 bit int:
37574         4: {
37575             getValue: function (dataView, dataOffset, littleEndian) {
37576                 return dataView.getUint32(dataOffset, littleEndian);
37577             },
37578             size: 4
37579         },
37580         // rational = two long values, first is numerator, second is denominator:
37581         5: {
37582             getValue: function (dataView, dataOffset, littleEndian) {
37583                 return dataView.getUint32(dataOffset, littleEndian) /
37584                     dataView.getUint32(dataOffset + 4, littleEndian);
37585             },
37586             size: 8
37587         },
37588         // slong, 32 bit signed int:
37589         9: {
37590             getValue: function (dataView, dataOffset, littleEndian) {
37591                 return dataView.getInt32(dataOffset, littleEndian);
37592             },
37593             size: 4
37594         },
37595         // srational, two slongs, first is numerator, second is denominator:
37596         10: {
37597             getValue: function (dataView, dataOffset, littleEndian) {
37598                 return dataView.getInt32(dataOffset, littleEndian) /
37599                     dataView.getInt32(dataOffset + 4, littleEndian);
37600             },
37601             size: 8
37602         }
37603     },
37604     
37605     footer : {
37606         STANDARD : [
37607             {
37608                 tag : 'div',
37609                 cls : 'btn-group roo-upload-cropbox-rotate-left',
37610                 action : 'rotate-left',
37611                 cn : [
37612                     {
37613                         tag : 'button',
37614                         cls : 'btn btn-default',
37615                         html : '<i class="fa fa-undo"></i>'
37616                     }
37617                 ]
37618             },
37619             {
37620                 tag : 'div',
37621                 cls : 'btn-group roo-upload-cropbox-picture',
37622                 action : 'picture',
37623                 cn : [
37624                     {
37625                         tag : 'button',
37626                         cls : 'btn btn-default',
37627                         html : '<i class="fa fa-picture-o"></i>'
37628                     }
37629                 ]
37630             },
37631             {
37632                 tag : 'div',
37633                 cls : 'btn-group roo-upload-cropbox-rotate-right',
37634                 action : 'rotate-right',
37635                 cn : [
37636                     {
37637                         tag : 'button',
37638                         cls : 'btn btn-default',
37639                         html : '<i class="fa fa-repeat"></i>'
37640                     }
37641                 ]
37642             }
37643         ],
37644         DOCUMENT : [
37645             {
37646                 tag : 'div',
37647                 cls : 'btn-group roo-upload-cropbox-rotate-left',
37648                 action : 'rotate-left',
37649                 cn : [
37650                     {
37651                         tag : 'button',
37652                         cls : 'btn btn-default',
37653                         html : '<i class="fa fa-undo"></i>'
37654                     }
37655                 ]
37656             },
37657             {
37658                 tag : 'div',
37659                 cls : 'btn-group roo-upload-cropbox-download',
37660                 action : 'download',
37661                 cn : [
37662                     {
37663                         tag : 'button',
37664                         cls : 'btn btn-default',
37665                         html : '<i class="fa fa-download"></i>'
37666                     }
37667                 ]
37668             },
37669             {
37670                 tag : 'div',
37671                 cls : 'btn-group roo-upload-cropbox-crop',
37672                 action : 'crop',
37673                 cn : [
37674                     {
37675                         tag : 'button',
37676                         cls : 'btn btn-default',
37677                         html : '<i class="fa fa-crop"></i>'
37678                     }
37679                 ]
37680             },
37681             {
37682                 tag : 'div',
37683                 cls : 'btn-group roo-upload-cropbox-trash',
37684                 action : 'trash',
37685                 cn : [
37686                     {
37687                         tag : 'button',
37688                         cls : 'btn btn-default',
37689                         html : '<i class="fa fa-trash"></i>'
37690                     }
37691                 ]
37692             },
37693             {
37694                 tag : 'div',
37695                 cls : 'btn-group roo-upload-cropbox-rotate-right',
37696                 action : 'rotate-right',
37697                 cn : [
37698                     {
37699                         tag : 'button',
37700                         cls : 'btn btn-default',
37701                         html : '<i class="fa fa-repeat"></i>'
37702                     }
37703                 ]
37704             }
37705         ],
37706         ROTATOR : [
37707             {
37708                 tag : 'div',
37709                 cls : 'btn-group roo-upload-cropbox-rotate-left',
37710                 action : 'rotate-left',
37711                 cn : [
37712                     {
37713                         tag : 'button',
37714                         cls : 'btn btn-default',
37715                         html : '<i class="fa fa-undo"></i>'
37716                     }
37717                 ]
37718             },
37719             {
37720                 tag : 'div',
37721                 cls : 'btn-group roo-upload-cropbox-rotate-right',
37722                 action : 'rotate-right',
37723                 cn : [
37724                     {
37725                         tag : 'button',
37726                         cls : 'btn btn-default',
37727                         html : '<i class="fa fa-repeat"></i>'
37728                     }
37729                 ]
37730             }
37731         ]
37732     }
37733 });
37734
37735 /*
37736 * Licence: LGPL
37737 */
37738
37739 /**
37740  * @class Roo.bootstrap.DocumentManager
37741  * @extends Roo.bootstrap.Component
37742  * Bootstrap DocumentManager class
37743  * @cfg {String} paramName default 'imageUpload'
37744  * @cfg {String} toolTipName default 'filename'
37745  * @cfg {String} method default POST
37746  * @cfg {String} url action url
37747  * @cfg {Number} boxes number of boxes, 0 is no limit.. default 0
37748  * @cfg {Boolean} multiple multiple upload default true
37749  * @cfg {Number} thumbSize default 300
37750  * @cfg {String} fieldLabel
37751  * @cfg {Number} labelWidth default 4
37752  * @cfg {String} labelAlign (left|top) default left
37753  * @cfg {Boolean} editable (true|false) allow edit when upload a image default true
37754 * @cfg {Number} labellg set the width of label (1-12)
37755  * @cfg {Number} labelmd set the width of label (1-12)
37756  * @cfg {Number} labelsm set the width of label (1-12)
37757  * @cfg {Number} labelxs set the width of label (1-12)
37758  * 
37759  * @constructor
37760  * Create a new DocumentManager
37761  * @param {Object} config The config object
37762  */
37763
37764 Roo.bootstrap.DocumentManager = function(config){
37765     Roo.bootstrap.DocumentManager.superclass.constructor.call(this, config);
37766     
37767     this.files = [];
37768     this.delegates = [];
37769     
37770     this.addEvents({
37771         /**
37772          * @event initial
37773          * Fire when initial the DocumentManager
37774          * @param {Roo.bootstrap.DocumentManager} this
37775          */
37776         "initial" : true,
37777         /**
37778          * @event inspect
37779          * inspect selected file
37780          * @param {Roo.bootstrap.DocumentManager} this
37781          * @param {File} file
37782          */
37783         "inspect" : true,
37784         /**
37785          * @event exception
37786          * Fire when xhr load exception
37787          * @param {Roo.bootstrap.DocumentManager} this
37788          * @param {XMLHttpRequest} xhr
37789          */
37790         "exception" : true,
37791         /**
37792          * @event afterupload
37793          * Fire when xhr load exception
37794          * @param {Roo.bootstrap.DocumentManager} this
37795          * @param {XMLHttpRequest} xhr
37796          */
37797         "afterupload" : true,
37798         /**
37799          * @event prepare
37800          * prepare the form data
37801          * @param {Roo.bootstrap.DocumentManager} this
37802          * @param {Object} formData
37803          */
37804         "prepare" : true,
37805         /**
37806          * @event remove
37807          * Fire when remove the file
37808          * @param {Roo.bootstrap.DocumentManager} this
37809          * @param {Object} file
37810          */
37811         "remove" : true,
37812         /**
37813          * @event refresh
37814          * Fire after refresh the file
37815          * @param {Roo.bootstrap.DocumentManager} this
37816          */
37817         "refresh" : true,
37818         /**
37819          * @event click
37820          * Fire after click the image
37821          * @param {Roo.bootstrap.DocumentManager} this
37822          * @param {Object} file
37823          */
37824         "click" : true,
37825         /**
37826          * @event edit
37827          * Fire when upload a image and editable set to true
37828          * @param {Roo.bootstrap.DocumentManager} this
37829          * @param {Object} file
37830          */
37831         "edit" : true,
37832         /**
37833          * @event beforeselectfile
37834          * Fire before select file
37835          * @param {Roo.bootstrap.DocumentManager} this
37836          */
37837         "beforeselectfile" : true,
37838         /**
37839          * @event process
37840          * Fire before process file
37841          * @param {Roo.bootstrap.DocumentManager} this
37842          * @param {Object} file
37843          */
37844         "process" : true,
37845         /**
37846          * @event previewrendered
37847          * Fire when preview rendered
37848          * @param {Roo.bootstrap.DocumentManager} this
37849          * @param {Object} file
37850          */
37851         "previewrendered" : true,
37852         /**
37853          */
37854         "previewResize" : true
37855         
37856     });
37857 };
37858
37859 Roo.extend(Roo.bootstrap.DocumentManager, Roo.bootstrap.Component,  {
37860     
37861     boxes : 0,
37862     inputName : '',
37863     thumbSize : 300,
37864     multiple : true,
37865     files : false,
37866     method : 'POST',
37867     url : '',
37868     paramName : 'imageUpload',
37869     toolTipName : 'filename',
37870     fieldLabel : '',
37871     labelWidth : 4,
37872     labelAlign : 'left',
37873     editable : true,
37874     delegates : false,
37875     xhr : false, 
37876     
37877     labellg : 0,
37878     labelmd : 0,
37879     labelsm : 0,
37880     labelxs : 0,
37881     
37882     getAutoCreate : function()
37883     {   
37884         var managerWidget = {
37885             tag : 'div',
37886             cls : 'roo-document-manager',
37887             cn : [
37888                 {
37889                     tag : 'input',
37890                     cls : 'roo-document-manager-selector',
37891                     type : 'file'
37892                 },
37893                 {
37894                     tag : 'div',
37895                     cls : 'roo-document-manager-uploader',
37896                     cn : [
37897                         {
37898                             tag : 'div',
37899                             cls : 'roo-document-manager-upload-btn',
37900                             html : '<i class="fa fa-plus"></i>'
37901                         }
37902                     ]
37903                     
37904                 }
37905             ]
37906         };
37907         
37908         var content = [
37909             {
37910                 tag : 'div',
37911                 cls : 'column col-md-12',
37912                 cn : managerWidget
37913             }
37914         ];
37915         
37916         if(this.fieldLabel.length){
37917             
37918             content = [
37919                 {
37920                     tag : 'div',
37921                     cls : 'column col-md-12',
37922                     html : this.fieldLabel
37923                 },
37924                 {
37925                     tag : 'div',
37926                     cls : 'column col-md-12',
37927                     cn : managerWidget
37928                 }
37929             ];
37930
37931             if(this.labelAlign == 'left'){
37932                 content = [
37933                     {
37934                         tag : 'div',
37935                         cls : 'column',
37936                         html : this.fieldLabel
37937                     },
37938                     {
37939                         tag : 'div',
37940                         cls : 'column',
37941                         cn : managerWidget
37942                     }
37943                 ];
37944                 
37945                 if(this.labelWidth > 12){
37946                     content[0].style = "width: " + this.labelWidth + 'px';
37947                 }
37948
37949                 if(this.labelWidth < 13 && this.labelmd == 0){
37950                     this.labelmd = this.labelWidth;
37951                 }
37952
37953                 if(this.labellg > 0){
37954                     content[0].cls += ' col-lg-' + this.labellg;
37955                     content[1].cls += ' col-lg-' + (12 - this.labellg);
37956                 }
37957
37958                 if(this.labelmd > 0){
37959                     content[0].cls += ' col-md-' + this.labelmd;
37960                     content[1].cls += ' col-md-' + (12 - this.labelmd);
37961                 }
37962
37963                 if(this.labelsm > 0){
37964                     content[0].cls += ' col-sm-' + this.labelsm;
37965                     content[1].cls += ' col-sm-' + (12 - this.labelsm);
37966                 }
37967
37968                 if(this.labelxs > 0){
37969                     content[0].cls += ' col-xs-' + this.labelxs;
37970                     content[1].cls += ' col-xs-' + (12 - this.labelxs);
37971                 }
37972                 
37973             }
37974         }
37975         
37976         var cfg = {
37977             tag : 'div',
37978             cls : 'row clearfix',
37979             cn : content
37980         };
37981         
37982         return cfg;
37983         
37984     },
37985     
37986     initEvents : function()
37987     {
37988         this.managerEl = this.el.select('.roo-document-manager', true).first();
37989         this.managerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
37990         
37991         this.selectorEl = this.el.select('.roo-document-manager-selector', true).first();
37992         this.selectorEl.hide();
37993         
37994         if(this.multiple){
37995             this.selectorEl.attr('multiple', 'multiple');
37996         }
37997         
37998         this.selectorEl.on('change', this.onFileSelected, this);
37999         
38000         this.uploader = this.el.select('.roo-document-manager-uploader', true).first();
38001         this.uploader.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
38002         
38003         this.uploader.on('click', this.onUploaderClick, this);
38004         
38005         this.renderProgressDialog();
38006         
38007         var _this = this;
38008         
38009         window.addEventListener("resize", function() { _this.refresh(); } );
38010         
38011         this.fireEvent('initial', this);
38012     },
38013     
38014     renderProgressDialog : function()
38015     {
38016         var _this = this;
38017         
38018         this.progressDialog = new Roo.bootstrap.Modal({
38019             cls : 'roo-document-manager-progress-dialog',
38020             allow_close : false,
38021             animate : false,
38022             title : '',
38023             buttons : [
38024                 {
38025                     name  :'cancel',
38026                     weight : 'danger',
38027                     html : 'Cancel'
38028                 }
38029             ], 
38030             listeners : { 
38031                 btnclick : function() {
38032                     _this.uploadCancel();
38033                     this.hide();
38034                 }
38035             }
38036         });
38037          
38038         this.progressDialog.render(Roo.get(document.body));
38039          
38040         this.progress = new Roo.bootstrap.Progress({
38041             cls : 'roo-document-manager-progress',
38042             active : true,
38043             striped : true
38044         });
38045         
38046         this.progress.render(this.progressDialog.getChildContainer());
38047         
38048         this.progressBar = new Roo.bootstrap.ProgressBar({
38049             cls : 'roo-document-manager-progress-bar',
38050             aria_valuenow : 0,
38051             aria_valuemin : 0,
38052             aria_valuemax : 12,
38053             panel : 'success'
38054         });
38055         
38056         this.progressBar.render(this.progress.getChildContainer());
38057     },
38058     
38059     onUploaderClick : function(e)
38060     {
38061         e.preventDefault();
38062      
38063         if(this.fireEvent('beforeselectfile', this) != false){
38064             this.selectorEl.dom.click();
38065         }
38066         
38067     },
38068     
38069     onFileSelected : function(e)
38070     {
38071         e.preventDefault();
38072         
38073         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
38074             return;
38075         }
38076         
38077         Roo.each(this.selectorEl.dom.files, function(file){
38078             if(this.fireEvent('inspect', this, file) != false){
38079                 this.files.push(file);
38080             }
38081         }, this);
38082         
38083         this.queue();
38084         
38085     },
38086     
38087     queue : function()
38088     {
38089         this.selectorEl.dom.value = '';
38090         
38091         if(!this.files || !this.files.length){
38092             return;
38093         }
38094         
38095         if(this.boxes > 0 && this.files.length > this.boxes){
38096             this.files = this.files.slice(0, this.boxes);
38097         }
38098         
38099         this.uploader.show();
38100         
38101         if(this.boxes > 0 && this.files.length > this.boxes - 1){
38102             this.uploader.hide();
38103         }
38104         
38105         var _this = this;
38106         
38107         var files = [];
38108         
38109         var docs = [];
38110         
38111         Roo.each(this.files, function(file){
38112             
38113             if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
38114                 var f = this.renderPreview(file);
38115                 files.push(f);
38116                 return;
38117             }
38118             
38119             if(file.type.indexOf('image') != -1){
38120                 this.delegates.push(
38121                     (function(){
38122                         _this.process(file);
38123                     }).createDelegate(this)
38124                 );
38125         
38126                 return;
38127             }
38128             
38129             docs.push(
38130                 (function(){
38131                     _this.process(file);
38132                 }).createDelegate(this)
38133             );
38134             
38135         }, this);
38136         
38137         this.files = files;
38138         
38139         this.delegates = this.delegates.concat(docs);
38140         
38141         if(!this.delegates.length){
38142             this.refresh();
38143             return;
38144         }
38145         
38146         this.progressBar.aria_valuemax = this.delegates.length;
38147         
38148         this.arrange();
38149         
38150         return;
38151     },
38152     
38153     arrange : function()
38154     {
38155         if(!this.delegates.length){
38156             this.progressDialog.hide();
38157             this.refresh();
38158             return;
38159         }
38160         
38161         var delegate = this.delegates.shift();
38162         
38163         this.progressDialog.show();
38164         
38165         this.progressDialog.setTitle((this.progressBar.aria_valuemax - this.delegates.length) + ' / ' + this.progressBar.aria_valuemax);
38166         
38167         this.progressBar.update(this.progressBar.aria_valuemax - this.delegates.length);
38168         
38169         delegate();
38170     },
38171     
38172     refresh : function()
38173     {
38174         this.uploader.show();
38175         
38176         if(this.boxes > 0 && this.files.length > this.boxes - 1){
38177             this.uploader.hide();
38178         }
38179         
38180         Roo.isTouch ? this.closable(false) : this.closable(true);
38181         
38182         this.fireEvent('refresh', this);
38183     },
38184     
38185     onRemove : function(e, el, o)
38186     {
38187         e.preventDefault();
38188         
38189         this.fireEvent('remove', this, o);
38190         
38191     },
38192     
38193     remove : function(o)
38194     {
38195         var files = [];
38196         
38197         Roo.each(this.files, function(file){
38198             if(typeof(file.id) == 'undefined' || file.id * 1 < 1 || file.id != o.id){
38199                 files.push(file);
38200                 return;
38201             }
38202
38203             o.target.remove();
38204
38205         }, this);
38206         
38207         this.files = files;
38208         
38209         this.refresh();
38210     },
38211     
38212     clear : function()
38213     {
38214         Roo.each(this.files, function(file){
38215             if(!file.target){
38216                 return;
38217             }
38218             
38219             file.target.remove();
38220
38221         }, this);
38222         
38223         this.files = [];
38224         
38225         this.refresh();
38226     },
38227     
38228     onClick : function(e, el, o)
38229     {
38230         e.preventDefault();
38231         
38232         this.fireEvent('click', this, o);
38233         
38234     },
38235     
38236     closable : function(closable)
38237     {
38238         Roo.each(this.managerEl.select('.roo-document-manager-preview > button.close', true).elements, function(el){
38239             
38240             el.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
38241             
38242             if(closable){
38243                 el.show();
38244                 return;
38245             }
38246             
38247             el.hide();
38248             
38249         }, this);
38250     },
38251     
38252     xhrOnLoad : function(xhr)
38253     {
38254         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
38255             el.remove();
38256         }, this);
38257         
38258         if (xhr.readyState !== 4) {
38259             this.arrange();
38260             this.fireEvent('exception', this, xhr);
38261             return;
38262         }
38263
38264         var response = Roo.decode(xhr.responseText);
38265         
38266         if(!response.success){
38267             this.arrange();
38268             this.fireEvent('exception', this, xhr);
38269             return;
38270         }
38271         
38272         var file = this.renderPreview(response.data);
38273         
38274         this.files.push(file);
38275         
38276         this.arrange();
38277         
38278         this.fireEvent('afterupload', this, xhr);
38279         
38280     },
38281     
38282     xhrOnError : function(xhr)
38283     {
38284         Roo.log('xhr on error');
38285         
38286         var response = Roo.decode(xhr.responseText);
38287           
38288         Roo.log(response);
38289         
38290         this.arrange();
38291     },
38292     
38293     process : function(file)
38294     {
38295         if(this.fireEvent('process', this, file) !== false){
38296             if(this.editable && file.type.indexOf('image') != -1){
38297                 this.fireEvent('edit', this, file);
38298                 return;
38299             }
38300
38301             this.uploadStart(file, false);
38302
38303             return;
38304         }
38305         
38306     },
38307     
38308     uploadStart : function(file, crop)
38309     {
38310         this.xhr = new XMLHttpRequest();
38311         
38312         if(typeof(file.id) != 'undefined' && file.id * 1 > 0){
38313             this.arrange();
38314             return;
38315         }
38316         
38317         file.xhr = this.xhr;
38318             
38319         this.managerEl.createChild({
38320             tag : 'div',
38321             cls : 'roo-document-manager-loading',
38322             cn : [
38323                 {
38324                     tag : 'div',
38325                     tooltip : file.name,
38326                     cls : 'roo-document-manager-thumb',
38327                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
38328                 }
38329             ]
38330
38331         });
38332
38333         this.xhr.open(this.method, this.url, true);
38334         
38335         var headers = {
38336             "Accept": "application/json",
38337             "Cache-Control": "no-cache",
38338             "X-Requested-With": "XMLHttpRequest"
38339         };
38340         
38341         for (var headerName in headers) {
38342             var headerValue = headers[headerName];
38343             if (headerValue) {
38344                 this.xhr.setRequestHeader(headerName, headerValue);
38345             }
38346         }
38347         
38348         var _this = this;
38349         
38350         this.xhr.onload = function()
38351         {
38352             _this.xhrOnLoad(_this.xhr);
38353         }
38354         
38355         this.xhr.onerror = function()
38356         {
38357             _this.xhrOnError(_this.xhr);
38358         }
38359         
38360         var formData = new FormData();
38361
38362         formData.append('returnHTML', 'NO');
38363         
38364         if(crop){
38365             formData.append('crop', crop);
38366         }
38367         
38368         formData.append(this.paramName, file, file.name);
38369         
38370         var options = {
38371             file : file, 
38372             manually : false
38373         };
38374         
38375         if(this.fireEvent('prepare', this, formData, options) != false){
38376             
38377             if(options.manually){
38378                 return;
38379             }
38380             
38381             this.xhr.send(formData);
38382             return;
38383         };
38384         
38385         this.uploadCancel();
38386     },
38387     
38388     uploadCancel : function()
38389     {
38390         if (this.xhr) {
38391             this.xhr.abort();
38392         }
38393         
38394         this.delegates = [];
38395         
38396         Roo.each(this.managerEl.select('.roo-document-manager-loading', true).elements, function(el){
38397             el.remove();
38398         }, this);
38399         
38400         this.arrange();
38401     },
38402     
38403     renderPreview : function(file)
38404     {
38405         if(typeof(file.target) != 'undefined' && file.target){
38406             return file;
38407         }
38408         
38409         var img_src = encodeURI(baseURL +'/Images/Thumb/' + this.thumbSize + '/' + file.id + '/' + file.filename);
38410         
38411         var previewEl = this.managerEl.createChild({
38412             tag : 'div',
38413             cls : 'roo-document-manager-preview',
38414             cn : [
38415                 {
38416                     tag : 'div',
38417                     tooltip : file[this.toolTipName],
38418                     cls : 'roo-document-manager-thumb',
38419                     html : '<img tooltip="' + file[this.toolTipName] + '" src="' + img_src + '">'
38420                 },
38421                 {
38422                     tag : 'button',
38423                     cls : 'close',
38424                     html : '<i class="fa fa-times-circle"></i>'
38425                 }
38426             ]
38427         });
38428
38429         var close = previewEl.select('button.close', true).first();
38430
38431         close.on('click', this.onRemove, this, file);
38432
38433         file.target = previewEl;
38434
38435         var image = previewEl.select('img', true).first();
38436         
38437         var _this = this;
38438         
38439         image.dom.addEventListener("load", function(){ _this.onPreviewLoad(file, image); });
38440         
38441         image.on('click', this.onClick, this, file);
38442         
38443         this.fireEvent('previewrendered', this, file);
38444         
38445         return file;
38446         
38447     },
38448     
38449     onPreviewLoad : function(file, image)
38450     {
38451         if(typeof(file.target) == 'undefined' || !file.target){
38452             return;
38453         }
38454         
38455         var width = image.dom.naturalWidth || image.dom.width;
38456         var height = image.dom.naturalHeight || image.dom.height;
38457         
38458         if(!this.previewResize) {
38459             return;
38460         }
38461         
38462         if(width > height){
38463             file.target.addClass('wide');
38464             return;
38465         }
38466         
38467         file.target.addClass('tall');
38468         return;
38469         
38470     },
38471     
38472     uploadFromSource : function(file, crop)
38473     {
38474         this.xhr = new XMLHttpRequest();
38475         
38476         this.managerEl.createChild({
38477             tag : 'div',
38478             cls : 'roo-document-manager-loading',
38479             cn : [
38480                 {
38481                     tag : 'div',
38482                     tooltip : file.name,
38483                     cls : 'roo-document-manager-thumb',
38484                     html : '<i class="fa fa-circle-o-notch fa-spin"></i>'
38485                 }
38486             ]
38487
38488         });
38489
38490         this.xhr.open(this.method, this.url, true);
38491         
38492         var headers = {
38493             "Accept": "application/json",
38494             "Cache-Control": "no-cache",
38495             "X-Requested-With": "XMLHttpRequest"
38496         };
38497         
38498         for (var headerName in headers) {
38499             var headerValue = headers[headerName];
38500             if (headerValue) {
38501                 this.xhr.setRequestHeader(headerName, headerValue);
38502             }
38503         }
38504         
38505         var _this = this;
38506         
38507         this.xhr.onload = function()
38508         {
38509             _this.xhrOnLoad(_this.xhr);
38510         }
38511         
38512         this.xhr.onerror = function()
38513         {
38514             _this.xhrOnError(_this.xhr);
38515         }
38516         
38517         var formData = new FormData();
38518
38519         formData.append('returnHTML', 'NO');
38520         
38521         formData.append('crop', crop);
38522         
38523         if(typeof(file.filename) != 'undefined'){
38524             formData.append('filename', file.filename);
38525         }
38526         
38527         if(typeof(file.mimetype) != 'undefined'){
38528             formData.append('mimetype', file.mimetype);
38529         }
38530         
38531         Roo.log(formData);
38532         
38533         if(this.fireEvent('prepare', this, formData) != false){
38534             this.xhr.send(formData);
38535         };
38536     }
38537 });
38538
38539 /*
38540 * Licence: LGPL
38541 */
38542
38543 /**
38544  * @class Roo.bootstrap.DocumentViewer
38545  * @extends Roo.bootstrap.Component
38546  * Bootstrap DocumentViewer class
38547  * @cfg {Boolean} showDownload (true|false) show download button (default true)
38548  * @cfg {Boolean} showTrash (true|false) show trash button (default true)
38549  * 
38550  * @constructor
38551  * Create a new DocumentViewer
38552  * @param {Object} config The config object
38553  */
38554
38555 Roo.bootstrap.DocumentViewer = function(config){
38556     Roo.bootstrap.DocumentViewer.superclass.constructor.call(this, config);
38557     
38558     this.addEvents({
38559         /**
38560          * @event initial
38561          * Fire after initEvent
38562          * @param {Roo.bootstrap.DocumentViewer} this
38563          */
38564         "initial" : true,
38565         /**
38566          * @event click
38567          * Fire after click
38568          * @param {Roo.bootstrap.DocumentViewer} this
38569          */
38570         "click" : true,
38571         /**
38572          * @event download
38573          * Fire after download button
38574          * @param {Roo.bootstrap.DocumentViewer} this
38575          */
38576         "download" : true,
38577         /**
38578          * @event trash
38579          * Fire after trash button
38580          * @param {Roo.bootstrap.DocumentViewer} this
38581          */
38582         "trash" : true
38583         
38584     });
38585 };
38586
38587 Roo.extend(Roo.bootstrap.DocumentViewer, Roo.bootstrap.Component,  {
38588     
38589     showDownload : true,
38590     
38591     showTrash : true,
38592     
38593     getAutoCreate : function()
38594     {
38595         var cfg = {
38596             tag : 'div',
38597             cls : 'roo-document-viewer',
38598             cn : [
38599                 {
38600                     tag : 'div',
38601                     cls : 'roo-document-viewer-body',
38602                     cn : [
38603                         {
38604                             tag : 'div',
38605                             cls : 'roo-document-viewer-thumb',
38606                             cn : [
38607                                 {
38608                                     tag : 'img',
38609                                     cls : 'roo-document-viewer-image'
38610                                 }
38611                             ]
38612                         }
38613                     ]
38614                 },
38615                 {
38616                     tag : 'div',
38617                     cls : 'roo-document-viewer-footer',
38618                     cn : {
38619                         tag : 'div',
38620                         cls : 'btn-group btn-group-justified roo-document-viewer-btn-group',
38621                         cn : [
38622                             {
38623                                 tag : 'div',
38624                                 cls : 'btn-group roo-document-viewer-download',
38625                                 cn : [
38626                                     {
38627                                         tag : 'button',
38628                                         cls : 'btn btn-default',
38629                                         html : '<i class="fa fa-download"></i>'
38630                                     }
38631                                 ]
38632                             },
38633                             {
38634                                 tag : 'div',
38635                                 cls : 'btn-group roo-document-viewer-trash',
38636                                 cn : [
38637                                     {
38638                                         tag : 'button',
38639                                         cls : 'btn btn-default',
38640                                         html : '<i class="fa fa-trash"></i>'
38641                                     }
38642                                 ]
38643                             }
38644                         ]
38645                     }
38646                 }
38647             ]
38648         };
38649         
38650         return cfg;
38651     },
38652     
38653     initEvents : function()
38654     {
38655         this.bodyEl = this.el.select('.roo-document-viewer-body', true).first();
38656         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
38657         
38658         this.thumbEl = this.el.select('.roo-document-viewer-thumb', true).first();
38659         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
38660         
38661         this.imageEl = this.el.select('.roo-document-viewer-image', true).first();
38662         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
38663         
38664         this.footerEl = this.el.select('.roo-document-viewer-footer', true).first();
38665         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY);
38666         
38667         this.downloadBtn = this.el.select('.roo-document-viewer-download', true).first();
38668         this.downloadBtn.setVisibilityMode(Roo.Element.DISPLAY);
38669         
38670         this.trashBtn = this.el.select('.roo-document-viewer-trash', true).first();
38671         this.trashBtn.setVisibilityMode(Roo.Element.DISPLAY);
38672         
38673         this.bodyEl.on('click', this.onClick, this);
38674         this.downloadBtn.on('click', this.onDownload, this);
38675         this.trashBtn.on('click', this.onTrash, this);
38676         
38677         this.downloadBtn.hide();
38678         this.trashBtn.hide();
38679         
38680         if(this.showDownload){
38681             this.downloadBtn.show();
38682         }
38683         
38684         if(this.showTrash){
38685             this.trashBtn.show();
38686         }
38687         
38688         if(!this.showDownload && !this.showTrash) {
38689             this.footerEl.hide();
38690         }
38691         
38692     },
38693     
38694     initial : function()
38695     {
38696         this.fireEvent('initial', this);
38697         
38698     },
38699     
38700     onClick : function(e)
38701     {
38702         e.preventDefault();
38703         
38704         this.fireEvent('click', this);
38705     },
38706     
38707     onDownload : function(e)
38708     {
38709         e.preventDefault();
38710         
38711         this.fireEvent('download', this);
38712     },
38713     
38714     onTrash : function(e)
38715     {
38716         e.preventDefault();
38717         
38718         this.fireEvent('trash', this);
38719     }
38720     
38721 });
38722 /*
38723  * - LGPL
38724  *
38725  * FieldLabel
38726  * 
38727  */
38728
38729 /**
38730  * @class Roo.bootstrap.form.FieldLabel
38731  * @extends Roo.bootstrap.Component
38732  * Bootstrap FieldLabel class
38733  * @cfg {String} html contents of the element
38734  * @cfg {String} tag tag of the element default label
38735  * @cfg {String} cls class of the element
38736  * @cfg {String} target label target 
38737  * @cfg {Boolean} allowBlank (true|false) target allowBlank default true
38738  * @cfg {String} invalidClass DEPRICATED - BS4 uses is-invalid
38739  * @cfg {String} validClass DEPRICATED - BS4 uses is-valid
38740  * @cfg {String} iconTooltip default "This field is required"
38741  * @cfg {String} indicatorpos (left|right) default left
38742  * 
38743  * @constructor
38744  * Create a new FieldLabel
38745  * @param {Object} config The config object
38746  */
38747
38748 Roo.bootstrap.form.FieldLabel = function(config){
38749     Roo.bootstrap.Element.superclass.constructor.call(this, config);
38750     
38751     this.addEvents({
38752             /**
38753              * @event invalid
38754              * Fires after the field has been marked as invalid.
38755              * @param {Roo.form.FieldLabel} this
38756              * @param {String} msg The validation message
38757              */
38758             invalid : true,
38759             /**
38760              * @event valid
38761              * Fires after the field has been validated with no errors.
38762              * @param {Roo.form.FieldLabel} this
38763              */
38764             valid : true
38765         });
38766 };
38767
38768 Roo.extend(Roo.bootstrap.form.FieldLabel, Roo.bootstrap.Component,  {
38769     
38770     tag: 'label',
38771     cls: '',
38772     html: '',
38773     target: '',
38774     allowBlank : true,
38775     invalidClass : 'has-warning',
38776     validClass : 'has-success',
38777     iconTooltip : 'This field is required',
38778     indicatorpos : 'left',
38779     
38780     getAutoCreate : function(){
38781         
38782         var cls = "";
38783         if (!this.allowBlank) {
38784             cls  = "visible";
38785         }
38786         
38787         var cfg = {
38788             tag : this.tag,
38789             cls : 'roo-bootstrap-field-label ' + this.cls,
38790             for : this.target,
38791             cn : [
38792                 {
38793                     tag : 'i',
38794                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star ' + cls,
38795                     tooltip : this.iconTooltip
38796                 },
38797                 {
38798                     tag : 'span',
38799                     html : this.html
38800                 }
38801             ] 
38802         };
38803         
38804         if(this.indicatorpos == 'right'){
38805             var cfg = {
38806                 tag : this.tag,
38807                 cls : 'roo-bootstrap-field-label ' + this.cls,
38808                 for : this.target,
38809                 cn : [
38810                     {
38811                         tag : 'span',
38812                         html : this.html
38813                     },
38814                     {
38815                         tag : 'i',
38816                         cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star '+ cls,
38817                         tooltip : this.iconTooltip
38818                     }
38819                 ] 
38820             };
38821         }
38822         
38823         return cfg;
38824     },
38825     
38826     initEvents: function() 
38827     {
38828         Roo.bootstrap.Element.superclass.initEvents.call(this);
38829         
38830         this.indicator = this.indicatorEl();
38831         
38832         if(this.indicator){
38833             this.indicator.removeClass('visible');
38834             this.indicator.addClass('invisible');
38835         }
38836         
38837         Roo.bootstrap.form.FieldLabel.register(this);
38838     },
38839     
38840     indicatorEl : function()
38841     {
38842         var indicator = this.el.select('i.roo-required-indicator',true).first();
38843         
38844         if(!indicator){
38845             return false;
38846         }
38847         
38848         return indicator;
38849         
38850     },
38851     
38852     /**
38853      * Mark this field as valid
38854      */
38855     markValid : function()
38856     {
38857         if(this.indicator){
38858             this.indicator.removeClass('visible');
38859             this.indicator.addClass('invisible');
38860         }
38861         if (Roo.bootstrap.version == 3) {
38862             this.el.removeClass(this.invalidClass);
38863             this.el.addClass(this.validClass);
38864         } else {
38865             this.el.removeClass('is-invalid');
38866             this.el.addClass('is-valid');
38867         }
38868         
38869         
38870         this.fireEvent('valid', this);
38871     },
38872     
38873     /**
38874      * Mark this field as invalid
38875      * @param {String} msg The validation message
38876      */
38877     markInvalid : function(msg)
38878     {
38879         if(this.indicator){
38880             this.indicator.removeClass('invisible');
38881             this.indicator.addClass('visible');
38882         }
38883           if (Roo.bootstrap.version == 3) {
38884             this.el.removeClass(this.validClass);
38885             this.el.addClass(this.invalidClass);
38886         } else {
38887             this.el.removeClass('is-valid');
38888             this.el.addClass('is-invalid');
38889         }
38890         
38891         
38892         this.fireEvent('invalid', this, msg);
38893     }
38894     
38895    
38896 });
38897
38898 Roo.apply(Roo.bootstrap.form.FieldLabel, {
38899     
38900     groups: {},
38901     
38902      /**
38903     * register a FieldLabel Group
38904     * @param {Roo.bootstrap.form.FieldLabel} the FieldLabel to add
38905     */
38906     register : function(label)
38907     {
38908         if(this.groups.hasOwnProperty(label.target)){
38909             return;
38910         }
38911      
38912         this.groups[label.target] = label;
38913         
38914     },
38915     /**
38916     * fetch a FieldLabel Group based on the target
38917     * @param {string} target
38918     * @returns {Roo.bootstrap.form.FieldLabel} the CheckBox group
38919     */
38920     get: function(target) {
38921         if (typeof(this.groups[target]) == 'undefined') {
38922             return false;
38923         }
38924         
38925         return this.groups[target] ;
38926     }
38927 });
38928
38929  
38930
38931  /*
38932  * - LGPL
38933  *
38934  * page DateSplitField.
38935  * 
38936  */
38937
38938
38939 /**
38940  * @class Roo.bootstrap.form.DateSplitField
38941  * @extends Roo.bootstrap.Component
38942  * Bootstrap DateSplitField class
38943  * @cfg {string} fieldLabel - the label associated
38944  * @cfg {Number} labelWidth set the width of label (0-12)
38945  * @cfg {String} labelAlign (top|left)
38946  * @cfg {Boolean} dayAllowBlank (true|false) default false
38947  * @cfg {Boolean} monthAllowBlank (true|false) default false
38948  * @cfg {Boolean} yearAllowBlank (true|false) default false
38949  * @cfg {string} dayPlaceholder 
38950  * @cfg {string} monthPlaceholder
38951  * @cfg {string} yearPlaceholder
38952  * @cfg {string} dayFormat default 'd'
38953  * @cfg {string} monthFormat default 'm'
38954  * @cfg {string} yearFormat default 'Y'
38955  * @cfg {Number} labellg set the width of label (1-12)
38956  * @cfg {Number} labelmd set the width of label (1-12)
38957  * @cfg {Number} labelsm set the width of label (1-12)
38958  * @cfg {Number} labelxs set the width of label (1-12)
38959
38960  *     
38961  * @constructor
38962  * Create a new DateSplitField
38963  * @param {Object} config The config object
38964  */
38965
38966 Roo.bootstrap.form.DateSplitField = function(config){
38967     Roo.bootstrap.form.DateSplitField.superclass.constructor.call(this, config);
38968     
38969     this.addEvents({
38970         // raw events
38971          /**
38972          * @event years
38973          * getting the data of years
38974          * @param {Roo.bootstrap.form.DateSplitField} this
38975          * @param {Object} years
38976          */
38977         "years" : true,
38978         /**
38979          * @event days
38980          * getting the data of days
38981          * @param {Roo.bootstrap.form.DateSplitField} this
38982          * @param {Object} days
38983          */
38984         "days" : true,
38985         /**
38986          * @event invalid
38987          * Fires after the field has been marked as invalid.
38988          * @param {Roo.form.Field} this
38989          * @param {String} msg The validation message
38990          */
38991         invalid : true,
38992        /**
38993          * @event valid
38994          * Fires after the field has been validated with no errors.
38995          * @param {Roo.form.Field} this
38996          */
38997         valid : true
38998     });
38999 };
39000
39001 Roo.extend(Roo.bootstrap.form.DateSplitField, Roo.bootstrap.Component,  {
39002     
39003     fieldLabel : '',
39004     labelAlign : 'top',
39005     labelWidth : 3,
39006     dayAllowBlank : false,
39007     monthAllowBlank : false,
39008     yearAllowBlank : false,
39009     dayPlaceholder : '',
39010     monthPlaceholder : '',
39011     yearPlaceholder : '',
39012     dayFormat : 'd',
39013     monthFormat : 'm',
39014     yearFormat : 'Y',
39015     isFormField : true,
39016     labellg : 0,
39017     labelmd : 0,
39018     labelsm : 0,
39019     labelxs : 0,
39020     
39021     getAutoCreate : function()
39022     {
39023         var cfg = {
39024             tag : 'div',
39025             cls : 'row roo-date-split-field-group',
39026             cn : [
39027                 {
39028                     tag : 'input',
39029                     type : 'hidden',
39030                     cls : 'form-hidden-field roo-date-split-field-group-value',
39031                     name : this.name
39032                 }
39033             ]
39034         };
39035         
39036         var labelCls = 'col-md-12';
39037         var contentCls = 'col-md-4';
39038         
39039         if(this.fieldLabel){
39040             
39041             var label = {
39042                 tag : 'div',
39043                 cls : 'column roo-date-split-field-label col-md-' + ((this.labelAlign == 'top') ? '12' : this.labelWidth),
39044                 cn : [
39045                     {
39046                         tag : 'label',
39047                         html : this.fieldLabel
39048                     }
39049                 ]
39050             };
39051             
39052             if(this.labelAlign == 'left'){
39053             
39054                 if(this.labelWidth > 12){
39055                     label.style = "width: " + this.labelWidth + 'px';
39056                 }
39057
39058                 if(this.labelWidth < 13 && this.labelmd == 0){
39059                     this.labelmd = this.labelWidth;
39060                 }
39061
39062                 if(this.labellg > 0){
39063                     labelCls = ' col-lg-' + this.labellg;
39064                     contentCls = ' col-lg-' + ((12 - this.labellg) / 3);
39065                 }
39066
39067                 if(this.labelmd > 0){
39068                     labelCls = ' col-md-' + this.labelmd;
39069                     contentCls = ' col-md-' + ((12 - this.labelmd) / 3);
39070                 }
39071
39072                 if(this.labelsm > 0){
39073                     labelCls = ' col-sm-' + this.labelsm;
39074                     contentCls = ' col-sm-' + ((12 - this.labelsm) / 3);
39075                 }
39076
39077                 if(this.labelxs > 0){
39078                     labelCls = ' col-xs-' + this.labelxs;
39079                     contentCls = ' col-xs-' + ((12 - this.labelxs) / 3);
39080                 }
39081             }
39082             
39083             label.cls += ' ' + labelCls;
39084             
39085             cfg.cn.push(label);
39086         }
39087         
39088         Roo.each(['day', 'month', 'year'], function(t){
39089             cfg.cn.push({
39090                 tag : 'div',
39091                 cls : 'column roo-date-split-field-' + t + ' ' + contentCls
39092             });
39093         }, this);
39094         
39095         return cfg;
39096     },
39097     
39098     inputEl: function ()
39099     {
39100         return this.el.select('.roo-date-split-field-group-value', true).first();
39101     },
39102     
39103     onRender : function(ct, position) 
39104     {
39105         var _this = this;
39106         
39107         Roo.bootstrap.DateSplitFiel.superclass.onRender.call(this, ct, position);
39108         
39109         this.inputEl = this.el.select('.roo-date-split-field-group-value', true).first();
39110         
39111         this.dayField = new Roo.bootstrap.form.ComboBox({
39112             allowBlank : this.dayAllowBlank,
39113             alwaysQuery : true,
39114             displayField : 'value',
39115             editable : false,
39116             fieldLabel : '',
39117             forceSelection : true,
39118             mode : 'local',
39119             placeholder : this.dayPlaceholder,
39120             selectOnFocus : true,
39121             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
39122             triggerAction : 'all',
39123             typeAhead : true,
39124             valueField : 'value',
39125             store : new Roo.data.SimpleStore({
39126                 data : (function() {    
39127                     var days = [];
39128                     _this.fireEvent('days', _this, days);
39129                     return days;
39130                 })(),
39131                 fields : [ 'value' ]
39132             }),
39133             listeners : {
39134                 select : function (_self, record, index)
39135                 {
39136                     _this.setValue(_this.getValue());
39137                 }
39138             }
39139         });
39140
39141         this.dayField.render(this.el.select('.roo-date-split-field-day', true).first(), null);
39142         
39143         this.monthField = new Roo.bootstrap.form.MonthField({
39144             after : '<i class=\"fa fa-calendar\"></i>',
39145             allowBlank : this.monthAllowBlank,
39146             placeholder : this.monthPlaceholder,
39147             readOnly : true,
39148             listeners : {
39149                 render : function (_self)
39150                 {
39151                     this.el.select('span.input-group-addon', true).first().on('click', function(e){
39152                         e.preventDefault();
39153                         _self.focus();
39154                     });
39155                 },
39156                 select : function (_self, oldvalue, newvalue)
39157                 {
39158                     _this.setValue(_this.getValue());
39159                 }
39160             }
39161         });
39162         
39163         this.monthField.render(this.el.select('.roo-date-split-field-month', true).first(), null);
39164         
39165         this.yearField = new Roo.bootstrap.form.ComboBox({
39166             allowBlank : this.yearAllowBlank,
39167             alwaysQuery : true,
39168             displayField : 'value',
39169             editable : false,
39170             fieldLabel : '',
39171             forceSelection : true,
39172             mode : 'local',
39173             placeholder : this.yearPlaceholder,
39174             selectOnFocus : true,
39175             tpl : '<div class="roo-select2-result"><b>{value}</b></div>',
39176             triggerAction : 'all',
39177             typeAhead : true,
39178             valueField : 'value',
39179             store : new Roo.data.SimpleStore({
39180                 data : (function() {
39181                     var years = [];
39182                     _this.fireEvent('years', _this, years);
39183                     return years;
39184                 })(),
39185                 fields : [ 'value' ]
39186             }),
39187             listeners : {
39188                 select : function (_self, record, index)
39189                 {
39190                     _this.setValue(_this.getValue());
39191                 }
39192             }
39193         });
39194
39195         this.yearField.render(this.el.select('.roo-date-split-field-year', true).first(), null);
39196     },
39197     
39198     setValue : function(v, format)
39199     {
39200         this.inputEl.dom.value = v;
39201         
39202         var f = format || (this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat);
39203         
39204         var d = Date.parseDate(v, f);
39205         
39206         if(!d){
39207             this.validate();
39208             return;
39209         }
39210         
39211         this.setDay(d.format(this.dayFormat));
39212         this.setMonth(d.format(this.monthFormat));
39213         this.setYear(d.format(this.yearFormat));
39214         
39215         this.validate();
39216         
39217         return;
39218     },
39219     
39220     setDay : function(v)
39221     {
39222         this.dayField.setValue(v);
39223         this.inputEl.dom.value = this.getValue();
39224         this.validate();
39225         return;
39226     },
39227     
39228     setMonth : function(v)
39229     {
39230         this.monthField.setValue(v, true);
39231         this.inputEl.dom.value = this.getValue();
39232         this.validate();
39233         return;
39234     },
39235     
39236     setYear : function(v)
39237     {
39238         this.yearField.setValue(v);
39239         this.inputEl.dom.value = this.getValue();
39240         this.validate();
39241         return;
39242     },
39243     
39244     getDay : function()
39245     {
39246         return this.dayField.getValue();
39247     },
39248     
39249     getMonth : function()
39250     {
39251         return this.monthField.getValue();
39252     },
39253     
39254     getYear : function()
39255     {
39256         return this.yearField.getValue();
39257     },
39258     
39259     getValue : function()
39260     {
39261         var f = this.yearFormat + '-' + this.monthFormat + '-' + this.dayFormat;
39262         
39263         var date = this.yearField.getValue() + '-' + this.monthField.getValue() + '-' + this.dayField.getValue();
39264         
39265         return date;
39266     },
39267     
39268     reset : function()
39269     {
39270         this.setDay('');
39271         this.setMonth('');
39272         this.setYear('');
39273         this.inputEl.dom.value = '';
39274         this.validate();
39275         return;
39276     },
39277     
39278     validate : function()
39279     {
39280         var d = this.dayField.validate();
39281         var m = this.monthField.validate();
39282         var y = this.yearField.validate();
39283         
39284         var valid = true;
39285         
39286         if(
39287                 (!this.dayAllowBlank && !d) ||
39288                 (!this.monthAllowBlank && !m) ||
39289                 (!this.yearAllowBlank && !y)
39290         ){
39291             valid = false;
39292         }
39293         
39294         if(this.dayAllowBlank && this.monthAllowBlank && this.yearAllowBlank){
39295             return valid;
39296         }
39297         
39298         if(valid){
39299             this.markValid();
39300             return valid;
39301         }
39302         
39303         this.markInvalid();
39304         
39305         return valid;
39306     },
39307     
39308     markValid : function()
39309     {
39310         
39311         var label = this.el.select('label', true).first();
39312         var icon = this.el.select('i.fa-star', true).first();
39313
39314         if(label && icon){
39315             icon.remove();
39316         }
39317         
39318         this.fireEvent('valid', this);
39319     },
39320     
39321      /**
39322      * Mark this field as invalid
39323      * @param {String} msg The validation message
39324      */
39325     markInvalid : function(msg)
39326     {
39327         
39328         var label = this.el.select('label', true).first();
39329         var icon = this.el.select('i.fa-star', true).first();
39330
39331         if(label && !icon){
39332             this.el.select('.roo-date-split-field-label', true).createChild({
39333                 tag : 'i',
39334                 cls : 'text-danger fa fa-lg fa-star',
39335                 tooltip : 'This field is required',
39336                 style : 'margin-right:5px;'
39337             }, label, true);
39338         }
39339         
39340         this.fireEvent('invalid', this, msg);
39341     },
39342     
39343     clearInvalid : function()
39344     {
39345         var label = this.el.select('label', true).first();
39346         var icon = this.el.select('i.fa-star', true).first();
39347
39348         if(label && icon){
39349             icon.remove();
39350         }
39351         
39352         this.fireEvent('valid', this);
39353     },
39354     
39355     getName: function()
39356     {
39357         return this.name;
39358     }
39359     
39360 });
39361
39362  
39363
39364 /**
39365  * @class Roo.bootstrap.LayoutMasonry
39366  * @extends Roo.bootstrap.Component
39367  * @children Roo.bootstrap.Element Roo.bootstrap.Img Roo.bootstrap.MasonryBrick
39368  * Bootstrap Layout Masonry class
39369  *
39370  * This is based on 
39371  * http://masonry.desandro.com
39372  *
39373  * The idea is to render all the bricks based on vertical width...
39374  *
39375  * The original code extends 'outlayer' - we might need to use that....
39376
39377  * @constructor
39378  * Create a new Element
39379  * @param {Object} config The config object
39380  */
39381
39382 Roo.bootstrap.LayoutMasonry = function(config){
39383     
39384     Roo.bootstrap.LayoutMasonry.superclass.constructor.call(this, config);
39385     
39386     this.bricks = [];
39387     
39388     Roo.bootstrap.LayoutMasonry.register(this);
39389     
39390     this.addEvents({
39391         // raw events
39392         /**
39393          * @event layout
39394          * Fire after layout the items
39395          * @param {Roo.bootstrap.LayoutMasonry} this
39396          * @param {Roo.EventObject} e
39397          */
39398         "layout" : true
39399     });
39400     
39401 };
39402
39403 Roo.extend(Roo.bootstrap.LayoutMasonry, Roo.bootstrap.Component,  {
39404     
39405     /**
39406      * @cfg {Boolean} isLayoutInstant = no animation?
39407      */   
39408     isLayoutInstant : false, // needed?
39409    
39410     /**
39411      * @cfg {Number} boxWidth  width of the columns
39412      */   
39413     boxWidth : 450,
39414     
39415       /**
39416      * @cfg {Number} boxHeight  - 0 for square, or fix it at a certian height
39417      */   
39418     boxHeight : 0,
39419     
39420     /**
39421      * @cfg {Number} padWidth padding below box..
39422      */   
39423     padWidth : 10, 
39424     
39425     /**
39426      * @cfg {Number} gutter gutter width..
39427      */   
39428     gutter : 10,
39429     
39430      /**
39431      * @cfg {Number} maxCols maximum number of columns
39432      */   
39433     
39434     maxCols: 0,
39435     
39436     /**
39437      * @cfg {Boolean} isAutoInitial defalut true
39438      */   
39439     isAutoInitial : true, 
39440     
39441     containerWidth: 0,
39442     
39443     /**
39444      * @cfg {Boolean} isHorizontal defalut false
39445      */   
39446     isHorizontal : false, 
39447
39448     currentSize : null,
39449     
39450     tag: 'div',
39451     
39452     cls: '',
39453     
39454     bricks: null, //CompositeElement
39455     
39456     cols : 1,
39457     
39458     _isLayoutInited : false,
39459     
39460 //    isAlternative : false, // only use for vertical layout...
39461     
39462     /**
39463      * @cfg {Number} alternativePadWidth padding below box..
39464      */   
39465     alternativePadWidth : 50,
39466     
39467     selectedBrick : [],
39468     
39469     getAutoCreate : function(){
39470         
39471         var cfg = Roo.apply({}, Roo.bootstrap.LayoutMasonry.superclass.getAutoCreate.call(this));
39472         
39473         var cfg = {
39474             tag: this.tag,
39475             cls: 'blog-masonary-wrapper ' + this.cls,
39476             cn : {
39477                 cls : 'mas-boxes masonary'
39478             }
39479         };
39480         
39481         return cfg;
39482     },
39483     
39484     getChildContainer: function( )
39485     {
39486         if (this.boxesEl) {
39487             return this.boxesEl;
39488         }
39489         
39490         this.boxesEl = this.el.select('.mas-boxes').first();
39491         
39492         return this.boxesEl;
39493     },
39494     
39495     
39496     initEvents : function()
39497     {
39498         var _this = this;
39499         
39500         if(this.isAutoInitial){
39501             Roo.log('hook children rendered');
39502             this.on('childrenrendered', function() {
39503                 Roo.log('children rendered');
39504                 _this.initial();
39505             } ,this);
39506         }
39507     },
39508     
39509     initial : function()
39510     {
39511         this.selectedBrick = [];
39512         
39513         this.currentSize = this.el.getBox(true);
39514         
39515         Roo.EventManager.onWindowResize(this.resize, this); 
39516
39517         if(!this.isAutoInitial){
39518             this.layout();
39519             return;
39520         }
39521         
39522         this.layout();
39523         
39524         return;
39525         //this.layout.defer(500,this);
39526         
39527     },
39528     
39529     resize : function()
39530     {
39531         var cs = this.el.getBox(true);
39532         
39533         if (
39534                 this.currentSize.width == cs.width && 
39535                 this.currentSize.x == cs.x && 
39536                 this.currentSize.height == cs.height && 
39537                 this.currentSize.y == cs.y 
39538         ) {
39539             Roo.log("no change in with or X or Y");
39540             return;
39541         }
39542         
39543         this.currentSize = cs;
39544         
39545         this.layout();
39546         
39547     },
39548     
39549     layout : function()
39550     {   
39551         this._resetLayout();
39552         
39553         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
39554         
39555         this.layoutItems( isInstant );
39556       
39557         this._isLayoutInited = true;
39558         
39559         this.fireEvent('layout', this);
39560         
39561     },
39562     
39563     _resetLayout : function()
39564     {
39565         if(this.isHorizontal){
39566             this.horizontalMeasureColumns();
39567             return;
39568         }
39569         
39570         this.verticalMeasureColumns();
39571         
39572     },
39573     
39574     verticalMeasureColumns : function()
39575     {
39576         this.getContainerWidth();
39577         
39578 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
39579 //            this.colWidth = Math.floor(this.containerWidth * 0.8);
39580 //            return;
39581 //        }
39582         
39583         var boxWidth = this.boxWidth + this.padWidth;
39584         
39585         if(this.containerWidth < this.boxWidth){
39586             boxWidth = this.containerWidth
39587         }
39588         
39589         var containerWidth = this.containerWidth;
39590         
39591         var cols = Math.floor(containerWidth / boxWidth);
39592         
39593         this.cols = Math.max( cols, 1 );
39594         
39595         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
39596         
39597         var totalBoxWidth = this.cols * boxWidth - this.padWidth;
39598         
39599         var avail = Math.floor((containerWidth - totalBoxWidth) / this.cols);
39600         
39601         this.colWidth = boxWidth + avail - this.padWidth;
39602         
39603         this.unitWidth = Math.round((this.colWidth - (this.gutter * 2)) / 3);
39604         this.unitHeight = this.boxHeight > 0 ? this.boxHeight  : this.unitWidth;
39605     },
39606     
39607     horizontalMeasureColumns : function()
39608     {
39609         this.getContainerWidth();
39610         
39611         var boxWidth = this.boxWidth;
39612         
39613         if(this.containerWidth < boxWidth){
39614             boxWidth = this.containerWidth;
39615         }
39616         
39617         this.unitWidth = Math.floor((boxWidth - (this.gutter * 2)) / 3);
39618         
39619         this.el.setHeight(boxWidth);
39620         
39621     },
39622     
39623     getContainerWidth : function()
39624     {
39625         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
39626     },
39627     
39628     layoutItems : function( isInstant )
39629     {
39630         Roo.log(this.bricks);
39631         
39632         var items = Roo.apply([], this.bricks);
39633         
39634         if(this.isHorizontal){
39635             this._horizontalLayoutItems( items , isInstant );
39636             return;
39637         }
39638         
39639 //        if(Roo.lib.Dom.getViewWidth() < 768 && this.isAlternative){
39640 //            this._verticalAlternativeLayoutItems( items , isInstant );
39641 //            return;
39642 //        }
39643         
39644         this._verticalLayoutItems( items , isInstant );
39645         
39646     },
39647     
39648     _verticalLayoutItems : function ( items , isInstant)
39649     {
39650         if ( !items || !items.length ) {
39651             return;
39652         }
39653         
39654         var standard = [
39655             ['xs', 'xs', 'xs', 'tall'],
39656             ['xs', 'xs', 'tall'],
39657             ['xs', 'xs', 'sm'],
39658             ['xs', 'xs', 'xs'],
39659             ['xs', 'tall'],
39660             ['xs', 'sm'],
39661             ['xs', 'xs'],
39662             ['xs'],
39663             
39664             ['sm', 'xs', 'xs'],
39665             ['sm', 'xs'],
39666             ['sm'],
39667             
39668             ['tall', 'xs', 'xs', 'xs'],
39669             ['tall', 'xs', 'xs'],
39670             ['tall', 'xs'],
39671             ['tall']
39672             
39673         ];
39674         
39675         var queue = [];
39676         
39677         var boxes = [];
39678         
39679         var box = [];
39680         
39681         Roo.each(items, function(item, k){
39682             
39683             switch (item.size) {
39684                 // these layouts take up a full box,
39685                 case 'md' :
39686                 case 'md-left' :
39687                 case 'md-right' :
39688                 case 'wide' :
39689                     
39690                     if(box.length){
39691                         boxes.push(box);
39692                         box = [];
39693                     }
39694                     
39695                     boxes.push([item]);
39696                     
39697                     break;
39698                     
39699                 case 'xs' :
39700                 case 'sm' :
39701                 case 'tall' :
39702                     
39703                     box.push(item);
39704                     
39705                     break;
39706                 default :
39707                     break;
39708                     
39709             }
39710             
39711         }, this);
39712         
39713         if(box.length){
39714             boxes.push(box);
39715             box = [];
39716         }
39717         
39718         var filterPattern = function(box, length)
39719         {
39720             if(!box.length){
39721                 return;
39722             }
39723             
39724             var match = false;
39725             
39726             var pattern = box.slice(0, length);
39727             
39728             var format = [];
39729             
39730             Roo.each(pattern, function(i){
39731                 format.push(i.size);
39732             }, this);
39733             
39734             Roo.each(standard, function(s){
39735                 
39736                 if(String(s) != String(format)){
39737                     return;
39738                 }
39739                 
39740                 match = true;
39741                 return false;
39742                 
39743             }, this);
39744             
39745             if(!match && length == 1){
39746                 return;
39747             }
39748             
39749             if(!match){
39750                 filterPattern(box, length - 1);
39751                 return;
39752             }
39753                 
39754             queue.push(pattern);
39755
39756             box = box.slice(length, box.length);
39757
39758             filterPattern(box, 4);
39759
39760             return;
39761             
39762         }
39763         
39764         Roo.each(boxes, function(box, k){
39765             
39766             if(!box.length){
39767                 return;
39768             }
39769             
39770             if(box.length == 1){
39771                 queue.push(box);
39772                 return;
39773             }
39774             
39775             filterPattern(box, 4);
39776             
39777         }, this);
39778         
39779         this._processVerticalLayoutQueue( queue, isInstant );
39780         
39781     },
39782     
39783 //    _verticalAlternativeLayoutItems : function( items , isInstant )
39784 //    {
39785 //        if ( !items || !items.length ) {
39786 //            return;
39787 //        }
39788 //
39789 //        this._processVerticalAlternativeLayoutQueue( items, isInstant );
39790 //        
39791 //    },
39792     
39793     _horizontalLayoutItems : function ( items , isInstant)
39794     {
39795         if ( !items || !items.length || items.length < 3) {
39796             return;
39797         }
39798         
39799         items.reverse();
39800         
39801         var eItems = items.slice(0, 3);
39802         
39803         items = items.slice(3, items.length);
39804         
39805         var standard = [
39806             ['xs', 'xs', 'xs', 'wide'],
39807             ['xs', 'xs', 'wide'],
39808             ['xs', 'xs', 'sm'],
39809             ['xs', 'xs', 'xs'],
39810             ['xs', 'wide'],
39811             ['xs', 'sm'],
39812             ['xs', 'xs'],
39813             ['xs'],
39814             
39815             ['sm', 'xs', 'xs'],
39816             ['sm', 'xs'],
39817             ['sm'],
39818             
39819             ['wide', 'xs', 'xs', 'xs'],
39820             ['wide', 'xs', 'xs'],
39821             ['wide', 'xs'],
39822             ['wide'],
39823             
39824             ['wide-thin']
39825         ];
39826         
39827         var queue = [];
39828         
39829         var boxes = [];
39830         
39831         var box = [];
39832         
39833         Roo.each(items, function(item, k){
39834             
39835             switch (item.size) {
39836                 case 'md' :
39837                 case 'md-left' :
39838                 case 'md-right' :
39839                 case 'tall' :
39840                     
39841                     if(box.length){
39842                         boxes.push(box);
39843                         box = [];
39844                     }
39845                     
39846                     boxes.push([item]);
39847                     
39848                     break;
39849                     
39850                 case 'xs' :
39851                 case 'sm' :
39852                 case 'wide' :
39853                 case 'wide-thin' :
39854                     
39855                     box.push(item);
39856                     
39857                     break;
39858                 default :
39859                     break;
39860                     
39861             }
39862             
39863         }, this);
39864         
39865         if(box.length){
39866             boxes.push(box);
39867             box = [];
39868         }
39869         
39870         var filterPattern = function(box, length)
39871         {
39872             if(!box.length){
39873                 return;
39874             }
39875             
39876             var match = false;
39877             
39878             var pattern = box.slice(0, length);
39879             
39880             var format = [];
39881             
39882             Roo.each(pattern, function(i){
39883                 format.push(i.size);
39884             }, this);
39885             
39886             Roo.each(standard, function(s){
39887                 
39888                 if(String(s) != String(format)){
39889                     return;
39890                 }
39891                 
39892                 match = true;
39893                 return false;
39894                 
39895             }, this);
39896             
39897             if(!match && length == 1){
39898                 return;
39899             }
39900             
39901             if(!match){
39902                 filterPattern(box, length - 1);
39903                 return;
39904             }
39905                 
39906             queue.push(pattern);
39907
39908             box = box.slice(length, box.length);
39909
39910             filterPattern(box, 4);
39911
39912             return;
39913             
39914         }
39915         
39916         Roo.each(boxes, function(box, k){
39917             
39918             if(!box.length){
39919                 return;
39920             }
39921             
39922             if(box.length == 1){
39923                 queue.push(box);
39924                 return;
39925             }
39926             
39927             filterPattern(box, 4);
39928             
39929         }, this);
39930         
39931         
39932         var prune = [];
39933         
39934         var pos = this.el.getBox(true);
39935         
39936         var minX = pos.x;
39937         
39938         var maxX = pos.right - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
39939         
39940         var hit_end = false;
39941         
39942         Roo.each(queue, function(box){
39943             
39944             if(hit_end){
39945                 
39946                 Roo.each(box, function(b){
39947                 
39948                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
39949                     b.el.hide();
39950
39951                 }, this);
39952
39953                 return;
39954             }
39955             
39956             var mx = 0;
39957             
39958             Roo.each(box, function(b){
39959                 
39960                 b.el.setVisibilityMode(Roo.Element.DISPLAY);
39961                 b.el.show();
39962
39963                 mx = Math.max(mx, b.x);
39964                 
39965             }, this);
39966             
39967             maxX = maxX - this.unitWidth * mx - this.gutter * (mx - 1) - this.padWidth;
39968             
39969             if(maxX < minX){
39970                 
39971                 Roo.each(box, function(b){
39972                 
39973                     b.el.setVisibilityMode(Roo.Element.DISPLAY);
39974                     b.el.hide();
39975                     
39976                 }, this);
39977                 
39978                 hit_end = true;
39979                 
39980                 return;
39981             }
39982             
39983             prune.push(box);
39984             
39985         }, this);
39986         
39987         this._processHorizontalLayoutQueue( prune, eItems, isInstant );
39988     },
39989     
39990     /** Sets position of item in DOM
39991     * @param {Element} item
39992     * @param {Number} x - horizontal position
39993     * @param {Number} y - vertical position
39994     * @param {Boolean} isInstant - disables transitions
39995     */
39996     _processVerticalLayoutQueue : function( queue, isInstant )
39997     {
39998         var pos = this.el.getBox(true);
39999         var x = pos.x;
40000         var y = pos.y;
40001         var maxY = [];
40002         
40003         for (var i = 0; i < this.cols; i++){
40004             maxY[i] = pos.y;
40005         }
40006         
40007         Roo.each(queue, function(box, k){
40008             
40009             var col = k % this.cols;
40010             
40011             Roo.each(box, function(b,kk){
40012                 
40013                 b.el.position('absolute');
40014                 
40015                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
40016                 var height = Math.floor(this.unitHeight * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
40017                 
40018                 if(b.size == 'md-left' || b.size == 'md-right'){
40019                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
40020                     height = Math.floor(this.unitHeight * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
40021                 }
40022                 
40023                 b.el.setWidth(width);
40024                 b.el.setHeight(height);
40025                 // iframe?
40026                 b.el.select('iframe',true).setSize(width,height);
40027                 
40028             }, this);
40029             
40030             for (var i = 0; i < this.cols; i++){
40031                 
40032                 if(maxY[i] < maxY[col]){
40033                     col = i;
40034                     continue;
40035                 }
40036                 
40037                 col = Math.min(col, i);
40038                 
40039             }
40040             
40041             x = pos.x + col * (this.colWidth + this.padWidth);
40042             
40043             y = maxY[col];
40044             
40045             var positions = [];
40046             
40047             switch (box.length){
40048                 case 1 :
40049                     positions = this.getVerticalOneBoxColPositions(x, y, box);
40050                     break;
40051                 case 2 :
40052                     positions = this.getVerticalTwoBoxColPositions(x, y, box);
40053                     break;
40054                 case 3 :
40055                     positions = this.getVerticalThreeBoxColPositions(x, y, box);
40056                     break;
40057                 case 4 :
40058                     positions = this.getVerticalFourBoxColPositions(x, y, box);
40059                     break;
40060                 default :
40061                     break;
40062             }
40063             
40064             Roo.each(box, function(b,kk){
40065                 
40066                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
40067                 
40068                 var sz = b.el.getSize();
40069                 
40070                 maxY[col] = Math.max(maxY[col], positions[kk].y + sz.height + this.padWidth);
40071                 
40072             }, this);
40073             
40074         }, this);
40075         
40076         var mY = 0;
40077         
40078         for (var i = 0; i < this.cols; i++){
40079             mY = Math.max(mY, maxY[i]);
40080         }
40081         
40082         this.el.setHeight(mY - pos.y);
40083         
40084     },
40085     
40086 //    _processVerticalAlternativeLayoutQueue : function( items, isInstant )
40087 //    {
40088 //        var pos = this.el.getBox(true);
40089 //        var x = pos.x;
40090 //        var y = pos.y;
40091 //        var maxX = pos.right;
40092 //        
40093 //        var maxHeight = 0;
40094 //        
40095 //        Roo.each(items, function(item, k){
40096 //            
40097 //            var c = k % 2;
40098 //            
40099 //            item.el.position('absolute');
40100 //                
40101 //            var width = Math.floor(this.colWidth + item.el.getPadding('lr'));
40102 //
40103 //            item.el.setWidth(width);
40104 //
40105 //            var height = Math.floor(this.colWidth * item.y / item.x + item.el.getPadding('tb'));
40106 //
40107 //            item.el.setHeight(height);
40108 //            
40109 //            if(c == 0){
40110 //                item.el.setXY([x, y], isInstant ? false : true);
40111 //            } else {
40112 //                item.el.setXY([maxX - width, y], isInstant ? false : true);
40113 //            }
40114 //            
40115 //            y = y + height + this.alternativePadWidth;
40116 //            
40117 //            maxHeight = maxHeight + height + this.alternativePadWidth;
40118 //            
40119 //        }, this);
40120 //        
40121 //        this.el.setHeight(maxHeight);
40122 //        
40123 //    },
40124     
40125     _processHorizontalLayoutQueue : function( queue, eItems, isInstant )
40126     {
40127         var pos = this.el.getBox(true);
40128         
40129         var minX = pos.x;
40130         var minY = pos.y;
40131         
40132         var maxX = pos.right;
40133         
40134         this._processHorizontalEndItem(eItems, maxX, minX, minY, isInstant);
40135         
40136         var maxX = maxX - this.unitWidth * 3 - this.gutter * 2 - this.padWidth;
40137         
40138         Roo.each(queue, function(box, k){
40139             
40140             Roo.each(box, function(b, kk){
40141                 
40142                 b.el.position('absolute');
40143                 
40144                 var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
40145                 var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
40146                 
40147                 if(b.size == 'md-left' || b.size == 'md-right'){
40148                     width = Math.floor(this.unitWidth * (b.x - 1) + (this.gutter * (b.x - 2)) + b.el.getPadding('lr'));
40149                     height = Math.floor(this.unitWidth * (b.y - 1) + (this.gutter * (b.y - 2)) + b.el.getPadding('tb'));
40150                 }
40151                 
40152                 b.el.setWidth(width);
40153                 b.el.setHeight(height);
40154                 
40155             }, this);
40156             
40157             if(!box.length){
40158                 return;
40159             }
40160             
40161             var positions = [];
40162             
40163             switch (box.length){
40164                 case 1 :
40165                     positions = this.getHorizontalOneBoxColPositions(maxX, minY, box);
40166                     break;
40167                 case 2 :
40168                     positions = this.getHorizontalTwoBoxColPositions(maxX, minY, box);
40169                     break;
40170                 case 3 :
40171                     positions = this.getHorizontalThreeBoxColPositions(maxX, minY, box);
40172                     break;
40173                 case 4 :
40174                     positions = this.getHorizontalFourBoxColPositions(maxX, minY, box);
40175                     break;
40176                 default :
40177                     break;
40178             }
40179             
40180             Roo.each(box, function(b,kk){
40181                 
40182                 b.el.setXY([positions[kk].x, positions[kk].y], isInstant ? false : true);
40183                 
40184                 maxX = Math.min(maxX, positions[kk].x - this.padWidth);
40185                 
40186             }, this);
40187             
40188         }, this);
40189         
40190     },
40191     
40192     _processHorizontalEndItem : function(eItems, maxX, minX, minY, isInstant)
40193     {
40194         Roo.each(eItems, function(b,k){
40195             
40196             b.size = (k == 0) ? 'sm' : 'xs';
40197             b.x = (k == 0) ? 2 : 1;
40198             b.y = (k == 0) ? 2 : 1;
40199             
40200             b.el.position('absolute');
40201             
40202             var width = Math.floor(this.unitWidth * b.x + (this.gutter * (b.x - 1)) + b.el.getPadding('lr'));
40203                 
40204             b.el.setWidth(width);
40205             
40206             var height = Math.floor(this.unitWidth * b.y + (this.gutter * (b.y - 1)) + b.el.getPadding('tb'));
40207             
40208             b.el.setHeight(height);
40209             
40210         }, this);
40211
40212         var positions = [];
40213         
40214         positions.push({
40215             x : maxX - this.unitWidth * 2 - this.gutter,
40216             y : minY
40217         });
40218         
40219         positions.push({
40220             x : maxX - this.unitWidth,
40221             y : minY + (this.unitWidth + this.gutter) * 2
40222         });
40223         
40224         positions.push({
40225             x : maxX - this.unitWidth * 3 - this.gutter * 2,
40226             y : minY
40227         });
40228         
40229         Roo.each(eItems, function(b,k){
40230             
40231             b.el.setXY([positions[k].x, positions[k].y], isInstant ? false : true);
40232
40233         }, this);
40234         
40235     },
40236     
40237     getVerticalOneBoxColPositions : function(x, y, box)
40238     {
40239         var pos = [];
40240         
40241         var rand = Math.floor(Math.random() * ((4 - box[0].x)));
40242         
40243         if(box[0].size == 'md-left'){
40244             rand = 0;
40245         }
40246         
40247         if(box[0].size == 'md-right'){
40248             rand = 1;
40249         }
40250         
40251         pos.push({
40252             x : x + (this.unitWidth + this.gutter) * rand,
40253             y : y
40254         });
40255         
40256         return pos;
40257     },
40258     
40259     getVerticalTwoBoxColPositions : function(x, y, box)
40260     {
40261         var pos = [];
40262         
40263         if(box[0].size == 'xs'){
40264             
40265             pos.push({
40266                 x : x,
40267                 y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[1].y))
40268             });
40269
40270             pos.push({
40271                 x : x + (this.unitWidth + this.gutter) * (3 - box[1].x),
40272                 y : y
40273             });
40274             
40275             return pos;
40276             
40277         }
40278         
40279         pos.push({
40280             x : x,
40281             y : y
40282         });
40283
40284         pos.push({
40285             x : x + (this.unitWidth + this.gutter) * 2,
40286             y : y + ((this.unitHeight + this.gutter) * Math.floor(Math.random() * box[0].y))
40287         });
40288         
40289         return pos;
40290         
40291     },
40292     
40293     getVerticalThreeBoxColPositions : function(x, y, box)
40294     {
40295         var pos = [];
40296         
40297         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
40298             
40299             pos.push({
40300                 x : x,
40301                 y : y
40302             });
40303
40304             pos.push({
40305                 x : x + (this.unitWidth + this.gutter) * 1,
40306                 y : y
40307             });
40308             
40309             pos.push({
40310                 x : x + (this.unitWidth + this.gutter) * 2,
40311                 y : y
40312             });
40313             
40314             return pos;
40315             
40316         }
40317         
40318         if(box[0].size == 'xs' && box[1].size == 'xs'){
40319             
40320             pos.push({
40321                 x : x,
40322                 y : y
40323             });
40324
40325             pos.push({
40326                 x : x,
40327                 y : y + ((this.unitHeight + this.gutter) * (box[2].y - 1))
40328             });
40329             
40330             pos.push({
40331                 x : x + (this.unitWidth + this.gutter) * 1,
40332                 y : y
40333             });
40334             
40335             return pos;
40336             
40337         }
40338         
40339         pos.push({
40340             x : x,
40341             y : y
40342         });
40343
40344         pos.push({
40345             x : x + (this.unitWidth + this.gutter) * 2,
40346             y : y
40347         });
40348
40349         pos.push({
40350             x : x + (this.unitWidth + this.gutter) * 2,
40351             y : y + (this.unitHeight + this.gutter) * (box[0].y - 1)
40352         });
40353             
40354         return pos;
40355         
40356     },
40357     
40358     getVerticalFourBoxColPositions : function(x, y, box)
40359     {
40360         var pos = [];
40361         
40362         if(box[0].size == 'xs'){
40363             
40364             pos.push({
40365                 x : x,
40366                 y : y
40367             });
40368
40369             pos.push({
40370                 x : x,
40371                 y : y + (this.unitHeight + this.gutter) * 1
40372             });
40373             
40374             pos.push({
40375                 x : x,
40376                 y : y + (this.unitHeight + this.gutter) * 2
40377             });
40378             
40379             pos.push({
40380                 x : x + (this.unitWidth + this.gutter) * 1,
40381                 y : y
40382             });
40383             
40384             return pos;
40385             
40386         }
40387         
40388         pos.push({
40389             x : x,
40390             y : y
40391         });
40392
40393         pos.push({
40394             x : x + (this.unitWidth + this.gutter) * 2,
40395             y : y
40396         });
40397
40398         pos.push({
40399             x : x + (this.unitHeightunitWidth + this.gutter) * 2,
40400             y : y + (this.unitHeight + this.gutter) * 1
40401         });
40402
40403         pos.push({
40404             x : x + (this.unitWidth + this.gutter) * 2,
40405             y : y + (this.unitWidth + this.gutter) * 2
40406         });
40407
40408         return pos;
40409         
40410     },
40411     
40412     getHorizontalOneBoxColPositions : function(maxX, minY, box)
40413     {
40414         var pos = [];
40415         
40416         if(box[0].size == 'md-left'){
40417             pos.push({
40418                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
40419                 y : minY
40420             });
40421             
40422             return pos;
40423         }
40424         
40425         if(box[0].size == 'md-right'){
40426             pos.push({
40427                 x : maxX - this.unitWidth * (box[0].x - 1) - this.gutter * (box[0].x - 2),
40428                 y : minY + (this.unitWidth + this.gutter) * 1
40429             });
40430             
40431             return pos;
40432         }
40433         
40434         var rand = Math.floor(Math.random() * (4 - box[0].y));
40435         
40436         pos.push({
40437             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40438             y : minY + (this.unitWidth + this.gutter) * rand
40439         });
40440         
40441         return pos;
40442         
40443     },
40444     
40445     getHorizontalTwoBoxColPositions : function(maxX, minY, box)
40446     {
40447         var pos = [];
40448         
40449         if(box[0].size == 'xs'){
40450             
40451             pos.push({
40452                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40453                 y : minY
40454             });
40455
40456             pos.push({
40457                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40458                 y : minY + (this.unitWidth + this.gutter) * (3 - box[1].y)
40459             });
40460             
40461             return pos;
40462             
40463         }
40464         
40465         pos.push({
40466             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40467             y : minY
40468         });
40469
40470         pos.push({
40471             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40472             y : minY + (this.unitWidth + this.gutter) * 2
40473         });
40474         
40475         return pos;
40476         
40477     },
40478     
40479     getHorizontalThreeBoxColPositions : function(maxX, minY, box)
40480     {
40481         var pos = [];
40482         
40483         if(box[0].size == 'xs' && box[1].size == 'xs' && box[2].size == 'xs'){
40484             
40485             pos.push({
40486                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40487                 y : minY
40488             });
40489
40490             pos.push({
40491                 x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40492                 y : minY + (this.unitWidth + this.gutter) * 1
40493             });
40494             
40495             pos.push({
40496                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
40497                 y : minY + (this.unitWidth + this.gutter) * 2
40498             });
40499             
40500             return pos;
40501             
40502         }
40503         
40504         if(box[0].size == 'xs' && box[1].size == 'xs'){
40505             
40506             pos.push({
40507                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40508                 y : minY
40509             });
40510
40511             pos.push({
40512                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40513                 y : minY
40514             });
40515             
40516             pos.push({
40517                 x : maxX - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
40518                 y : minY + (this.unitWidth + this.gutter) * 1
40519             });
40520             
40521             return pos;
40522             
40523         }
40524         
40525         pos.push({
40526             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40527             y : minY
40528         });
40529
40530         pos.push({
40531             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40532             y : minY + (this.unitWidth + this.gutter) * 2
40533         });
40534
40535         pos.push({
40536             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
40537             y : minY + (this.unitWidth + this.gutter) * 2
40538         });
40539             
40540         return pos;
40541         
40542     },
40543     
40544     getHorizontalFourBoxColPositions : function(maxX, minY, box)
40545     {
40546         var pos = [];
40547         
40548         if(box[0].size == 'xs'){
40549             
40550             pos.push({
40551                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40552                 y : minY
40553             });
40554
40555             pos.push({
40556                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40557                 y : minY
40558             });
40559             
40560             pos.push({
40561                 x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1) - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
40562                 y : minY
40563             });
40564             
40565             pos.push({
40566                 x : maxX - this.unitWidth * box[3].x - this.gutter * (box[3].x - 1),
40567                 y : minY + (this.unitWidth + this.gutter) * 1
40568             });
40569             
40570             return pos;
40571             
40572         }
40573         
40574         pos.push({
40575             x : maxX - this.unitWidth * box[0].x - this.gutter * (box[0].x - 1),
40576             y : minY
40577         });
40578         
40579         pos.push({
40580             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1),
40581             y : minY + (this.unitWidth + this.gutter) * 2
40582         });
40583         
40584         pos.push({
40585             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1),
40586             y : minY + (this.unitWidth + this.gutter) * 2
40587         });
40588         
40589         pos.push({
40590             x : maxX - this.unitWidth * box[1].x - this.gutter * (box[1].x - 1) - this.unitWidth * box[2].x - this.gutter * (box[2].x - 1) - this.unitWidth * box[3].x - this.gutter * (box[3].x - 1),
40591             y : minY + (this.unitWidth + this.gutter) * 2
40592         });
40593
40594         return pos;
40595         
40596     },
40597     
40598     /**
40599     * remove a Masonry Brick
40600     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to remove
40601     */
40602     removeBrick : function(brick_id)
40603     {
40604         if (!brick_id) {
40605             return;
40606         }
40607         
40608         for (var i = 0; i<this.bricks.length; i++) {
40609             if (this.bricks[i].id == brick_id) {
40610                 this.bricks.splice(i,1);
40611                 this.el.dom.removeChild(Roo.get(brick_id).dom);
40612                 this.initial();
40613             }
40614         }
40615     },
40616     
40617     /**
40618     * adds a Masonry Brick
40619     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
40620     */
40621     addBrick : function(cfg)
40622     {
40623         var cn = new Roo.bootstrap.MasonryBrick(cfg);
40624         //this.register(cn);
40625         cn.parentId = this.id;
40626         cn.render(this.el);
40627         return cn;
40628     },
40629     
40630     /**
40631     * register a Masonry Brick
40632     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
40633     */
40634     
40635     register : function(brick)
40636     {
40637         this.bricks.push(brick);
40638         brick.masonryId = this.id;
40639     },
40640     
40641     /**
40642     * clear all the Masonry Brick
40643     */
40644     clearAll : function()
40645     {
40646         this.bricks = [];
40647         //this.getChildContainer().dom.innerHTML = "";
40648         this.el.dom.innerHTML = '';
40649     },
40650     
40651     getSelected : function()
40652     {
40653         if (!this.selectedBrick) {
40654             return false;
40655         }
40656         
40657         return this.selectedBrick;
40658     }
40659 });
40660
40661 Roo.apply(Roo.bootstrap.LayoutMasonry, {
40662     
40663     groups: {},
40664      /**
40665     * register a Masonry Layout
40666     * @param {Roo.bootstrap.LayoutMasonry} the masonry layout to add
40667     */
40668     
40669     register : function(layout)
40670     {
40671         this.groups[layout.id] = layout;
40672     },
40673     /**
40674     * fetch a  Masonry Layout based on the masonry layout ID
40675     * @param {string} the masonry layout to add
40676     * @returns {Roo.bootstrap.LayoutMasonry} the masonry layout
40677     */
40678     
40679     get: function(layout_id) {
40680         if (typeof(this.groups[layout_id]) == 'undefined') {
40681             return false;
40682         }
40683         return this.groups[layout_id] ;
40684     }
40685     
40686     
40687     
40688 });
40689
40690  
40691
40692  /**
40693  *
40694  * This is based on 
40695  * http://masonry.desandro.com
40696  *
40697  * The idea is to render all the bricks based on vertical width...
40698  *
40699  * The original code extends 'outlayer' - we might need to use that....
40700  * 
40701  */
40702
40703
40704 /**
40705  * @class Roo.bootstrap.LayoutMasonryAuto
40706  * @extends Roo.bootstrap.Component
40707  * Bootstrap Layout Masonry class
40708  * 
40709  * @constructor
40710  * Create a new Element
40711  * @param {Object} config The config object
40712  */
40713
40714 Roo.bootstrap.LayoutMasonryAuto = function(config){
40715     Roo.bootstrap.LayoutMasonryAuto.superclass.constructor.call(this, config);
40716 };
40717
40718 Roo.extend(Roo.bootstrap.LayoutMasonryAuto, Roo.bootstrap.Component,  {
40719     
40720       /**
40721      * @cfg {Boolean} isFitWidth  - resize the width..
40722      */   
40723     isFitWidth : false,  // options..
40724     /**
40725      * @cfg {Boolean} isOriginLeft = left align?
40726      */   
40727     isOriginLeft : true,
40728     /**
40729      * @cfg {Boolean} isOriginTop = top align?
40730      */   
40731     isOriginTop : false,
40732     /**
40733      * @cfg {Boolean} isLayoutInstant = no animation?
40734      */   
40735     isLayoutInstant : false, // needed?
40736     /**
40737      * @cfg {Boolean} isResizingContainer = not sure if this is used..
40738      */   
40739     isResizingContainer : true,
40740     /**
40741      * @cfg {Number} columnWidth  width of the columns 
40742      */   
40743     
40744     columnWidth : 0,
40745     
40746     /**
40747      * @cfg {Number} maxCols maximum number of columns
40748      */   
40749     
40750     maxCols: 0,
40751     /**
40752      * @cfg {Number} padHeight padding below box..
40753      */   
40754     
40755     padHeight : 10, 
40756     
40757     /**
40758      * @cfg {Boolean} isAutoInitial defalut true
40759      */   
40760     
40761     isAutoInitial : true, 
40762     
40763     // private?
40764     gutter : 0,
40765     
40766     containerWidth: 0,
40767     initialColumnWidth : 0,
40768     currentSize : null,
40769     
40770     colYs : null, // array.
40771     maxY : 0,
40772     padWidth: 10,
40773     
40774     
40775     tag: 'div',
40776     cls: '',
40777     bricks: null, //CompositeElement
40778     cols : 0, // array?
40779     // element : null, // wrapped now this.el
40780     _isLayoutInited : null, 
40781     
40782     
40783     getAutoCreate : function(){
40784         
40785         var cfg = {
40786             tag: this.tag,
40787             cls: 'blog-masonary-wrapper ' + this.cls,
40788             cn : {
40789                 cls : 'mas-boxes masonary'
40790             }
40791         };
40792         
40793         return cfg;
40794     },
40795     
40796     getChildContainer: function( )
40797     {
40798         if (this.boxesEl) {
40799             return this.boxesEl;
40800         }
40801         
40802         this.boxesEl = this.el.select('.mas-boxes').first();
40803         
40804         return this.boxesEl;
40805     },
40806     
40807     
40808     initEvents : function()
40809     {
40810         var _this = this;
40811         
40812         if(this.isAutoInitial){
40813             Roo.log('hook children rendered');
40814             this.on('childrenrendered', function() {
40815                 Roo.log('children rendered');
40816                 _this.initial();
40817             } ,this);
40818         }
40819         
40820     },
40821     
40822     initial : function()
40823     {
40824         this.reloadItems();
40825
40826         this.currentSize = this.el.getBox(true);
40827
40828         /// was window resize... - let's see if this works..
40829         Roo.EventManager.onWindowResize(this.resize, this); 
40830
40831         if(!this.isAutoInitial){
40832             this.layout();
40833             return;
40834         }
40835         
40836         this.layout.defer(500,this);
40837     },
40838     
40839     reloadItems: function()
40840     {
40841         this.bricks = this.el.select('.masonry-brick', true);
40842         
40843         this.bricks.each(function(b) {
40844             //Roo.log(b.getSize());
40845             if (!b.attr('originalwidth')) {
40846                 b.attr('originalwidth',  b.getSize().width);
40847             }
40848             
40849         });
40850         
40851         Roo.log(this.bricks.elements.length);
40852     },
40853     
40854     resize : function()
40855     {
40856         Roo.log('resize');
40857         var cs = this.el.getBox(true);
40858         
40859         if (this.currentSize.width == cs.width && this.currentSize.x == cs.x ) {
40860             Roo.log("no change in with or X");
40861             return;
40862         }
40863         this.currentSize = cs;
40864         this.layout();
40865     },
40866     
40867     layout : function()
40868     {
40869          Roo.log('layout');
40870         this._resetLayout();
40871         //this._manageStamps();
40872       
40873         // don't animate first layout
40874         var isInstant = this.isLayoutInstant !== undefined ? this.isLayoutInstant : !this._isLayoutInited;
40875         this.layoutItems( isInstant );
40876       
40877         // flag for initalized
40878         this._isLayoutInited = true;
40879     },
40880     
40881     layoutItems : function( isInstant )
40882     {
40883         //var items = this._getItemsForLayout( this.items );
40884         // original code supports filtering layout items.. we just ignore it..
40885         
40886         this._layoutItems( this.bricks , isInstant );
40887       
40888         this._postLayout();
40889     },
40890     _layoutItems : function ( items , isInstant)
40891     {
40892        //this.fireEvent( 'layout', this, items );
40893     
40894
40895         if ( !items || !items.elements.length ) {
40896           // no items, emit event with empty array
40897             return;
40898         }
40899
40900         var queue = [];
40901         items.each(function(item) {
40902             Roo.log("layout item");
40903             Roo.log(item);
40904             // get x/y object from method
40905             var position = this._getItemLayoutPosition( item );
40906             // enqueue
40907             position.item = item;
40908             position.isInstant = isInstant; // || item.isLayoutInstant; << not set yet...
40909             queue.push( position );
40910         }, this);
40911       
40912         this._processLayoutQueue( queue );
40913     },
40914     /** Sets position of item in DOM
40915     * @param {Element} item
40916     * @param {Number} x - horizontal position
40917     * @param {Number} y - vertical position
40918     * @param {Boolean} isInstant - disables transitions
40919     */
40920     _processLayoutQueue : function( queue )
40921     {
40922         for ( var i=0, len = queue.length; i < len; i++ ) {
40923             var obj = queue[i];
40924             obj.item.position('absolute');
40925             obj.item.setXY([obj.x,obj.y], obj.isInstant ? false : true);
40926         }
40927     },
40928       
40929     
40930     /**
40931     * Any logic you want to do after each layout,
40932     * i.e. size the container
40933     */
40934     _postLayout : function()
40935     {
40936         this.resizeContainer();
40937     },
40938     
40939     resizeContainer : function()
40940     {
40941         if ( !this.isResizingContainer ) {
40942             return;
40943         }
40944         var size = this._getContainerSize();
40945         if ( size ) {
40946             this.el.setSize(size.width,size.height);
40947             this.boxesEl.setSize(size.width,size.height);
40948         }
40949     },
40950     
40951     
40952     
40953     _resetLayout : function()
40954     {
40955         //this.getSize();  // -- does not really do anything.. it probably applies left/right etc. to obuject but not used
40956         this.colWidth = this.el.getWidth();
40957         //this.gutter = this.el.getWidth(); 
40958         
40959         this.measureColumns();
40960
40961         // reset column Y
40962         var i = this.cols;
40963         this.colYs = [];
40964         while (i--) {
40965             this.colYs.push( 0 );
40966         }
40967     
40968         this.maxY = 0;
40969     },
40970
40971     measureColumns : function()
40972     {
40973         this.getContainerWidth();
40974       // if columnWidth is 0, default to outerWidth of first item
40975         if ( !this.columnWidth ) {
40976             var firstItem = this.bricks.first();
40977             Roo.log(firstItem);
40978             this.columnWidth  = this.containerWidth;
40979             if (firstItem && firstItem.attr('originalwidth') ) {
40980                 this.columnWidth = 1* (firstItem.attr('originalwidth') || firstItem.getWidth());
40981             }
40982             // columnWidth fall back to item of first element
40983             Roo.log("set column width?");
40984                         this.initialColumnWidth = this.columnWidth  ;
40985
40986             // if first elem has no width, default to size of container
40987             
40988         }
40989         
40990         
40991         if (this.initialColumnWidth) {
40992             this.columnWidth = this.initialColumnWidth;
40993         }
40994         
40995         
40996             
40997         // column width is fixed at the top - however if container width get's smaller we should
40998         // reduce it...
40999         
41000         // this bit calcs how man columns..
41001             
41002         var columnWidth = this.columnWidth += this.gutter;
41003       
41004         // calculate columns
41005         var containerWidth = this.containerWidth + this.gutter;
41006         
41007         var cols = (containerWidth - this.padWidth) / (columnWidth - this.padWidth);
41008         // fix rounding errors, typically with gutters
41009         var excess = columnWidth - containerWidth % columnWidth;
41010         
41011         
41012         // if overshoot is less than a pixel, round up, otherwise floor it
41013         var mathMethod = excess && excess < 1 ? 'round' : 'floor';
41014         cols = Math[ mathMethod ]( cols );
41015         this.cols = Math.max( cols, 1 );
41016         this.cols = this.maxCols > 0 ? Math.min( this.cols, this.maxCols ) : this.cols;
41017         
41018          // padding positioning..
41019         var totalColWidth = this.cols * this.columnWidth;
41020         var padavail = this.containerWidth - totalColWidth;
41021         // so for 2 columns - we need 3 'pads'
41022         
41023         var padNeeded = (1+this.cols) * this.padWidth;
41024         
41025         var padExtra = Math.floor((padavail - padNeeded) / this.cols);
41026         
41027         this.columnWidth += padExtra
41028         //this.padWidth = Math.floor(padavail /  ( this.cols));
41029         
41030         // adjust colum width so that padding is fixed??
41031         
41032         // we have 3 columns ... total = width * 3
41033         // we have X left over... that should be used by 
41034         
41035         //if (this.expandC) {
41036             
41037         //}
41038         
41039         
41040         
41041     },
41042     
41043     getContainerWidth : function()
41044     {
41045        /* // container is parent if fit width
41046         var container = this.isFitWidth ? this.element.parentNode : this.element;
41047         // check that this.size and size are there
41048         // IE8 triggers resize on body size change, so they might not be
41049         
41050         var size = getSize( container );  //FIXME
41051         this.containerWidth = size && size.innerWidth; //FIXME
41052         */
41053          
41054         this.containerWidth = this.el.getBox(true).width;  //maybe use getComputedWidth
41055         
41056     },
41057     
41058     _getItemLayoutPosition : function( item )  // what is item?
41059     {
41060         // we resize the item to our columnWidth..
41061       
41062         item.setWidth(this.columnWidth);
41063         item.autoBoxAdjust  = false;
41064         
41065         var sz = item.getSize();
41066  
41067         // how many columns does this brick span
41068         var remainder = this.containerWidth % this.columnWidth;
41069         
41070         var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
41071         // round if off by 1 pixel, otherwise use ceil
41072         var colSpan = Math[ mathMethod ]( sz.width  / this.columnWidth );
41073         colSpan = Math.min( colSpan, this.cols );
41074         
41075         // normally this should be '1' as we dont' currently allow multi width columns..
41076         
41077         var colGroup = this._getColGroup( colSpan );
41078         // get the minimum Y value from the columns
41079         var minimumY = Math.min.apply( Math, colGroup );
41080         Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
41081         
41082         var shortColIndex = colGroup.indexOf(  minimumY ); // broken on ie8..?? probably...
41083          
41084         // position the brick
41085         var position = {
41086             x: this.currentSize.x + (this.padWidth /2) + ((this.columnWidth + this.padWidth )* shortColIndex),
41087             y: this.currentSize.y + minimumY + this.padHeight
41088         };
41089         
41090         Roo.log(position);
41091         // apply setHeight to necessary columns
41092         var setHeight = minimumY + sz.height + this.padHeight;
41093         //Roo.log([ 'setHeight',  minimumY, sz.height, setHeight ]);
41094         
41095         var setSpan = this.cols + 1 - colGroup.length;
41096         for ( var i = 0; i < setSpan; i++ ) {
41097           this.colYs[ shortColIndex + i ] = setHeight ;
41098         }
41099       
41100         return position;
41101     },
41102     
41103     /**
41104      * @param {Number} colSpan - number of columns the element spans
41105      * @returns {Array} colGroup
41106      */
41107     _getColGroup : function( colSpan )
41108     {
41109         if ( colSpan < 2 ) {
41110           // if brick spans only one column, use all the column Ys
41111           return this.colYs;
41112         }
41113       
41114         var colGroup = [];
41115         // how many different places could this brick fit horizontally
41116         var groupCount = this.cols + 1 - colSpan;
41117         // for each group potential horizontal position
41118         for ( var i = 0; i < groupCount; i++ ) {
41119           // make an array of colY values for that one group
41120           var groupColYs = this.colYs.slice( i, i + colSpan );
41121           // and get the max value of the array
41122           colGroup[i] = Math.max.apply( Math, groupColYs );
41123         }
41124         return colGroup;
41125     },
41126     /*
41127     _manageStamp : function( stamp )
41128     {
41129         var stampSize =  stamp.getSize();
41130         var offset = stamp.getBox();
41131         // get the columns that this stamp affects
41132         var firstX = this.isOriginLeft ? offset.x : offset.right;
41133         var lastX = firstX + stampSize.width;
41134         var firstCol = Math.floor( firstX / this.columnWidth );
41135         firstCol = Math.max( 0, firstCol );
41136         
41137         var lastCol = Math.floor( lastX / this.columnWidth );
41138         // lastCol should not go over if multiple of columnWidth #425
41139         lastCol -= lastX % this.columnWidth ? 0 : 1;
41140         lastCol = Math.min( this.cols - 1, lastCol );
41141         
41142         // set colYs to bottom of the stamp
41143         var stampMaxY = ( this.isOriginTop ? offset.y : offset.bottom ) +
41144             stampSize.height;
41145             
41146         for ( var i = firstCol; i <= lastCol; i++ ) {
41147           this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
41148         }
41149     },
41150     */
41151     
41152     _getContainerSize : function()
41153     {
41154         this.maxY = Math.max.apply( Math, this.colYs );
41155         var size = {
41156             height: this.maxY
41157         };
41158       
41159         if ( this.isFitWidth ) {
41160             size.width = this._getContainerFitWidth();
41161         }
41162       
41163         return size;
41164     },
41165     
41166     _getContainerFitWidth : function()
41167     {
41168         var unusedCols = 0;
41169         // count unused columns
41170         var i = this.cols;
41171         while ( --i ) {
41172           if ( this.colYs[i] !== 0 ) {
41173             break;
41174           }
41175           unusedCols++;
41176         }
41177         // fit container to columns that have been used
41178         return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
41179     },
41180     
41181     needsResizeLayout : function()
41182     {
41183         var previousWidth = this.containerWidth;
41184         this.getContainerWidth();
41185         return previousWidth !== this.containerWidth;
41186     }
41187  
41188 });
41189
41190  
41191
41192  /*
41193  * - LGPL
41194  *
41195  * element
41196  * 
41197  */
41198
41199 /**
41200  * @class Roo.bootstrap.MasonryBrick
41201  * @extends Roo.bootstrap.Component
41202  * Bootstrap MasonryBrick class
41203  * 
41204  * @constructor
41205  * Create a new MasonryBrick
41206  * @param {Object} config The config object
41207  */
41208
41209 Roo.bootstrap.MasonryBrick = function(config){
41210     
41211     Roo.bootstrap.MasonryBrick.superclass.constructor.call(this, config);
41212     
41213     Roo.bootstrap.MasonryBrick.register(this);
41214     
41215     this.addEvents({
41216         // raw events
41217         /**
41218          * @event click
41219          * When a MasonryBrick is clcik
41220          * @param {Roo.bootstrap.MasonryBrick} this
41221          * @param {Roo.EventObject} e
41222          */
41223         "click" : true
41224     });
41225 };
41226
41227 Roo.extend(Roo.bootstrap.MasonryBrick, Roo.bootstrap.Component,  {
41228     
41229     /**
41230      * @cfg {String} title
41231      */   
41232     title : '',
41233     /**
41234      * @cfg {String} html
41235      */   
41236     html : '',
41237     /**
41238      * @cfg {String} bgimage
41239      */   
41240     bgimage : '',
41241     /**
41242      * @cfg {String} videourl
41243      */   
41244     videourl : '',
41245     /**
41246      * @cfg {String} cls
41247      */   
41248     cls : '',
41249     /**
41250      * @cfg {String} href
41251      */   
41252     href : '',
41253     /**
41254      * @cfg {String} size (xs|sm|md|md-left|md-right|tall|wide)
41255      */   
41256     size : 'xs',
41257     
41258     /**
41259      * @cfg {String} placetitle (center|bottom)
41260      */   
41261     placetitle : '',
41262     
41263     /**
41264      * @cfg {Boolean} isFitContainer defalut true
41265      */   
41266     isFitContainer : true, 
41267     
41268     /**
41269      * @cfg {Boolean} preventDefault defalut false
41270      */   
41271     preventDefault : false, 
41272     
41273     /**
41274      * @cfg {Boolean} inverse defalut false
41275      */   
41276     maskInverse : false, 
41277     
41278     getAutoCreate : function()
41279     {
41280         if(!this.isFitContainer){
41281             return this.getSplitAutoCreate();
41282         }
41283         
41284         var cls = 'masonry-brick masonry-brick-full';
41285         
41286         if(this.href.length){
41287             cls += ' masonry-brick-link';
41288         }
41289         
41290         if(this.bgimage.length){
41291             cls += ' masonry-brick-image';
41292         }
41293         
41294         if(this.maskInverse){
41295             cls += ' mask-inverse';
41296         }
41297         
41298         if(!this.html.length && !this.maskInverse && !this.videourl.length){
41299             cls += ' enable-mask';
41300         }
41301         
41302         if(this.size){
41303             cls += ' masonry-' + this.size + '-brick';
41304         }
41305         
41306         if(this.placetitle.length){
41307             
41308             switch (this.placetitle) {
41309                 case 'center' :
41310                     cls += ' masonry-center-title';
41311                     break;
41312                 case 'bottom' :
41313                     cls += ' masonry-bottom-title';
41314                     break;
41315                 default:
41316                     break;
41317             }
41318             
41319         } else {
41320             if(!this.html.length && !this.bgimage.length){
41321                 cls += ' masonry-center-title';
41322             }
41323
41324             if(!this.html.length && this.bgimage.length){
41325                 cls += ' masonry-bottom-title';
41326             }
41327         }
41328         
41329         if(this.cls){
41330             cls += ' ' + this.cls;
41331         }
41332         
41333         var cfg = {
41334             tag: (this.href.length) ? 'a' : 'div',
41335             cls: cls,
41336             cn: [
41337                 {
41338                     tag: 'div',
41339                     cls: 'masonry-brick-mask'
41340                 },
41341                 {
41342                     tag: 'div',
41343                     cls: 'masonry-brick-paragraph',
41344                     cn: []
41345                 }
41346             ]
41347         };
41348         
41349         if(this.href.length){
41350             cfg.href = this.href;
41351         }
41352         
41353         var cn = cfg.cn[1].cn;
41354         
41355         if(this.title.length){
41356             cn.push({
41357                 tag: 'h4',
41358                 cls: 'masonry-brick-title',
41359                 html: this.title
41360             });
41361         }
41362         
41363         if(this.html.length){
41364             cn.push({
41365                 tag: 'p',
41366                 cls: 'masonry-brick-text',
41367                 html: this.html
41368             });
41369         }
41370         
41371         if (!this.title.length && !this.html.length) {
41372             cfg.cn[1].cls += ' hide';
41373         }
41374         
41375         if(this.bgimage.length){
41376             cfg.cn.push({
41377                 tag: 'img',
41378                 cls: 'masonry-brick-image-view',
41379                 src: this.bgimage
41380             });
41381         }
41382         
41383         if(this.videourl.length){
41384             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
41385             // youtube support only?
41386             cfg.cn.push({
41387                 tag: 'iframe',
41388                 cls: 'masonry-brick-image-view',
41389                 src: vurl,
41390                 frameborder : 0,
41391                 allowfullscreen : true
41392             });
41393         }
41394         
41395         return cfg;
41396         
41397     },
41398     
41399     getSplitAutoCreate : function()
41400     {
41401         var cls = 'masonry-brick masonry-brick-split';
41402         
41403         if(this.href.length){
41404             cls += ' masonry-brick-link';
41405         }
41406         
41407         if(this.bgimage.length){
41408             cls += ' masonry-brick-image';
41409         }
41410         
41411         if(this.size){
41412             cls += ' masonry-' + this.size + '-brick';
41413         }
41414         
41415         switch (this.placetitle) {
41416             case 'center' :
41417                 cls += ' masonry-center-title';
41418                 break;
41419             case 'bottom' :
41420                 cls += ' masonry-bottom-title';
41421                 break;
41422             default:
41423                 if(!this.bgimage.length){
41424                     cls += ' masonry-center-title';
41425                 }
41426
41427                 if(this.bgimage.length){
41428                     cls += ' masonry-bottom-title';
41429                 }
41430                 break;
41431         }
41432         
41433         if(this.cls){
41434             cls += ' ' + this.cls;
41435         }
41436         
41437         var cfg = {
41438             tag: (this.href.length) ? 'a' : 'div',
41439             cls: cls,
41440             cn: [
41441                 {
41442                     tag: 'div',
41443                     cls: 'masonry-brick-split-head',
41444                     cn: [
41445                         {
41446                             tag: 'div',
41447                             cls: 'masonry-brick-paragraph',
41448                             cn: []
41449                         }
41450                     ]
41451                 },
41452                 {
41453                     tag: 'div',
41454                     cls: 'masonry-brick-split-body',
41455                     cn: []
41456                 }
41457             ]
41458         };
41459         
41460         if(this.href.length){
41461             cfg.href = this.href;
41462         }
41463         
41464         if(this.title.length){
41465             cfg.cn[0].cn[0].cn.push({
41466                 tag: 'h4',
41467                 cls: 'masonry-brick-title',
41468                 html: this.title
41469             });
41470         }
41471         
41472         if(this.html.length){
41473             cfg.cn[1].cn.push({
41474                 tag: 'p',
41475                 cls: 'masonry-brick-text',
41476                 html: this.html
41477             });
41478         }
41479
41480         if(this.bgimage.length){
41481             cfg.cn[0].cn.push({
41482                 tag: 'img',
41483                 cls: 'masonry-brick-image-view',
41484                 src: this.bgimage
41485             });
41486         }
41487         
41488         if(this.videourl.length){
41489             var vurl = this.videourl.replace(/https:\/\/youtu\.be/, 'https://www.youtube.com/embed/');
41490             // youtube support only?
41491             cfg.cn[0].cn.cn.push({
41492                 tag: 'iframe',
41493                 cls: 'masonry-brick-image-view',
41494                 src: vurl,
41495                 frameborder : 0,
41496                 allowfullscreen : true
41497             });
41498         }
41499         
41500         return cfg;
41501     },
41502     
41503     initEvents: function() 
41504     {
41505         switch (this.size) {
41506             case 'xs' :
41507                 this.x = 1;
41508                 this.y = 1;
41509                 break;
41510             case 'sm' :
41511                 this.x = 2;
41512                 this.y = 2;
41513                 break;
41514             case 'md' :
41515             case 'md-left' :
41516             case 'md-right' :
41517                 this.x = 3;
41518                 this.y = 3;
41519                 break;
41520             case 'tall' :
41521                 this.x = 2;
41522                 this.y = 3;
41523                 break;
41524             case 'wide' :
41525                 this.x = 3;
41526                 this.y = 2;
41527                 break;
41528             case 'wide-thin' :
41529                 this.x = 3;
41530                 this.y = 1;
41531                 break;
41532                         
41533             default :
41534                 break;
41535         }
41536         
41537         if(Roo.isTouch){
41538             this.el.on('touchstart', this.onTouchStart, this);
41539             this.el.on('touchmove', this.onTouchMove, this);
41540             this.el.on('touchend', this.onTouchEnd, this);
41541             this.el.on('contextmenu', this.onContextMenu, this);
41542         } else {
41543             this.el.on('mouseenter'  ,this.enter, this);
41544             this.el.on('mouseleave', this.leave, this);
41545             this.el.on('click', this.onClick, this);
41546         }
41547         
41548         if (typeof(this.parent().bricks) == 'object' && this.parent().bricks != null) {
41549             this.parent().bricks.push(this);   
41550         }
41551         
41552     },
41553     
41554     onClick: function(e, el)
41555     {
41556         var time = this.endTimer - this.startTimer;
41557         // Roo.log(e.preventDefault());
41558         if(Roo.isTouch){
41559             if(time > 1000){
41560                 e.preventDefault();
41561                 return;
41562             }
41563         }
41564         
41565         if(!this.preventDefault){
41566             return;
41567         }
41568         
41569         e.preventDefault();
41570         
41571         if (this.activeClass != '') {
41572             this.selectBrick();
41573         }
41574         
41575         this.fireEvent('click', this, e);
41576     },
41577     
41578     enter: function(e, el)
41579     {
41580         e.preventDefault();
41581         
41582         if(!this.isFitContainer || this.maskInverse || this.videourl.length){
41583             return;
41584         }
41585         
41586         if(this.bgimage.length && this.html.length){
41587             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
41588         }
41589     },
41590     
41591     leave: function(e, el)
41592     {
41593         e.preventDefault();
41594         
41595         if(!this.isFitContainer || this.maskInverse  || this.videourl.length){
41596             return;
41597         }
41598         
41599         if(this.bgimage.length && this.html.length){
41600             this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
41601         }
41602     },
41603     
41604     onTouchStart: function(e, el)
41605     {
41606 //        e.preventDefault();
41607         
41608         this.touchmoved = false;
41609         
41610         if(!this.isFitContainer){
41611             return;
41612         }
41613         
41614         if(!this.bgimage.length || !this.html.length){
41615             return;
41616         }
41617         
41618         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0.9, true);
41619         
41620         this.timer = new Date().getTime();
41621         
41622     },
41623     
41624     onTouchMove: function(e, el)
41625     {
41626         this.touchmoved = true;
41627     },
41628     
41629     onContextMenu : function(e,el)
41630     {
41631         e.preventDefault();
41632         e.stopPropagation();
41633         return false;
41634     },
41635     
41636     onTouchEnd: function(e, el)
41637     {
41638 //        e.preventDefault();
41639         
41640         if((new Date().getTime() - this.timer > 1000) || !this.href.length || this.touchmoved){
41641         
41642             this.leave(e,el);
41643             
41644             return;
41645         }
41646         
41647         if(!this.bgimage.length || !this.html.length){
41648             
41649             if(this.href.length){
41650                 window.location.href = this.href;
41651             }
41652             
41653             return;
41654         }
41655         
41656         if(!this.isFitContainer){
41657             return;
41658         }
41659         
41660         this.el.select('.masonry-brick-paragraph', true).first().setOpacity(0, true);
41661         
41662         window.location.href = this.href;
41663     },
41664     
41665     //selection on single brick only
41666     selectBrick : function() {
41667         
41668         if (!this.parentId) {
41669             return;
41670         }
41671         
41672         var m = Roo.bootstrap.LayoutMasonry.get(this.parentId);
41673         var index = m.selectedBrick.indexOf(this.id);
41674         
41675         if ( index > -1) {
41676             m.selectedBrick.splice(index,1);
41677             this.el.removeClass(this.activeClass);
41678             return;
41679         }
41680         
41681         for(var i = 0; i < m.selectedBrick.length; i++) {
41682             var b = Roo.bootstrap.MasonryBrick.get(m.selectedBrick[i]);
41683             b.el.removeClass(b.activeClass);
41684         }
41685         
41686         m.selectedBrick = [];
41687         
41688         m.selectedBrick.push(this.id);
41689         this.el.addClass(this.activeClass);
41690         return;
41691     },
41692     
41693     isSelected : function(){
41694         return this.el.hasClass(this.activeClass);
41695         
41696     }
41697 });
41698
41699 Roo.apply(Roo.bootstrap.MasonryBrick, {
41700     
41701     //groups: {},
41702     groups : new Roo.util.MixedCollection(false, function(o) { return o.el.id; }),
41703      /**
41704     * register a Masonry Brick
41705     * @param {Roo.bootstrap.MasonryBrick} the masonry brick to add
41706     */
41707     
41708     register : function(brick)
41709     {
41710         //this.groups[brick.id] = brick;
41711         this.groups.add(brick.id, brick);
41712     },
41713     /**
41714     * fetch a  masonry brick based on the masonry brick ID
41715     * @param {string} the masonry brick to add
41716     * @returns {Roo.bootstrap.MasonryBrick} the masonry brick
41717     */
41718     
41719     get: function(brick_id) 
41720     {
41721         // if (typeof(this.groups[brick_id]) == 'undefined') {
41722         //     return false;
41723         // }
41724         // return this.groups[brick_id] ;
41725         
41726         if(this.groups.key(brick_id)) {
41727             return this.groups.key(brick_id);
41728         }
41729         
41730         return false;
41731     }
41732     
41733     
41734     
41735 });
41736
41737  /*
41738  * - LGPL
41739  *
41740  * element
41741  * 
41742  */
41743
41744 /**
41745  * @class Roo.bootstrap.Brick
41746  * @extends Roo.bootstrap.Component
41747  * Bootstrap Brick class
41748  * 
41749  * @constructor
41750  * Create a new Brick
41751  * @param {Object} config The config object
41752  */
41753
41754 Roo.bootstrap.Brick = function(config){
41755     Roo.bootstrap.Brick.superclass.constructor.call(this, config);
41756     
41757     this.addEvents({
41758         // raw events
41759         /**
41760          * @event click
41761          * When a Brick is click
41762          * @param {Roo.bootstrap.Brick} this
41763          * @param {Roo.EventObject} e
41764          */
41765         "click" : true
41766     });
41767 };
41768
41769 Roo.extend(Roo.bootstrap.Brick, Roo.bootstrap.Component,  {
41770     
41771     /**
41772      * @cfg {String} title
41773      */   
41774     title : '',
41775     /**
41776      * @cfg {String} html
41777      */   
41778     html : '',
41779     /**
41780      * @cfg {String} bgimage
41781      */   
41782     bgimage : '',
41783     /**
41784      * @cfg {String} cls
41785      */   
41786     cls : '',
41787     /**
41788      * @cfg {String} href
41789      */   
41790     href : '',
41791     /**
41792      * @cfg {String} video
41793      */   
41794     video : '',
41795     /**
41796      * @cfg {Boolean} square
41797      */   
41798     square : true,
41799     
41800     getAutoCreate : function()
41801     {
41802         var cls = 'roo-brick';
41803         
41804         if(this.href.length){
41805             cls += ' roo-brick-link';
41806         }
41807         
41808         if(this.bgimage.length){
41809             cls += ' roo-brick-image';
41810         }
41811         
41812         if(!this.html.length && !this.bgimage.length){
41813             cls += ' roo-brick-center-title';
41814         }
41815         
41816         if(!this.html.length && this.bgimage.length){
41817             cls += ' roo-brick-bottom-title';
41818         }
41819         
41820         if(this.cls){
41821             cls += ' ' + this.cls;
41822         }
41823         
41824         var cfg = {
41825             tag: (this.href.length) ? 'a' : 'div',
41826             cls: cls,
41827             cn: [
41828                 {
41829                     tag: 'div',
41830                     cls: 'roo-brick-paragraph',
41831                     cn: []
41832                 }
41833             ]
41834         };
41835         
41836         if(this.href.length){
41837             cfg.href = this.href;
41838         }
41839         
41840         var cn = cfg.cn[0].cn;
41841         
41842         if(this.title.length){
41843             cn.push({
41844                 tag: 'h4',
41845                 cls: 'roo-brick-title',
41846                 html: this.title
41847             });
41848         }
41849         
41850         if(this.html.length){
41851             cn.push({
41852                 tag: 'p',
41853                 cls: 'roo-brick-text',
41854                 html: this.html
41855             });
41856         } else {
41857             cn.cls += ' hide';
41858         }
41859         
41860         if(this.bgimage.length){
41861             cfg.cn.push({
41862                 tag: 'img',
41863                 cls: 'roo-brick-image-view',
41864                 src: this.bgimage
41865             });
41866         }
41867         
41868         return cfg;
41869     },
41870     
41871     initEvents: function() 
41872     {
41873         if(this.title.length || this.html.length){
41874             this.el.on('mouseenter'  ,this.enter, this);
41875             this.el.on('mouseleave', this.leave, this);
41876         }
41877         
41878         Roo.EventManager.onWindowResize(this.resize, this); 
41879         
41880         if(this.bgimage.length){
41881             this.imageEl = this.el.select('.roo-brick-image-view', true).first();
41882             this.imageEl.on('load', this.onImageLoad, this);
41883             return;
41884         }
41885         
41886         this.resize();
41887     },
41888     
41889     onImageLoad : function()
41890     {
41891         this.resize();
41892     },
41893     
41894     resize : function()
41895     {
41896         var paragraph = this.el.select('.roo-brick-paragraph', true).first();
41897         
41898         paragraph.setHeight(paragraph.getWidth() + paragraph.getPadding('tb'));
41899         
41900         if(this.bgimage.length){
41901             var image = this.el.select('.roo-brick-image-view', true).first();
41902             
41903             image.setWidth(paragraph.getWidth());
41904             
41905             if(this.square){
41906                 image.setHeight(paragraph.getWidth());
41907             }
41908             
41909             this.el.setHeight(image.getHeight());
41910             paragraph.setHeight(image.getHeight());
41911             
41912         }
41913         
41914     },
41915     
41916     enter: function(e, el)
41917     {
41918         e.preventDefault();
41919         
41920         if(this.bgimage.length){
41921             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0.9, true);
41922             this.el.select('.roo-brick-image-view', true).first().setOpacity(0.1, true);
41923         }
41924     },
41925     
41926     leave: function(e, el)
41927     {
41928         e.preventDefault();
41929         
41930         if(this.bgimage.length){
41931             this.el.select('.roo-brick-paragraph', true).first().setOpacity(0, true);
41932             this.el.select('.roo-brick-image-view', true).first().setOpacity(1, true);
41933         }
41934     }
41935     
41936 });
41937
41938  
41939
41940  /*
41941  * - LGPL
41942  *
41943  * Number field 
41944  */
41945
41946 /**
41947  * @class Roo.bootstrap.form.NumberField
41948  * @extends Roo.bootstrap.form.Input
41949  * Bootstrap NumberField class
41950  * 
41951  * 
41952  * 
41953  * 
41954  * @constructor
41955  * Create a new NumberField
41956  * @param {Object} config The config object
41957  */
41958
41959 Roo.bootstrap.form.NumberField = function(config){
41960     Roo.bootstrap.form.NumberField.superclass.constructor.call(this, config);
41961 };
41962
41963 Roo.extend(Roo.bootstrap.form.NumberField, Roo.bootstrap.form.Input, {
41964     
41965     /**
41966      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
41967      */
41968     allowDecimals : true,
41969     /**
41970      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
41971      */
41972     decimalSeparator : ".",
41973     /**
41974      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
41975      */
41976     decimalPrecision : 2,
41977     /**
41978      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
41979      */
41980     allowNegative : true,
41981     
41982     /**
41983      * @cfg {Boolean} allowZero False to blank out if the user enters '0' (defaults to true)
41984      */
41985     allowZero: true,
41986     /**
41987      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
41988      */
41989     minValue : Number.NEGATIVE_INFINITY,
41990     /**
41991      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
41992      */
41993     maxValue : Number.MAX_VALUE,
41994     /**
41995      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
41996      */
41997     minText : "The minimum value for this field is {0}",
41998     /**
41999      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
42000      */
42001     maxText : "The maximum value for this field is {0}",
42002     /**
42003      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
42004      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
42005      */
42006     nanText : "{0} is not a valid number",
42007     /**
42008      * @cfg {String} thousandsDelimiter Symbol of thousandsDelimiter
42009      */
42010     thousandsDelimiter : false,
42011     /**
42012      * @cfg {String} valueAlign alignment of value
42013      */
42014     valueAlign : "left",
42015
42016     getAutoCreate : function()
42017     {
42018         var hiddenInput = {
42019             tag: 'input',
42020             type: 'hidden',
42021             id: Roo.id(),
42022             cls: 'hidden-number-input'
42023         };
42024         
42025         if (this.name) {
42026             hiddenInput.name = this.name;
42027         }
42028         
42029         this.name = '';
42030         
42031         var cfg = Roo.bootstrap.form.NumberField.superclass.getAutoCreate.call(this);
42032         
42033         this.name = hiddenInput.name;
42034         
42035         if(cfg.cn.length > 0) {
42036             cfg.cn.push(hiddenInput);
42037         }
42038         
42039         return cfg;
42040     },
42041
42042     // private
42043     initEvents : function()
42044     {   
42045         Roo.bootstrap.form.NumberField.superclass.initEvents.call(this);
42046         
42047         var allowed = "0123456789";
42048         
42049         if(this.allowDecimals){
42050             allowed += this.decimalSeparator;
42051         }
42052         
42053         if(this.allowNegative){
42054             allowed += "-";
42055         }
42056         
42057         if(this.thousandsDelimiter) {
42058             allowed += ",";
42059         }
42060         
42061         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
42062         
42063         var keyPress = function(e){
42064             
42065             var k = e.getKey();
42066             
42067             var c = e.getCharCode();
42068             
42069             if(
42070                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
42071                     allowed.indexOf(String.fromCharCode(c)) === -1
42072             ){
42073                 e.stopEvent();
42074                 return;
42075             }
42076             
42077             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
42078                 return;
42079             }
42080             
42081             if(allowed.indexOf(String.fromCharCode(c)) === -1){
42082                 e.stopEvent();
42083             }
42084         };
42085         
42086         this.el.on("keypress", keyPress, this);
42087     },
42088     
42089     validateValue : function(value)
42090     {
42091         
42092         if(!Roo.bootstrap.form.NumberField.superclass.validateValue.call(this, value)){
42093             return false;
42094         }
42095         
42096         var num = this.parseValue(value);
42097         
42098         if(isNaN(num)){
42099             this.markInvalid(String.format(this.nanText, value));
42100             return false;
42101         }
42102         
42103         if(num < this.minValue){
42104             this.markInvalid(String.format(this.minText, this.minValue));
42105             return false;
42106         }
42107         
42108         if(num > this.maxValue){
42109             this.markInvalid(String.format(this.maxText, this.maxValue));
42110             return false;
42111         }
42112         
42113         return true;
42114     },
42115
42116     getValue : function()
42117     {
42118         var v = this.hiddenEl().getValue();
42119         
42120         return this.fixPrecision(this.parseValue(v));
42121     },
42122
42123     parseValue : function(value)
42124     {
42125         if(this.thousandsDelimiter) {
42126             value += "";
42127             r = new RegExp(",", "g");
42128             value = value.replace(r, "");
42129         }
42130         
42131         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
42132         return isNaN(value) ? '' : value;
42133     },
42134
42135     fixPrecision : function(value)
42136     {
42137         if(this.thousandsDelimiter) {
42138             value += "";
42139             r = new RegExp(",", "g");
42140             value = value.replace(r, "");
42141         }
42142         
42143         var nan = isNaN(value);
42144         
42145         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
42146             return nan ? '' : value;
42147         }
42148         return parseFloat(value).toFixed(this.decimalPrecision);
42149     },
42150
42151     setValue : function(v)
42152     {
42153         v = String(this.fixPrecision(v)).replace(".", this.decimalSeparator);
42154         
42155         this.value = v;
42156         
42157         if(this.rendered){
42158             
42159             this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
42160             
42161             this.inputEl().dom.value = (v == '') ? '' :
42162                 Roo.util.Format.number(v, this.decimalPrecision, this.thousandsDelimiter || '');
42163             
42164             if(!this.allowZero && v === '0') {
42165                 this.hiddenEl().dom.value = '';
42166                 this.inputEl().dom.value = '';
42167             }
42168             
42169             this.validate();
42170         }
42171     },
42172
42173     decimalPrecisionFcn : function(v)
42174     {
42175         return Math.floor(v);
42176     },
42177
42178     beforeBlur : function()
42179     {
42180         var v = this.parseValue(this.getRawValue());
42181         
42182         if(v || v === 0 || v === ''){
42183             this.setValue(v);
42184         }
42185     },
42186     
42187     hiddenEl : function()
42188     {
42189         return this.el.select('input.hidden-number-input',true).first();
42190     }
42191     
42192 });
42193
42194  
42195
42196 /*
42197 * Licence: LGPL
42198 */
42199
42200 /**
42201  * @class Roo.bootstrap.DocumentSlider
42202  * @extends Roo.bootstrap.Component
42203  * Bootstrap DocumentSlider class
42204  * 
42205  * @constructor
42206  * Create a new DocumentViewer
42207  * @param {Object} config The config object
42208  */
42209
42210 Roo.bootstrap.DocumentSlider = function(config){
42211     Roo.bootstrap.DocumentSlider.superclass.constructor.call(this, config);
42212     
42213     this.files = [];
42214     
42215     this.addEvents({
42216         /**
42217          * @event initial
42218          * Fire after initEvent
42219          * @param {Roo.bootstrap.DocumentSlider} this
42220          */
42221         "initial" : true,
42222         /**
42223          * @event update
42224          * Fire after update
42225          * @param {Roo.bootstrap.DocumentSlider} this
42226          */
42227         "update" : true,
42228         /**
42229          * @event click
42230          * Fire after click
42231          * @param {Roo.bootstrap.DocumentSlider} this
42232          */
42233         "click" : true
42234     });
42235 };
42236
42237 Roo.extend(Roo.bootstrap.DocumentSlider, Roo.bootstrap.Component,  {
42238     
42239     files : false,
42240     
42241     indicator : 0,
42242     
42243     getAutoCreate : function()
42244     {
42245         var cfg = {
42246             tag : 'div',
42247             cls : 'roo-document-slider',
42248             cn : [
42249                 {
42250                     tag : 'div',
42251                     cls : 'roo-document-slider-header',
42252                     cn : [
42253                         {
42254                             tag : 'div',
42255                             cls : 'roo-document-slider-header-title'
42256                         }
42257                     ]
42258                 },
42259                 {
42260                     tag : 'div',
42261                     cls : 'roo-document-slider-body',
42262                     cn : [
42263                         {
42264                             tag : 'div',
42265                             cls : 'roo-document-slider-prev',
42266                             cn : [
42267                                 {
42268                                     tag : 'i',
42269                                     cls : 'fa fa-chevron-left'
42270                                 }
42271                             ]
42272                         },
42273                         {
42274                             tag : 'div',
42275                             cls : 'roo-document-slider-thumb',
42276                             cn : [
42277                                 {
42278                                     tag : 'img',
42279                                     cls : 'roo-document-slider-image'
42280                                 }
42281                             ]
42282                         },
42283                         {
42284                             tag : 'div',
42285                             cls : 'roo-document-slider-next',
42286                             cn : [
42287                                 {
42288                                     tag : 'i',
42289                                     cls : 'fa fa-chevron-right'
42290                                 }
42291                             ]
42292                         }
42293                     ]
42294                 }
42295             ]
42296         };
42297         
42298         return cfg;
42299     },
42300     
42301     initEvents : function()
42302     {
42303         this.headerEl = this.el.select('.roo-document-slider-header', true).first();
42304         this.headerEl.setVisibilityMode(Roo.Element.DISPLAY);
42305         
42306         this.titleEl = this.el.select('.roo-document-slider-header .roo-document-slider-header-title', true).first();
42307         this.titleEl.setVisibilityMode(Roo.Element.DISPLAY);
42308         
42309         this.bodyEl = this.el.select('.roo-document-slider-body', true).first();
42310         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY);
42311         
42312         this.thumbEl = this.el.select('.roo-document-slider-thumb', true).first();
42313         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY);
42314         
42315         this.imageEl = this.el.select('.roo-document-slider-image', true).first();
42316         this.imageEl.setVisibilityMode(Roo.Element.DISPLAY);
42317         
42318         this.prevIndicator = this.el.select('.roo-document-slider-prev i', true).first();
42319         this.prevIndicator.setVisibilityMode(Roo.Element.DISPLAY);
42320         
42321         this.nextIndicator = this.el.select('.roo-document-slider-next i', true).first();
42322         this.nextIndicator.setVisibilityMode(Roo.Element.DISPLAY);
42323         
42324         this.thumbEl.on('click', this.onClick, this);
42325         
42326         this.prevIndicator.on('click', this.prev, this);
42327         
42328         this.nextIndicator.on('click', this.next, this);
42329         
42330     },
42331     
42332     initial : function()
42333     {
42334         if(this.files.length){
42335             this.indicator = 1;
42336             this.update()
42337         }
42338         
42339         this.fireEvent('initial', this);
42340     },
42341     
42342     update : function()
42343     {
42344         this.imageEl.attr('src', this.files[this.indicator - 1]);
42345         
42346         this.titleEl.dom.innerHTML = String.format('{0} / {1}', this.indicator, this.files.length);
42347         
42348         this.prevIndicator.show();
42349         
42350         if(this.indicator == 1){
42351             this.prevIndicator.hide();
42352         }
42353         
42354         this.nextIndicator.show();
42355         
42356         if(this.indicator == this.files.length){
42357             this.nextIndicator.hide();
42358         }
42359         
42360         this.thumbEl.scrollTo('top');
42361         
42362         this.fireEvent('update', this);
42363     },
42364     
42365     onClick : function(e)
42366     {
42367         e.preventDefault();
42368         
42369         this.fireEvent('click', this);
42370     },
42371     
42372     prev : function(e)
42373     {
42374         e.preventDefault();
42375         
42376         this.indicator = Math.max(1, this.indicator - 1);
42377         
42378         this.update();
42379     },
42380     
42381     next : function(e)
42382     {
42383         e.preventDefault();
42384         
42385         this.indicator = Math.min(this.files.length, this.indicator + 1);
42386         
42387         this.update();
42388     }
42389 });
42390 /*
42391  * - LGPL
42392  *
42393  * RadioSet
42394  *
42395  *
42396  */
42397
42398 /**
42399  * @class Roo.bootstrap.form.RadioSet
42400  * @extends Roo.bootstrap.form.Input
42401  * @children Roo.bootstrap.form.Radio
42402  * Bootstrap RadioSet class
42403  * @cfg {String} indicatorpos (left|right) default left
42404  * @cfg {Boolean} inline (true|false) inline the element (default true)
42405  * @cfg {String} weight (primary|warning|info|danger|success) The text that appears beside the radio
42406  * @constructor
42407  * Create a new RadioSet
42408  * @param {Object} config The config object
42409  */
42410
42411 Roo.bootstrap.form.RadioSet = function(config){
42412     
42413     Roo.bootstrap.form.RadioSet.superclass.constructor.call(this, config);
42414     
42415     this.radioes = [];
42416     
42417     Roo.bootstrap.form.RadioSet.register(this);
42418     
42419     this.addEvents({
42420         /**
42421         * @event check
42422         * Fires when the element is checked or unchecked.
42423         * @param {Roo.bootstrap.form.RadioSet} this This radio
42424         * @param {Roo.bootstrap.form.Radio} item The checked item
42425         */
42426        check : true,
42427        /**
42428         * @event click
42429         * Fires when the element is click.
42430         * @param {Roo.bootstrap.form.RadioSet} this This radio set
42431         * @param {Roo.bootstrap.form.Radio} item The checked item
42432         * @param {Roo.EventObject} e The event object
42433         */
42434        click : true
42435     });
42436     
42437 };
42438
42439 Roo.extend(Roo.bootstrap.form.RadioSet, Roo.bootstrap.form.Input,  {
42440
42441     radioes : false,
42442     
42443     inline : true,
42444     
42445     weight : '',
42446     
42447     indicatorpos : 'left',
42448     
42449     getAutoCreate : function()
42450     {
42451         var label = {
42452             tag : 'label',
42453             cls : 'roo-radio-set-label',
42454             cn : [
42455                 {
42456                     tag : 'span',
42457                     html : this.fieldLabel
42458                 }
42459             ]
42460         };
42461         if (Roo.bootstrap.version == 3) {
42462             
42463             
42464             if(this.indicatorpos == 'left'){
42465                 label.cn.unshift({
42466                     tag : 'i',
42467                     cls : 'roo-required-indicator left-indicator text-danger fa fa-lg fa-star',
42468                     tooltip : 'This field is required'
42469                 });
42470             } else {
42471                 label.cn.push({
42472                     tag : 'i',
42473                     cls : 'roo-required-indicator right-indicator text-danger fa fa-lg fa-star',
42474                     tooltip : 'This field is required'
42475                 });
42476             }
42477         }
42478         var items = {
42479             tag : 'div',
42480             cls : 'roo-radio-set-items'
42481         };
42482         
42483         var align = (!this.labelAlign) ? this.parentLabelAlign() : this.labelAlign;
42484         
42485         if (align === 'left' && this.fieldLabel.length) {
42486             
42487             items = {
42488                 cls : "roo-radio-set-right", 
42489                 cn: [
42490                     items
42491                 ]
42492             };
42493             
42494             if(this.labelWidth > 12){
42495                 label.style = "width: " + this.labelWidth + 'px';
42496             }
42497             
42498             if(this.labelWidth < 13 && this.labelmd == 0){
42499                 this.labelmd = this.labelWidth;
42500             }
42501             
42502             if(this.labellg > 0){
42503                 label.cls += ' col-lg-' + this.labellg;
42504                 items.cls += ' col-lg-' + (12 - this.labellg);
42505             }
42506             
42507             if(this.labelmd > 0){
42508                 label.cls += ' col-md-' + this.labelmd;
42509                 items.cls += ' col-md-' + (12 - this.labelmd);
42510             }
42511             
42512             if(this.labelsm > 0){
42513                 label.cls += ' col-sm-' + this.labelsm;
42514                 items.cls += ' col-sm-' + (12 - this.labelsm);
42515             }
42516             
42517             if(this.labelxs > 0){
42518                 label.cls += ' col-xs-' + this.labelxs;
42519                 items.cls += ' col-xs-' + (12 - this.labelxs);
42520             }
42521         }
42522         
42523         var cfg = {
42524             tag : 'div',
42525             cls : 'roo-radio-set',
42526             cn : [
42527                 {
42528                     tag : 'input',
42529                     cls : 'roo-radio-set-input',
42530                     type : 'hidden',
42531                     name : this.name,
42532                     value : this.value ? this.value :  ''
42533                 },
42534                 label,
42535                 items
42536             ]
42537         };
42538         
42539         if(this.weight.length){
42540             cfg.cls += ' roo-radio-' + this.weight;
42541         }
42542         
42543         if(this.inline) {
42544             cfg.cls += ' roo-radio-set-inline';
42545         }
42546         
42547         var settings=this;
42548         ['xs','sm','md','lg'].map(function(size){
42549             if (settings[size]) {
42550                 cfg.cls += ' col-' + size + '-' + settings[size];
42551             }
42552         });
42553         
42554         return cfg;
42555         
42556     },
42557
42558     initEvents : function()
42559     {
42560         this.labelEl = this.el.select('.roo-radio-set-label', true).first();
42561         this.labelEl.setVisibilityMode(Roo.Element.DISPLAY);
42562         
42563         if(!this.fieldLabel.length){
42564             this.labelEl.hide();
42565         }
42566         
42567         this.itemsEl = this.el.select('.roo-radio-set-items', true).first();
42568         this.itemsEl.setVisibilityMode(Roo.Element.DISPLAY);
42569         
42570         this.indicator = this.indicatorEl();
42571         
42572         if(this.indicator){
42573             this.indicator.addClass('invisible');
42574         }
42575         
42576         this.originalValue = this.getValue();
42577         
42578     },
42579     
42580     inputEl: function ()
42581     {
42582         return this.el.select('.roo-radio-set-input', true).first();
42583     },
42584     
42585     getChildContainer : function()
42586     {
42587         return this.itemsEl;
42588     },
42589     
42590     register : function(item)
42591     {
42592         this.radioes.push(item);
42593         
42594     },
42595     
42596     validate : function()
42597     {   
42598         if(this.getVisibilityEl().hasClass('hidden')){
42599             return true;
42600         }
42601         
42602         var valid = false;
42603         
42604         Roo.each(this.radioes, function(i){
42605             if(!i.checked){
42606                 return;
42607             }
42608             
42609             valid = true;
42610             return false;
42611         });
42612         
42613         if(this.allowBlank) {
42614             return true;
42615         }
42616         
42617         if(this.disabled || valid){
42618             this.markValid();
42619             return true;
42620         }
42621         
42622         this.markInvalid();
42623         return false;
42624         
42625     },
42626     
42627     markValid : function()
42628     {
42629         if(this.labelEl.isVisible(true) && this.indicatorEl()){
42630             this.indicatorEl().removeClass('visible');
42631             this.indicatorEl().addClass('invisible');
42632         }
42633         
42634         
42635         if (Roo.bootstrap.version == 3) {
42636             this.el.removeClass([this.invalidClass, this.validClass]);
42637             this.el.addClass(this.validClass);
42638         } else {
42639             this.el.removeClass(['is-invalid','is-valid']);
42640             this.el.addClass(['is-valid']);
42641         }
42642         this.fireEvent('valid', this);
42643     },
42644     
42645     markInvalid : function(msg)
42646     {
42647         if(this.allowBlank || this.disabled){
42648             return;
42649         }
42650         
42651         if(this.labelEl.isVisible(true) && this.indicatorEl()){
42652             this.indicatorEl().removeClass('invisible');
42653             this.indicatorEl().addClass('visible');
42654         }
42655         if (Roo.bootstrap.version == 3) {
42656             this.el.removeClass([this.invalidClass, this.validClass]);
42657             this.el.addClass(this.invalidClass);
42658         } else {
42659             this.el.removeClass(['is-invalid','is-valid']);
42660             this.el.addClass(['is-invalid']);
42661         }
42662         
42663         this.fireEvent('invalid', this, msg);
42664         
42665     },
42666     
42667     setValue : function(v, suppressEvent)
42668     {   
42669         if(this.value === v){
42670             return;
42671         }
42672         
42673         this.value = v;
42674         
42675         if(this.rendered){
42676             this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
42677         }
42678         
42679         Roo.each(this.radioes, function(i){
42680             i.checked = false;
42681             i.el.removeClass('checked');
42682         });
42683         
42684         Roo.each(this.radioes, function(i){
42685             
42686             if(i.value === v || i.value.toString() === v.toString()){
42687                 i.checked = true;
42688                 i.el.addClass('checked');
42689                 
42690                 if(suppressEvent !== true){
42691                     this.fireEvent('check', this, i);
42692                 }
42693                 
42694                 return false;
42695             }
42696             
42697         }, this);
42698         
42699         this.validate();
42700     },
42701     
42702     clearInvalid : function(){
42703         
42704         if(!this.el || this.preventMark){
42705             return;
42706         }
42707         
42708         this.el.removeClass([this.invalidClass]);
42709         
42710         this.fireEvent('valid', this);
42711     }
42712     
42713 });
42714
42715 Roo.apply(Roo.bootstrap.form.RadioSet, {
42716     
42717     groups: {},
42718     
42719     register : function(set)
42720     {
42721         this.groups[set.name] = set;
42722     },
42723     
42724     get: function(name) 
42725     {
42726         if (typeof(this.groups[name]) == 'undefined') {
42727             return false;
42728         }
42729         
42730         return this.groups[name] ;
42731     }
42732     
42733 });
42734 /*
42735  * Based on:
42736  * Ext JS Library 1.1.1
42737  * Copyright(c) 2006-2007, Ext JS, LLC.
42738  *
42739  * Originally Released Under LGPL - original licence link has changed is not relivant.
42740  *
42741  * Fork - LGPL
42742  * <script type="text/javascript">
42743  */
42744
42745
42746 /**
42747  * @class Roo.bootstrap.SplitBar
42748  * @extends Roo.util.Observable
42749  * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
42750  * <br><br>
42751  * Usage:
42752  * <pre><code>
42753 var split = new Roo.bootstrap.SplitBar("elementToDrag", "elementToSize",
42754                    Roo.bootstrap.SplitBar.HORIZONTAL, Roo.bootstrap.SplitBar.LEFT);
42755 split.setAdapter(new Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter("container"));
42756 split.minSize = 100;
42757 split.maxSize = 600;
42758 split.animate = true;
42759 split.on('moved', splitterMoved);
42760 </code></pre>
42761  * @constructor
42762  * Create a new SplitBar
42763  * @config {String/HTMLElement/Roo.Element} dragElement The element to be dragged and act as the SplitBar. 
42764  * @config {String/HTMLElement/Roo.Element} resizingElement The element to be resized based on where the SplitBar element is dragged 
42765  * @config {Number} orientation (optional) Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
42766  * @config {Number} placement (optional) Either Roo.bootstrap.SplitBar.LEFT or Roo.bootstrap.SplitBar.RIGHT for horizontal or  
42767                         Roo.bootstrap.SplitBar.TOP or Roo.bootstrap.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
42768                         position of the SplitBar).
42769  */
42770 Roo.bootstrap.SplitBar = function(cfg){
42771     
42772     /** @private */
42773     
42774     //{
42775     //  dragElement : elm
42776     //  resizingElement: el,
42777         // optional..
42778     //    orientation : Either Roo.bootstrap.SplitBar.HORIZONTAL
42779     //    placement : Roo.bootstrap.SplitBar.LEFT  ,
42780         // existingProxy ???
42781     //}
42782     
42783     this.el = Roo.get(cfg.dragElement, true);
42784     this.el.dom.unselectable = "on";
42785     /** @private */
42786     this.resizingEl = Roo.get(cfg.resizingElement, true);
42787
42788     /**
42789      * @private
42790      * The orientation of the split. Either Roo.bootstrap.SplitBar.HORIZONTAL or Roo.bootstrap.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
42791      * Note: If this is changed after creating the SplitBar, the placement property must be manually updated
42792      * @type Number
42793      */
42794     this.orientation = cfg.orientation || Roo.bootstrap.SplitBar.HORIZONTAL;
42795     
42796     /**
42797      * The minimum size of the resizing element. (Defaults to 0)
42798      * @type Number
42799      */
42800     this.minSize = 0;
42801     
42802     /**
42803      * The maximum size of the resizing element. (Defaults to 2000)
42804      * @type Number
42805      */
42806     this.maxSize = 2000;
42807     
42808     /**
42809      * Whether to animate the transition to the new size
42810      * @type Boolean
42811      */
42812     this.animate = false;
42813     
42814     /**
42815      * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
42816      * @type Boolean
42817      */
42818     this.useShim = false;
42819     
42820     /** @private */
42821     this.shim = null;
42822     
42823     if(!cfg.existingProxy){
42824         /** @private */
42825         this.proxy = Roo.bootstrap.SplitBar.createProxy(this.orientation);
42826     }else{
42827         this.proxy = Roo.get(cfg.existingProxy).dom;
42828     }
42829     /** @private */
42830     this.dd = new Roo.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
42831     
42832     /** @private */
42833     this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
42834     
42835     /** @private */
42836     this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
42837     
42838     /** @private */
42839     this.dragSpecs = {};
42840     
42841     /**
42842      * @private The adapter to use to positon and resize elements
42843      */
42844     this.adapter = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
42845     this.adapter.init(this);
42846     
42847     if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
42848         /** @private */
42849         this.placement = cfg.placement || (this.el.getX() > this.resizingEl.getX() ? Roo.bootstrap.SplitBar.LEFT : Roo.bootstrap.SplitBar.RIGHT);
42850         this.el.addClass("roo-splitbar-h");
42851     }else{
42852         /** @private */
42853         this.placement = cfg.placement || (this.el.getY() > this.resizingEl.getY() ? Roo.bootstrap.SplitBar.TOP : Roo.bootstrap.SplitBar.BOTTOM);
42854         this.el.addClass("roo-splitbar-v");
42855     }
42856     
42857     this.addEvents({
42858         /**
42859          * @event resize
42860          * Fires when the splitter is moved (alias for {@link #event-moved})
42861          * @param {Roo.bootstrap.SplitBar} this
42862          * @param {Number} newSize the new width or height
42863          */
42864         "resize" : true,
42865         /**
42866          * @event moved
42867          * Fires when the splitter is moved
42868          * @param {Roo.bootstrap.SplitBar} this
42869          * @param {Number} newSize the new width or height
42870          */
42871         "moved" : true,
42872         /**
42873          * @event beforeresize
42874          * Fires before the splitter is dragged
42875          * @param {Roo.bootstrap.SplitBar} this
42876          */
42877         "beforeresize" : true,
42878
42879         "beforeapply" : true
42880     });
42881
42882     Roo.util.Observable.call(this);
42883 };
42884
42885 Roo.extend(Roo.bootstrap.SplitBar, Roo.util.Observable, {
42886     onStartProxyDrag : function(x, y){
42887         this.fireEvent("beforeresize", this);
42888         if(!this.overlay){
42889             var o = Roo.DomHelper.insertFirst(document.body,  {cls: "roo-drag-overlay", html: "&#160;"}, true);
42890             o.unselectable();
42891             o.enableDisplayMode("block");
42892             // all splitbars share the same overlay
42893             Roo.bootstrap.SplitBar.prototype.overlay = o;
42894         }
42895         this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
42896         this.overlay.show();
42897         Roo.get(this.proxy).setDisplayed("block");
42898         var size = this.adapter.getElementSize(this);
42899         this.activeMinSize = this.getMinimumSize();;
42900         this.activeMaxSize = this.getMaximumSize();;
42901         var c1 = size - this.activeMinSize;
42902         var c2 = Math.max(this.activeMaxSize - size, 0);
42903         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
42904             this.dd.resetConstraints();
42905             this.dd.setXConstraint(
42906                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c1 : c2, 
42907                 this.placement == Roo.bootstrap.SplitBar.LEFT ? c2 : c1
42908             );
42909             this.dd.setYConstraint(0, 0);
42910         }else{
42911             this.dd.resetConstraints();
42912             this.dd.setXConstraint(0, 0);
42913             this.dd.setYConstraint(
42914                 this.placement == Roo.bootstrap.SplitBar.TOP ? c1 : c2, 
42915                 this.placement == Roo.bootstrap.SplitBar.TOP ? c2 : c1
42916             );
42917          }
42918         this.dragSpecs.startSize = size;
42919         this.dragSpecs.startPoint = [x, y];
42920         Roo.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
42921     },
42922     
42923     /** 
42924      * @private Called after the drag operation by the DDProxy
42925      */
42926     onEndProxyDrag : function(e){
42927         Roo.get(this.proxy).setDisplayed(false);
42928         var endPoint = Roo.lib.Event.getXY(e);
42929         if(this.overlay){
42930             this.overlay.hide();
42931         }
42932         var newSize;
42933         if(this.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
42934             newSize = this.dragSpecs.startSize + 
42935                 (this.placement == Roo.bootstrap.SplitBar.LEFT ?
42936                     endPoint[0] - this.dragSpecs.startPoint[0] :
42937                     this.dragSpecs.startPoint[0] - endPoint[0]
42938                 );
42939         }else{
42940             newSize = this.dragSpecs.startSize + 
42941                 (this.placement == Roo.bootstrap.SplitBar.TOP ?
42942                     endPoint[1] - this.dragSpecs.startPoint[1] :
42943                     this.dragSpecs.startPoint[1] - endPoint[1]
42944                 );
42945         }
42946         newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
42947         if(newSize != this.dragSpecs.startSize){
42948             if(this.fireEvent('beforeapply', this, newSize) !== false){
42949                 this.adapter.setElementSize(this, newSize);
42950                 this.fireEvent("moved", this, newSize);
42951                 this.fireEvent("resize", this, newSize);
42952             }
42953         }
42954     },
42955     
42956     /**
42957      * Get the adapter this SplitBar uses
42958      * @return The adapter object
42959      */
42960     getAdapter : function(){
42961         return this.adapter;
42962     },
42963     
42964     /**
42965      * Set the adapter this SplitBar uses
42966      * @param {Object} adapter A SplitBar adapter object
42967      */
42968     setAdapter : function(adapter){
42969         this.adapter = adapter;
42970         this.adapter.init(this);
42971     },
42972     
42973     /**
42974      * Gets the minimum size for the resizing element
42975      * @return {Number} The minimum size
42976      */
42977     getMinimumSize : function(){
42978         return this.minSize;
42979     },
42980     
42981     /**
42982      * Sets the minimum size for the resizing element
42983      * @param {Number} minSize The minimum size
42984      */
42985     setMinimumSize : function(minSize){
42986         this.minSize = minSize;
42987     },
42988     
42989     /**
42990      * Gets the maximum size for the resizing element
42991      * @return {Number} The maximum size
42992      */
42993     getMaximumSize : function(){
42994         return this.maxSize;
42995     },
42996     
42997     /**
42998      * Sets the maximum size for the resizing element
42999      * @param {Number} maxSize The maximum size
43000      */
43001     setMaximumSize : function(maxSize){
43002         this.maxSize = maxSize;
43003     },
43004     
43005     /**
43006      * Sets the initialize size for the resizing element
43007      * @param {Number} size The initial size
43008      */
43009     setCurrentSize : function(size){
43010         var oldAnimate = this.animate;
43011         this.animate = false;
43012         this.adapter.setElementSize(this, size);
43013         this.animate = oldAnimate;
43014     },
43015     
43016     /**
43017      * Destroy this splitbar. 
43018      * @param {Boolean} removeEl True to remove the element
43019      */
43020     destroy : function(removeEl){
43021         if(this.shim){
43022             this.shim.remove();
43023         }
43024         this.dd.unreg();
43025         this.proxy.parentNode.removeChild(this.proxy);
43026         if(removeEl){
43027             this.el.remove();
43028         }
43029     }
43030 });
43031
43032 /**
43033  * @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.
43034  */
43035 Roo.bootstrap.SplitBar.createProxy = function(dir){
43036     var proxy = new Roo.Element(document.createElement("div"));
43037     proxy.unselectable();
43038     var cls = 'roo-splitbar-proxy';
43039     proxy.addClass(cls + ' ' + (dir == Roo.bootstrap.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
43040     document.body.appendChild(proxy.dom);
43041     return proxy.dom;
43042 };
43043
43044 /** 
43045  * @class Roo.bootstrap.SplitBar.BasicLayoutAdapter
43046  * Default Adapter. It assumes the splitter and resizing element are not positioned
43047  * elements and only gets/sets the width of the element. Generally used for table based layouts.
43048  */
43049 Roo.bootstrap.SplitBar.BasicLayoutAdapter = function(){
43050 };
43051
43052 Roo.bootstrap.SplitBar.BasicLayoutAdapter.prototype = {
43053     // do nothing for now
43054     init : function(s){
43055     
43056     },
43057     /**
43058      * Called before drag operations to get the current size of the resizing element. 
43059      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
43060      */
43061      getElementSize : function(s){
43062         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
43063             return s.resizingEl.getWidth();
43064         }else{
43065             return s.resizingEl.getHeight();
43066         }
43067     },
43068     
43069     /**
43070      * Called after drag operations to set the size of the resizing element.
43071      * @param {Roo.bootstrap.SplitBar} s The SplitBar using this adapter
43072      * @param {Number} newSize The new size to set
43073      * @param {Function} onComplete A function to be invoked when resizing is complete
43074      */
43075     setElementSize : function(s, newSize, onComplete){
43076         if(s.orientation == Roo.bootstrap.SplitBar.HORIZONTAL){
43077             if(!s.animate){
43078                 s.resizingEl.setWidth(newSize);
43079                 if(onComplete){
43080                     onComplete(s, newSize);
43081                 }
43082             }else{
43083                 s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
43084             }
43085         }else{
43086             
43087             if(!s.animate){
43088                 s.resizingEl.setHeight(newSize);
43089                 if(onComplete){
43090                     onComplete(s, newSize);
43091                 }
43092             }else{
43093                 s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
43094             }
43095         }
43096     }
43097 };
43098
43099 /** 
43100  *@class Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter
43101  * @extends Roo.bootstrap.SplitBar.BasicLayoutAdapter
43102  * Adapter that  moves the splitter element to align with the resized sizing element. 
43103  * Used with an absolute positioned SplitBar.
43104  * @param {String/HTMLElement/Roo.Element} container The container that wraps around the absolute positioned content. If it's
43105  * document.body, make sure you assign an id to the body element.
43106  */
43107 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter = function(container){
43108     this.basic = new Roo.bootstrap.SplitBar.BasicLayoutAdapter();
43109     this.container = Roo.get(container);
43110 };
43111
43112 Roo.bootstrap.SplitBar.AbsoluteLayoutAdapter.prototype = {
43113     init : function(s){
43114         this.basic.init(s);
43115     },
43116     
43117     getElementSize : function(s){
43118         return this.basic.getElementSize(s);
43119     },
43120     
43121     setElementSize : function(s, newSize, onComplete){
43122         this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
43123     },
43124     
43125     moveSplitter : function(s){
43126         var yes = Roo.bootstrap.SplitBar;
43127         switch(s.placement){
43128             case yes.LEFT:
43129                 s.el.setX(s.resizingEl.getRight());
43130                 break;
43131             case yes.RIGHT:
43132                 s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
43133                 break;
43134             case yes.TOP:
43135                 s.el.setY(s.resizingEl.getBottom());
43136                 break;
43137             case yes.BOTTOM:
43138                 s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
43139                 break;
43140         }
43141     }
43142 };
43143
43144 /**
43145  * Orientation constant - Create a vertical SplitBar
43146  * @static
43147  * @type Number
43148  */
43149 Roo.bootstrap.SplitBar.VERTICAL = 1;
43150
43151 /**
43152  * Orientation constant - Create a horizontal SplitBar
43153  * @static
43154  * @type Number
43155  */
43156 Roo.bootstrap.SplitBar.HORIZONTAL = 2;
43157
43158 /**
43159  * Placement constant - The resizing element is to the left of the splitter element
43160  * @static
43161  * @type Number
43162  */
43163 Roo.bootstrap.SplitBar.LEFT = 1;
43164
43165 /**
43166  * Placement constant - The resizing element is to the right of the splitter element
43167  * @static
43168  * @type Number
43169  */
43170 Roo.bootstrap.SplitBar.RIGHT = 2;
43171
43172 /**
43173  * Placement constant - The resizing element is positioned above the splitter element
43174  * @static
43175  * @type Number
43176  */
43177 Roo.bootstrap.SplitBar.TOP = 3;
43178
43179 /**
43180  * Placement constant - The resizing element is positioned under splitter element
43181  * @static
43182  * @type Number
43183  */
43184 Roo.bootstrap.SplitBar.BOTTOM = 4;
43185 /*
43186  * Based on:
43187  * Ext JS Library 1.1.1
43188  * Copyright(c) 2006-2007, Ext JS, LLC.
43189  *
43190  * Originally Released Under LGPL - original licence link has changed is not relivant.
43191  *
43192  * Fork - LGPL
43193  * <script type="text/javascript">
43194  */
43195
43196 /**
43197  * @class Roo.bootstrap.layout.Manager
43198  * @extends Roo.bootstrap.Component
43199  * @abstract
43200  * Base class for layout managers.
43201  */
43202 Roo.bootstrap.layout.Manager = function(config)
43203 {
43204     this.monitorWindowResize = true; // do this before we apply configuration.
43205     
43206     Roo.bootstrap.layout.Manager.superclass.constructor.call(this,config);
43207
43208
43209
43210
43211
43212     /** false to disable window resize monitoring @type Boolean */
43213     
43214     this.regions = {};
43215     this.addEvents({
43216         /**
43217          * @event layout
43218          * Fires when a layout is performed.
43219          * @param {Roo.LayoutManager} this
43220          */
43221         "layout" : true,
43222         /**
43223          * @event regionresized
43224          * Fires when the user resizes a region.
43225          * @param {Roo.LayoutRegion} region The resized region
43226          * @param {Number} newSize The new size (width for east/west, height for north/south)
43227          */
43228         "regionresized" : true,
43229         /**
43230          * @event regioncollapsed
43231          * Fires when a region is collapsed.
43232          * @param {Roo.LayoutRegion} region The collapsed region
43233          */
43234         "regioncollapsed" : true,
43235         /**
43236          * @event regionexpanded
43237          * Fires when a region is expanded.
43238          * @param {Roo.LayoutRegion} region The expanded region
43239          */
43240         "regionexpanded" : true
43241     });
43242     this.updating = false;
43243
43244     if (config.el) {
43245         this.el = Roo.get(config.el);
43246         this.initEvents();
43247     }
43248
43249 };
43250
43251 Roo.extend(Roo.bootstrap.layout.Manager, Roo.bootstrap.Component, {
43252
43253
43254     regions : null,
43255
43256     monitorWindowResize : true,
43257
43258
43259     updating : false,
43260
43261
43262     onRender : function(ct, position)
43263     {
43264         if(!this.el){
43265             this.el = Roo.get(ct);
43266             this.initEvents();
43267         }
43268         //this.fireEvent('render',this);
43269     },
43270
43271
43272     initEvents: function()
43273     {
43274
43275
43276         // ie scrollbar fix
43277         if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
43278             document.body.scroll = "no";
43279         }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
43280             this.el.position('relative');
43281         }
43282         this.id = this.el.id;
43283         this.el.addClass("roo-layout-container");
43284         Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
43285         if(this.el.dom != document.body ) {
43286             this.el.on('resize', this.layout,this);
43287             this.el.on('show', this.layout,this);
43288         }
43289
43290     },
43291
43292     /**
43293      * Returns true if this layout is currently being updated
43294      * @return {Boolean}
43295      */
43296     isUpdating : function(){
43297         return this.updating;
43298     },
43299
43300     /**
43301      * Suspend the LayoutManager from doing auto-layouts while
43302      * making multiple add or remove calls
43303      */
43304     beginUpdate : function(){
43305         this.updating = true;
43306     },
43307
43308     /**
43309      * Restore auto-layouts and optionally disable the manager from performing a layout
43310      * @param {Boolean} noLayout true to disable a layout update
43311      */
43312     endUpdate : function(noLayout){
43313         this.updating = false;
43314         if(!noLayout){
43315             this.layout();
43316         }
43317     },
43318
43319     layout: function(){
43320         // abstract...
43321     },
43322
43323     onRegionResized : function(region, newSize){
43324         this.fireEvent("regionresized", region, newSize);
43325         this.layout();
43326     },
43327
43328     onRegionCollapsed : function(region){
43329         this.fireEvent("regioncollapsed", region);
43330     },
43331
43332     onRegionExpanded : function(region){
43333         this.fireEvent("regionexpanded", region);
43334     },
43335
43336     /**
43337      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
43338      * performs box-model adjustments.
43339      * @return {Object} The size as an object {width: (the width), height: (the height)}
43340      */
43341     getViewSize : function()
43342     {
43343         var size;
43344         if(this.el.dom != document.body){
43345             size = this.el.getSize();
43346         }else{
43347             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
43348         }
43349         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
43350         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
43351         return size;
43352     },
43353
43354     /**
43355      * Returns the Element this layout is bound to.
43356      * @return {Roo.Element}
43357      */
43358     getEl : function(){
43359         return this.el;
43360     },
43361
43362     /**
43363      * Returns the specified region.
43364      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
43365      * @return {Roo.LayoutRegion}
43366      */
43367     getRegion : function(target){
43368         return this.regions[target.toLowerCase()];
43369     },
43370
43371     onWindowResize : function(){
43372         if(this.monitorWindowResize){
43373             this.layout();
43374         }
43375     }
43376 });
43377 /*
43378  * Based on:
43379  * Ext JS Library 1.1.1
43380  * Copyright(c) 2006-2007, Ext JS, LLC.
43381  *
43382  * Originally Released Under LGPL - original licence link has changed is not relivant.
43383  *
43384  * Fork - LGPL
43385  * <script type="text/javascript">
43386  */
43387 /**
43388  * @class Roo.bootstrap.layout.Border
43389  * @extends Roo.bootstrap.layout.Manager
43390  * @children Roo.bootstrap.panel.Content Roo.bootstrap.panel.Nest Roo.bootstrap.panel.Grid
43391  * @parent builder Roo.bootstrap.panel.Nest Roo.bootstrap.panel.Nest Roo.bootstrap.Modal
43392  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
43393  * please see: examples/bootstrap/nested.html<br><br>
43394  
43395 <b>The container the layout is rendered into can be either the body element or any other element.
43396 If it is not the body element, the container needs to either be an absolute positioned element,
43397 or you will need to add "position:relative" to the css of the container.  You will also need to specify
43398 the container size if it is not the body element.</b>
43399
43400 * @constructor
43401 * Create a new Border
43402 * @param {Object} config Configuration options
43403  */
43404 Roo.bootstrap.layout.Border = function(config){
43405     config = config || {};
43406     Roo.bootstrap.layout.Border.superclass.constructor.call(this, config);
43407     
43408     
43409     
43410     Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
43411         if(config[region]){
43412             config[region].region = region;
43413             this.addRegion(config[region]);
43414         }
43415     },this);
43416     
43417 };
43418
43419 Roo.bootstrap.layout.Border.regions =  ["center", "north","south","east","west"];
43420
43421 Roo.extend(Roo.bootstrap.layout.Border, Roo.bootstrap.layout.Manager, {
43422     
43423         /**
43424          * @cfg {Roo.bootstrap.layout.Region} center region to go in center
43425          */
43426         /**
43427          * @cfg {Roo.bootstrap.layout.Region} west region to go in west
43428          */
43429         /**
43430          * @cfg {Roo.bootstrap.layout.Region} east region to go in east
43431          */
43432         /**
43433          * @cfg {Roo.bootstrap.layout.Region} south region to go in south
43434          */
43435         /**
43436          * @cfg {Roo.bootstrap.layout.Region} north region to go in north
43437          */
43438         
43439         
43440         
43441         
43442     parent : false, // this might point to a 'nest' or a ???
43443     
43444     /**
43445      * Creates and adds a new region if it doesn't already exist.
43446      * @param {String} target The target region key (north, south, east, west or center).
43447      * @param {Object} config The regions config object
43448      * @return {BorderLayoutRegion} The new region
43449      */
43450     addRegion : function(config)
43451     {
43452         if(!this.regions[config.region]){
43453             var r = this.factory(config);
43454             this.bindRegion(r);
43455         }
43456         return this.regions[config.region];
43457     },
43458
43459     // private (kinda)
43460     bindRegion : function(r){
43461         this.regions[r.config.region] = r;
43462         
43463         r.on("visibilitychange",    this.layout, this);
43464         r.on("paneladded",          this.layout, this);
43465         r.on("panelremoved",        this.layout, this);
43466         r.on("invalidated",         this.layout, this);
43467         r.on("resized",             this.onRegionResized, this);
43468         r.on("collapsed",           this.onRegionCollapsed, this);
43469         r.on("expanded",            this.onRegionExpanded, this);
43470     },
43471
43472     /**
43473      * Performs a layout update.
43474      */
43475     layout : function()
43476     {
43477         if(this.updating) {
43478             return;
43479         }
43480         
43481         // render all the rebions if they have not been done alreayd?
43482         Roo.each(Roo.bootstrap.layout.Border.regions, function(region) {
43483             if(this.regions[region] && !this.regions[region].bodyEl){
43484                 this.regions[region].onRender(this.el)
43485             }
43486         },this);
43487         
43488         var size = this.getViewSize();
43489         var w = size.width;
43490         var h = size.height;
43491         var centerW = w;
43492         var centerH = h;
43493         var centerY = 0;
43494         var centerX = 0;
43495         //var x = 0, y = 0;
43496
43497         var rs = this.regions;
43498         var north = rs["north"];
43499         var south = rs["south"]; 
43500         var west = rs["west"];
43501         var east = rs["east"];
43502         var center = rs["center"];
43503         //if(this.hideOnLayout){ // not supported anymore
43504             //c.el.setStyle("display", "none");
43505         //}
43506         if(north && north.isVisible()){
43507             var b = north.getBox();
43508             var m = north.getMargins();
43509             b.width = w - (m.left+m.right);
43510             b.x = m.left;
43511             b.y = m.top;
43512             centerY = b.height + b.y + m.bottom;
43513             centerH -= centerY;
43514             north.updateBox(this.safeBox(b));
43515         }
43516         if(south && south.isVisible()){
43517             var b = south.getBox();
43518             var m = south.getMargins();
43519             b.width = w - (m.left+m.right);
43520             b.x = m.left;
43521             var totalHeight = (b.height + m.top + m.bottom);
43522             b.y = h - totalHeight + m.top;
43523             centerH -= totalHeight;
43524             south.updateBox(this.safeBox(b));
43525         }
43526         if(west && west.isVisible()){
43527             var b = west.getBox();
43528             var m = west.getMargins();
43529             b.height = centerH - (m.top+m.bottom);
43530             b.x = m.left;
43531             b.y = centerY + m.top;
43532             var totalWidth = (b.width + m.left + m.right);
43533             centerX += totalWidth;
43534             centerW -= totalWidth;
43535             west.updateBox(this.safeBox(b));
43536         }
43537         if(east && east.isVisible()){
43538             var b = east.getBox();
43539             var m = east.getMargins();
43540             b.height = centerH - (m.top+m.bottom);
43541             var totalWidth = (b.width + m.left + m.right);
43542             b.x = w - totalWidth + m.left;
43543             b.y = centerY + m.top;
43544             centerW -= totalWidth;
43545             east.updateBox(this.safeBox(b));
43546         }
43547         if(center){
43548             var m = center.getMargins();
43549             var centerBox = {
43550                 x: centerX + m.left,
43551                 y: centerY + m.top,
43552                 width: centerW - (m.left+m.right),
43553                 height: centerH - (m.top+m.bottom)
43554             };
43555             //if(this.hideOnLayout){
43556                 //center.el.setStyle("display", "block");
43557             //}
43558             center.updateBox(this.safeBox(centerBox));
43559         }
43560         this.el.repaint();
43561         this.fireEvent("layout", this);
43562     },
43563
43564     // private
43565     safeBox : function(box){
43566         box.width = Math.max(0, box.width);
43567         box.height = Math.max(0, box.height);
43568         return box;
43569     },
43570
43571     /**
43572      * Adds a ContentPanel (or subclass) to this layout.
43573      * @param {String} target The target region key (north, south, east, west or center).
43574      * @param {Roo.ContentPanel} panel The panel to add
43575      * @return {Roo.ContentPanel} The added panel
43576      */
43577     add : function(target, panel){
43578          
43579         target = target.toLowerCase();
43580         return this.regions[target].add(panel);
43581     },
43582
43583     /**
43584      * Remove a ContentPanel (or subclass) to this layout.
43585      * @param {String} target The target region key (north, south, east, west or center).
43586      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
43587      * @return {Roo.ContentPanel} The removed panel
43588      */
43589     remove : function(target, panel){
43590         target = target.toLowerCase();
43591         return this.regions[target].remove(panel);
43592     },
43593
43594     /**
43595      * Searches all regions for a panel with the specified id
43596      * @param {String} panelId
43597      * @return {Roo.ContentPanel} The panel or null if it wasn't found
43598      */
43599     findPanel : function(panelId){
43600         var rs = this.regions;
43601         for(var target in rs){
43602             if(typeof rs[target] != "function"){
43603                 var p = rs[target].getPanel(panelId);
43604                 if(p){
43605                     return p;
43606                 }
43607             }
43608         }
43609         return null;
43610     },
43611
43612     /**
43613      * Searches all regions for a panel with the specified id and activates (shows) it.
43614      * @param {String/ContentPanel} panelId The panels id or the panel itself
43615      * @return {Roo.ContentPanel} The shown panel or null
43616      */
43617     showPanel : function(panelId) {
43618       var rs = this.regions;
43619       for(var target in rs){
43620          var r = rs[target];
43621          if(typeof r != "function"){
43622             if(r.hasPanel(panelId)){
43623                return r.showPanel(panelId);
43624             }
43625          }
43626       }
43627       return null;
43628    },
43629
43630    /**
43631      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
43632      * @param {Roo.state.Provider} provider (optional) An alternate state provider
43633      */
43634    /*
43635     restoreState : function(provider){
43636         if(!provider){
43637             provider = Roo.state.Manager;
43638         }
43639         var sm = new Roo.LayoutStateManager();
43640         sm.init(this, provider);
43641     },
43642 */
43643  
43644  
43645     /**
43646      * Adds a xtype elements to the layout.
43647      * <pre><code>
43648
43649 layout.addxtype({
43650        xtype : 'ContentPanel',
43651        region: 'west',
43652        items: [ .... ]
43653    }
43654 );
43655
43656 layout.addxtype({
43657         xtype : 'NestedLayoutPanel',
43658         region: 'west',
43659         layout: {
43660            center: { },
43661            west: { }   
43662         },
43663         items : [ ... list of content panels or nested layout panels.. ]
43664    }
43665 );
43666 </code></pre>
43667      * @param {Object} cfg Xtype definition of item to add.
43668      */
43669     addxtype : function(cfg)
43670     {
43671         // basically accepts a pannel...
43672         // can accept a layout region..!?!?
43673         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
43674         
43675         
43676         // theory?  children can only be panels??
43677         
43678         //if (!cfg.xtype.match(/Panel$/)) {
43679         //    return false;
43680         //}
43681         var ret = false;
43682         
43683         if (typeof(cfg.region) == 'undefined') {
43684             Roo.log("Failed to add Panel, region was not set");
43685             Roo.log(cfg);
43686             return false;
43687         }
43688         var region = cfg.region;
43689         delete cfg.region;
43690         
43691           
43692         var xitems = [];
43693         if (cfg.items) {
43694             xitems = cfg.items;
43695             delete cfg.items;
43696         }
43697         var nb = false;
43698         
43699         if ( region == 'center') {
43700             Roo.log("Center: " + cfg.title);
43701         }
43702         
43703         
43704         switch(cfg.xtype) 
43705         {
43706             case 'Content':  // ContentPanel (el, cfg)
43707             case 'Scroll':  // ContentPanel (el, cfg)
43708             case 'View': 
43709                 cfg.autoCreate = cfg.autoCreate || true;
43710                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
43711                 //} else {
43712                 //    var el = this.el.createChild();
43713                 //    ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
43714                 //}
43715                 
43716                 this.add(region, ret);
43717                 break;
43718             
43719             /*
43720             case 'TreePanel': // our new panel!
43721                 cfg.el = this.el.createChild();
43722                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
43723                 this.add(region, ret);
43724                 break;
43725             */
43726             
43727             case 'Nest': 
43728                 // create a new Layout (which is  a Border Layout...
43729                 
43730                 var clayout = cfg.layout;
43731                 clayout.el  = this.el.createChild();
43732                 clayout.items   = clayout.items  || [];
43733                 
43734                 delete cfg.layout;
43735                 
43736                 // replace this exitems with the clayout ones..
43737                 xitems = clayout.items;
43738                  
43739                 // force background off if it's in center...
43740                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
43741                     cfg.background = false;
43742                 }
43743                 cfg.layout  = new Roo.bootstrap.layout.Border(clayout);
43744                 
43745                 
43746                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
43747                 //console.log('adding nested layout panel '  + cfg.toSource());
43748                 this.add(region, ret);
43749                 nb = {}; /// find first...
43750                 break;
43751             
43752             case 'Grid':
43753                 
43754                 // needs grid and region
43755                 
43756                 //var el = this.getRegion(region).el.createChild();
43757                 /*
43758                  *var el = this.el.createChild();
43759                 // create the grid first...
43760                 cfg.grid.container = el;
43761                 cfg.grid = new cfg.grid.xns[cfg.grid.xtype](cfg.grid);
43762                 */
43763                 
43764                 if (region == 'center' && this.active ) {
43765                     cfg.background = false;
43766                 }
43767                 
43768                 ret = new cfg.xns[cfg.xtype](cfg); // new panel!!!!!
43769                 
43770                 this.add(region, ret);
43771                 /*
43772                 if (cfg.background) {
43773                     // render grid on panel activation (if panel background)
43774                     ret.on('activate', function(gp) {
43775                         if (!gp.grid.rendered) {
43776                     //        gp.grid.render(el);
43777                         }
43778                     });
43779                 } else {
43780                   //  cfg.grid.render(el);
43781                 }
43782                 */
43783                 break;
43784            
43785            
43786             case 'Border': // it can get called on it'self... - might need to check if this is fixed?
43787                 // it was the old xcomponent building that caused this before.
43788                 // espeically if border is the top element in the tree.
43789                 ret = this;
43790                 break; 
43791                 
43792                     
43793                 
43794                 
43795                 
43796             default:
43797                 /*
43798                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
43799                     
43800                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
43801                     this.add(region, ret);
43802                 } else {
43803                 */
43804                     Roo.log(cfg);
43805                     throw "Can not add '" + cfg.xtype + "' to Border";
43806                     return null;
43807              
43808                                 
43809              
43810         }
43811         this.beginUpdate();
43812         // add children..
43813         var region = '';
43814         var abn = {};
43815         Roo.each(xitems, function(i)  {
43816             region = nb && i.region ? i.region : false;
43817             
43818             var add = ret.addxtype(i);
43819            
43820             if (region) {
43821                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
43822                 if (!i.background) {
43823                     abn[region] = nb[region] ;
43824                 }
43825             }
43826             
43827         });
43828         this.endUpdate();
43829
43830         // make the last non-background panel active..
43831         //if (nb) { Roo.log(abn); }
43832         if (nb) {
43833             
43834             for(var r in abn) {
43835                 region = this.getRegion(r);
43836                 if (region) {
43837                     // tried using nb[r], but it does not work..
43838                      
43839                     region.showPanel(abn[r]);
43840                    
43841                 }
43842             }
43843         }
43844         return ret;
43845         
43846     },
43847     
43848     
43849 // private
43850     factory : function(cfg)
43851     {
43852         
43853         var validRegions = Roo.bootstrap.layout.Border.regions;
43854
43855         var target = cfg.region;
43856         cfg.mgr = this;
43857         
43858         var r = Roo.bootstrap.layout;
43859         Roo.log(target);
43860         switch(target){
43861             case "north":
43862                 return new r.North(cfg);
43863             case "south":
43864                 return new r.South(cfg);
43865             case "east":
43866                 return new r.East(cfg);
43867             case "west":
43868                 return new r.West(cfg);
43869             case "center":
43870                 return new r.Center(cfg);
43871         }
43872         throw 'Layout region "'+target+'" not supported.';
43873     }
43874     
43875     
43876 });
43877  /*
43878  * Based on:
43879  * Ext JS Library 1.1.1
43880  * Copyright(c) 2006-2007, Ext JS, LLC.
43881  *
43882  * Originally Released Under LGPL - original licence link has changed is not relivant.
43883  *
43884  * Fork - LGPL
43885  * <script type="text/javascript">
43886  */
43887  
43888 /**
43889  * @class Roo.bootstrap.layout.Basic
43890  * @extends Roo.util.Observable
43891  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
43892  * and does not have a titlebar, tabs or any other features. All it does is size and position 
43893  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
43894  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
43895  * @cfg {string}   region  the region that it inhabits..
43896  * @cfg {bool}   skipConfig skip config?
43897  * 
43898
43899  */
43900 Roo.bootstrap.layout.Basic = function(config){
43901     
43902     this.mgr = config.mgr;
43903     
43904     this.position = config.region;
43905     
43906     var skipConfig = config.skipConfig;
43907     
43908     this.events = {
43909         /**
43910          * @scope Roo.BasicLayoutRegion
43911          */
43912         
43913         /**
43914          * @event beforeremove
43915          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
43916          * @param {Roo.LayoutRegion} this
43917          * @param {Roo.ContentPanel} panel The panel
43918          * @param {Object} e The cancel event object
43919          */
43920         "beforeremove" : true,
43921         /**
43922          * @event invalidated
43923          * Fires when the layout for this region is changed.
43924          * @param {Roo.LayoutRegion} this
43925          */
43926         "invalidated" : true,
43927         /**
43928          * @event visibilitychange
43929          * Fires when this region is shown or hidden 
43930          * @param {Roo.LayoutRegion} this
43931          * @param {Boolean} visibility true or false
43932          */
43933         "visibilitychange" : true,
43934         /**
43935          * @event paneladded
43936          * Fires when a panel is added. 
43937          * @param {Roo.LayoutRegion} this
43938          * @param {Roo.ContentPanel} panel The panel
43939          */
43940         "paneladded" : true,
43941         /**
43942          * @event panelremoved
43943          * Fires when a panel is removed. 
43944          * @param {Roo.LayoutRegion} this
43945          * @param {Roo.ContentPanel} panel The panel
43946          */
43947         "panelremoved" : true,
43948         /**
43949          * @event beforecollapse
43950          * Fires when this region before collapse.
43951          * @param {Roo.LayoutRegion} this
43952          */
43953         "beforecollapse" : true,
43954         /**
43955          * @event collapsed
43956          * Fires when this region is collapsed.
43957          * @param {Roo.LayoutRegion} this
43958          */
43959         "collapsed" : true,
43960         /**
43961          * @event expanded
43962          * Fires when this region is expanded.
43963          * @param {Roo.LayoutRegion} this
43964          */
43965         "expanded" : true,
43966         /**
43967          * @event slideshow
43968          * Fires when this region is slid into view.
43969          * @param {Roo.LayoutRegion} this
43970          */
43971         "slideshow" : true,
43972         /**
43973          * @event slidehide
43974          * Fires when this region slides out of view. 
43975          * @param {Roo.LayoutRegion} this
43976          */
43977         "slidehide" : true,
43978         /**
43979          * @event panelactivated
43980          * Fires when a panel is activated. 
43981          * @param {Roo.LayoutRegion} this
43982          * @param {Roo.ContentPanel} panel The activated panel
43983          */
43984         "panelactivated" : true,
43985         /**
43986          * @event resized
43987          * Fires when the user resizes this region. 
43988          * @param {Roo.LayoutRegion} this
43989          * @param {Number} newSize The new size (width for east/west, height for north/south)
43990          */
43991         "resized" : true
43992     };
43993     /** A collection of panels in this region. @type Roo.util.MixedCollection */
43994     this.panels = new Roo.util.MixedCollection();
43995     this.panels.getKey = this.getPanelId.createDelegate(this);
43996     this.box = null;
43997     this.activePanel = null;
43998     // ensure listeners are added...
43999     
44000     if (config.listeners || config.events) {
44001         Roo.bootstrap.layout.Basic.superclass.constructor.call(this, {
44002             listeners : config.listeners || {},
44003             events : config.events || {}
44004         });
44005     }
44006     
44007     if(skipConfig !== true){
44008         this.applyConfig(config);
44009     }
44010 };
44011
44012 Roo.extend(Roo.bootstrap.layout.Basic, Roo.util.Observable,
44013 {
44014     getPanelId : function(p){
44015         return p.getId();
44016     },
44017     
44018     applyConfig : function(config){
44019         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
44020         this.config = config;
44021         
44022     },
44023     
44024     /**
44025      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
44026      * the width, for horizontal (north, south) the height.
44027      * @param {Number} newSize The new width or height
44028      */
44029     resizeTo : function(newSize){
44030         var el = this.el ? this.el :
44031                  (this.activePanel ? this.activePanel.getEl() : null);
44032         if(el){
44033             switch(this.position){
44034                 case "east":
44035                 case "west":
44036                     el.setWidth(newSize);
44037                     this.fireEvent("resized", this, newSize);
44038                 break;
44039                 case "north":
44040                 case "south":
44041                     el.setHeight(newSize);
44042                     this.fireEvent("resized", this, newSize);
44043                 break;                
44044             }
44045         }
44046     },
44047     
44048     getBox : function(){
44049         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
44050     },
44051     
44052     getMargins : function(){
44053         return this.margins;
44054     },
44055     
44056     updateBox : function(box){
44057         this.box = box;
44058         var el = this.activePanel.getEl();
44059         el.dom.style.left = box.x + "px";
44060         el.dom.style.top = box.y + "px";
44061         this.activePanel.setSize(box.width, box.height);
44062     },
44063     
44064     /**
44065      * Returns the container element for this region.
44066      * @return {Roo.Element}
44067      */
44068     getEl : function(){
44069         return this.activePanel;
44070     },
44071     
44072     /**
44073      * Returns true if this region is currently visible.
44074      * @return {Boolean}
44075      */
44076     isVisible : function(){
44077         return this.activePanel ? true : false;
44078     },
44079     
44080     setActivePanel : function(panel){
44081         panel = this.getPanel(panel);
44082         if(this.activePanel && this.activePanel != panel){
44083             this.activePanel.setActiveState(false);
44084             this.activePanel.getEl().setLeftTop(-10000,-10000);
44085         }
44086         this.activePanel = panel;
44087         panel.setActiveState(true);
44088         if(this.box){
44089             panel.setSize(this.box.width, this.box.height);
44090         }
44091         this.fireEvent("panelactivated", this, panel);
44092         this.fireEvent("invalidated");
44093     },
44094     
44095     /**
44096      * Show the specified panel.
44097      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
44098      * @return {Roo.ContentPanel} The shown panel or null
44099      */
44100     showPanel : function(panel){
44101         panel = this.getPanel(panel);
44102         if(panel){
44103             this.setActivePanel(panel);
44104         }
44105         return panel;
44106     },
44107     
44108     /**
44109      * Get the active panel for this region.
44110      * @return {Roo.ContentPanel} The active panel or null
44111      */
44112     getActivePanel : function(){
44113         return this.activePanel;
44114     },
44115     
44116     /**
44117      * Add the passed ContentPanel(s)
44118      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
44119      * @return {Roo.ContentPanel} The panel added (if only one was added)
44120      */
44121     add : function(panel){
44122         if(arguments.length > 1){
44123             for(var i = 0, len = arguments.length; i < len; i++) {
44124                 this.add(arguments[i]);
44125             }
44126             return null;
44127         }
44128         if(this.hasPanel(panel)){
44129             this.showPanel(panel);
44130             return panel;
44131         }
44132         var el = panel.getEl();
44133         if(el.dom.parentNode != this.mgr.el.dom){
44134             this.mgr.el.dom.appendChild(el.dom);
44135         }
44136         if(panel.setRegion){
44137             panel.setRegion(this);
44138         }
44139         this.panels.add(panel);
44140         el.setStyle("position", "absolute");
44141         if(!panel.background){
44142             this.setActivePanel(panel);
44143             if(this.config.initialSize && this.panels.getCount()==1){
44144                 this.resizeTo(this.config.initialSize);
44145             }
44146         }
44147         this.fireEvent("paneladded", this, panel);
44148         return panel;
44149     },
44150     
44151     /**
44152      * Returns true if the panel is in this region.
44153      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
44154      * @return {Boolean}
44155      */
44156     hasPanel : function(panel){
44157         if(typeof panel == "object"){ // must be panel obj
44158             panel = panel.getId();
44159         }
44160         return this.getPanel(panel) ? true : false;
44161     },
44162     
44163     /**
44164      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
44165      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
44166      * @param {Boolean} preservePanel Overrides the config preservePanel option
44167      * @return {Roo.ContentPanel} The panel that was removed
44168      */
44169     remove : function(panel, preservePanel){
44170         panel = this.getPanel(panel);
44171         if(!panel){
44172             return null;
44173         }
44174         var e = {};
44175         this.fireEvent("beforeremove", this, panel, e);
44176         if(e.cancel === true){
44177             return null;
44178         }
44179         var panelId = panel.getId();
44180         this.panels.removeKey(panelId);
44181         return panel;
44182     },
44183     
44184     /**
44185      * Returns the panel specified or null if it's not in this region.
44186      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
44187      * @return {Roo.ContentPanel}
44188      */
44189     getPanel : function(id){
44190         if(typeof id == "object"){ // must be panel obj
44191             return id;
44192         }
44193         return this.panels.get(id);
44194     },
44195     
44196     /**
44197      * Returns this regions position (north/south/east/west/center).
44198      * @return {String} 
44199      */
44200     getPosition: function(){
44201         return this.position;    
44202     }
44203 });/*
44204  * Based on:
44205  * Ext JS Library 1.1.1
44206  * Copyright(c) 2006-2007, Ext JS, LLC.
44207  *
44208  * Originally Released Under LGPL - original licence link has changed is not relivant.
44209  *
44210  * Fork - LGPL
44211  * <script type="text/javascript">
44212  */
44213  
44214 /**
44215  * @class Roo.bootstrap.layout.Region
44216  * @extends Roo.bootstrap.layout.Basic
44217  * This class represents a region in a layout manager.
44218  
44219  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
44220  * @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})
44221  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
44222  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
44223  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
44224  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
44225  * @cfg {String}    title           The title for the region (overrides panel titles)
44226  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
44227  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
44228  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
44229  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
44230  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
44231  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
44232  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
44233  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
44234  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
44235  * @cfg {String}    overflow       (hidden|visible) if you have menus in the region, then you need to set this to visible.
44236
44237  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
44238  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
44239  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
44240  * @cfg {Number}    width           For East/West panels
44241  * @cfg {Number}    height          For North/South panels
44242  * @cfg {Boolean}   split           To show the splitter
44243  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
44244  * 
44245  * @cfg {string}   cls             Extra CSS classes to add to region
44246  * 
44247  * @cfg {Roo.bootstrap.layout.Manager}   mgr The manager
44248  * @cfg {string}   region  the region that it inhabits..
44249  *
44250
44251  * @xxxcfg {Boolean}   collapsible     DISABLED False to disable collapsing (defaults to true)
44252  * @xxxcfg {Boolean}   collapsed       DISABLED True to set the initial display to collapsed (defaults to false)
44253
44254  * @xxxcfg {String}    collapsedTitle  DISABLED Optional string message to display in the collapsed block of a north or south region
44255  * @xxxxcfg {Boolean}   floatable       DISABLED False to disable floating (defaults to true)
44256  * @xxxxcfg {Boolean}   showPin         True to show a pin button NOT SUPPORTED YET
44257  */
44258 Roo.bootstrap.layout.Region = function(config)
44259 {
44260     this.applyConfig(config);
44261
44262     var mgr = config.mgr;
44263     var pos = config.region;
44264     config.skipConfig = true;
44265     Roo.bootstrap.layout.Region.superclass.constructor.call(this, config);
44266     
44267     if (mgr.el) {
44268         this.onRender(mgr.el);   
44269     }
44270      
44271     this.visible = true;
44272     this.collapsed = false;
44273     this.unrendered_panels = [];
44274 };
44275
44276 Roo.extend(Roo.bootstrap.layout.Region, Roo.bootstrap.layout.Basic, {
44277
44278     position: '', // set by wrapper (eg. north/south etc..)
44279     unrendered_panels : null,  // unrendered panels.
44280     
44281     tabPosition : false,
44282     
44283     mgr: false, // points to 'Border'
44284     
44285     
44286     createBody : function(){
44287         /** This region's body element 
44288         * @type Roo.Element */
44289         this.bodyEl = this.el.createChild({
44290                 tag: "div",
44291                 cls: "roo-layout-panel-body tab-content" // bootstrap added...
44292         });
44293     },
44294
44295     onRender: function(ctr, pos)
44296     {
44297         var dh = Roo.DomHelper;
44298         /** This region's container element 
44299         * @type Roo.Element */
44300         this.el = dh.append(ctr.dom, {
44301                 tag: "div",
44302                 cls: (this.config.cls || '') + " roo-layout-region roo-layout-panel roo-layout-panel-" + this.position
44303             }, true);
44304         /** This region's title element 
44305         * @type Roo.Element */
44306     
44307         this.titleEl = dh.append(this.el.dom,  {
44308                 tag: "div",
44309                 unselectable: "on",
44310                 cls: "roo-unselectable roo-layout-panel-hd breadcrumb roo-layout-title-" + this.position,
44311                 children:[
44312                     {tag: "span", cls: "roo-unselectable roo-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
44313                     {tag: "div", cls: "roo-unselectable roo-layout-panel-hd-tools", unselectable: "on"}
44314                 ]
44315             }, true);
44316         
44317         this.titleEl.enableDisplayMode();
44318         /** This region's title text element 
44319         * @type HTMLElement */
44320         this.titleTextEl = this.titleEl.dom.firstChild;
44321         this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
44322         /*
44323         this.closeBtn = this.createTool(this.tools.dom, "roo-layout-close");
44324         this.closeBtn.enableDisplayMode();
44325         this.closeBtn.on("click", this.closeClicked, this);
44326         this.closeBtn.hide();
44327     */
44328         this.createBody(this.config);
44329         if(this.config.hideWhenEmpty){
44330             this.hide();
44331             this.on("paneladded", this.validateVisibility, this);
44332             this.on("panelremoved", this.validateVisibility, this);
44333         }
44334         if(this.autoScroll){
44335             this.bodyEl.setStyle("overflow", "auto");
44336         }else{
44337             this.bodyEl.setStyle("overflow", this.config.overflow || 'hidden');
44338         }
44339         //if(c.titlebar !== false){
44340             if((!this.config.titlebar && !this.config.title) || this.config.titlebar === false){
44341                 this.titleEl.hide();
44342             }else{
44343                 this.titleEl.show();
44344                 if(this.config.title){
44345                     this.titleTextEl.innerHTML = this.config.title;
44346                 }
44347             }
44348         //}
44349         if(this.config.collapsed){
44350             this.collapse(true);
44351         }
44352         if(this.config.hidden){
44353             this.hide();
44354         }
44355         
44356         if (this.unrendered_panels && this.unrendered_panels.length) {
44357             for (var i =0;i< this.unrendered_panels.length; i++) {
44358                 this.add(this.unrendered_panels[i]);
44359             }
44360             this.unrendered_panels = null;
44361             
44362         }
44363         
44364     },
44365     
44366     applyConfig : function(c)
44367     {
44368         /*
44369          *if(c.collapsible && this.position != "center" && !this.collapsedEl){
44370             var dh = Roo.DomHelper;
44371             if(c.titlebar !== false){
44372                 this.collapseBtn = this.createTool(this.tools.dom, "roo-layout-collapse-"+this.position);
44373                 this.collapseBtn.on("click", this.collapse, this);
44374                 this.collapseBtn.enableDisplayMode();
44375                 /*
44376                 if(c.showPin === true || this.showPin){
44377                     this.stickBtn = this.createTool(this.tools.dom, "roo-layout-stick");
44378                     this.stickBtn.enableDisplayMode();
44379                     this.stickBtn.on("click", this.expand, this);
44380                     this.stickBtn.hide();
44381                 }
44382                 
44383             }
44384             */
44385             /** This region's collapsed element
44386             * @type Roo.Element */
44387             /*
44388              *
44389             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
44390                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
44391             ]}, true);
44392             
44393             if(c.floatable !== false){
44394                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
44395                this.collapsedEl.on("click", this.collapseClick, this);
44396             }
44397
44398             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
44399                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
44400                    id: "message", unselectable: "on", style:{"float":"left"}});
44401                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
44402              }
44403             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
44404             this.expandBtn.on("click", this.expand, this);
44405             
44406         }
44407         
44408         if(this.collapseBtn){
44409             this.collapseBtn.setVisible(c.collapsible == true);
44410         }
44411         
44412         this.cmargins = c.cmargins || this.cmargins ||
44413                          (this.position == "west" || this.position == "east" ?
44414                              {top: 0, left: 2, right:2, bottom: 0} :
44415                              {top: 2, left: 0, right:0, bottom: 2});
44416         */
44417         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
44418         
44419         
44420         this.tabPosition = [ 'top','bottom', 'west'].indexOf(c.tabPosition) > -1 ? c.tabPosition : "top";
44421         
44422         this.autoScroll = c.autoScroll || false;
44423         
44424         
44425        
44426         
44427         this.duration = c.duration || .30;
44428         this.slideDuration = c.slideDuration || .45;
44429         this.config = c;
44430        
44431     },
44432     /**
44433      * Returns true if this region is currently visible.
44434      * @return {Boolean}
44435      */
44436     isVisible : function(){
44437         return this.visible;
44438     },
44439
44440     /**
44441      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
44442      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
44443      */
44444     //setCollapsedTitle : function(title){
44445     //    title = title || "&#160;";
44446      //   if(this.collapsedTitleTextEl){
44447       //      this.collapsedTitleTextEl.innerHTML = title;
44448        // }
44449     //},
44450
44451     getBox : function(){
44452         var b;
44453       //  if(!this.collapsed){
44454             b = this.el.getBox(false, true);
44455        // }else{
44456           //  b = this.collapsedEl.getBox(false, true);
44457         //}
44458         return b;
44459     },
44460
44461     getMargins : function(){
44462         return this.margins;
44463         //return this.collapsed ? this.cmargins : this.margins;
44464     },
44465 /*
44466     highlight : function(){
44467         this.el.addClass("x-layout-panel-dragover");
44468     },
44469
44470     unhighlight : function(){
44471         this.el.removeClass("x-layout-panel-dragover");
44472     },
44473 */
44474     updateBox : function(box)
44475     {
44476         if (!this.bodyEl) {
44477             return; // not rendered yet..
44478         }
44479         
44480         this.box = box;
44481         if(!this.collapsed){
44482             this.el.dom.style.left = box.x + "px";
44483             this.el.dom.style.top = box.y + "px";
44484             this.updateBody(box.width, box.height);
44485         }else{
44486             this.collapsedEl.dom.style.left = box.x + "px";
44487             this.collapsedEl.dom.style.top = box.y + "px";
44488             this.collapsedEl.setSize(box.width, box.height);
44489         }
44490         if(this.tabs){
44491             this.tabs.autoSizeTabs();
44492         }
44493     },
44494
44495     updateBody : function(w, h)
44496     {
44497         if(w !== null){
44498             this.el.setWidth(w);
44499             w -= this.el.getBorderWidth("rl");
44500             if(this.config.adjustments){
44501                 w += this.config.adjustments[0];
44502             }
44503         }
44504         if(h !== null && h > 0){
44505             this.el.setHeight(h);
44506             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
44507             h -= this.el.getBorderWidth("tb");
44508             if(this.config.adjustments){
44509                 h += this.config.adjustments[1];
44510             }
44511             this.bodyEl.setHeight(h);
44512             if(this.tabs){
44513                 h = this.tabs.syncHeight(h);
44514             }
44515         }
44516         if(this.panelSize){
44517             w = w !== null ? w : this.panelSize.width;
44518             h = h !== null ? h : this.panelSize.height;
44519         }
44520         if(this.activePanel){
44521             var el = this.activePanel.getEl();
44522             w = w !== null ? w : el.getWidth();
44523             h = h !== null ? h : el.getHeight();
44524             this.panelSize = {width: w, height: h};
44525             this.activePanel.setSize(w, h);
44526         }
44527         if(Roo.isIE && this.tabs){
44528             this.tabs.el.repaint();
44529         }
44530     },
44531
44532     /**
44533      * Returns the container element for this region.
44534      * @return {Roo.Element}
44535      */
44536     getEl : function(){
44537         return this.el;
44538     },
44539
44540     /**
44541      * Hides this region.
44542      */
44543     hide : function(){
44544         //if(!this.collapsed){
44545             this.el.dom.style.left = "-2000px";
44546             this.el.hide();
44547         //}else{
44548          //   this.collapsedEl.dom.style.left = "-2000px";
44549          //   this.collapsedEl.hide();
44550        // }
44551         this.visible = false;
44552         this.fireEvent("visibilitychange", this, false);
44553     },
44554
44555     /**
44556      * Shows this region if it was previously hidden.
44557      */
44558     show : function(){
44559         //if(!this.collapsed){
44560             this.el.show();
44561         //}else{
44562         //    this.collapsedEl.show();
44563        // }
44564         this.visible = true;
44565         this.fireEvent("visibilitychange", this, true);
44566     },
44567 /*
44568     closeClicked : function(){
44569         if(this.activePanel){
44570             this.remove(this.activePanel);
44571         }
44572     },
44573
44574     collapseClick : function(e){
44575         if(this.isSlid){
44576            e.stopPropagation();
44577            this.slideIn();
44578         }else{
44579            e.stopPropagation();
44580            this.slideOut();
44581         }
44582     },
44583 */
44584     /**
44585      * Collapses this region.
44586      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
44587      */
44588     /*
44589     collapse : function(skipAnim, skipCheck = false){
44590         if(this.collapsed) {
44591             return;
44592         }
44593         
44594         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
44595             
44596             this.collapsed = true;
44597             if(this.split){
44598                 this.split.el.hide();
44599             }
44600             if(this.config.animate && skipAnim !== true){
44601                 this.fireEvent("invalidated", this);
44602                 this.animateCollapse();
44603             }else{
44604                 this.el.setLocation(-20000,-20000);
44605                 this.el.hide();
44606                 this.collapsedEl.show();
44607                 this.fireEvent("collapsed", this);
44608                 this.fireEvent("invalidated", this);
44609             }
44610         }
44611         
44612     },
44613 */
44614     animateCollapse : function(){
44615         // overridden
44616     },
44617
44618     /**
44619      * Expands this region if it was previously collapsed.
44620      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
44621      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
44622      */
44623     /*
44624     expand : function(e, skipAnim){
44625         if(e) {
44626             e.stopPropagation();
44627         }
44628         if(!this.collapsed || this.el.hasActiveFx()) {
44629             return;
44630         }
44631         if(this.isSlid){
44632             this.afterSlideIn();
44633             skipAnim = true;
44634         }
44635         this.collapsed = false;
44636         if(this.config.animate && skipAnim !== true){
44637             this.animateExpand();
44638         }else{
44639             this.el.show();
44640             if(this.split){
44641                 this.split.el.show();
44642             }
44643             this.collapsedEl.setLocation(-2000,-2000);
44644             this.collapsedEl.hide();
44645             this.fireEvent("invalidated", this);
44646             this.fireEvent("expanded", this);
44647         }
44648     },
44649 */
44650     animateExpand : function(){
44651         // overridden
44652     },
44653
44654     initTabs : function()
44655     {
44656         //this.bodyEl.setStyle("overflow", "hidden"); -- this is set in render?
44657         
44658         var ts = new Roo.bootstrap.panel.Tabs({
44659             el: this.bodyEl.dom,
44660             region : this,
44661             tabPosition: this.tabPosition ? this.tabPosition  : 'top',
44662             disableTooltips: this.config.disableTabTips,
44663             toolbar : this.config.toolbar
44664         });
44665         
44666         if(this.config.hideTabs){
44667             ts.stripWrap.setDisplayed(false);
44668         }
44669         this.tabs = ts;
44670         ts.resizeTabs = this.config.resizeTabs === true;
44671         ts.minTabWidth = this.config.minTabWidth || 40;
44672         ts.maxTabWidth = this.config.maxTabWidth || 250;
44673         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
44674         ts.monitorResize = false;
44675         //ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden"); // this is set in render?
44676         ts.bodyEl.addClass('roo-layout-tabs-body');
44677         this.panels.each(this.initPanelAsTab, this);
44678     },
44679
44680     initPanelAsTab : function(panel){
44681         var ti = this.tabs.addTab(
44682             panel.getEl().id,
44683             panel.getTitle(),
44684             null,
44685             this.config.closeOnTab && panel.isClosable(),
44686             panel.tpl
44687         );
44688         if(panel.tabTip !== undefined){
44689             ti.setTooltip(panel.tabTip);
44690         }
44691         ti.on("activate", function(){
44692               this.setActivePanel(panel);
44693         }, this);
44694         
44695         if(this.config.closeOnTab){
44696             ti.on("beforeclose", function(t, e){
44697                 e.cancel = true;
44698                 this.remove(panel);
44699             }, this);
44700         }
44701         
44702         panel.tabItem = ti;
44703         
44704         return ti;
44705     },
44706
44707     updatePanelTitle : function(panel, title)
44708     {
44709         if(this.activePanel == panel){
44710             this.updateTitle(title);
44711         }
44712         if(this.tabs){
44713             var ti = this.tabs.getTab(panel.getEl().id);
44714             ti.setText(title);
44715             if(panel.tabTip !== undefined){
44716                 ti.setTooltip(panel.tabTip);
44717             }
44718         }
44719     },
44720
44721     updateTitle : function(title){
44722         if(this.titleTextEl && !this.config.title){
44723             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
44724         }
44725     },
44726
44727     setActivePanel : function(panel)
44728     {
44729         panel = this.getPanel(panel);
44730         if(this.activePanel && this.activePanel != panel){
44731             if(this.activePanel.setActiveState(false) === false){
44732                 return;
44733             }
44734         }
44735         this.activePanel = panel;
44736         panel.setActiveState(true);
44737         if(this.panelSize){
44738             panel.setSize(this.panelSize.width, this.panelSize.height);
44739         }
44740         if(this.closeBtn){
44741             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
44742         }
44743         this.updateTitle(panel.getTitle());
44744         if(this.tabs){
44745             this.fireEvent("invalidated", this);
44746         }
44747         this.fireEvent("panelactivated", this, panel);
44748     },
44749
44750     /**
44751      * Shows the specified panel.
44752      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
44753      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
44754      */
44755     showPanel : function(panel)
44756     {
44757         panel = this.getPanel(panel);
44758         if(panel){
44759             if(this.tabs){
44760                 var tab = this.tabs.getTab(panel.getEl().id);
44761                 if(tab.isHidden()){
44762                     this.tabs.unhideTab(tab.id);
44763                 }
44764                 tab.activate();
44765             }else{
44766                 this.setActivePanel(panel);
44767             }
44768         }
44769         return panel;
44770     },
44771
44772     /**
44773      * Get the active panel for this region.
44774      * @return {Roo.ContentPanel} The active panel or null
44775      */
44776     getActivePanel : function(){
44777         return this.activePanel;
44778     },
44779
44780     validateVisibility : function(){
44781         if(this.panels.getCount() < 1){
44782             this.updateTitle("&#160;");
44783             this.closeBtn.hide();
44784             this.hide();
44785         }else{
44786             if(!this.isVisible()){
44787                 this.show();
44788             }
44789         }
44790     },
44791
44792     /**
44793      * Adds the passed ContentPanel(s) to this region.
44794      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
44795      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
44796      */
44797     add : function(panel)
44798     {
44799         if(arguments.length > 1){
44800             for(var i = 0, len = arguments.length; i < len; i++) {
44801                 this.add(arguments[i]);
44802             }
44803             return null;
44804         }
44805         
44806         // if we have not been rendered yet, then we can not really do much of this..
44807         if (!this.bodyEl) {
44808             this.unrendered_panels.push(panel);
44809             return panel;
44810         }
44811         
44812         
44813         
44814         
44815         if(this.hasPanel(panel)){
44816             this.showPanel(panel);
44817             return panel;
44818         }
44819         panel.setRegion(this);
44820         this.panels.add(panel);
44821        /* if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
44822             // sinle panel - no tab...?? would it not be better to render it with the tabs,
44823             // and hide them... ???
44824             this.bodyEl.dom.appendChild(panel.getEl().dom);
44825             if(panel.background !== true){
44826                 this.setActivePanel(panel);
44827             }
44828             this.fireEvent("paneladded", this, panel);
44829             return panel;
44830         }
44831         */
44832         if(!this.tabs){
44833             this.initTabs();
44834         }else{
44835             this.initPanelAsTab(panel);
44836         }
44837         
44838         
44839         if(panel.background !== true){
44840             this.tabs.activate(panel.getEl().id);
44841         }
44842         this.fireEvent("paneladded", this, panel);
44843         return panel;
44844     },
44845
44846     /**
44847      * Hides the tab for the specified panel.
44848      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
44849      */
44850     hidePanel : function(panel){
44851         if(this.tabs && (panel = this.getPanel(panel))){
44852             this.tabs.hideTab(panel.getEl().id);
44853         }
44854     },
44855
44856     /**
44857      * Unhides the tab for a previously hidden panel.
44858      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
44859      */
44860     unhidePanel : function(panel){
44861         if(this.tabs && (panel = this.getPanel(panel))){
44862             this.tabs.unhideTab(panel.getEl().id);
44863         }
44864     },
44865
44866     clearPanels : function(){
44867         while(this.panels.getCount() > 0){
44868              this.remove(this.panels.first());
44869         }
44870     },
44871
44872     /**
44873      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
44874      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
44875      * @param {Boolean} preservePanel Overrides the config preservePanel option
44876      * @return {Roo.ContentPanel} The panel that was removed
44877      */
44878     remove : function(panel, preservePanel)
44879     {
44880         panel = this.getPanel(panel);
44881         if(!panel){
44882             return null;
44883         }
44884         var e = {};
44885         this.fireEvent("beforeremove", this, panel, e);
44886         if(e.cancel === true){
44887             return null;
44888         }
44889         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
44890         var panelId = panel.getId();
44891         this.panels.removeKey(panelId);
44892         if(preservePanel){
44893             document.body.appendChild(panel.getEl().dom);
44894         }
44895         if(this.tabs){
44896             this.tabs.removeTab(panel.getEl().id);
44897         }else if (!preservePanel){
44898             this.bodyEl.dom.removeChild(panel.getEl().dom);
44899         }
44900         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
44901             var p = this.panels.first();
44902             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
44903             tempEl.appendChild(p.getEl().dom);
44904             this.bodyEl.update("");
44905             this.bodyEl.dom.appendChild(p.getEl().dom);
44906             tempEl = null;
44907             this.updateTitle(p.getTitle());
44908             this.tabs = null;
44909             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
44910             this.setActivePanel(p);
44911         }
44912         panel.setRegion(null);
44913         if(this.activePanel == panel){
44914             this.activePanel = null;
44915         }
44916         if(this.config.autoDestroy !== false && preservePanel !== true){
44917             try{panel.destroy();}catch(e){}
44918         }
44919         this.fireEvent("panelremoved", this, panel);
44920         return panel;
44921     },
44922
44923     /**
44924      * Returns the TabPanel component used by this region
44925      * @return {Roo.TabPanel}
44926      */
44927     getTabs : function(){
44928         return this.tabs;
44929     },
44930
44931     createTool : function(parentEl, className){
44932         var btn = Roo.DomHelper.append(parentEl, {
44933             tag: "div",
44934             cls: "x-layout-tools-button",
44935             children: [ {
44936                 tag: "div",
44937                 cls: "roo-layout-tools-button-inner " + className,
44938                 html: "&#160;"
44939             }]
44940         }, true);
44941         btn.addClassOnOver("roo-layout-tools-button-over");
44942         return btn;
44943     }
44944 });/*
44945  * Based on:
44946  * Ext JS Library 1.1.1
44947  * Copyright(c) 2006-2007, Ext JS, LLC.
44948  *
44949  * Originally Released Under LGPL - original licence link has changed is not relivant.
44950  *
44951  * Fork - LGPL
44952  * <script type="text/javascript">
44953  */
44954  
44955
44956
44957 /**
44958  * @class Roo.SplitLayoutRegion
44959  * @extends Roo.LayoutRegion
44960  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
44961  */
44962 Roo.bootstrap.layout.Split = function(config){
44963     this.cursor = config.cursor;
44964     Roo.bootstrap.layout.Split.superclass.constructor.call(this, config);
44965 };
44966
44967 Roo.extend(Roo.bootstrap.layout.Split, Roo.bootstrap.layout.Region,
44968 {
44969     splitTip : "Drag to resize.",
44970     collapsibleSplitTip : "Drag to resize. Double click to hide.",
44971     useSplitTips : false,
44972
44973     applyConfig : function(config){
44974         Roo.bootstrap.layout.Split.superclass.applyConfig.call(this, config);
44975     },
44976     
44977     onRender : function(ctr,pos) {
44978         
44979         Roo.bootstrap.layout.Split.superclass.onRender.call(this, ctr,pos);
44980         if(!this.config.split){
44981             return;
44982         }
44983         if(!this.split){
44984             
44985             var splitEl = Roo.DomHelper.append(ctr.dom,  {
44986                             tag: "div",
44987                             id: this.el.id + "-split",
44988                             cls: "roo-layout-split roo-layout-split-"+this.position,
44989                             html: "&#160;"
44990             });
44991             /** The SplitBar for this region 
44992             * @type Roo.SplitBar */
44993             // does not exist yet...
44994             Roo.log([this.position, this.orientation]);
44995             
44996             this.split = new Roo.bootstrap.SplitBar({
44997                 dragElement : splitEl,
44998                 resizingElement: this.el,
44999                 orientation : this.orientation
45000             });
45001             
45002             this.split.on("moved", this.onSplitMove, this);
45003             this.split.useShim = this.config.useShim === true;
45004             this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
45005             if(this.useSplitTips){
45006                 this.split.el.dom.title = this.config.collapsible ? this.collapsibleSplitTip : this.splitTip;
45007             }
45008             //if(config.collapsible){
45009             //    this.split.el.on("dblclick", this.collapse,  this);
45010             //}
45011         }
45012         if(typeof this.config.minSize != "undefined"){
45013             this.split.minSize = this.config.minSize;
45014         }
45015         if(typeof this.config.maxSize != "undefined"){
45016             this.split.maxSize = this.config.maxSize;
45017         }
45018         if(this.config.hideWhenEmpty || this.config.hidden || this.config.collapsed){
45019             this.hideSplitter();
45020         }
45021         
45022     },
45023
45024     getHMaxSize : function(){
45025          var cmax = this.config.maxSize || 10000;
45026          var center = this.mgr.getRegion("center");
45027          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
45028     },
45029
45030     getVMaxSize : function(){
45031          var cmax = this.config.maxSize || 10000;
45032          var center = this.mgr.getRegion("center");
45033          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
45034     },
45035
45036     onSplitMove : function(split, newSize){
45037         this.fireEvent("resized", this, newSize);
45038     },
45039     
45040     /** 
45041      * Returns the {@link Roo.SplitBar} for this region.
45042      * @return {Roo.SplitBar}
45043      */
45044     getSplitBar : function(){
45045         return this.split;
45046     },
45047     
45048     hide : function(){
45049         this.hideSplitter();
45050         Roo.bootstrap.layout.Split.superclass.hide.call(this);
45051     },
45052
45053     hideSplitter : function(){
45054         if(this.split){
45055             this.split.el.setLocation(-2000,-2000);
45056             this.split.el.hide();
45057         }
45058     },
45059
45060     show : function(){
45061         if(this.split){
45062             this.split.el.show();
45063         }
45064         Roo.bootstrap.layout.Split.superclass.show.call(this);
45065     },
45066     
45067     beforeSlide: function(){
45068         if(Roo.isGecko){// firefox overflow auto bug workaround
45069             this.bodyEl.clip();
45070             if(this.tabs) {
45071                 this.tabs.bodyEl.clip();
45072             }
45073             if(this.activePanel){
45074                 this.activePanel.getEl().clip();
45075                 
45076                 if(this.activePanel.beforeSlide){
45077                     this.activePanel.beforeSlide();
45078                 }
45079             }
45080         }
45081     },
45082     
45083     afterSlide : function(){
45084         if(Roo.isGecko){// firefox overflow auto bug workaround
45085             this.bodyEl.unclip();
45086             if(this.tabs) {
45087                 this.tabs.bodyEl.unclip();
45088             }
45089             if(this.activePanel){
45090                 this.activePanel.getEl().unclip();
45091                 if(this.activePanel.afterSlide){
45092                     this.activePanel.afterSlide();
45093                 }
45094             }
45095         }
45096     },
45097
45098     initAutoHide : function(){
45099         if(this.autoHide !== false){
45100             if(!this.autoHideHd){
45101                 var st = new Roo.util.DelayedTask(this.slideIn, this);
45102                 this.autoHideHd = {
45103                     "mouseout": function(e){
45104                         if(!e.within(this.el, true)){
45105                             st.delay(500);
45106                         }
45107                     },
45108                     "mouseover" : function(e){
45109                         st.cancel();
45110                     },
45111                     scope : this
45112                 };
45113             }
45114             this.el.on(this.autoHideHd);
45115         }
45116     },
45117
45118     clearAutoHide : function(){
45119         if(this.autoHide !== false){
45120             this.el.un("mouseout", this.autoHideHd.mouseout);
45121             this.el.un("mouseover", this.autoHideHd.mouseover);
45122         }
45123     },
45124
45125     clearMonitor : function(){
45126         Roo.get(document).un("click", this.slideInIf, this);
45127     },
45128
45129     // these names are backwards but not changed for compat
45130     slideOut : function(){
45131         if(this.isSlid || this.el.hasActiveFx()){
45132             return;
45133         }
45134         this.isSlid = true;
45135         if(this.collapseBtn){
45136             this.collapseBtn.hide();
45137         }
45138         this.closeBtnState = this.closeBtn.getStyle('display');
45139         this.closeBtn.hide();
45140         if(this.stickBtn){
45141             this.stickBtn.show();
45142         }
45143         this.el.show();
45144         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
45145         this.beforeSlide();
45146         this.el.setStyle("z-index", 10001);
45147         this.el.slideIn(this.getSlideAnchor(), {
45148             callback: function(){
45149                 this.afterSlide();
45150                 this.initAutoHide();
45151                 Roo.get(document).on("click", this.slideInIf, this);
45152                 this.fireEvent("slideshow", this);
45153             },
45154             scope: this,
45155             block: true
45156         });
45157     },
45158
45159     afterSlideIn : function(){
45160         this.clearAutoHide();
45161         this.isSlid = false;
45162         this.clearMonitor();
45163         this.el.setStyle("z-index", "");
45164         if(this.collapseBtn){
45165             this.collapseBtn.show();
45166         }
45167         this.closeBtn.setStyle('display', this.closeBtnState);
45168         if(this.stickBtn){
45169             this.stickBtn.hide();
45170         }
45171         this.fireEvent("slidehide", this);
45172     },
45173
45174     slideIn : function(cb){
45175         if(!this.isSlid || this.el.hasActiveFx()){
45176             Roo.callback(cb);
45177             return;
45178         }
45179         this.isSlid = false;
45180         this.beforeSlide();
45181         this.el.slideOut(this.getSlideAnchor(), {
45182             callback: function(){
45183                 this.el.setLeftTop(-10000, -10000);
45184                 this.afterSlide();
45185                 this.afterSlideIn();
45186                 Roo.callback(cb);
45187             },
45188             scope: this,
45189             block: true
45190         });
45191     },
45192     
45193     slideInIf : function(e){
45194         if(!e.within(this.el)){
45195             this.slideIn();
45196         }
45197     },
45198
45199     animateCollapse : function(){
45200         this.beforeSlide();
45201         this.el.setStyle("z-index", 20000);
45202         var anchor = this.getSlideAnchor();
45203         this.el.slideOut(anchor, {
45204             callback : function(){
45205                 this.el.setStyle("z-index", "");
45206                 this.collapsedEl.slideIn(anchor, {duration:.3});
45207                 this.afterSlide();
45208                 this.el.setLocation(-10000,-10000);
45209                 this.el.hide();
45210                 this.fireEvent("collapsed", this);
45211             },
45212             scope: this,
45213             block: true
45214         });
45215     },
45216
45217     animateExpand : function(){
45218         this.beforeSlide();
45219         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
45220         this.el.setStyle("z-index", 20000);
45221         this.collapsedEl.hide({
45222             duration:.1
45223         });
45224         this.el.slideIn(this.getSlideAnchor(), {
45225             callback : function(){
45226                 this.el.setStyle("z-index", "");
45227                 this.afterSlide();
45228                 if(this.split){
45229                     this.split.el.show();
45230                 }
45231                 this.fireEvent("invalidated", this);
45232                 this.fireEvent("expanded", this);
45233             },
45234             scope: this,
45235             block: true
45236         });
45237     },
45238
45239     anchors : {
45240         "west" : "left",
45241         "east" : "right",
45242         "north" : "top",
45243         "south" : "bottom"
45244     },
45245
45246     sanchors : {
45247         "west" : "l",
45248         "east" : "r",
45249         "north" : "t",
45250         "south" : "b"
45251     },
45252
45253     canchors : {
45254         "west" : "tl-tr",
45255         "east" : "tr-tl",
45256         "north" : "tl-bl",
45257         "south" : "bl-tl"
45258     },
45259
45260     getAnchor : function(){
45261         return this.anchors[this.position];
45262     },
45263
45264     getCollapseAnchor : function(){
45265         return this.canchors[this.position];
45266     },
45267
45268     getSlideAnchor : function(){
45269         return this.sanchors[this.position];
45270     },
45271
45272     getAlignAdj : function(){
45273         var cm = this.cmargins;
45274         switch(this.position){
45275             case "west":
45276                 return [0, 0];
45277             break;
45278             case "east":
45279                 return [0, 0];
45280             break;
45281             case "north":
45282                 return [0, 0];
45283             break;
45284             case "south":
45285                 return [0, 0];
45286             break;
45287         }
45288     },
45289
45290     getExpandAdj : function(){
45291         var c = this.collapsedEl, cm = this.cmargins;
45292         switch(this.position){
45293             case "west":
45294                 return [-(cm.right+c.getWidth()+cm.left), 0];
45295             break;
45296             case "east":
45297                 return [cm.right+c.getWidth()+cm.left, 0];
45298             break;
45299             case "north":
45300                 return [0, -(cm.top+cm.bottom+c.getHeight())];
45301             break;
45302             case "south":
45303                 return [0, cm.top+cm.bottom+c.getHeight()];
45304             break;
45305         }
45306     }
45307 });/*
45308  * Based on:
45309  * Ext JS Library 1.1.1
45310  * Copyright(c) 2006-2007, Ext JS, LLC.
45311  *
45312  * Originally Released Under LGPL - original licence link has changed is not relivant.
45313  *
45314  * Fork - LGPL
45315  * <script type="text/javascript">
45316  */
45317 /*
45318  * These classes are private internal classes
45319  */
45320 Roo.bootstrap.layout.Center = function(config){
45321     config.region = "center";
45322     Roo.bootstrap.layout.Region.call(this, config);
45323     this.visible = true;
45324     this.minWidth = config.minWidth || 20;
45325     this.minHeight = config.minHeight || 20;
45326 };
45327
45328 Roo.extend(Roo.bootstrap.layout.Center, Roo.bootstrap.layout.Region, {
45329     hide : function(){
45330         // center panel can't be hidden
45331     },
45332     
45333     show : function(){
45334         // center panel can't be hidden
45335     },
45336     
45337     getMinWidth: function(){
45338         return this.minWidth;
45339     },
45340     
45341     getMinHeight: function(){
45342         return this.minHeight;
45343     }
45344 });
45345
45346
45347
45348
45349  
45350
45351
45352
45353
45354
45355
45356 Roo.bootstrap.layout.North = function(config)
45357 {
45358     config.region = 'north';
45359     config.cursor = 'n-resize';
45360     
45361     Roo.bootstrap.layout.Split.call(this, config);
45362     
45363     
45364     if(this.split){
45365         this.split.placement = Roo.bootstrap.SplitBar.TOP;
45366         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
45367         this.split.el.addClass("roo-layout-split-v");
45368     }
45369     //var size = config.initialSize || config.height;
45370     //if(this.el && typeof size != "undefined"){
45371     //    this.el.setHeight(size);
45372     //}
45373 };
45374 Roo.extend(Roo.bootstrap.layout.North, Roo.bootstrap.layout.Split,
45375 {
45376     orientation: Roo.bootstrap.SplitBar.VERTICAL,
45377      
45378      
45379     onRender : function(ctr, pos)
45380     {
45381         Roo.bootstrap.layout.Split.prototype.onRender.call(this, ctr, pos);
45382         var size = this.config.initialSize || this.config.height;
45383         if(this.el && typeof size != "undefined"){
45384             this.el.setHeight(size);
45385         }
45386     
45387     },
45388     
45389     getBox : function(){
45390         if(this.collapsed){
45391             return this.collapsedEl.getBox();
45392         }
45393         var box = this.el.getBox();
45394         if(this.split){
45395             box.height += this.split.el.getHeight();
45396         }
45397         return box;
45398     },
45399     
45400     updateBox : function(box){
45401         if(this.split && !this.collapsed){
45402             box.height -= this.split.el.getHeight();
45403             this.split.el.setLeft(box.x);
45404             this.split.el.setTop(box.y+box.height);
45405             this.split.el.setWidth(box.width);
45406         }
45407         if(this.collapsed){
45408             this.updateBody(box.width, null);
45409         }
45410         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
45411     }
45412 });
45413
45414
45415
45416
45417
45418 Roo.bootstrap.layout.South = function(config){
45419     config.region = 'south';
45420     config.cursor = 's-resize';
45421     Roo.bootstrap.layout.Split.call(this, config);
45422     if(this.split){
45423         this.split.placement = Roo.bootstrap.SplitBar.BOTTOM;
45424         this.split.orientation = Roo.bootstrap.SplitBar.VERTICAL;
45425         this.split.el.addClass("roo-layout-split-v");
45426     }
45427     
45428 };
45429
45430 Roo.extend(Roo.bootstrap.layout.South, Roo.bootstrap.layout.Split, {
45431     orientation: Roo.bootstrap.SplitBar.VERTICAL,
45432     
45433     onRender : function(ctr, pos)
45434     {
45435         Roo.bootstrap.layout.Split.prototype.onRender.call(this, ctr, pos);
45436         var size = this.config.initialSize || this.config.height;
45437         if(this.el && typeof size != "undefined"){
45438             this.el.setHeight(size);
45439         }
45440     
45441     },
45442     
45443     getBox : function(){
45444         if(this.collapsed){
45445             return this.collapsedEl.getBox();
45446         }
45447         var box = this.el.getBox();
45448         if(this.split){
45449             var sh = this.split.el.getHeight();
45450             box.height += sh;
45451             box.y -= sh;
45452         }
45453         return box;
45454     },
45455     
45456     updateBox : function(box){
45457         if(this.split && !this.collapsed){
45458             var sh = this.split.el.getHeight();
45459             box.height -= sh;
45460             box.y += sh;
45461             this.split.el.setLeft(box.x);
45462             this.split.el.setTop(box.y-sh);
45463             this.split.el.setWidth(box.width);
45464         }
45465         if(this.collapsed){
45466             this.updateBody(box.width, null);
45467         }
45468         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
45469     }
45470 });
45471
45472 Roo.bootstrap.layout.East = function(config){
45473     config.region = "east";
45474     config.cursor = "e-resize";
45475     Roo.bootstrap.layout.Split.call(this, config);
45476     if(this.split){
45477         this.split.placement = Roo.bootstrap.SplitBar.RIGHT;
45478         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
45479         this.split.el.addClass("roo-layout-split-h");
45480     }
45481     
45482 };
45483 Roo.extend(Roo.bootstrap.layout.East, Roo.bootstrap.layout.Split, {
45484     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
45485     
45486     onRender : function(ctr, pos)
45487     {
45488         Roo.bootstrap.layout.Split.prototype.onRender.call(this, ctr, pos);
45489         var size = this.config.initialSize || this.config.width;
45490         if(this.el && typeof size != "undefined"){
45491             this.el.setWidth(size);
45492         }
45493     
45494     },
45495     
45496     getBox : function(){
45497         if(this.collapsed){
45498             return this.collapsedEl.getBox();
45499         }
45500         var box = this.el.getBox();
45501         if(this.split){
45502             var sw = this.split.el.getWidth();
45503             box.width += sw;
45504             box.x -= sw;
45505         }
45506         return box;
45507     },
45508
45509     updateBox : function(box){
45510         if(this.split && !this.collapsed){
45511             var sw = this.split.el.getWidth();
45512             box.width -= sw;
45513             this.split.el.setLeft(box.x);
45514             this.split.el.setTop(box.y);
45515             this.split.el.setHeight(box.height);
45516             box.x += sw;
45517         }
45518         if(this.collapsed){
45519             this.updateBody(null, box.height);
45520         }
45521         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
45522     }
45523 });
45524
45525 Roo.bootstrap.layout.West = function(config){
45526     config.region = "west";
45527     config.cursor = "w-resize";
45528     
45529     Roo.bootstrap.layout.Split.call(this, config);
45530     if(this.split){
45531         this.split.placement = Roo.bootstrap.SplitBar.LEFT;
45532         this.split.orientation = Roo.bootstrap.SplitBar.HORIZONTAL;
45533         this.split.el.addClass("roo-layout-split-h");
45534     }
45535     
45536 };
45537 Roo.extend(Roo.bootstrap.layout.West, Roo.bootstrap.layout.Split, {
45538     orientation: Roo.bootstrap.SplitBar.HORIZONTAL,
45539     
45540     onRender: function(ctr, pos)
45541     {
45542         Roo.bootstrap.layout.West.superclass.onRender.call(this, ctr,pos);
45543         var size = this.config.initialSize || this.config.width;
45544         if(typeof size != "undefined"){
45545             this.el.setWidth(size);
45546         }
45547     },
45548     
45549     getBox : function(){
45550         if(this.collapsed){
45551             return this.collapsedEl.getBox();
45552         }
45553         var box = this.el.getBox();
45554         if (box.width == 0) {
45555             box.width = this.config.width; // kludge?
45556         }
45557         if(this.split){
45558             box.width += this.split.el.getWidth();
45559         }
45560         return box;
45561     },
45562     
45563     updateBox : function(box){
45564         if(this.split && !this.collapsed){
45565             var sw = this.split.el.getWidth();
45566             box.width -= sw;
45567             this.split.el.setLeft(box.x+box.width);
45568             this.split.el.setTop(box.y);
45569             this.split.el.setHeight(box.height);
45570         }
45571         if(this.collapsed){
45572             this.updateBody(null, box.height);
45573         }
45574         Roo.bootstrap.layout.Region.prototype.updateBox.call(this, box);
45575     }
45576 });/*
45577  * Based on:
45578  * Ext JS Library 1.1.1
45579  * Copyright(c) 2006-2007, Ext JS, LLC.
45580  *
45581  * Originally Released Under LGPL - original licence link has changed is not relivant.
45582  *
45583  * Fork - LGPL
45584  * <script type="text/javascript">
45585  */
45586 /**
45587  * @class Roo.bootstrap.paenl.Content
45588  * @extends Roo.util.Observable
45589  * @children Roo.bootstrap.Component
45590  * @parent builder Roo.bootstrap.layout.Border
45591  * A basic ContentPanel element. - a panel that contain any content (eg. forms etc.)
45592  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
45593  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
45594  * @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
45595  * @cfg {Boolean}   closable      True if the panel can be closed/removed
45596  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
45597  * @cfg {String/HTMLElement/Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
45598  * @cfg {Toolbar}   toolbar       A toolbar for this panel
45599  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
45600  * @cfg {String} title          The title for this panel
45601  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
45602  * @cfg {String} url            Calls {@link #setUrl} with this value
45603  * @cfg {String} region  [required] (center|north|south|east|west) which region to put this panel on (when used with xtype constructors)
45604  * @cfg {String/Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
45605  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
45606  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
45607  * @cfg {Boolean} iframe      contents are an iframe - makes showing remote sources/CSS feasible..
45608  * @cfg {Boolean} badges render the badges
45609  * @cfg {String} cls  extra classes to use  
45610  * @cfg {String} background (primary|secondary|success|info|warning|danger|light|dark)
45611  
45612  * @constructor
45613  * Create a new ContentPanel.
45614  * @param {String/Object} config A string to set only the title or a config object
45615  
45616  */
45617 Roo.bootstrap.panel.Content = function( config){
45618     
45619     this.tpl = config.tpl || false;
45620     
45621     var el = config.el;
45622     var content = config.content;
45623
45624     if(config.autoCreate){ // xtype is available if this is called from factory
45625         el = Roo.id();
45626     }
45627     this.el = Roo.get(el);
45628     if(!this.el && config && config.autoCreate){
45629         if(typeof config.autoCreate == "object"){
45630             if(!config.autoCreate.id){
45631                 config.autoCreate.id = config.id||el;
45632             }
45633             this.el = Roo.DomHelper.append(document.body,
45634                         config.autoCreate, true);
45635         }else{
45636             var elcfg =  {
45637                 tag: "div",
45638                 cls: (config.cls || '') +
45639                     (config.background ? ' bg-' + config.background : '') +
45640                     " roo-layout-inactive-content",
45641                 id: config.id||el
45642             };
45643             if (config.iframe) {
45644                 elcfg.cn = [
45645                     {
45646                         tag : 'iframe',
45647                         style : 'border: 0px',
45648                         src : 'about:blank'
45649                     }
45650                 ];
45651             }
45652               
45653             if (config.html) {
45654                 elcfg.html = config.html;
45655                 
45656             }
45657                         
45658             this.el = Roo.DomHelper.append(document.body, elcfg , true);
45659             if (config.iframe) {
45660                 this.iframeEl = this.el.select('iframe',true).first();
45661             }
45662             
45663         }
45664     } 
45665     this.closable = false;
45666     this.loaded = false;
45667     this.active = false;
45668    
45669       
45670     if (config.toolbar && !config.toolbar.el && config.toolbar.xtype) {
45671         
45672         this.toolbar = new config.toolbar.xns[config.toolbar.xtype](config.toolbar);
45673         
45674         this.wrapEl = this.el; //this.el.wrap();
45675         var ti = [];
45676         if (config.toolbar.items) {
45677             ti = config.toolbar.items ;
45678             delete config.toolbar.items ;
45679         }
45680         
45681         var nitems = [];
45682         this.toolbar.render(this.wrapEl, 'before');
45683         for(var i =0;i < ti.length;i++) {
45684           //  Roo.log(['add child', items[i]]);
45685             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
45686         }
45687         this.toolbar.items = nitems;
45688         this.toolbar.el.insertBefore(this.wrapEl.dom.firstChild);
45689         delete config.toolbar;
45690         
45691     }
45692     /*
45693     // xtype created footer. - not sure if will work as we normally have to render first..
45694     if (this.footer && !this.footer.el && this.footer.xtype) {
45695         if (!this.wrapEl) {
45696             this.wrapEl = this.el.wrap();
45697         }
45698     
45699         this.footer.container = this.wrapEl.createChild();
45700          
45701         this.footer = Roo.factory(this.footer, Roo);
45702         
45703     }
45704     */
45705     
45706      if(typeof config == "string"){
45707         this.title = config;
45708     }else{
45709         Roo.apply(this, config);
45710     }
45711     
45712     if(this.resizeEl){
45713         this.resizeEl = Roo.get(this.resizeEl, true);
45714     }else{
45715         this.resizeEl = this.el;
45716     }
45717     // handle view.xtype
45718     
45719  
45720     
45721     
45722     this.addEvents({
45723         /**
45724          * @event activate
45725          * Fires when this panel is activated. 
45726          * @param {Roo.ContentPanel} this
45727          */
45728         "activate" : true,
45729         /**
45730          * @event deactivate
45731          * Fires when this panel is activated. 
45732          * @param {Roo.ContentPanel} this
45733          */
45734         "deactivate" : true,
45735
45736         /**
45737          * @event resize
45738          * Fires when this panel is resized if fitToFrame is true.
45739          * @param {Roo.ContentPanel} this
45740          * @param {Number} width The width after any component adjustments
45741          * @param {Number} height The height after any component adjustments
45742          */
45743         "resize" : true,
45744         
45745          /**
45746          * @event render
45747          * Fires when this tab is created
45748          * @param {Roo.ContentPanel} this
45749          */
45750         "render" : true,
45751         
45752           /**
45753          * @event scroll
45754          * Fires when this content is scrolled
45755          * @param {Roo.ContentPanel} this
45756          * @param {Event} scrollEvent
45757          */
45758         "scroll" : true
45759         
45760         
45761         
45762     });
45763     
45764
45765     
45766     
45767     if(this.autoScroll && !this.iframe){
45768         this.resizeEl.setStyle("overflow", "auto");
45769         this.resizeEl.on('scroll', this.onScroll, this);
45770     } else {
45771         // fix randome scrolling
45772         //this.el.on('scroll', function() {
45773         //    Roo.log('fix random scolling');
45774         //    this.scrollTo('top',0); 
45775         //});
45776     }
45777     content = content || this.content;
45778     if(content){
45779         this.setContent(content);
45780     }
45781     if(config && config.url){
45782         this.setUrl(this.url, this.params, this.loadOnce);
45783     }
45784     
45785     
45786     
45787     Roo.bootstrap.panel.Content.superclass.constructor.call(this);
45788     
45789     if (this.view && typeof(this.view.xtype) != 'undefined') {
45790         this.view.el = this.el.appendChild(document.createElement("div"));
45791         this.view = Roo.factory(this.view); 
45792         this.view.render  &&  this.view.render(false, '');  
45793     }
45794     
45795     
45796     this.fireEvent('render', this);
45797 };
45798
45799 Roo.extend(Roo.bootstrap.panel.Content, Roo.bootstrap.Component, {
45800     
45801     cls : '',
45802     background : '',
45803     
45804     tabTip : '',
45805     
45806     iframe : false,
45807     iframeEl : false,
45808     
45809     /* Resize Element - use this to work out scroll etc. */
45810     resizeEl : false,
45811     
45812     setRegion : function(region){
45813         this.region = region;
45814         this.setActiveClass(region && !this.background);
45815     },
45816     
45817     
45818     setActiveClass: function(state)
45819     {
45820         if(state){
45821            this.el.replaceClass("roo-layout-inactive-content", "roo-layout-active-content");
45822            this.el.setStyle('position','relative');
45823         }else{
45824            this.el.replaceClass("roo-layout-active-content", "roo-layout-inactive-content");
45825            this.el.setStyle('position', 'absolute');
45826         } 
45827     },
45828     
45829     /**
45830      * Returns the toolbar for this Panel if one was configured. 
45831      * @return {Roo.Toolbar} 
45832      */
45833     getToolbar : function(){
45834         return this.toolbar;
45835     },
45836     
45837     setActiveState : function(active)
45838     {
45839         this.active = active;
45840         this.setActiveClass(active);
45841         if(!active){
45842             if(this.fireEvent("deactivate", this) === false){
45843                 return false;
45844             }
45845             return true;
45846         }
45847         this.fireEvent("activate", this);
45848         return true;
45849     },
45850     /**
45851      * Updates this panel's element (not for iframe)
45852      * @param {String} content The new content
45853      * @param {Boolean} loadScripts (optional) true to look for and process scripts
45854     */
45855     setContent : function(content, loadScripts){
45856         if (this.iframe) {
45857             return;
45858         }
45859         
45860         this.el.update(content, loadScripts);
45861     },
45862
45863     ignoreResize : function(w, h)
45864     {
45865         //return false; // always resize?
45866         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
45867             return true;
45868         }else{
45869             this.lastSize = {width: w, height: h};
45870             return false;
45871         }
45872     },
45873     /**
45874      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
45875      * @return {Roo.UpdateManager} The UpdateManager
45876      */
45877     getUpdateManager : function(){
45878         if (this.iframe) {
45879             return false;
45880         }
45881         return this.el.getUpdateManager();
45882     },
45883      /**
45884      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
45885      * Does not work with IFRAME contents
45886      * @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:
45887 <pre><code>
45888 panel.load({
45889     url: "your-url.php",
45890     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
45891     callback: yourFunction,
45892     scope: yourObject, //(optional scope)
45893     discardUrl: false,
45894     nocache: false,
45895     text: "Loading...",
45896     timeout: 30,
45897     scripts: false
45898 });
45899 </code></pre>
45900      
45901      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
45902      * 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.
45903      * @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}
45904      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
45905      * @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.
45906      * @return {Roo.ContentPanel} this
45907      */
45908     load : function(){
45909         
45910         if (this.iframe) {
45911             return this;
45912         }
45913         
45914         var um = this.el.getUpdateManager();
45915         um.update.apply(um, arguments);
45916         return this;
45917     },
45918
45919
45920     /**
45921      * 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.
45922      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
45923      * @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)
45924      * @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)
45925      * @return {Roo.UpdateManager|Boolean} The UpdateManager or false if IFRAME
45926      */
45927     setUrl : function(url, params, loadOnce){
45928         if (this.iframe) {
45929             this.iframeEl.dom.src = url;
45930             return false;
45931         }
45932         
45933         if(this.refreshDelegate){
45934             this.removeListener("activate", this.refreshDelegate);
45935         }
45936         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
45937         this.on("activate", this.refreshDelegate);
45938         return this.el.getUpdateManager();
45939     },
45940     
45941     _handleRefresh : function(url, params, loadOnce){
45942         if(!loadOnce || !this.loaded){
45943             var updater = this.el.getUpdateManager();
45944             updater.update(url, params, this._setLoaded.createDelegate(this));
45945         }
45946     },
45947     
45948     _setLoaded : function(){
45949         this.loaded = true;
45950     }, 
45951     
45952     /**
45953      * Returns this panel's id
45954      * @return {String} 
45955      */
45956     getId : function(){
45957         return this.el.id;
45958     },
45959     
45960     /** 
45961      * Returns this panel's element - used by regiosn to add.
45962      * @return {Roo.Element} 
45963      */
45964     getEl : function(){
45965         return this.wrapEl || this.el;
45966     },
45967     
45968    
45969     
45970     adjustForComponents : function(width, height)
45971     {
45972         //Roo.log('adjustForComponents ');
45973         if(this.resizeEl != this.el){
45974             width -= this.el.getFrameWidth('lr');
45975             height -= this.el.getFrameWidth('tb');
45976         }
45977         if(this.toolbar){
45978             var te = this.toolbar.getEl();
45979             te.setWidth(width);
45980             height -= te.getHeight();
45981         }
45982         if(this.footer){
45983             var te = this.footer.getEl();
45984             te.setWidth(width);
45985             height -= te.getHeight();
45986         }
45987         
45988         
45989         if(this.adjustments){
45990             width += this.adjustments[0];
45991             height += this.adjustments[1];
45992         }
45993         return {"width": width, "height": height};
45994     },
45995     
45996     setSize : function(width, height){
45997         if(this.fitToFrame && !this.ignoreResize(width, height)){
45998             if(this.fitContainer && this.resizeEl != this.el){
45999                 this.el.setSize(width, height);
46000             }
46001             var size = this.adjustForComponents(width, height);
46002             if (this.iframe) {
46003                 this.iframeEl.setSize(width,height);
46004             }
46005             
46006             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
46007             this.fireEvent('resize', this, size.width, size.height);
46008             
46009             
46010         }
46011     },
46012     
46013     /**
46014      * Returns this panel's title
46015      * @return {String} 
46016      */
46017     getTitle : function(){
46018         
46019         if (typeof(this.title) != 'object') {
46020             return this.title;
46021         }
46022         
46023         var t = '';
46024         for (var k in this.title) {
46025             if (!this.title.hasOwnProperty(k)) {
46026                 continue;
46027             }
46028             
46029             if (k.indexOf('-') >= 0) {
46030                 var s = k.split('-');
46031                 for (var i = 0; i<s.length; i++) {
46032                     t += "<span class='visible-"+s[i]+"'>"+this.title[k]+"</span>";
46033                 }
46034             } else {
46035                 t += "<span class='visible-"+k+"'>"+this.title[k]+"</span>";
46036             }
46037         }
46038         return t;
46039     },
46040     
46041     /**
46042      * Set this panel's title
46043      * @param {String} title
46044      */
46045     setTitle : function(title){
46046         this.title = title;
46047         if(this.region){
46048             this.region.updatePanelTitle(this, title);
46049         }
46050     },
46051     
46052     /**
46053      * Returns true is this panel was configured to be closable
46054      * @return {Boolean} 
46055      */
46056     isClosable : function(){
46057         return this.closable;
46058     },
46059     
46060     beforeSlide : function(){
46061         this.el.clip();
46062         this.resizeEl.clip();
46063     },
46064     
46065     afterSlide : function(){
46066         this.el.unclip();
46067         this.resizeEl.unclip();
46068     },
46069     
46070     /**
46071      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
46072      *   Will fail silently if the {@link #setUrl} method has not been called.
46073      *   This does not activate the panel, just updates its content.
46074      */
46075     refresh : function(){
46076         if(this.refreshDelegate){
46077            this.loaded = false;
46078            this.refreshDelegate();
46079         }
46080     },
46081     
46082     /**
46083      * Destroys this panel
46084      */
46085     destroy : function(){
46086         this.el.removeAllListeners();
46087         var tempEl = document.createElement("span");
46088         tempEl.appendChild(this.el.dom);
46089         tempEl.innerHTML = "";
46090         this.el.remove();
46091         this.el = null;
46092     },
46093     
46094     /**
46095      * form - if the content panel contains a form - this is a reference to it.
46096      * @type {Roo.form.Form}
46097      */
46098     form : false,
46099     /**
46100      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
46101      *    This contains a reference to it.
46102      * @type {Roo.View}
46103      */
46104     view : false,
46105     
46106       /**
46107      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
46108      * <pre><code>
46109
46110 layout.addxtype({
46111        xtype : 'Form',
46112        items: [ .... ]
46113    }
46114 );
46115
46116 </code></pre>
46117      * @param {Object} cfg Xtype definition of item to add.
46118      */
46119     
46120     
46121     getChildContainer: function () {
46122         return this.getEl();
46123     },
46124     
46125     
46126     onScroll : function(e)
46127     {
46128         this.fireEvent('scroll', this, e);
46129     }
46130     
46131     
46132     /*
46133         var  ret = new Roo.factory(cfg);
46134         return ret;
46135         
46136         
46137         // add form..
46138         if (cfg.xtype.match(/^Form$/)) {
46139             
46140             var el;
46141             //if (this.footer) {
46142             //    el = this.footer.container.insertSibling(false, 'before');
46143             //} else {
46144                 el = this.el.createChild();
46145             //}
46146
46147             this.form = new  Roo.form.Form(cfg);
46148             
46149             
46150             if ( this.form.allItems.length) {
46151                 this.form.render(el.dom);
46152             }
46153             return this.form;
46154         }
46155         // should only have one of theses..
46156         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
46157             // views.. should not be just added - used named prop 'view''
46158             
46159             cfg.el = this.el.appendChild(document.createElement("div"));
46160             // factory?
46161             
46162             var ret = new Roo.factory(cfg);
46163              
46164              ret.render && ret.render(false, ''); // render blank..
46165             this.view = ret;
46166             return ret;
46167         }
46168         return false;
46169     }
46170     \*/
46171 });
46172  
46173 /**
46174  * @class Roo.bootstrap.panel.Grid
46175  * @extends Roo.bootstrap.panel.Content
46176  * @constructor
46177  * Create a new GridPanel.
46178  * @cfg {Roo.bootstrap.Table} grid The grid for this panel
46179  * @cfg {Roo.bootstrap.nav.Simplebar} toolbar the toolbar at the top of the grid.
46180  * @param {Object} config A the config object
46181   
46182  */
46183
46184
46185
46186 Roo.bootstrap.panel.Grid = function(config)
46187 {
46188     
46189       
46190     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
46191         {tag: "div", cls: "roo-layout-grid-wrapper roo-layout-inactive-content"}, true);
46192
46193     config.el = this.wrapper;
46194     //this.el = this.wrapper;
46195     
46196       if (config.container) {
46197         // ctor'ed from a Border/panel.grid
46198         
46199         
46200         this.wrapper.setStyle("overflow", "hidden");
46201         this.wrapper.addClass('roo-grid-container');
46202
46203     }
46204     
46205     
46206     if(config.toolbar){
46207         var tool_el = this.wrapper.createChild();    
46208         this.toolbar = Roo.factory(config.toolbar);
46209         var ti = [];
46210         if (config.toolbar.items) {
46211             ti = config.toolbar.items ;
46212             delete config.toolbar.items ;
46213         }
46214         
46215         var nitems = [];
46216         this.toolbar.render(tool_el);
46217         for(var i =0;i < ti.length;i++) {
46218           //  Roo.log(['add child', items[i]]);
46219             nitems.push(this.toolbar.addxtype(Roo.apply({}, ti[i])));
46220         }
46221         this.toolbar.items = nitems;
46222         
46223         delete config.toolbar;
46224     }
46225     
46226     Roo.bootstrap.panel.Grid.superclass.constructor.call(this, config);
46227     config.grid.scrollBody = true;;
46228     config.grid.monitorWindowResize = false; // turn off autosizing
46229     config.grid.autoHeight = false;
46230     config.grid.autoWidth = false;
46231     
46232     this.grid = new config.grid.xns[config.grid.xtype](config.grid);
46233     
46234     if (config.background) {
46235         // render grid on panel activation (if panel background)
46236         this.on('activate', function(gp) {
46237             if (!gp.grid.rendered) {
46238                 gp.grid.render(this.wrapper);
46239                 gp.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");   
46240             }
46241         });
46242             
46243     } else {
46244         this.grid.render(this.wrapper);
46245         this.grid.getGridEl().replaceClass("roo-layout-inactive-content", "roo-layout-component-panel");               
46246
46247     }
46248     //this.wrapper.dom.appendChild(config.grid.getGridEl().dom);
46249     // ??? needed ??? config.el = this.wrapper;
46250     
46251     
46252     
46253   
46254     // xtype created footer. - not sure if will work as we normally have to render first..
46255     if (this.footer && !this.footer.el && this.footer.xtype) {
46256         
46257         var ctr = this.grid.getView().getFooterPanel(true);
46258         this.footer.dataSource = this.grid.dataSource;
46259         this.footer = Roo.factory(this.footer, Roo);
46260         this.footer.render(ctr);
46261         
46262     }
46263     
46264     
46265     
46266     
46267      
46268 };
46269
46270 Roo.extend(Roo.bootstrap.panel.Grid, Roo.bootstrap.panel.Content,
46271 {
46272   
46273     getId : function(){
46274         return this.grid.id;
46275     },
46276     
46277     /**
46278      * Returns the grid for this panel
46279      * @return {Roo.bootstrap.Table} 
46280      */
46281     getGrid : function(){
46282         return this.grid;    
46283     },
46284     
46285     setSize : function(width, height)
46286     {
46287      
46288         //if(!this.ignoreResize(width, height)){
46289             var grid = this.grid;
46290             var size = this.adjustForComponents(width, height);
46291             // tfoot is not a footer?
46292           
46293             
46294             var gridel = grid.getGridEl();
46295             gridel.setSize(size.width, size.height);
46296             
46297             var tbd = grid.getGridEl().select('tbody', true).first();
46298             var thd = grid.getGridEl().select('thead',true).first();
46299             var tbf= grid.getGridEl().select('tfoot', true).first();
46300
46301             if (tbf) {
46302                 size.height -= tbf.getHeight();
46303             }
46304             if (thd) {
46305                 size.height -= thd.getHeight();
46306             }
46307             
46308             tbd.setSize(size.width, size.height );
46309             // this is for the account management tab -seems to work there.
46310             var thd = grid.getGridEl().select('thead',true).first();
46311             //if (tbd) {
46312             //    tbd.setSize(size.width, size.height - thd.getHeight());
46313             //}
46314              
46315             grid.autoSize();
46316         //}
46317    
46318     },
46319      
46320     
46321     
46322     beforeSlide : function(){
46323         this.grid.getView().scroller.clip();
46324     },
46325     
46326     afterSlide : function(){
46327         this.grid.getView().scroller.unclip();
46328     },
46329     
46330     destroy : function(){
46331         this.grid.destroy();
46332         delete this.grid;
46333         Roo.bootstrap.panel.Grid.superclass.destroy.call(this); 
46334     }
46335 });
46336
46337 /**
46338  * @class Roo.bootstrap.panel.Nest
46339  * @extends Roo.bootstrap.panel.Content
46340  * @constructor
46341  * Create a new Panel, that can contain a layout.Border.
46342  * 
46343  * 
46344  * @param {String/Object} config A string to set only the title or a config object
46345  */
46346 Roo.bootstrap.panel.Nest = function(config)
46347 {
46348     // construct with only one argument..
46349     /* FIXME - implement nicer consturctors
46350     if (layout.layout) {
46351         config = layout;
46352         layout = config.layout;
46353         delete config.layout;
46354     }
46355     if (layout.xtype && !layout.getEl) {
46356         // then layout needs constructing..
46357         layout = Roo.factory(layout, Roo);
46358     }
46359     */
46360     
46361     config.el =  config.layout.getEl();
46362     
46363     Roo.bootstrap.panel.Nest.superclass.constructor.call(this, config);
46364     
46365     config.layout.monitorWindowResize = false; // turn off autosizing
46366     this.layout = config.layout;
46367     this.layout.getEl().addClass("roo-layout-nested-layout");
46368     this.layout.parent = this;
46369     
46370     
46371     
46372     
46373 };
46374
46375 Roo.extend(Roo.bootstrap.panel.Nest, Roo.bootstrap.panel.Content, {
46376     /**
46377     * @cfg {Roo.BorderLayout} layout The layout for this panel
46378     */
46379     layout : false,
46380
46381     setSize : function(width, height){
46382         if(!this.ignoreResize(width, height)){
46383             var size = this.adjustForComponents(width, height);
46384             var el = this.layout.getEl();
46385             if (size.height < 1) {
46386                 el.setWidth(size.width);   
46387             } else {
46388                 el.setSize(size.width, size.height);
46389             }
46390             var touch = el.dom.offsetWidth;
46391             this.layout.layout();
46392             // ie requires a double layout on the first pass
46393             if(Roo.isIE && !this.initialized){
46394                 this.initialized = true;
46395                 this.layout.layout();
46396             }
46397         }
46398     },
46399     
46400     // activate all subpanels if not currently active..
46401     
46402     setActiveState : function(active){
46403         this.active = active;
46404         this.setActiveClass(active);
46405         
46406         if(!active){
46407             this.fireEvent("deactivate", this);
46408             return;
46409         }
46410         
46411         this.fireEvent("activate", this);
46412         // not sure if this should happen before or after..
46413         if (!this.layout) {
46414             return; // should not happen..
46415         }
46416         var reg = false;
46417         for (var r in this.layout.regions) {
46418             reg = this.layout.getRegion(r);
46419             if (reg.getActivePanel()) {
46420                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
46421                 reg.setActivePanel(reg.getActivePanel());
46422                 continue;
46423             }
46424             if (!reg.panels.length) {
46425                 continue;
46426             }
46427             reg.showPanel(reg.getPanel(0));
46428         }
46429         
46430         
46431         
46432         
46433     },
46434     
46435     /**
46436      * Returns the nested BorderLayout for this panel
46437      * @return {Roo.BorderLayout} 
46438      */
46439     getLayout : function(){
46440         return this.layout;
46441     },
46442     
46443      /**
46444      * Adds a xtype elements to the layout of the nested panel
46445      * <pre><code>
46446
46447 panel.addxtype({
46448        xtype : 'ContentPanel',
46449        region: 'west',
46450        items: [ .... ]
46451    }
46452 );
46453
46454 panel.addxtype({
46455         xtype : 'NestedLayoutPanel',
46456         region: 'west',
46457         layout: {
46458            center: { },
46459            west: { }   
46460         },
46461         items : [ ... list of content panels or nested layout panels.. ]
46462    }
46463 );
46464 </code></pre>
46465      * @param {Object} cfg Xtype definition of item to add.
46466      */
46467     addxtype : function(cfg) {
46468         return this.layout.addxtype(cfg);
46469     
46470     }
46471 });/*
46472  * Based on:
46473  * Ext JS Library 1.1.1
46474  * Copyright(c) 2006-2007, Ext JS, LLC.
46475  *
46476  * Originally Released Under LGPL - original licence link has changed is not relivant.
46477  *
46478  * Fork - LGPL
46479  * <script type="text/javascript">
46480  */
46481 /**
46482  * @class Roo.TabPanel
46483  * @extends Roo.util.Observable
46484  * A lightweight tab container.
46485  * <br><br>
46486  * Usage:
46487  * <pre><code>
46488 // basic tabs 1, built from existing content
46489 var tabs = new Roo.TabPanel("tabs1");
46490 tabs.addTab("script", "View Script");
46491 tabs.addTab("markup", "View Markup");
46492 tabs.activate("script");
46493
46494 // more advanced tabs, built from javascript
46495 var jtabs = new Roo.TabPanel("jtabs");
46496 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
46497
46498 // set up the UpdateManager
46499 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
46500 var updater = tab2.getUpdateManager();
46501 updater.setDefaultUrl("ajax1.htm");
46502 tab2.on('activate', updater.refresh, updater, true);
46503
46504 // Use setUrl for Ajax loading
46505 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
46506 tab3.setUrl("ajax2.htm", null, true);
46507
46508 // Disabled tab
46509 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
46510 tab4.disable();
46511
46512 jtabs.activate("jtabs-1");
46513  * </code></pre>
46514  * @constructor
46515  * Create a new TabPanel.
46516  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
46517  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
46518  */
46519 Roo.bootstrap.panel.Tabs = function(config){
46520     /**
46521     * The container element for this TabPanel.
46522     * @type Roo.Element
46523     */
46524     this.el = Roo.get(config.el);
46525     delete config.el;
46526     if(config){
46527         if(typeof config == "boolean"){
46528             this.tabPosition = config ? "bottom" : "top";
46529         }else{
46530             Roo.apply(this, config);
46531         }
46532     }
46533     
46534     if(this.tabPosition == "bottom"){
46535         // if tabs are at the bottom = create the body first.
46536         this.bodyEl = Roo.get(this.createBody(this.el.dom));
46537         this.el.addClass("roo-tabs-bottom");
46538     }
46539     // next create the tabs holders
46540     
46541     if (this.tabPosition == "west"){
46542         
46543         var reg = this.region; // fake it..
46544         while (reg) {
46545             if (!reg.mgr.parent) {
46546                 break;
46547             }
46548             reg = reg.mgr.parent.region;
46549         }
46550         Roo.log("got nest?");
46551         Roo.log(reg);
46552         if (reg.mgr.getRegion('west')) {
46553             var ctrdom = reg.mgr.getRegion('west').bodyEl.dom;
46554             this.stripWrap = Roo.get(this.createStrip(ctrdom ), true);
46555             this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
46556             this.stripEl.setVisibilityMode(Roo.Element.DISPLAY);
46557             this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
46558         
46559             
46560         }
46561         
46562         
46563     } else {
46564      
46565         this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
46566         this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
46567         this.stripEl.setVisibilityMode(Roo.Element.DISPLAY);
46568         this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
46569     }
46570     
46571     
46572     if(Roo.isIE){
46573         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
46574     }
46575     
46576     // finally - if tabs are at the top, then create the body last..
46577     if(this.tabPosition != "bottom"){
46578         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
46579          * @type Roo.Element
46580          */
46581         this.bodyEl = Roo.get(this.createBody(this.el.dom));
46582         this.el.addClass("roo-tabs-top");
46583     }
46584     this.items = [];
46585
46586     this.bodyEl.setStyle("position", "relative");
46587
46588     this.active = null;
46589     this.activateDelegate = this.activate.createDelegate(this);
46590
46591     this.addEvents({
46592         /**
46593          * @event tabchange
46594          * Fires when the active tab changes
46595          * @param {Roo.TabPanel} this
46596          * @param {Roo.TabPanelItem} activePanel The new active tab
46597          */
46598         "tabchange": true,
46599         /**
46600          * @event beforetabchange
46601          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
46602          * @param {Roo.TabPanel} this
46603          * @param {Object} e Set cancel to true on this object to cancel the tab change
46604          * @param {Roo.TabPanelItem} tab The tab being changed to
46605          */
46606         "beforetabchange" : true
46607     });
46608
46609     Roo.EventManager.onWindowResize(this.onResize, this);
46610     this.cpad = this.el.getPadding("lr");
46611     this.hiddenCount = 0;
46612
46613
46614     // toolbar on the tabbar support...
46615     if (this.toolbar) {
46616         alert("no toolbar support yet");
46617         this.toolbar  = false;
46618         /*
46619         var tcfg = this.toolbar;
46620         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
46621         this.toolbar = new Roo.Toolbar(tcfg);
46622         if (Roo.isSafari) {
46623             var tbl = tcfg.container.child('table', true);
46624             tbl.setAttribute('width', '100%');
46625         }
46626         */
46627         
46628     }
46629    
46630
46631
46632     Roo.bootstrap.panel.Tabs.superclass.constructor.call(this);
46633 };
46634
46635 Roo.extend(Roo.bootstrap.panel.Tabs, Roo.util.Observable, {
46636     /*
46637      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
46638      */
46639     tabPosition : "top",
46640     /*
46641      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
46642      */
46643     currentTabWidth : 0,
46644     /*
46645      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
46646      */
46647     minTabWidth : 40,
46648     /*
46649      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
46650      */
46651     maxTabWidth : 250,
46652     /*
46653      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
46654      */
46655     preferredTabWidth : 175,
46656     /*
46657      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
46658      */
46659     resizeTabs : false,
46660     /*
46661      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
46662      */
46663     monitorResize : true,
46664     /*
46665      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
46666      */
46667     toolbar : false,  // set by caller..
46668     
46669     region : false, /// set by caller
46670     
46671     disableTooltips : true, // not used yet...
46672
46673     /**
46674      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
46675      * @param {String} id The id of the div to use <b>or create</b>
46676      * @param {String} text The text for the tab
46677      * @param {String} content (optional) Content to put in the TabPanelItem body
46678      * @param {Boolean} closable (optional) True to create a close icon on the tab
46679      * @return {Roo.TabPanelItem} The created TabPanelItem
46680      */
46681     addTab : function(id, text, content, closable, tpl)
46682     {
46683         var item = new Roo.bootstrap.panel.TabItem({
46684             panel: this,
46685             id : id,
46686             text : text,
46687             closable : closable,
46688             tpl : tpl
46689         });
46690         this.addTabItem(item);
46691         if(content){
46692             item.setContent(content);
46693         }
46694         return item;
46695     },
46696
46697     /**
46698      * Returns the {@link Roo.TabPanelItem} with the specified id/index
46699      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
46700      * @return {Roo.TabPanelItem}
46701      */
46702     getTab : function(id){
46703         return this.items[id];
46704     },
46705
46706     /**
46707      * Hides the {@link Roo.TabPanelItem} with the specified id/index
46708      * @param {String/Number} id The id or index of the TabPanelItem to hide.
46709      */
46710     hideTab : function(id){
46711         var t = this.items[id];
46712         if(!t.isHidden()){
46713            t.setHidden(true);
46714            this.hiddenCount++;
46715            this.autoSizeTabs();
46716         }
46717     },
46718
46719     /**
46720      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
46721      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
46722      */
46723     unhideTab : function(id){
46724         var t = this.items[id];
46725         if(t.isHidden()){
46726            t.setHidden(false);
46727            this.hiddenCount--;
46728            this.autoSizeTabs();
46729         }
46730     },
46731
46732     /**
46733      * Adds an existing {@link Roo.TabPanelItem}.
46734      * @param {Roo.TabPanelItem} item The TabPanelItem to add
46735      */
46736     addTabItem : function(item)
46737     {
46738         this.items[item.id] = item;
46739         this.items.push(item);
46740         this.autoSizeTabs();
46741       //  if(this.resizeTabs){
46742     //       item.setWidth(this.currentTabWidth || this.preferredTabWidth);
46743   //         this.autoSizeTabs();
46744 //        }else{
46745 //            item.autoSize();
46746        // }
46747     },
46748
46749     /**
46750      * Removes a {@link Roo.TabPanelItem}.
46751      * @param {String/Number} id The id or index of the TabPanelItem to remove.
46752      */
46753     removeTab : function(id){
46754         var items = this.items;
46755         var tab = items[id];
46756         if(!tab) { return; }
46757         var index = items.indexOf(tab);
46758         if(this.active == tab && items.length > 1){
46759             var newTab = this.getNextAvailable(index);
46760             if(newTab) {
46761                 newTab.activate();
46762             }
46763         }
46764         this.stripEl.dom.removeChild(tab.pnode.dom);
46765         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
46766             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
46767         }
46768         items.splice(index, 1);
46769         delete this.items[tab.id];
46770         tab.fireEvent("close", tab);
46771         tab.purgeListeners();
46772         this.autoSizeTabs();
46773     },
46774
46775     getNextAvailable : function(start){
46776         var items = this.items;
46777         var index = start;
46778         // look for a next tab that will slide over to
46779         // replace the one being removed
46780         while(index < items.length){
46781             var item = items[++index];
46782             if(item && !item.isHidden()){
46783                 return item;
46784             }
46785         }
46786         // if one isn't found select the previous tab (on the left)
46787         index = start;
46788         while(index >= 0){
46789             var item = items[--index];
46790             if(item && !item.isHidden()){
46791                 return item;
46792             }
46793         }
46794         return null;
46795     },
46796
46797     /**
46798      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
46799      * @param {String/Number} id The id or index of the TabPanelItem to disable.
46800      */
46801     disableTab : function(id){
46802         var tab = this.items[id];
46803         if(tab && this.active != tab){
46804             tab.disable();
46805         }
46806     },
46807
46808     /**
46809      * Enables a {@link Roo.TabPanelItem} that is disabled.
46810      * @param {String/Number} id The id or index of the TabPanelItem to enable.
46811      */
46812     enableTab : function(id){
46813         var tab = this.items[id];
46814         tab.enable();
46815     },
46816
46817     /**
46818      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
46819      * @param {String/Number} id The id or index of the TabPanelItem to activate.
46820      * @return {Roo.TabPanelItem} The TabPanelItem.
46821      */
46822     activate : function(id)
46823     {
46824         //Roo.log('activite:'  + id);
46825         
46826         var tab = this.items[id];
46827         if(!tab){
46828             return null;
46829         }
46830         if(tab == this.active || tab.disabled){
46831             return tab;
46832         }
46833         var e = {};
46834         this.fireEvent("beforetabchange", this, e, tab);
46835         if(e.cancel !== true && !tab.disabled){
46836             if(this.active){
46837                 this.active.hide();
46838             }
46839             this.active = this.items[id];
46840             this.active.show();
46841             this.fireEvent("tabchange", this, this.active);
46842         }
46843         return tab;
46844     },
46845
46846     /**
46847      * Gets the active {@link Roo.TabPanelItem}.
46848      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
46849      */
46850     getActiveTab : function(){
46851         return this.active;
46852     },
46853
46854     /**
46855      * Updates the tab body element to fit the height of the container element
46856      * for overflow scrolling
46857      * @param {Number} targetHeight (optional) Override the starting height from the elements height
46858      */
46859     syncHeight : function(targetHeight){
46860         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
46861         var bm = this.bodyEl.getMargins();
46862         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
46863         this.bodyEl.setHeight(newHeight);
46864         return newHeight;
46865     },
46866
46867     onResize : function(){
46868         if(this.monitorResize){
46869             this.autoSizeTabs();
46870         }
46871     },
46872
46873     /**
46874      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
46875      */
46876     beginUpdate : function(){
46877         this.updating = true;
46878     },
46879
46880     /**
46881      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
46882      */
46883     endUpdate : function(){
46884         this.updating = false;
46885         this.autoSizeTabs();
46886     },
46887
46888     /**
46889      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
46890      */
46891     autoSizeTabs : function()
46892     {
46893         var count = this.items.length;
46894         var vcount = count - this.hiddenCount;
46895         
46896         if (vcount < 2) {
46897             this.stripEl.hide();
46898         } else {
46899             this.stripEl.show();
46900         }
46901         
46902         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
46903             return;
46904         }
46905         
46906         
46907         var w = Math.max(this.el.getWidth() - this.cpad, 10);
46908         var availWidth = Math.floor(w / vcount);
46909         var b = this.stripBody;
46910         if(b.getWidth() > w){
46911             var tabs = this.items;
46912             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
46913             if(availWidth < this.minTabWidth){
46914                 /*if(!this.sleft){    // incomplete scrolling code
46915                     this.createScrollButtons();
46916                 }
46917                 this.showScroll();
46918                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
46919             }
46920         }else{
46921             if(this.currentTabWidth < this.preferredTabWidth){
46922                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
46923             }
46924         }
46925     },
46926
46927     /**
46928      * Returns the number of tabs in this TabPanel.
46929      * @return {Number}
46930      */
46931      getCount : function(){
46932          return this.items.length;
46933      },
46934
46935     /**
46936      * Resizes all the tabs to the passed width
46937      * @param {Number} The new width
46938      */
46939     setTabWidth : function(width){
46940         this.currentTabWidth = width;
46941         for(var i = 0, len = this.items.length; i < len; i++) {
46942                 if(!this.items[i].isHidden()) {
46943                 this.items[i].setWidth(width);
46944             }
46945         }
46946     },
46947
46948     /**
46949      * Destroys this TabPanel
46950      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
46951      */
46952     destroy : function(removeEl){
46953         Roo.EventManager.removeResizeListener(this.onResize, this);
46954         for(var i = 0, len = this.items.length; i < len; i++){
46955             this.items[i].purgeListeners();
46956         }
46957         if(removeEl === true){
46958             this.el.update("");
46959             this.el.remove();
46960         }
46961     },
46962     
46963     createStrip : function(container)
46964     {
46965         var strip = document.createElement("nav");
46966         strip.className = Roo.bootstrap.version == 4 ?
46967             "navbar-light bg-light" : 
46968             "navbar navbar-default"; //"x-tabs-wrap";
46969         container.appendChild(strip);
46970         return strip;
46971     },
46972     
46973     createStripList : function(strip)
46974     {
46975         // div wrapper for retard IE
46976         // returns the "tr" element.
46977         strip.innerHTML = '<ul class="nav nav-tabs" role="tablist"></ul>';
46978         //'<div class="x-tabs-strip-wrap">'+
46979           //  '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
46980           //  '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
46981         return strip.firstChild; //.firstChild.firstChild.firstChild;
46982     },
46983     createBody : function(container)
46984     {
46985         var body = document.createElement("div");
46986         Roo.id(body, "tab-body");
46987         //Roo.fly(body).addClass("x-tabs-body");
46988         Roo.fly(body).addClass("tab-content");
46989         container.appendChild(body);
46990         return body;
46991     },
46992     createItemBody :function(bodyEl, id){
46993         var body = Roo.getDom(id);
46994         if(!body){
46995             body = document.createElement("div");
46996             body.id = id;
46997         }
46998         //Roo.fly(body).addClass("x-tabs-item-body");
46999         Roo.fly(body).addClass("tab-pane");
47000          bodyEl.insertBefore(body, bodyEl.firstChild);
47001         return body;
47002     },
47003     /** @private */
47004     createStripElements :  function(stripEl, text, closable, tpl)
47005     {
47006         var td = document.createElement("li"); // was td..
47007         td.className = 'nav-item';
47008         
47009         //stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
47010         
47011         
47012         stripEl.appendChild(td);
47013         /*if(closable){
47014             td.className = "x-tabs-closable";
47015             if(!this.closeTpl){
47016                 this.closeTpl = new Roo.Template(
47017                    '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
47018                    '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
47019                    '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
47020                 );
47021             }
47022             var el = this.closeTpl.overwrite(td, {"text": text});
47023             var close = el.getElementsByTagName("div")[0];
47024             var inner = el.getElementsByTagName("em")[0];
47025             return {"el": el, "close": close, "inner": inner};
47026         } else {
47027         */
47028         // not sure what this is..
47029 //            if(!this.tabTpl){
47030                 //this.tabTpl = new Roo.Template(
47031                 //   '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
47032                 //   '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
47033                 //);
47034 //                this.tabTpl = new Roo.Template(
47035 //                   '<a href="#">' +
47036 //                   '<span unselectable="on"' +
47037 //                            (this.disableTooltips ? '' : ' title="{text}"') +
47038 //                            ' >{text}</span></a>'
47039 //                );
47040 //                
47041 //            }
47042
47043
47044             var template = tpl || this.tabTpl || false;
47045             
47046             if(!template){
47047                 template =  new Roo.Template(
47048                         Roo.bootstrap.version == 4 ? 
47049                             (
47050                                 '<a class="nav-link" href="#" unselectable="on"' +
47051                                      (this.disableTooltips ? '' : ' title="{text}"') +
47052                                      ' >{text}</a>'
47053                             ) : (
47054                                 '<a class="nav-link" href="#">' +
47055                                 '<span unselectable="on"' +
47056                                          (this.disableTooltips ? '' : ' title="{text}"') +
47057                                     ' >{text}</span></a>'
47058                             )
47059                 );
47060             }
47061             
47062             switch (typeof(template)) {
47063                 case 'object' :
47064                     break;
47065                 case 'string' :
47066                     template = new Roo.Template(template);
47067                     break;
47068                 default :
47069                     break;
47070             }
47071             
47072             var el = template.overwrite(td, {"text": text});
47073             
47074             var inner = el.getElementsByTagName("span")[0];
47075             
47076             return {"el": el, "inner": inner};
47077             
47078     }
47079         
47080     
47081 });
47082
47083 /**
47084  * @class Roo.TabPanelItem
47085  * @extends Roo.util.Observable
47086  * Represents an individual item (tab plus body) in a TabPanel.
47087  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
47088  * @param {String} id The id of this TabPanelItem
47089  * @param {String} text The text for the tab of this TabPanelItem
47090  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
47091  */
47092 Roo.bootstrap.panel.TabItem = function(config){
47093     /**
47094      * The {@link Roo.TabPanel} this TabPanelItem belongs to
47095      * @type Roo.TabPanel
47096      */
47097     this.tabPanel = config.panel;
47098     /**
47099      * The id for this TabPanelItem
47100      * @type String
47101      */
47102     this.id = config.id;
47103     /** @private */
47104     this.disabled = false;
47105     /** @private */
47106     this.text = config.text;
47107     /** @private */
47108     this.loaded = false;
47109     this.closable = config.closable;
47110
47111     /**
47112      * The body element for this TabPanelItem.
47113      * @type Roo.Element
47114      */
47115     this.bodyEl = Roo.get(this.tabPanel.createItemBody(this.tabPanel.bodyEl.dom, config.id));
47116     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
47117     this.bodyEl.setStyle("display", "block");
47118     this.bodyEl.setStyle("zoom", "1");
47119     //this.hideAction();
47120
47121     var els = this.tabPanel.createStripElements(this.tabPanel.stripEl.dom, config.text, config.closable, config.tpl);
47122     /** @private */
47123     this.el = Roo.get(els.el);
47124     this.inner = Roo.get(els.inner, true);
47125      this.textEl = Roo.bootstrap.version == 4 ?
47126         this.el : Roo.get(this.el.dom.firstChild, true);
47127
47128     this.pnode = this.linode = Roo.get(els.el.parentNode, true);
47129     this.status_node = Roo.bootstrap.version == 4 ? this.el : this.linode;
47130
47131     
47132 //    this.el.on("mousedown", this.onTabMouseDown, this);
47133     this.el.on("click", this.onTabClick, this);
47134     /** @private */
47135     if(config.closable){
47136         var c = Roo.get(els.close, true);
47137         c.dom.title = this.closeText;
47138         c.addClassOnOver("close-over");
47139         c.on("click", this.closeClick, this);
47140      }
47141
47142     this.addEvents({
47143          /**
47144          * @event activate
47145          * Fires when this tab becomes the active tab.
47146          * @param {Roo.TabPanel} tabPanel The parent TabPanel
47147          * @param {Roo.TabPanelItem} this
47148          */
47149         "activate": true,
47150         /**
47151          * @event beforeclose
47152          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
47153          * @param {Roo.TabPanelItem} this
47154          * @param {Object} e Set cancel to true on this object to cancel the close.
47155          */
47156         "beforeclose": true,
47157         /**
47158          * @event close
47159          * Fires when this tab is closed.
47160          * @param {Roo.TabPanelItem} this
47161          */
47162          "close": true,
47163         /**
47164          * @event deactivate
47165          * Fires when this tab is no longer the active tab.
47166          * @param {Roo.TabPanel} tabPanel The parent TabPanel
47167          * @param {Roo.TabPanelItem} this
47168          */
47169          "deactivate" : true
47170     });
47171     this.hidden = false;
47172
47173     Roo.bootstrap.panel.TabItem.superclass.constructor.call(this);
47174 };
47175
47176 Roo.extend(Roo.bootstrap.panel.TabItem, Roo.util.Observable,
47177            {
47178     purgeListeners : function(){
47179        Roo.util.Observable.prototype.purgeListeners.call(this);
47180        this.el.removeAllListeners();
47181     },
47182     /**
47183      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
47184      */
47185     show : function(){
47186         this.status_node.addClass("active");
47187         this.showAction();
47188         if(Roo.isOpera){
47189             this.tabPanel.stripWrap.repaint();
47190         }
47191         this.fireEvent("activate", this.tabPanel, this);
47192     },
47193
47194     /**
47195      * Returns true if this tab is the active tab.
47196      * @return {Boolean}
47197      */
47198     isActive : function(){
47199         return this.tabPanel.getActiveTab() == this;
47200     },
47201
47202     /**
47203      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
47204      */
47205     hide : function(){
47206         this.status_node.removeClass("active");
47207         this.hideAction();
47208         this.fireEvent("deactivate", this.tabPanel, this);
47209     },
47210
47211     hideAction : function(){
47212         this.bodyEl.hide();
47213         this.bodyEl.setStyle("position", "absolute");
47214         this.bodyEl.setLeft("-20000px");
47215         this.bodyEl.setTop("-20000px");
47216     },
47217
47218     showAction : function(){
47219         this.bodyEl.setStyle("position", "relative");
47220         this.bodyEl.setTop("");
47221         this.bodyEl.setLeft("");
47222         this.bodyEl.show();
47223     },
47224
47225     /**
47226      * Set the tooltip for the tab.
47227      * @param {String} tooltip The tab's tooltip
47228      */
47229     setTooltip : function(text){
47230         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
47231             this.textEl.dom.qtip = text;
47232             this.textEl.dom.removeAttribute('title');
47233         }else{
47234             this.textEl.dom.title = text;
47235         }
47236     },
47237
47238     onTabClick : function(e){
47239         e.preventDefault();
47240         this.tabPanel.activate(this.id);
47241     },
47242
47243     onTabMouseDown : function(e){
47244         e.preventDefault();
47245         this.tabPanel.activate(this.id);
47246     },
47247 /*
47248     getWidth : function(){
47249         return this.inner.getWidth();
47250     },
47251
47252     setWidth : function(width){
47253         var iwidth = width - this.linode.getPadding("lr");
47254         this.inner.setWidth(iwidth);
47255         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
47256         this.linode.setWidth(width);
47257     },
47258 */
47259     /**
47260      * Show or hide the tab
47261      * @param {Boolean} hidden True to hide or false to show.
47262      */
47263     setHidden : function(hidden){
47264         this.hidden = hidden;
47265         this.linode.setStyle("display", hidden ? "none" : "");
47266     },
47267
47268     /**
47269      * Returns true if this tab is "hidden"
47270      * @return {Boolean}
47271      */
47272     isHidden : function(){
47273         return this.hidden;
47274     },
47275
47276     /**
47277      * Returns the text for this tab
47278      * @return {String}
47279      */
47280     getText : function(){
47281         return this.text;
47282     },
47283     /*
47284     autoSize : function(){
47285         //this.el.beginMeasure();
47286         this.textEl.setWidth(1);
47287         /*
47288          *  #2804 [new] Tabs in Roojs
47289          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
47290          */
47291         //this.setWidth(this.textEl.dom.scrollWidth+this.linode.getPadding("lr")+this.inner.getPadding("lr") + 2);
47292         //this.el.endMeasure();
47293     //},
47294
47295     /**
47296      * Sets the text for the tab (Note: this also sets the tooltip text)
47297      * @param {String} text The tab's text and tooltip
47298      */
47299     setText : function(text){
47300         this.text = text;
47301         this.textEl.update(text);
47302         this.setTooltip(text);
47303         //if(!this.tabPanel.resizeTabs){
47304         //    this.autoSize();
47305         //}
47306     },
47307     /**
47308      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
47309      */
47310     activate : function(){
47311         this.tabPanel.activate(this.id);
47312     },
47313
47314     /**
47315      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
47316      */
47317     disable : function(){
47318         if(this.tabPanel.active != this){
47319             this.disabled = true;
47320             this.status_node.addClass("disabled");
47321         }
47322     },
47323
47324     /**
47325      * Enables this TabPanelItem if it was previously disabled.
47326      */
47327     enable : function(){
47328         this.disabled = false;
47329         this.status_node.removeClass("disabled");
47330     },
47331
47332     /**
47333      * Sets the content for this TabPanelItem.
47334      * @param {String} content The content
47335      * @param {Boolean} loadScripts true to look for and load scripts
47336      */
47337     setContent : function(content, loadScripts){
47338         this.bodyEl.update(content, loadScripts);
47339     },
47340
47341     /**
47342      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
47343      * @return {Roo.UpdateManager} The UpdateManager
47344      */
47345     getUpdateManager : function(){
47346         return this.bodyEl.getUpdateManager();
47347     },
47348
47349     /**
47350      * Set a URL to be used to load the content for this TabPanelItem.
47351      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
47352      * @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)
47353      * @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)
47354      * @return {Roo.UpdateManager} The UpdateManager
47355      */
47356     setUrl : function(url, params, loadOnce){
47357         if(this.refreshDelegate){
47358             this.un('activate', this.refreshDelegate);
47359         }
47360         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
47361         this.on("activate", this.refreshDelegate);
47362         return this.bodyEl.getUpdateManager();
47363     },
47364
47365     /** @private */
47366     _handleRefresh : function(url, params, loadOnce){
47367         if(!loadOnce || !this.loaded){
47368             var updater = this.bodyEl.getUpdateManager();
47369             updater.update(url, params, this._setLoaded.createDelegate(this));
47370         }
47371     },
47372
47373     /**
47374      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
47375      *   Will fail silently if the setUrl method has not been called.
47376      *   This does not activate the panel, just updates its content.
47377      */
47378     refresh : function(){
47379         if(this.refreshDelegate){
47380            this.loaded = false;
47381            this.refreshDelegate();
47382         }
47383     },
47384
47385     /** @private */
47386     _setLoaded : function(){
47387         this.loaded = true;
47388     },
47389
47390     /** @private */
47391     closeClick : function(e){
47392         var o = {};
47393         e.stopEvent();
47394         this.fireEvent("beforeclose", this, o);
47395         if(o.cancel !== true){
47396             this.tabPanel.removeTab(this.id);
47397         }
47398     },
47399     /**
47400      * The text displayed in the tooltip for the close icon.
47401      * @type String
47402      */
47403     closeText : "Close this tab"
47404 });
47405 /**
47406 *    This script refer to:
47407 *    Title: International Telephone Input
47408 *    Author: Jack O'Connor
47409 *    Code version:  v12.1.12
47410 *    Availability: https://github.com/jackocnr/intl-tel-input.git
47411 **/
47412
47413 Roo.bootstrap.form.PhoneInputData = function() {
47414     var d = [
47415       [
47416         "Afghanistan (‫افغانستان‬‎)",
47417         "af",
47418         "93"
47419       ],
47420       [
47421         "Albania (Shqipëri)",
47422         "al",
47423         "355"
47424       ],
47425       [
47426         "Algeria (‫الجزائر‬‎)",
47427         "dz",
47428         "213"
47429       ],
47430       [
47431         "American Samoa",
47432         "as",
47433         "1684"
47434       ],
47435       [
47436         "Andorra",
47437         "ad",
47438         "376"
47439       ],
47440       [
47441         "Angola",
47442         "ao",
47443         "244"
47444       ],
47445       [
47446         "Anguilla",
47447         "ai",
47448         "1264"
47449       ],
47450       [
47451         "Antigua and Barbuda",
47452         "ag",
47453         "1268"
47454       ],
47455       [
47456         "Argentina",
47457         "ar",
47458         "54"
47459       ],
47460       [
47461         "Armenia (Հայաստան)",
47462         "am",
47463         "374"
47464       ],
47465       [
47466         "Aruba",
47467         "aw",
47468         "297"
47469       ],
47470       [
47471         "Australia",
47472         "au",
47473         "61",
47474         0
47475       ],
47476       [
47477         "Austria (Österreich)",
47478         "at",
47479         "43"
47480       ],
47481       [
47482         "Azerbaijan (Azərbaycan)",
47483         "az",
47484         "994"
47485       ],
47486       [
47487         "Bahamas",
47488         "bs",
47489         "1242"
47490       ],
47491       [
47492         "Bahrain (‫البحرين‬‎)",
47493         "bh",
47494         "973"
47495       ],
47496       [
47497         "Bangladesh (বাংলাদেশ)",
47498         "bd",
47499         "880"
47500       ],
47501       [
47502         "Barbados",
47503         "bb",
47504         "1246"
47505       ],
47506       [
47507         "Belarus (Беларусь)",
47508         "by",
47509         "375"
47510       ],
47511       [
47512         "Belgium (België)",
47513         "be",
47514         "32"
47515       ],
47516       [
47517         "Belize",
47518         "bz",
47519         "501"
47520       ],
47521       [
47522         "Benin (Bénin)",
47523         "bj",
47524         "229"
47525       ],
47526       [
47527         "Bermuda",
47528         "bm",
47529         "1441"
47530       ],
47531       [
47532         "Bhutan (འབྲུག)",
47533         "bt",
47534         "975"
47535       ],
47536       [
47537         "Bolivia",
47538         "bo",
47539         "591"
47540       ],
47541       [
47542         "Bosnia and Herzegovina (Босна и Херцеговина)",
47543         "ba",
47544         "387"
47545       ],
47546       [
47547         "Botswana",
47548         "bw",
47549         "267"
47550       ],
47551       [
47552         "Brazil (Brasil)",
47553         "br",
47554         "55"
47555       ],
47556       [
47557         "British Indian Ocean Territory",
47558         "io",
47559         "246"
47560       ],
47561       [
47562         "British Virgin Islands",
47563         "vg",
47564         "1284"
47565       ],
47566       [
47567         "Brunei",
47568         "bn",
47569         "673"
47570       ],
47571       [
47572         "Bulgaria (България)",
47573         "bg",
47574         "359"
47575       ],
47576       [
47577         "Burkina Faso",
47578         "bf",
47579         "226"
47580       ],
47581       [
47582         "Burundi (Uburundi)",
47583         "bi",
47584         "257"
47585       ],
47586       [
47587         "Cambodia (កម្ពុជា)",
47588         "kh",
47589         "855"
47590       ],
47591       [
47592         "Cameroon (Cameroun)",
47593         "cm",
47594         "237"
47595       ],
47596       [
47597         "Canada",
47598         "ca",
47599         "1",
47600         1,
47601         ["204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905"]
47602       ],
47603       [
47604         "Cape Verde (Kabu Verdi)",
47605         "cv",
47606         "238"
47607       ],
47608       [
47609         "Caribbean Netherlands",
47610         "bq",
47611         "599",
47612         1
47613       ],
47614       [
47615         "Cayman Islands",
47616         "ky",
47617         "1345"
47618       ],
47619       [
47620         "Central African Republic (République centrafricaine)",
47621         "cf",
47622         "236"
47623       ],
47624       [
47625         "Chad (Tchad)",
47626         "td",
47627         "235"
47628       ],
47629       [
47630         "Chile",
47631         "cl",
47632         "56"
47633       ],
47634       [
47635         "China (中国)",
47636         "cn",
47637         "86"
47638       ],
47639       [
47640         "Christmas Island",
47641         "cx",
47642         "61",
47643         2
47644       ],
47645       [
47646         "Cocos (Keeling) Islands",
47647         "cc",
47648         "61",
47649         1
47650       ],
47651       [
47652         "Colombia",
47653         "co",
47654         "57"
47655       ],
47656       [
47657         "Comoros (‫جزر القمر‬‎)",
47658         "km",
47659         "269"
47660       ],
47661       [
47662         "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)",
47663         "cd",
47664         "243"
47665       ],
47666       [
47667         "Congo (Republic) (Congo-Brazzaville)",
47668         "cg",
47669         "242"
47670       ],
47671       [
47672         "Cook Islands",
47673         "ck",
47674         "682"
47675       ],
47676       [
47677         "Costa Rica",
47678         "cr",
47679         "506"
47680       ],
47681       [
47682         "Côte d’Ivoire",
47683         "ci",
47684         "225"
47685       ],
47686       [
47687         "Croatia (Hrvatska)",
47688         "hr",
47689         "385"
47690       ],
47691       [
47692         "Cuba",
47693         "cu",
47694         "53"
47695       ],
47696       [
47697         "Curaçao",
47698         "cw",
47699         "599",
47700         0
47701       ],
47702       [
47703         "Cyprus (Κύπρος)",
47704         "cy",
47705         "357"
47706       ],
47707       [
47708         "Czech Republic (Česká republika)",
47709         "cz",
47710         "420"
47711       ],
47712       [
47713         "Denmark (Danmark)",
47714         "dk",
47715         "45"
47716       ],
47717       [
47718         "Djibouti",
47719         "dj",
47720         "253"
47721       ],
47722       [
47723         "Dominica",
47724         "dm",
47725         "1767"
47726       ],
47727       [
47728         "Dominican Republic (República Dominicana)",
47729         "do",
47730         "1",
47731         2,
47732         ["809", "829", "849"]
47733       ],
47734       [
47735         "Ecuador",
47736         "ec",
47737         "593"
47738       ],
47739       [
47740         "Egypt (‫مصر‬‎)",
47741         "eg",
47742         "20"
47743       ],
47744       [
47745         "El Salvador",
47746         "sv",
47747         "503"
47748       ],
47749       [
47750         "Equatorial Guinea (Guinea Ecuatorial)",
47751         "gq",
47752         "240"
47753       ],
47754       [
47755         "Eritrea",
47756         "er",
47757         "291"
47758       ],
47759       [
47760         "Estonia (Eesti)",
47761         "ee",
47762         "372"
47763       ],
47764       [
47765         "Ethiopia",
47766         "et",
47767         "251"
47768       ],
47769       [
47770         "Falkland Islands (Islas Malvinas)",
47771         "fk",
47772         "500"
47773       ],
47774       [
47775         "Faroe Islands (Føroyar)",
47776         "fo",
47777         "298"
47778       ],
47779       [
47780         "Fiji",
47781         "fj",
47782         "679"
47783       ],
47784       [
47785         "Finland (Suomi)",
47786         "fi",
47787         "358",
47788         0
47789       ],
47790       [
47791         "France",
47792         "fr",
47793         "33"
47794       ],
47795       [
47796         "French Guiana (Guyane française)",
47797         "gf",
47798         "594"
47799       ],
47800       [
47801         "French Polynesia (Polynésie française)",
47802         "pf",
47803         "689"
47804       ],
47805       [
47806         "Gabon",
47807         "ga",
47808         "241"
47809       ],
47810       [
47811         "Gambia",
47812         "gm",
47813         "220"
47814       ],
47815       [
47816         "Georgia (საქართველო)",
47817         "ge",
47818         "995"
47819       ],
47820       [
47821         "Germany (Deutschland)",
47822         "de",
47823         "49"
47824       ],
47825       [
47826         "Ghana (Gaana)",
47827         "gh",
47828         "233"
47829       ],
47830       [
47831         "Gibraltar",
47832         "gi",
47833         "350"
47834       ],
47835       [
47836         "Greece (Ελλάδα)",
47837         "gr",
47838         "30"
47839       ],
47840       [
47841         "Greenland (Kalaallit Nunaat)",
47842         "gl",
47843         "299"
47844       ],
47845       [
47846         "Grenada",
47847         "gd",
47848         "1473"
47849       ],
47850       [
47851         "Guadeloupe",
47852         "gp",
47853         "590",
47854         0
47855       ],
47856       [
47857         "Guam",
47858         "gu",
47859         "1671"
47860       ],
47861       [
47862         "Guatemala",
47863         "gt",
47864         "502"
47865       ],
47866       [
47867         "Guernsey",
47868         "gg",
47869         "44",
47870         1
47871       ],
47872       [
47873         "Guinea (Guinée)",
47874         "gn",
47875         "224"
47876       ],
47877       [
47878         "Guinea-Bissau (Guiné Bissau)",
47879         "gw",
47880         "245"
47881       ],
47882       [
47883         "Guyana",
47884         "gy",
47885         "592"
47886       ],
47887       [
47888         "Haiti",
47889         "ht",
47890         "509"
47891       ],
47892       [
47893         "Honduras",
47894         "hn",
47895         "504"
47896       ],
47897       [
47898         "Hong Kong (香港)",
47899         "hk",
47900         "852"
47901       ],
47902       [
47903         "Hungary (Magyarország)",
47904         "hu",
47905         "36"
47906       ],
47907       [
47908         "Iceland (Ísland)",
47909         "is",
47910         "354"
47911       ],
47912       [
47913         "India (भारत)",
47914         "in",
47915         "91"
47916       ],
47917       [
47918         "Indonesia",
47919         "id",
47920         "62"
47921       ],
47922       [
47923         "Iran (‫ایران‬‎)",
47924         "ir",
47925         "98"
47926       ],
47927       [
47928         "Iraq (‫العراق‬‎)",
47929         "iq",
47930         "964"
47931       ],
47932       [
47933         "Ireland",
47934         "ie",
47935         "353"
47936       ],
47937       [
47938         "Isle of Man",
47939         "im",
47940         "44",
47941         2
47942       ],
47943       [
47944         "Israel (‫ישראל‬‎)",
47945         "il",
47946         "972"
47947       ],
47948       [
47949         "Italy (Italia)",
47950         "it",
47951         "39",
47952         0
47953       ],
47954       [
47955         "Jamaica",
47956         "jm",
47957         "1876"
47958       ],
47959       [
47960         "Japan (日本)",
47961         "jp",
47962         "81"
47963       ],
47964       [
47965         "Jersey",
47966         "je",
47967         "44",
47968         3
47969       ],
47970       [
47971         "Jordan (‫الأردن‬‎)",
47972         "jo",
47973         "962"
47974       ],
47975       [
47976         "Kazakhstan (Казахстан)",
47977         "kz",
47978         "7",
47979         1
47980       ],
47981       [
47982         "Kenya",
47983         "ke",
47984         "254"
47985       ],
47986       [
47987         "Kiribati",
47988         "ki",
47989         "686"
47990       ],
47991       [
47992         "Kosovo",
47993         "xk",
47994         "383"
47995       ],
47996       [
47997         "Kuwait (‫الكويت‬‎)",
47998         "kw",
47999         "965"
48000       ],
48001       [
48002         "Kyrgyzstan (Кыргызстан)",
48003         "kg",
48004         "996"
48005       ],
48006       [
48007         "Laos (ລາວ)",
48008         "la",
48009         "856"
48010       ],
48011       [
48012         "Latvia (Latvija)",
48013         "lv",
48014         "371"
48015       ],
48016       [
48017         "Lebanon (‫لبنان‬‎)",
48018         "lb",
48019         "961"
48020       ],
48021       [
48022         "Lesotho",
48023         "ls",
48024         "266"
48025       ],
48026       [
48027         "Liberia",
48028         "lr",
48029         "231"
48030       ],
48031       [
48032         "Libya (‫ليبيا‬‎)",
48033         "ly",
48034         "218"
48035       ],
48036       [
48037         "Liechtenstein",
48038         "li",
48039         "423"
48040       ],
48041       [
48042         "Lithuania (Lietuva)",
48043         "lt",
48044         "370"
48045       ],
48046       [
48047         "Luxembourg",
48048         "lu",
48049         "352"
48050       ],
48051       [
48052         "Macau (澳門)",
48053         "mo",
48054         "853"
48055       ],
48056       [
48057         "Macedonia (FYROM) (Македонија)",
48058         "mk",
48059         "389"
48060       ],
48061       [
48062         "Madagascar (Madagasikara)",
48063         "mg",
48064         "261"
48065       ],
48066       [
48067         "Malawi",
48068         "mw",
48069         "265"
48070       ],
48071       [
48072         "Malaysia",
48073         "my",
48074         "60"
48075       ],
48076       [
48077         "Maldives",
48078         "mv",
48079         "960"
48080       ],
48081       [
48082         "Mali",
48083         "ml",
48084         "223"
48085       ],
48086       [
48087         "Malta",
48088         "mt",
48089         "356"
48090       ],
48091       [
48092         "Marshall Islands",
48093         "mh",
48094         "692"
48095       ],
48096       [
48097         "Martinique",
48098         "mq",
48099         "596"
48100       ],
48101       [
48102         "Mauritania (‫موريتانيا‬‎)",
48103         "mr",
48104         "222"
48105       ],
48106       [
48107         "Mauritius (Moris)",
48108         "mu",
48109         "230"
48110       ],
48111       [
48112         "Mayotte",
48113         "yt",
48114         "262",
48115         1
48116       ],
48117       [
48118         "Mexico (México)",
48119         "mx",
48120         "52"
48121       ],
48122       [
48123         "Micronesia",
48124         "fm",
48125         "691"
48126       ],
48127       [
48128         "Moldova (Republica Moldova)",
48129         "md",
48130         "373"
48131       ],
48132       [
48133         "Monaco",
48134         "mc",
48135         "377"
48136       ],
48137       [
48138         "Mongolia (Монгол)",
48139         "mn",
48140         "976"
48141       ],
48142       [
48143         "Montenegro (Crna Gora)",
48144         "me",
48145         "382"
48146       ],
48147       [
48148         "Montserrat",
48149         "ms",
48150         "1664"
48151       ],
48152       [
48153         "Morocco (‫المغرب‬‎)",
48154         "ma",
48155         "212",
48156         0
48157       ],
48158       [
48159         "Mozambique (Moçambique)",
48160         "mz",
48161         "258"
48162       ],
48163       [
48164         "Myanmar (Burma) (မြန်မာ)",
48165         "mm",
48166         "95"
48167       ],
48168       [
48169         "Namibia (Namibië)",
48170         "na",
48171         "264"
48172       ],
48173       [
48174         "Nauru",
48175         "nr",
48176         "674"
48177       ],
48178       [
48179         "Nepal (नेपाल)",
48180         "np",
48181         "977"
48182       ],
48183       [
48184         "Netherlands (Nederland)",
48185         "nl",
48186         "31"
48187       ],
48188       [
48189         "New Caledonia (Nouvelle-Calédonie)",
48190         "nc",
48191         "687"
48192       ],
48193       [
48194         "New Zealand",
48195         "nz",
48196         "64"
48197       ],
48198       [
48199         "Nicaragua",
48200         "ni",
48201         "505"
48202       ],
48203       [
48204         "Niger (Nijar)",
48205         "ne",
48206         "227"
48207       ],
48208       [
48209         "Nigeria",
48210         "ng",
48211         "234"
48212       ],
48213       [
48214         "Niue",
48215         "nu",
48216         "683"
48217       ],
48218       [
48219         "Norfolk Island",
48220         "nf",
48221         "672"
48222       ],
48223       [
48224         "North Korea (조선 민주주의 인민 공화국)",
48225         "kp",
48226         "850"
48227       ],
48228       [
48229         "Northern Mariana Islands",
48230         "mp",
48231         "1670"
48232       ],
48233       [
48234         "Norway (Norge)",
48235         "no",
48236         "47",
48237         0
48238       ],
48239       [
48240         "Oman (‫عُمان‬‎)",
48241         "om",
48242         "968"
48243       ],
48244       [
48245         "Pakistan (‫پاکستان‬‎)",
48246         "pk",
48247         "92"
48248       ],
48249       [
48250         "Palau",
48251         "pw",
48252         "680"
48253       ],
48254       [
48255         "Palestine (‫فلسطين‬‎)",
48256         "ps",
48257         "970"
48258       ],
48259       [
48260         "Panama (Panamá)",
48261         "pa",
48262         "507"
48263       ],
48264       [
48265         "Papua New Guinea",
48266         "pg",
48267         "675"
48268       ],
48269       [
48270         "Paraguay",
48271         "py",
48272         "595"
48273       ],
48274       [
48275         "Peru (Perú)",
48276         "pe",
48277         "51"
48278       ],
48279       [
48280         "Philippines",
48281         "ph",
48282         "63"
48283       ],
48284       [
48285         "Poland (Polska)",
48286         "pl",
48287         "48"
48288       ],
48289       [
48290         "Portugal",
48291         "pt",
48292         "351"
48293       ],
48294       [
48295         "Puerto Rico",
48296         "pr",
48297         "1",
48298         3,
48299         ["787", "939"]
48300       ],
48301       [
48302         "Qatar (‫قطر‬‎)",
48303         "qa",
48304         "974"
48305       ],
48306       [
48307         "Réunion (La Réunion)",
48308         "re",
48309         "262",
48310         0
48311       ],
48312       [
48313         "Romania (România)",
48314         "ro",
48315         "40"
48316       ],
48317       [
48318         "Russia (Россия)",
48319         "ru",
48320         "7",
48321         0
48322       ],
48323       [
48324         "Rwanda",
48325         "rw",
48326         "250"
48327       ],
48328       [
48329         "Saint Barthélemy",
48330         "bl",
48331         "590",
48332         1
48333       ],
48334       [
48335         "Saint Helena",
48336         "sh",
48337         "290"
48338       ],
48339       [
48340         "Saint Kitts and Nevis",
48341         "kn",
48342         "1869"
48343       ],
48344       [
48345         "Saint Lucia",
48346         "lc",
48347         "1758"
48348       ],
48349       [
48350         "Saint Martin (Saint-Martin (partie française))",
48351         "mf",
48352         "590",
48353         2
48354       ],
48355       [
48356         "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)",
48357         "pm",
48358         "508"
48359       ],
48360       [
48361         "Saint Vincent and the Grenadines",
48362         "vc",
48363         "1784"
48364       ],
48365       [
48366         "Samoa",
48367         "ws",
48368         "685"
48369       ],
48370       [
48371         "San Marino",
48372         "sm",
48373         "378"
48374       ],
48375       [
48376         "São Tomé and Príncipe (São Tomé e Príncipe)",
48377         "st",
48378         "239"
48379       ],
48380       [
48381         "Saudi Arabia (‫المملكة العربية السعودية‬‎)",
48382         "sa",
48383         "966"
48384       ],
48385       [
48386         "Senegal (Sénégal)",
48387         "sn",
48388         "221"
48389       ],
48390       [
48391         "Serbia (Србија)",
48392         "rs",
48393         "381"
48394       ],
48395       [
48396         "Seychelles",
48397         "sc",
48398         "248"
48399       ],
48400       [
48401         "Sierra Leone",
48402         "sl",
48403         "232"
48404       ],
48405       [
48406         "Singapore",
48407         "sg",
48408         "65"
48409       ],
48410       [
48411         "Sint Maarten",
48412         "sx",
48413         "1721"
48414       ],
48415       [
48416         "Slovakia (Slovensko)",
48417         "sk",
48418         "421"
48419       ],
48420       [
48421         "Slovenia (Slovenija)",
48422         "si",
48423         "386"
48424       ],
48425       [
48426         "Solomon Islands",
48427         "sb",
48428         "677"
48429       ],
48430       [
48431         "Somalia (Soomaaliya)",
48432         "so",
48433         "252"
48434       ],
48435       [
48436         "South Africa",
48437         "za",
48438         "27"
48439       ],
48440       [
48441         "South Korea (대한민국)",
48442         "kr",
48443         "82"
48444       ],
48445       [
48446         "South Sudan (‫جنوب السودان‬‎)",
48447         "ss",
48448         "211"
48449       ],
48450       [
48451         "Spain (España)",
48452         "es",
48453         "34"
48454       ],
48455       [
48456         "Sri Lanka (ශ්‍රී ලංකාව)",
48457         "lk",
48458         "94"
48459       ],
48460       [
48461         "Sudan (‫السودان‬‎)",
48462         "sd",
48463         "249"
48464       ],
48465       [
48466         "Suriname",
48467         "sr",
48468         "597"
48469       ],
48470       [
48471         "Svalbard and Jan Mayen",
48472         "sj",
48473         "47",
48474         1
48475       ],
48476       [
48477         "Swaziland",
48478         "sz",
48479         "268"
48480       ],
48481       [
48482         "Sweden (Sverige)",
48483         "se",
48484         "46"
48485       ],
48486       [
48487         "Switzerland (Schweiz)",
48488         "ch",
48489         "41"
48490       ],
48491       [
48492         "Syria (‫سوريا‬‎)",
48493         "sy",
48494         "963"
48495       ],
48496       [
48497         "Taiwan (台灣)",
48498         "tw",
48499         "886"
48500       ],
48501       [
48502         "Tajikistan",
48503         "tj",
48504         "992"
48505       ],
48506       [
48507         "Tanzania",
48508         "tz",
48509         "255"
48510       ],
48511       [
48512         "Thailand (ไทย)",
48513         "th",
48514         "66"
48515       ],
48516       [
48517         "Timor-Leste",
48518         "tl",
48519         "670"
48520       ],
48521       [
48522         "Togo",
48523         "tg",
48524         "228"
48525       ],
48526       [
48527         "Tokelau",
48528         "tk",
48529         "690"
48530       ],
48531       [
48532         "Tonga",
48533         "to",
48534         "676"
48535       ],
48536       [
48537         "Trinidad and Tobago",
48538         "tt",
48539         "1868"
48540       ],
48541       [
48542         "Tunisia (‫تونس‬‎)",
48543         "tn",
48544         "216"
48545       ],
48546       [
48547         "Turkey (Türkiye)",
48548         "tr",
48549         "90"
48550       ],
48551       [
48552         "Turkmenistan",
48553         "tm",
48554         "993"
48555       ],
48556       [
48557         "Turks and Caicos Islands",
48558         "tc",
48559         "1649"
48560       ],
48561       [
48562         "Tuvalu",
48563         "tv",
48564         "688"
48565       ],
48566       [
48567         "U.S. Virgin Islands",
48568         "vi",
48569         "1340"
48570       ],
48571       [
48572         "Uganda",
48573         "ug",
48574         "256"
48575       ],
48576       [
48577         "Ukraine (Україна)",
48578         "ua",
48579         "380"
48580       ],
48581       [
48582         "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)",
48583         "ae",
48584         "971"
48585       ],
48586       [
48587         "United Kingdom",
48588         "gb",
48589         "44",
48590         0
48591       ],
48592       [
48593         "United States",
48594         "us",
48595         "1",
48596         0
48597       ],
48598       [
48599         "Uruguay",
48600         "uy",
48601         "598"
48602       ],
48603       [
48604         "Uzbekistan (Oʻzbekiston)",
48605         "uz",
48606         "998"
48607       ],
48608       [
48609         "Vanuatu",
48610         "vu",
48611         "678"
48612       ],
48613       [
48614         "Vatican City (Città del Vaticano)",
48615         "va",
48616         "39",
48617         1
48618       ],
48619       [
48620         "Venezuela",
48621         "ve",
48622         "58"
48623       ],
48624       [
48625         "Vietnam (Việt Nam)",
48626         "vn",
48627         "84"
48628       ],
48629       [
48630         "Wallis and Futuna (Wallis-et-Futuna)",
48631         "wf",
48632         "681"
48633       ],
48634       [
48635         "Western Sahara (‫الصحراء الغربية‬‎)",
48636         "eh",
48637         "212",
48638         1
48639       ],
48640       [
48641         "Yemen (‫اليمن‬‎)",
48642         "ye",
48643         "967"
48644       ],
48645       [
48646         "Zambia",
48647         "zm",
48648         "260"
48649       ],
48650       [
48651         "Zimbabwe",
48652         "zw",
48653         "263"
48654       ],
48655       [
48656         "Åland Islands",
48657         "ax",
48658         "358",
48659         1
48660       ]
48661   ];
48662   
48663   return d;
48664 }/**
48665 *    This script refer to:
48666 *    Title: International Telephone Input
48667 *    Author: Jack O'Connor
48668 *    Code version:  v12.1.12
48669 *    Availability: https://github.com/jackocnr/intl-tel-input.git
48670 **/
48671
48672 /**
48673  * @class Roo.bootstrap.form.PhoneInput
48674  * @extends Roo.bootstrap.form.TriggerField
48675  * An input with International dial-code selection
48676  
48677  * @cfg {String} defaultDialCode default '+852'
48678  * @cfg {Array} preferedCountries default []
48679   
48680  * @constructor
48681  * Create a new PhoneInput.
48682  * @param {Object} config Configuration options
48683  */
48684
48685 Roo.bootstrap.form.PhoneInput = function(config) {
48686     Roo.bootstrap.form.PhoneInput.superclass.constructor.call(this, config);
48687 };
48688
48689 Roo.extend(Roo.bootstrap.form.PhoneInput, Roo.bootstrap.form.TriggerField, {
48690         /**
48691         * @cfg {Roo.data.Store} store [required] The data store to which this combo is bound (defaults to undefined)
48692         */
48693         listWidth: undefined,
48694         
48695         selectedClass: 'active',
48696         
48697         invalidClass : "has-warning",
48698         
48699         validClass: 'has-success',
48700         
48701         allowed: '0123456789',
48702         
48703         max_length: 15,
48704         
48705         /**
48706          * @cfg {String} defaultDialCode The default dial code when initializing the input
48707          */
48708         defaultDialCode: '+852',
48709         
48710         /**
48711          * @cfg {Array} preferedCountries A list of iso2 in array (e.g. ['hk','us']). Those related countries will show at the top of the input's choices
48712          */
48713         preferedCountries: false,
48714         
48715         getAutoCreate : function()
48716         {
48717             var data = Roo.bootstrap.form.PhoneInputData();
48718             var align = this.labelAlign || this.parentLabelAlign();
48719             var id = Roo.id();
48720             
48721             this.allCountries = [];
48722             this.dialCodeMapping = [];
48723             
48724             for (var i = 0; i < data.length; i++) {
48725               var c = data[i];
48726               this.allCountries[i] = {
48727                 name: c[0],
48728                 iso2: c[1],
48729                 dialCode: c[2],
48730                 priority: c[3] || 0,
48731                 areaCodes: c[4] || null
48732               };
48733               this.dialCodeMapping[c[2]] = {
48734                   name: c[0],
48735                   iso2: c[1],
48736                   priority: c[3] || 0,
48737                   areaCodes: c[4] || null
48738               };
48739             }
48740             
48741             var cfg = {
48742                 cls: 'form-group',
48743                 cn: []
48744             };
48745             
48746             var input =  {
48747                 tag: 'input',
48748                 id : id,
48749                 // type: 'number', -- do not use number - we get the flaky up/down arrows.
48750                 maxlength: this.max_length,
48751                 cls : 'form-control tel-input',
48752                 autocomplete: 'new-password'
48753             };
48754             
48755             var hiddenInput = {
48756                 tag: 'input',
48757                 type: 'hidden',
48758                 cls: 'hidden-tel-input'
48759             };
48760             
48761             if (this.name) {
48762                 hiddenInput.name = this.name;
48763             }
48764             
48765             if (this.disabled) {
48766                 input.disabled = true;
48767             }
48768             
48769             var flag_container = {
48770                 tag: 'div',
48771                 cls: 'flag-box',
48772                 cn: [
48773                     {
48774                         tag: 'div',
48775                         cls: 'flag'
48776                     },
48777                     {
48778                         tag: 'div',
48779                         cls: 'caret'
48780                     }
48781                 ]
48782             };
48783             
48784             var box = {
48785                 tag: 'div',
48786                 cls: this.hasFeedback ? 'has-feedback' : '',
48787                 cn: [
48788                     hiddenInput,
48789                     input,
48790                     {
48791                         tag: 'input',
48792                         cls: 'dial-code-holder',
48793                         disabled: true
48794                     }
48795                 ]
48796             };
48797             
48798             var container = {
48799                 cls: 'roo-select2-container input-group',
48800                 cn: [
48801                     flag_container,
48802                     box
48803                 ]
48804             };
48805             
48806             if (this.fieldLabel.length) {
48807                 var indicator = {
48808                     tag: 'i',
48809                     tooltip: 'This field is required'
48810                 };
48811                 
48812                 var label = {
48813                     tag: 'label',
48814                     'for':  id,
48815                     cls: 'control-label',
48816                     cn: []
48817                 };
48818                 
48819                 var label_text = {
48820                     tag: 'span',
48821                     html: this.fieldLabel
48822                 };
48823                 
48824                 indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star left-indicator';
48825                 label.cn = [
48826                     indicator,
48827                     label_text
48828                 ];
48829                 
48830                 if(this.indicatorpos == 'right') {
48831                     indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star right-indicator';
48832                     label.cn = [
48833                         label_text,
48834                         indicator
48835                     ];
48836                 }
48837                 
48838                 if(align == 'left') {
48839                     container = {
48840                         tag: 'div',
48841                         cn: [
48842                             container
48843                         ]
48844                     };
48845                     
48846                     if(this.labelWidth > 12){
48847                         label.style = "width: " + this.labelWidth + 'px';
48848                     }
48849                     if(this.labelWidth < 13 && this.labelmd == 0){
48850                         this.labelmd = this.labelWidth;
48851                     }
48852                     if(this.labellg > 0){
48853                         label.cls += ' col-lg-' + this.labellg;
48854                         input.cls += ' col-lg-' + (12 - this.labellg);
48855                     }
48856                     if(this.labelmd > 0){
48857                         label.cls += ' col-md-' + this.labelmd;
48858                         container.cls += ' col-md-' + (12 - this.labelmd);
48859                     }
48860                     if(this.labelsm > 0){
48861                         label.cls += ' col-sm-' + this.labelsm;
48862                         container.cls += ' col-sm-' + (12 - this.labelsm);
48863                     }
48864                     if(this.labelxs > 0){
48865                         label.cls += ' col-xs-' + this.labelxs;
48866                         container.cls += ' col-xs-' + (12 - this.labelxs);
48867                     }
48868                 }
48869             }
48870             
48871             cfg.cn = [
48872                 label,
48873                 container
48874             ];
48875             
48876             var settings = this;
48877             
48878             ['xs','sm','md','lg'].map(function(size){
48879                 if (settings[size]) {
48880                     cfg.cls += ' col-' + size + '-' + settings[size];
48881                 }
48882             });
48883             
48884             this.store = new Roo.data.Store({
48885                 proxy : new Roo.data.MemoryProxy({}),
48886                 reader : new Roo.data.JsonReader({
48887                     fields : [
48888                         {
48889                             'name' : 'name',
48890                             'type' : 'string'
48891                         },
48892                         {
48893                             'name' : 'iso2',
48894                             'type' : 'string'
48895                         },
48896                         {
48897                             'name' : 'dialCode',
48898                             'type' : 'string'
48899                         },
48900                         {
48901                             'name' : 'priority',
48902                             'type' : 'string'
48903                         },
48904                         {
48905                             'name' : 'areaCodes',
48906                             'type' : 'string'
48907                         }
48908                     ]
48909                 })
48910             });
48911             
48912             if(!this.preferedCountries) {
48913                 this.preferedCountries = [
48914                     'hk',
48915                     'gb',
48916                     'us'
48917                 ];
48918             }
48919             
48920             var p = this.preferedCountries.reverse();
48921             
48922             if(p) {
48923                 for (var i = 0; i < p.length; i++) {
48924                     for (var j = 0; j < this.allCountries.length; j++) {
48925                         if(this.allCountries[j].iso2 == p[i]) {
48926                             var t = this.allCountries[j];
48927                             this.allCountries.splice(j,1);
48928                             this.allCountries.unshift(t);
48929                         }
48930                     } 
48931                 }
48932             }
48933             
48934             this.store.proxy.data = {
48935                 success: true,
48936                 data: this.allCountries
48937             };
48938             
48939             return cfg;
48940         },
48941         
48942         initEvents : function()
48943         {
48944             this.createList();
48945             Roo.bootstrap.form.PhoneInput.superclass.initEvents.call(this);
48946             
48947             this.indicator = this.indicatorEl();
48948             this.flag = this.flagEl();
48949             this.dialCodeHolder = this.dialCodeHolderEl();
48950             
48951             this.trigger = this.el.select('div.flag-box',true).first();
48952             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
48953             
48954             var _this = this;
48955             
48956             (function(){
48957                 var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
48958                 _this.list.setWidth(lw);
48959             }).defer(100);
48960             
48961             this.list.on('mouseover', this.onViewOver, this);
48962             this.list.on('mousemove', this.onViewMove, this);
48963             this.inputEl().on("keyup", this.onKeyUp, this);
48964             this.inputEl().on("keypress", this.onKeyPress, this);
48965             
48966             this.tpl = '<li><a href="#"><div class="flag {iso2}"></div>{name} <span class="dial-code">+{dialCode}</span></a></li>';
48967
48968             this.view = new Roo.View(this.list, this.tpl, {
48969                 singleSelect:true, store: this.store, selectedClass: this.selectedClass
48970             });
48971             
48972             this.view.on('click', this.onViewClick, this);
48973             this.setValue(this.defaultDialCode);
48974         },
48975         
48976         onTriggerClick : function(e)
48977         {
48978             Roo.log('trigger click');
48979             if(this.disabled){
48980                 return;
48981             }
48982             
48983             if(this.isExpanded()){
48984                 this.collapse();
48985                 this.hasFocus = false;
48986             }else {
48987                 this.store.load({});
48988                 this.hasFocus = true;
48989                 this.expand();
48990             }
48991         },
48992         
48993         isExpanded : function()
48994         {
48995             return this.list.isVisible();
48996         },
48997         
48998         collapse : function()
48999         {
49000             if(!this.isExpanded()){
49001                 return;
49002             }
49003             this.list.hide();
49004             Roo.get(document).un('mousedown', this.collapseIf, this);
49005             Roo.get(document).un('mousewheel', this.collapseIf, this);
49006             this.fireEvent('collapse', this);
49007             this.validate();
49008         },
49009         
49010         expand : function()
49011         {
49012             Roo.log('expand');
49013
49014             if(this.isExpanded() || !this.hasFocus){
49015                 return;
49016             }
49017             
49018             var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
49019             this.list.setWidth(lw);
49020             
49021             this.list.show();
49022             this.restrictHeight();
49023             
49024             Roo.get(document).on('mousedown', this.collapseIf, this);
49025             Roo.get(document).on('mousewheel', this.collapseIf, this);
49026             
49027             this.fireEvent('expand', this);
49028         },
49029         
49030         restrictHeight : function()
49031         {
49032             this.list.alignTo(this.inputEl(), this.listAlign);
49033             this.list.alignTo(this.inputEl(), this.listAlign);
49034         },
49035         
49036         onViewOver : function(e, t)
49037         {
49038             if(this.inKeyMode){
49039                 return;
49040             }
49041             var item = this.view.findItemFromChild(t);
49042             
49043             if(item){
49044                 var index = this.view.indexOf(item);
49045                 this.select(index, false);
49046             }
49047         },
49048
49049         // private
49050         onViewClick : function(view, doFocus, el, e)
49051         {
49052             var index = this.view.getSelectedIndexes()[0];
49053             
49054             var r = this.store.getAt(index);
49055             
49056             if(r){
49057                 this.onSelect(r, index);
49058             }
49059             if(doFocus !== false && !this.blockFocus){
49060                 this.inputEl().focus();
49061             }
49062         },
49063         
49064         onViewMove : function(e, t)
49065         {
49066             this.inKeyMode = false;
49067         },
49068         
49069         select : function(index, scrollIntoView)
49070         {
49071             this.selectedIndex = index;
49072             this.view.select(index);
49073             if(scrollIntoView !== false){
49074                 var el = this.view.getNode(index);
49075                 if(el){
49076                     this.list.scrollChildIntoView(el, false);
49077                 }
49078             }
49079         },
49080         
49081         createList : function()
49082         {
49083             this.list = Roo.get(document.body).createChild({
49084                 tag: 'ul',
49085                 cls: 'typeahead typeahead-long dropdown-menu tel-list',
49086                 style: 'display:none'
49087             });
49088             
49089             this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
49090         },
49091         
49092         collapseIf : function(e)
49093         {
49094             var in_combo  = e.within(this.el);
49095             var in_list =  e.within(this.list);
49096             var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
49097             
49098             if (in_combo || in_list || is_list) {
49099                 return;
49100             }
49101             this.collapse();
49102         },
49103         
49104         onSelect : function(record, index)
49105         {
49106             if(this.fireEvent('beforeselect', this, record, index) !== false){
49107                 
49108                 this.setFlagClass(record.data.iso2);
49109                 this.setDialCode(record.data.dialCode);
49110                 this.hasFocus = false;
49111                 this.collapse();
49112                 this.fireEvent('select', this, record, index);
49113             }
49114         },
49115         
49116         flagEl : function()
49117         {
49118             var flag = this.el.select('div.flag',true).first();
49119             if(!flag){
49120                 return false;
49121             }
49122             return flag;
49123         },
49124         
49125         dialCodeHolderEl : function()
49126         {
49127             var d = this.el.select('input.dial-code-holder',true).first();
49128             if(!d){
49129                 return false;
49130             }
49131             return d;
49132         },
49133         
49134         setDialCode : function(v)
49135         {
49136             this.dialCodeHolder.dom.value = '+'+v;
49137         },
49138         
49139         setFlagClass : function(n)
49140         {
49141             this.flag.dom.className = 'flag '+n;
49142         },
49143         
49144         getValue : function()
49145         {
49146             var v = this.inputEl().getValue();
49147             if(this.dialCodeHolder) {
49148                 v = this.dialCodeHolder.dom.value+this.inputEl().getValue();
49149             }
49150             return v;
49151         },
49152         
49153         setValue : function(v)
49154         {
49155             var d = this.getDialCode(v);
49156             
49157             //invalid dial code
49158             if(v.length == 0 || !d || d.length == 0) {
49159                 if(this.rendered){
49160                     this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
49161                     this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
49162                 }
49163                 return;
49164             }
49165             
49166             //valid dial code
49167             this.setFlagClass(this.dialCodeMapping[d].iso2);
49168             this.setDialCode(d);
49169             this.inputEl().dom.value = v.replace('+'+d,'');
49170             this.hiddenEl().dom.value = this.getValue();
49171             
49172             this.validate();
49173         },
49174         
49175         getDialCode : function(v)
49176         {
49177             v = v ||  '';
49178             
49179             if (v.length == 0) {
49180                 return this.dialCodeHolder.dom.value;
49181             }
49182             
49183             var dialCode = "";
49184             if (v.charAt(0) != "+") {
49185                 return false;
49186             }
49187             var numericChars = "";
49188             for (var i = 1; i < v.length; i++) {
49189               var c = v.charAt(i);
49190               if (!isNaN(c)) {
49191                 numericChars += c;
49192                 if (this.dialCodeMapping[numericChars]) {
49193                   dialCode = v.substr(1, i);
49194                 }
49195                 if (numericChars.length == 4) {
49196                   break;
49197                 }
49198               }
49199             }
49200             return dialCode;
49201         },
49202         
49203         reset : function()
49204         {
49205             this.setValue(this.defaultDialCode);
49206             this.validate();
49207         },
49208         
49209         hiddenEl : function()
49210         {
49211             return this.el.select('input.hidden-tel-input',true).first();
49212         },
49213         
49214         // after setting val
49215         onKeyUp : function(e){
49216             this.setValue(this.getValue());
49217         },
49218         
49219         onKeyPress : function(e){
49220             if(this.allowed.indexOf(String.fromCharCode(e.getCharCode())) === -1){
49221                 e.stopEvent();
49222             }
49223         }
49224         
49225 });
49226 /**
49227  * @class Roo.bootstrap.form.MoneyField
49228  * @extends Roo.bootstrap.form.ComboBox
49229  * Bootstrap MoneyField class
49230  * 
49231  * @constructor
49232  * Create a new MoneyField.
49233  * @param {Object} config Configuration options
49234  */
49235
49236 Roo.bootstrap.form.MoneyField = function(config) {
49237     
49238     Roo.bootstrap.form.MoneyField.superclass.constructor.call(this, config);
49239     
49240 };
49241
49242 Roo.extend(Roo.bootstrap.form.MoneyField, Roo.bootstrap.form.ComboBox, {
49243     
49244     /**
49245      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
49246      */
49247     allowDecimals : true,
49248     /**
49249      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
49250      */
49251     decimalSeparator : ".",
49252     /**
49253      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
49254      */
49255     decimalPrecision : 0,
49256     /**
49257      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
49258      */
49259     allowNegative : true,
49260     /**
49261      * @cfg {Boolean} allowZero False to blank out if the user enters '0' (defaults to true)
49262      */
49263     allowZero: true,
49264     /**
49265      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
49266      */
49267     minValue : Number.NEGATIVE_INFINITY,
49268     /**
49269      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
49270      */
49271     maxValue : Number.MAX_VALUE,
49272     /**
49273      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
49274      */
49275     minText : "The minimum value for this field is {0}",
49276     /**
49277      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
49278      */
49279     maxText : "The maximum value for this field is {0}",
49280     /**
49281      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
49282      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
49283      */
49284     nanText : "{0} is not a valid number",
49285     /**
49286      * @cfg {Boolean} castInt (true|false) cast int if true (defalut true)
49287      */
49288     castInt : true,
49289     /**
49290      * @cfg {String} defaults currency of the MoneyField
49291      * value should be in lkey
49292      */
49293     defaultCurrency : false,
49294     /**
49295      * @cfg {String} thousandsDelimiter Symbol of thousandsDelimiter
49296      */
49297     thousandsDelimiter : false,
49298     /**
49299      * @cfg {Number} max_length Maximum input field length allowed (defaults to Number.MAX_VALUE)
49300      */
49301     max_length: false,
49302     
49303     inputlg : 9,
49304     inputmd : 9,
49305     inputsm : 9,
49306     inputxs : 6,
49307      /**
49308      * @cfg {Roo.data.Store} store  Store to lookup currency??
49309      */
49310     store : false,
49311     
49312     getAutoCreate : function()
49313     {
49314         var align = this.labelAlign || this.parentLabelAlign();
49315         
49316         var id = Roo.id();
49317
49318         var cfg = {
49319             cls: 'form-group',
49320             cn: []
49321         };
49322
49323         var input =  {
49324             tag: 'input',
49325             id : id,
49326             cls : 'form-control roo-money-amount-input',
49327             autocomplete: 'new-password'
49328         };
49329         
49330         var hiddenInput = {
49331             tag: 'input',
49332             type: 'hidden',
49333             id: Roo.id(),
49334             cls: 'hidden-number-input'
49335         };
49336         
49337         if(this.max_length) {
49338             input.maxlength = this.max_length; 
49339         }
49340         
49341         if (this.name) {
49342             hiddenInput.name = this.name;
49343         }
49344
49345         if (this.disabled) {
49346             input.disabled = true;
49347         }
49348
49349         var clg = 12 - this.inputlg;
49350         var cmd = 12 - this.inputmd;
49351         var csm = 12 - this.inputsm;
49352         var cxs = 12 - this.inputxs;
49353         
49354         var container = {
49355             tag : 'div',
49356             cls : 'row roo-money-field',
49357             cn : [
49358                 {
49359                     tag : 'div',
49360                     cls : 'roo-money-currency column col-lg-' + clg + ' col-md-' + cmd + ' col-sm-' + csm + ' col-xs-' + cxs,
49361                     cn : [
49362                         {
49363                             tag : 'div',
49364                             cls: 'roo-select2-container input-group',
49365                             cn: [
49366                                 {
49367                                     tag : 'input',
49368                                     cls : 'form-control roo-money-currency-input',
49369                                     autocomplete: 'new-password',
49370                                     readOnly : 1,
49371                                     name : this.currencyName
49372                                 },
49373                                 {
49374                                     tag :'span',
49375                                     cls : 'input-group-addon',
49376                                     cn : [
49377                                         {
49378                                             tag: 'span',
49379                                             cls: 'caret'
49380                                         }
49381                                     ]
49382                                 }
49383                             ]
49384                         }
49385                     ]
49386                 },
49387                 {
49388                     tag : 'div',
49389                     cls : 'roo-money-amount column col-lg-' + this.inputlg + ' col-md-' + this.inputmd + ' col-sm-' + this.inputsm + ' col-xs-' + this.inputxs,
49390                     cn : [
49391                         {
49392                             tag: 'div',
49393                             cls: this.hasFeedback ? 'has-feedback' : '',
49394                             cn: [
49395                                 input
49396                             ]
49397                         }
49398                     ]
49399                 }
49400             ]
49401             
49402         };
49403         
49404         if (this.fieldLabel.length) {
49405             var indicator = {
49406                 tag: 'i',
49407                 tooltip: 'This field is required'
49408             };
49409
49410             var label = {
49411                 tag: 'label',
49412                 'for':  id,
49413                 cls: 'control-label',
49414                 cn: []
49415             };
49416
49417             var label_text = {
49418                 tag: 'span',
49419                 html: this.fieldLabel
49420             };
49421
49422             indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star left-indicator';
49423             label.cn = [
49424                 indicator,
49425                 label_text
49426             ];
49427
49428             if(this.indicatorpos == 'right') {
49429                 indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star right-indicator';
49430                 label.cn = [
49431                     label_text,
49432                     indicator
49433                 ];
49434             }
49435
49436             if(align == 'left') {
49437                 container = {
49438                     tag: 'div',
49439                     cn: [
49440                         container
49441                     ]
49442                 };
49443
49444                 if(this.labelWidth > 12){
49445                     label.style = "width: " + this.labelWidth + 'px';
49446                 }
49447                 if(this.labelWidth < 13 && this.labelmd == 0){
49448                     this.labelmd = this.labelWidth;
49449                 }
49450                 if(this.labellg > 0){
49451                     label.cls += ' col-lg-' + this.labellg;
49452                     input.cls += ' col-lg-' + (12 - this.labellg);
49453                 }
49454                 if(this.labelmd > 0){
49455                     label.cls += ' col-md-' + this.labelmd;
49456                     container.cls += ' col-md-' + (12 - this.labelmd);
49457                 }
49458                 if(this.labelsm > 0){
49459                     label.cls += ' col-sm-' + this.labelsm;
49460                     container.cls += ' col-sm-' + (12 - this.labelsm);
49461                 }
49462                 if(this.labelxs > 0){
49463                     label.cls += ' col-xs-' + this.labelxs;
49464                     container.cls += ' col-xs-' + (12 - this.labelxs);
49465                 }
49466             }
49467         }
49468
49469         cfg.cn = [
49470             label,
49471             container,
49472             hiddenInput
49473         ];
49474         
49475         var settings = this;
49476
49477         ['xs','sm','md','lg'].map(function(size){
49478             if (settings[size]) {
49479                 cfg.cls += ' col-' + size + '-' + settings[size];
49480             }
49481         });
49482         
49483         return cfg;
49484     },
49485     
49486     initEvents : function()
49487     {
49488         this.indicator = this.indicatorEl();
49489         
49490         this.initCurrencyEvent();
49491         
49492         this.initNumberEvent();
49493     },
49494     
49495     initCurrencyEvent : function()
49496     {
49497         if (!this.store) {
49498             throw "can not find store for combo";
49499         }
49500         
49501         this.store = Roo.factory(this.store, Roo.data);
49502         this.store.parent = this;
49503         
49504         this.createList();
49505         
49506         this.triggerEl = this.el.select('.input-group-addon', true).first();
49507         
49508         this.triggerEl.on("click", this.onTriggerClick, this, { preventDefault : true });
49509         
49510         var _this = this;
49511         
49512         (function(){
49513             var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
49514             _this.list.setWidth(lw);
49515         }).defer(100);
49516         
49517         this.list.on('mouseover', this.onViewOver, this);
49518         this.list.on('mousemove', this.onViewMove, this);
49519         this.list.on('scroll', this.onViewScroll, this);
49520         
49521         if(!this.tpl){
49522             this.tpl = '<li><a href="#">{' + this.currencyField + '}</a></li>';
49523         }
49524         
49525         this.view = new Roo.View(this.list, this.tpl, {
49526             singleSelect:true, store: this.store, selectedClass: this.selectedClass
49527         });
49528         
49529         this.view.on('click', this.onViewClick, this);
49530         
49531         this.store.on('beforeload', this.onBeforeLoad, this);
49532         this.store.on('load', this.onLoad, this);
49533         this.store.on('loadexception', this.onLoadException, this);
49534         
49535         this.keyNav = new Roo.KeyNav(this.currencyEl(), {
49536             "up" : function(e){
49537                 this.inKeyMode = true;
49538                 this.selectPrev();
49539             },
49540
49541             "down" : function(e){
49542                 if(!this.isExpanded()){
49543                     this.onTriggerClick();
49544                 }else{
49545                     this.inKeyMode = true;
49546                     this.selectNext();
49547                 }
49548             },
49549
49550             "enter" : function(e){
49551                 this.collapse();
49552                 
49553                 if(this.fireEvent("specialkey", this, e)){
49554                     this.onViewClick(false);
49555                 }
49556                 
49557                 return true;
49558             },
49559
49560             "esc" : function(e){
49561                 this.collapse();
49562             },
49563
49564             "tab" : function(e){
49565                 this.collapse();
49566                 
49567                 if(this.fireEvent("specialkey", this, e)){
49568                     this.onViewClick(false);
49569                 }
49570                 
49571                 return true;
49572             },
49573
49574             scope : this,
49575
49576             doRelay : function(foo, bar, hname){
49577                 if(hname == 'down' || this.scope.isExpanded()){
49578                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
49579                 }
49580                 return true;
49581             },
49582
49583             forceKeyDown: true
49584         });
49585         
49586         this.currencyEl().on("click", this.onTriggerClick, this, { preventDefault : true });
49587         
49588     },
49589     
49590     initNumberEvent : function(e)
49591     {
49592         this.inputEl().on("keydown" , this.fireKey,  this);
49593         this.inputEl().on("focus", this.onFocus,  this);
49594         this.inputEl().on("blur", this.onBlur,  this);
49595         
49596         this.inputEl().relayEvent('keyup', this);
49597         
49598         if(this.indicator){
49599             this.indicator.addClass('invisible');
49600         }
49601  
49602         this.originalValue = this.getValue();
49603         
49604         if(this.validationEvent == 'keyup'){
49605             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
49606             this.inputEl().on('keyup', this.filterValidation, this);
49607         }
49608         else if(this.validationEvent !== false){
49609             this.inputEl().on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
49610         }
49611         
49612         if(this.selectOnFocus){
49613             this.on("focus", this.preFocus, this);
49614             
49615         }
49616         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
49617             this.inputEl().on("keypress", this.filterKeys, this);
49618         } else {
49619             this.inputEl().relayEvent('keypress', this);
49620         }
49621         
49622         var allowed = "0123456789";
49623         
49624         if(this.allowDecimals){
49625             allowed += this.decimalSeparator;
49626         }
49627         
49628         if(this.allowNegative){
49629             allowed += "-";
49630         }
49631         
49632         if(this.thousandsDelimiter) {
49633             allowed += ",";
49634         }
49635         
49636         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
49637         
49638         var keyPress = function(e){
49639             
49640             var k = e.getKey();
49641             
49642             var c = e.getCharCode();
49643             
49644             if(
49645                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
49646                     allowed.indexOf(String.fromCharCode(c)) === -1
49647             ){
49648                 e.stopEvent();
49649                 return;
49650             }
49651             
49652             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
49653                 return;
49654             }
49655             
49656             if(allowed.indexOf(String.fromCharCode(c)) === -1){
49657                 e.stopEvent();
49658             }
49659         };
49660         
49661         this.inputEl().on("keypress", keyPress, this);
49662         
49663     },
49664     
49665     onTriggerClick : function(e)
49666     {   
49667         if(this.disabled){
49668             return;
49669         }
49670         
49671         this.page = 0;
49672         this.loadNext = false;
49673         
49674         if(this.isExpanded()){
49675             this.collapse();
49676             return;
49677         }
49678         
49679         this.hasFocus = true;
49680         
49681         if(this.triggerAction == 'all') {
49682             this.doQuery(this.allQuery, true);
49683             return;
49684         }
49685         
49686         this.doQuery(this.getRawValue());
49687     },
49688     
49689     getCurrency : function()
49690     {   
49691         var v = this.currencyEl().getValue();
49692         
49693         return v;
49694     },
49695     
49696     restrictHeight : function()
49697     {
49698         this.list.alignTo(this.currencyEl(), this.listAlign);
49699         this.list.alignTo(this.currencyEl(), this.listAlign);
49700     },
49701     
49702     onViewClick : function(view, doFocus, el, e)
49703     {
49704         var index = this.view.getSelectedIndexes()[0];
49705         
49706         var r = this.store.getAt(index);
49707         
49708         if(r){
49709             this.onSelect(r, index);
49710         }
49711     },
49712     
49713     onSelect : function(record, index){
49714         
49715         if(this.fireEvent('beforeselect', this, record, index) !== false){
49716         
49717             this.setFromCurrencyData(index > -1 ? record.data : false);
49718             
49719             this.collapse();
49720             
49721             this.fireEvent('select', this, record, index);
49722         }
49723     },
49724     
49725     setFromCurrencyData : function(o)
49726     {
49727         var currency = '';
49728         
49729         this.lastCurrency = o;
49730         
49731         if (this.currencyField) {
49732             currency = !o || typeof(o[this.currencyField]) == 'undefined' ? '' : o[this.currencyField];
49733         } else {
49734             Roo.log('no  currencyField value set for '+ (this.name ? this.name : this.id));
49735         }
49736         
49737         this.lastSelectionText = currency;
49738         
49739         //setting default currency
49740         if(o[this.currencyField] * 1 == 0 && this.defaultCurrency) {
49741             this.setCurrency(this.defaultCurrency);
49742             return;
49743         }
49744         
49745         this.setCurrency(currency);
49746     },
49747     
49748     setFromData : function(o)
49749     {
49750         var c = {};
49751         
49752         c[this.currencyField] = !o || typeof(o[this.currencyName]) == 'undefined' ? '' : o[this.currencyName];
49753         
49754         this.setFromCurrencyData(c);
49755         
49756         var value = '';
49757         
49758         if (this.name) {
49759             value = !o || typeof(o[this.name]) == 'undefined' ? '' : o[this.name];
49760         } else {
49761             Roo.log('no value set for '+ (this.name ? this.name : this.id));
49762         }
49763         
49764         this.setValue(value);
49765         
49766     },
49767     
49768     setCurrency : function(v)
49769     {   
49770         this.currencyValue = v;
49771         
49772         if(this.rendered){
49773             this.currencyEl().dom.value = (v === null || v === undefined ? '' : v);
49774             this.validate();
49775         }
49776     },
49777     
49778     setValue : function(v)
49779     {
49780         v = String(this.fixPrecision(v)).replace(".", this.decimalSeparator);
49781         
49782         this.value = v;
49783         
49784         if(this.rendered){
49785             
49786             this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
49787             
49788             this.inputEl().dom.value = (v == '') ? '' :
49789                 Roo.util.Format.number(v, this.decimalPrecision, this.thousandsDelimiter || '');
49790             
49791             if(!this.allowZero && v === '0') {
49792                 this.hiddenEl().dom.value = '';
49793                 this.inputEl().dom.value = '';
49794             }
49795             
49796             this.validate();
49797         }
49798     },
49799     
49800     getRawValue : function()
49801     {
49802         var v = this.inputEl().getValue();
49803         
49804         return v;
49805     },
49806     
49807     getValue : function()
49808     {
49809         return this.fixPrecision(this.parseValue(this.getRawValue()));
49810     },
49811     
49812     parseValue : function(value)
49813     {
49814         if(this.thousandsDelimiter) {
49815             value += "";
49816             r = new RegExp(",", "g");
49817             value = value.replace(r, "");
49818         }
49819         
49820         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
49821         return isNaN(value) ? '' : value;
49822         
49823     },
49824     
49825     fixPrecision : function(value)
49826     {
49827         if(this.thousandsDelimiter) {
49828             value += "";
49829             r = new RegExp(",", "g");
49830             value = value.replace(r, "");
49831         }
49832         
49833         var nan = isNaN(value);
49834         
49835         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
49836             return nan ? '' : value;
49837         }
49838         return parseFloat(value).toFixed(this.decimalPrecision);
49839     },
49840     
49841     decimalPrecisionFcn : function(v)
49842     {
49843         return Math.floor(v);
49844     },
49845     
49846     validateValue : function(value)
49847     {
49848         if(!Roo.bootstrap.form.MoneyField.superclass.validateValue.call(this, value)){
49849             return false;
49850         }
49851         
49852         var num = this.parseValue(value);
49853         
49854         if(isNaN(num)){
49855             this.markInvalid(String.format(this.nanText, value));
49856             return false;
49857         }
49858         
49859         if(num < this.minValue){
49860             this.markInvalid(String.format(this.minText, this.minValue));
49861             return false;
49862         }
49863         
49864         if(num > this.maxValue){
49865             this.markInvalid(String.format(this.maxText, this.maxValue));
49866             return false;
49867         }
49868         
49869         return true;
49870     },
49871     
49872     validate : function()
49873     {
49874         if(this.disabled || this.allowBlank){
49875             this.markValid();
49876             return true;
49877         }
49878         
49879         var currency = this.getCurrency();
49880         
49881         if(this.validateValue(this.getRawValue()) && currency.length){
49882             this.markValid();
49883             return true;
49884         }
49885         
49886         this.markInvalid();
49887         return false;
49888     },
49889     
49890     getName: function()
49891     {
49892         return this.name;
49893     },
49894     
49895     beforeBlur : function()
49896     {
49897         if(!this.castInt){
49898             return;
49899         }
49900         
49901         var v = this.parseValue(this.getRawValue());
49902         
49903         if(v || v == 0){
49904             this.setValue(v);
49905         }
49906     },
49907     
49908     onBlur : function()
49909     {
49910         this.beforeBlur();
49911         
49912         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
49913             //this.el.removeClass(this.focusClass);
49914         }
49915         
49916         this.hasFocus = false;
49917         
49918         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
49919             this.validate();
49920         }
49921         
49922         var v = this.getValue();
49923         
49924         if(String(v) !== String(this.startValue)){
49925             this.fireEvent('change', this, v, this.startValue);
49926         }
49927         
49928         this.fireEvent("blur", this);
49929     },
49930     
49931     inputEl : function()
49932     {
49933         return this.el.select('.roo-money-amount-input', true).first();
49934     },
49935     
49936     currencyEl : function()
49937     {
49938         return this.el.select('.roo-money-currency-input', true).first();
49939     },
49940     
49941     hiddenEl : function()
49942     {
49943         return this.el.select('input.hidden-number-input',true).first();
49944     }
49945     
49946 });/**
49947  * @class Roo.bootstrap.BezierSignature
49948  * @extends Roo.bootstrap.Component
49949  * Bootstrap BezierSignature class
49950  * This script refer to:
49951  *    Title: Signature Pad
49952  *    Author: szimek
49953  *    Availability: https://github.com/szimek/signature_pad
49954  *
49955  * @constructor
49956  * Create a new BezierSignature
49957  * @param {Object} config The config object
49958  */
49959
49960 Roo.bootstrap.BezierSignature = function(config){
49961     Roo.bootstrap.BezierSignature.superclass.constructor.call(this, config);
49962     this.addEvents({
49963         "resize" : true
49964     });
49965 };
49966
49967 Roo.extend(Roo.bootstrap.BezierSignature, Roo.bootstrap.Component,
49968 {
49969      
49970     curve_data: [],
49971     
49972     is_empty: true,
49973     
49974     mouse_btn_down: true,
49975     
49976     /**
49977      * @cfg {int} canvas height
49978      */
49979     canvas_height: '200px',
49980     
49981     /**
49982      * @cfg {float|function} Radius of a single dot.
49983      */ 
49984     dot_size: false,
49985     
49986     /**
49987      * @cfg {float} Minimum width of a line. Defaults to 0.5.
49988      */
49989     min_width: 0.5,
49990     
49991     /**
49992      * @cfg {float} Maximum width of a line. Defaults to 2.5.
49993      */
49994     max_width: 2.5,
49995     
49996     /**
49997      * @cfg {integer} Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.
49998      */
49999     throttle: 16,
50000     
50001     /**
50002      * @cfg {integer} Add the next point only if the previous one is farther than x pixels. Defaults to 5.
50003      */
50004     min_distance: 5,
50005     
50006     /**
50007      * @cfg {string} Color used to clear the background. Can be any color format accepted by context.fillStyle. Defaults to "rgba(0,0,0,0)" (transparent black). Use a non-transparent color e.g. "rgb(255,255,255)" (opaque white) if you'd like to save signatures as JPEG images.
50008      */
50009     bg_color: 'rgba(0, 0, 0, 0)',
50010     
50011     /**
50012      * @cfg {string} Color used to draw the lines. Can be any color format accepted by context.fillStyle. Defaults to "black".
50013      */
50014     dot_color: 'black',
50015     
50016     /**
50017      * @cfg {float} Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.
50018      */ 
50019     velocity_filter_weight: 0.7,
50020     
50021     /**
50022      * @cfg {function} Callback when stroke begin. 
50023      */
50024     onBegin: false,
50025     
50026     /**
50027      * @cfg {function} Callback when stroke end.
50028      */
50029     onEnd: false,
50030     
50031     getAutoCreate : function()
50032     {
50033         var cls = 'roo-signature column';
50034         
50035         if(this.cls){
50036             cls += ' ' + this.cls;
50037         }
50038         
50039         var col_sizes = [
50040             'lg',
50041             'md',
50042             'sm',
50043             'xs'
50044         ];
50045         
50046         for(var i = 0; i < col_sizes.length; i++) {
50047             if(this[col_sizes[i]]) {
50048                 cls += " col-"+col_sizes[i]+"-"+this[col_sizes[i]];
50049             }
50050         }
50051         
50052         var cfg = {
50053             tag: 'div',
50054             cls: cls,
50055             cn: [
50056                 {
50057                     tag: 'div',
50058                     cls: 'roo-signature-body',
50059                     cn: [
50060                         {
50061                             tag: 'canvas',
50062                             cls: 'roo-signature-body-canvas',
50063                             height: this.canvas_height,
50064                             width: this.canvas_width
50065                         }
50066                     ]
50067                 },
50068                 {
50069                     tag: 'input',
50070                     type: 'file',
50071                     style: 'display: none'
50072                 }
50073             ]
50074         };
50075         
50076         return cfg;
50077     },
50078     
50079     initEvents: function() 
50080     {
50081         Roo.bootstrap.BezierSignature.superclass.initEvents.call(this);
50082         
50083         var canvas = this.canvasEl();
50084         
50085         // mouse && touch event swapping...
50086         canvas.dom.style.touchAction = 'none';
50087         canvas.dom.style.msTouchAction = 'none';
50088         
50089         this.mouse_btn_down = false;
50090         canvas.on('mousedown', this._handleMouseDown, this);
50091         canvas.on('mousemove', this._handleMouseMove, this);
50092         Roo.select('html').first().on('mouseup', this._handleMouseUp, this);
50093         
50094         if (window.PointerEvent) {
50095             canvas.on('pointerdown', this._handleMouseDown, this);
50096             canvas.on('pointermove', this._handleMouseMove, this);
50097             Roo.select('html').first().on('pointerup', this._handleMouseUp, this);
50098         }
50099         
50100         if ('ontouchstart' in window) {
50101             canvas.on('touchstart', this._handleTouchStart, this);
50102             canvas.on('touchmove', this._handleTouchMove, this);
50103             canvas.on('touchend', this._handleTouchEnd, this);
50104         }
50105         
50106         Roo.EventManager.onWindowResize(this.resize, this, true);
50107         
50108         // file input event
50109         this.fileEl().on('change', this.uploadImage, this);
50110         
50111         this.clear();
50112         
50113         this.resize();
50114     },
50115     
50116     resize: function(){
50117         
50118         var canvas = this.canvasEl().dom;
50119         var ctx = this.canvasElCtx();
50120         var img_data = false;
50121         
50122         if(canvas.width > 0) {
50123             var img_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
50124         }
50125         // setting canvas width will clean img data
50126         canvas.width = 0;
50127         
50128         var style = window.getComputedStyle ? 
50129             getComputedStyle(this.el.dom, null) : this.el.dom.currentStyle;
50130             
50131         var padding_left = parseInt(style.paddingLeft) || 0;
50132         var padding_right = parseInt(style.paddingRight) || 0;
50133         
50134         canvas.width = this.el.dom.clientWidth - padding_left - padding_right;
50135         
50136         if(img_data) {
50137             ctx.putImageData(img_data, 0, 0);
50138         }
50139     },
50140     
50141     _handleMouseDown: function(e)
50142     {
50143         if (e.browserEvent.which === 1) {
50144             this.mouse_btn_down = true;
50145             this.strokeBegin(e);
50146         }
50147     },
50148     
50149     _handleMouseMove: function (e)
50150     {
50151         if (this.mouse_btn_down) {
50152             this.strokeMoveUpdate(e);
50153         }
50154     },
50155     
50156     _handleMouseUp: function (e)
50157     {
50158         if (e.browserEvent.which === 1 && this.mouse_btn_down) {
50159             this.mouse_btn_down = false;
50160             this.strokeEnd(e);
50161         }
50162     },
50163     
50164     _handleTouchStart: function (e) {
50165         
50166         e.preventDefault();
50167         if (e.browserEvent.targetTouches.length === 1) {
50168             // var touch = e.browserEvent.changedTouches[0];
50169             // this.strokeBegin(touch);
50170             
50171              this.strokeBegin(e); // assume e catching the correct xy...
50172         }
50173     },
50174     
50175     _handleTouchMove: function (e) {
50176         e.preventDefault();
50177         // var touch = event.targetTouches[0];
50178         // _this._strokeMoveUpdate(touch);
50179         this.strokeMoveUpdate(e);
50180     },
50181     
50182     _handleTouchEnd: function (e) {
50183         var wasCanvasTouched = e.target === this.canvasEl().dom;
50184         if (wasCanvasTouched) {
50185             e.preventDefault();
50186             // var touch = event.changedTouches[0];
50187             // _this._strokeEnd(touch);
50188             this.strokeEnd(e);
50189         }
50190     },
50191     
50192     reset: function () {
50193         this._lastPoints = [];
50194         this._lastVelocity = 0;
50195         this._lastWidth = (this.min_width + this.max_width) / 2;
50196         this.canvasElCtx().fillStyle = this.dot_color;
50197     },
50198     
50199     strokeMoveUpdate: function(e)
50200     {
50201         this.strokeUpdate(e);
50202         
50203         if (this.throttle) {
50204             this.throttleStroke(this.strokeUpdate, this.throttle);
50205         }
50206         else {
50207             this.strokeUpdate(e);
50208         }
50209     },
50210     
50211     strokeBegin: function(e)
50212     {
50213         var newPointGroup = {
50214             color: this.dot_color,
50215             points: []
50216         };
50217         
50218         if (typeof this.onBegin === 'function') {
50219             this.onBegin(e);
50220         }
50221         
50222         this.curve_data.push(newPointGroup);
50223         this.reset();
50224         this.strokeUpdate(e);
50225     },
50226     
50227     strokeUpdate: function(e)
50228     {
50229         var rect = this.canvasEl().dom.getBoundingClientRect();
50230         var point = new this.Point(e.xy[0] - rect.left, e.xy[1] - rect.top, new Date().getTime());
50231         var lastPointGroup = this.curve_data[this.curve_data.length - 1];
50232         var lastPoints = lastPointGroup.points;
50233         var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
50234         var isLastPointTooClose = lastPoint
50235             ? point.distanceTo(lastPoint) <= this.min_distance
50236             : false;
50237         var color = lastPointGroup.color;
50238         if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
50239             var curve = this.addPoint(point);
50240             if (!lastPoint) {
50241                 this.drawDot({color: color, point: point});
50242             }
50243             else if (curve) {
50244                 this.drawCurve({color: color, curve: curve});
50245             }
50246             lastPoints.push({
50247                 time: point.time,
50248                 x: point.x,
50249                 y: point.y
50250             });
50251         }
50252     },
50253     
50254     strokeEnd: function(e)
50255     {
50256         this.strokeUpdate(e);
50257         if (typeof this.onEnd === 'function') {
50258             this.onEnd(e);
50259         }
50260     },
50261     
50262     addPoint:  function (point) {
50263         var _lastPoints = this._lastPoints;
50264         _lastPoints.push(point);
50265         if (_lastPoints.length > 2) {
50266             if (_lastPoints.length === 3) {
50267                 _lastPoints.unshift(_lastPoints[0]);
50268             }
50269             var widths = this.calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
50270             var curve = this.Bezier.fromPoints(_lastPoints, widths, this);
50271             _lastPoints.shift();
50272             return curve;
50273         }
50274         return null;
50275     },
50276     
50277     calculateCurveWidths: function (startPoint, endPoint) {
50278         var velocity = this.velocity_filter_weight * endPoint.velocityFrom(startPoint) +
50279             (1 - this.velocity_filter_weight) * this._lastVelocity;
50280
50281         var newWidth = Math.max(this.max_width / (velocity + 1), this.min_width);
50282         var widths = {
50283             end: newWidth,
50284             start: this._lastWidth
50285         };
50286         
50287         this._lastVelocity = velocity;
50288         this._lastWidth = newWidth;
50289         return widths;
50290     },
50291     
50292     drawDot: function (_a) {
50293         var color = _a.color, point = _a.point;
50294         var ctx = this.canvasElCtx();
50295         var width = typeof this.dot_size === 'function' ? this.dot_size() : this.dot_size;
50296         ctx.beginPath();
50297         this.drawCurveSegment(point.x, point.y, width);
50298         ctx.closePath();
50299         ctx.fillStyle = color;
50300         ctx.fill();
50301     },
50302     
50303     drawCurve: function (_a) {
50304         var color = _a.color, curve = _a.curve;
50305         var ctx = this.canvasElCtx();
50306         var widthDelta = curve.endWidth - curve.startWidth;
50307         var drawSteps = Math.floor(curve.length()) * 2;
50308         ctx.beginPath();
50309         ctx.fillStyle = color;
50310         for (var i = 0; i < drawSteps; i += 1) {
50311         var t = i / drawSteps;
50312         var tt = t * t;
50313         var ttt = tt * t;
50314         var u = 1 - t;
50315         var uu = u * u;
50316         var uuu = uu * u;
50317         var x = uuu * curve.startPoint.x;
50318         x += 3 * uu * t * curve.control1.x;
50319         x += 3 * u * tt * curve.control2.x;
50320         x += ttt * curve.endPoint.x;
50321         var y = uuu * curve.startPoint.y;
50322         y += 3 * uu * t * curve.control1.y;
50323         y += 3 * u * tt * curve.control2.y;
50324         y += ttt * curve.endPoint.y;
50325         var width = curve.startWidth + ttt * widthDelta;
50326         this.drawCurveSegment(x, y, width);
50327         }
50328         ctx.closePath();
50329         ctx.fill();
50330     },
50331     
50332     drawCurveSegment: function (x, y, width) {
50333         var ctx = this.canvasElCtx();
50334         ctx.moveTo(x, y);
50335         ctx.arc(x, y, width, 0, 2 * Math.PI, false);
50336         this.is_empty = false;
50337     },
50338     
50339     clear: function()
50340     {
50341         var ctx = this.canvasElCtx();
50342         var canvas = this.canvasEl().dom;
50343         ctx.fillStyle = this.bg_color;
50344         ctx.clearRect(0, 0, canvas.width, canvas.height);
50345         ctx.fillRect(0, 0, canvas.width, canvas.height);
50346         this.curve_data = [];
50347         this.reset();
50348         this.is_empty = true;
50349     },
50350     
50351     fileEl: function()
50352     {
50353         return  this.el.select('input',true).first();
50354     },
50355     
50356     canvasEl: function()
50357     {
50358         return this.el.select('canvas',true).first();
50359     },
50360     
50361     canvasElCtx: function()
50362     {
50363         return this.el.select('canvas',true).first().dom.getContext('2d');
50364     },
50365     
50366     getImage: function(type)
50367     {
50368         if(this.is_empty) {
50369             return false;
50370         }
50371         
50372         // encryption ?
50373         return this.canvasEl().dom.toDataURL('image/'+type, 1);
50374     },
50375     
50376     drawFromImage: function(img_src)
50377     {
50378         var img = new Image();
50379         
50380         img.onload = function(){
50381             this.canvasElCtx().drawImage(img, 0, 0);
50382         }.bind(this);
50383         
50384         img.src = img_src;
50385         
50386         this.is_empty = false;
50387     },
50388     
50389     selectImage: function()
50390     {
50391         this.fileEl().dom.click();
50392     },
50393     
50394     uploadImage: function(e)
50395     {
50396         var reader = new FileReader();
50397         
50398         reader.onload = function(e){
50399             var img = new Image();
50400             img.onload = function(){
50401                 this.reset();
50402                 this.canvasElCtx().drawImage(img, 0, 0);
50403             }.bind(this);
50404             img.src = e.target.result;
50405         }.bind(this);
50406         
50407         reader.readAsDataURL(e.target.files[0]);
50408     },
50409     
50410     // Bezier Point Constructor
50411     Point: (function () {
50412         function Point(x, y, time) {
50413             this.x = x;
50414             this.y = y;
50415             this.time = time || Date.now();
50416         }
50417         Point.prototype.distanceTo = function (start) {
50418             return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
50419         };
50420         Point.prototype.equals = function (other) {
50421             return this.x === other.x && this.y === other.y && this.time === other.time;
50422         };
50423         Point.prototype.velocityFrom = function (start) {
50424             return this.time !== start.time
50425             ? this.distanceTo(start) / (this.time - start.time)
50426             : 0;
50427         };
50428         return Point;
50429     }()),
50430     
50431     
50432     // Bezier Constructor
50433     Bezier: (function () {
50434         function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
50435             this.startPoint = startPoint;
50436             this.control2 = control2;
50437             this.control1 = control1;
50438             this.endPoint = endPoint;
50439             this.startWidth = startWidth;
50440             this.endWidth = endWidth;
50441         }
50442         Bezier.fromPoints = function (points, widths, scope) {
50443             var c2 = this.calculateControlPoints(points[0], points[1], points[2], scope).c2;
50444             var c3 = this.calculateControlPoints(points[1], points[2], points[3], scope).c1;
50445             return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
50446         };
50447         Bezier.calculateControlPoints = function (s1, s2, s3, scope) {
50448             var dx1 = s1.x - s2.x;
50449             var dy1 = s1.y - s2.y;
50450             var dx2 = s2.x - s3.x;
50451             var dy2 = s2.y - s3.y;
50452             var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
50453             var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
50454             var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
50455             var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
50456             var dxm = m1.x - m2.x;
50457             var dym = m1.y - m2.y;
50458             var k = l2 / (l1 + l2);
50459             var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
50460             var tx = s2.x - cm.x;
50461             var ty = s2.y - cm.y;
50462             return {
50463                 c1: new scope.Point(m1.x + tx, m1.y + ty),
50464                 c2: new scope.Point(m2.x + tx, m2.y + ty)
50465             };
50466         };
50467         Bezier.prototype.length = function () {
50468             var steps = 10;
50469             var length = 0;
50470             var px;
50471             var py;
50472             for (var i = 0; i <= steps; i += 1) {
50473                 var t = i / steps;
50474                 var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
50475                 var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
50476                 if (i > 0) {
50477                     var xdiff = cx - px;
50478                     var ydiff = cy - py;
50479                     length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
50480                 }
50481                 px = cx;
50482                 py = cy;
50483             }
50484             return length;
50485         };
50486         Bezier.prototype.point = function (t, start, c1, c2, end) {
50487             return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
50488             + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
50489             + (3.0 * c2 * (1.0 - t) * t * t)
50490             + (end * t * t * t);
50491         };
50492         return Bezier;
50493     }()),
50494     
50495     throttleStroke: function(fn, wait) {
50496       if (wait === void 0) { wait = 250; }
50497       var previous = 0;
50498       var timeout = null;
50499       var result;
50500       var storedContext;
50501       var storedArgs;
50502       var later = function () {
50503           previous = Date.now();
50504           timeout = null;
50505           result = fn.apply(storedContext, storedArgs);
50506           if (!timeout) {
50507               storedContext = null;
50508               storedArgs = [];
50509           }
50510       };
50511       return function wrapper() {
50512           var args = [];
50513           for (var _i = 0; _i < arguments.length; _i++) {
50514               args[_i] = arguments[_i];
50515           }
50516           var now = Date.now();
50517           var remaining = wait - (now - previous);
50518           storedContext = this;
50519           storedArgs = args;
50520           if (remaining <= 0 || remaining > wait) {
50521               if (timeout) {
50522                   clearTimeout(timeout);
50523                   timeout = null;
50524               }
50525               previous = now;
50526               result = fn.apply(storedContext, storedArgs);
50527               if (!timeout) {
50528                   storedContext = null;
50529                   storedArgs = [];
50530               }
50531           }
50532           else if (!timeout) {
50533               timeout = window.setTimeout(later, remaining);
50534           }
50535           return result;
50536       };
50537   }
50538   
50539 });
50540
50541  
50542
50543  // old names for form elements
50544 Roo.bootstrap.Form          =   Roo.bootstrap.form.Form;
50545 Roo.bootstrap.Input         =   Roo.bootstrap.form.Input;
50546 Roo.bootstrap.TextArea      =   Roo.bootstrap.form.TextArea;
50547 Roo.bootstrap.TriggerField  =   Roo.bootstrap.form.TriggerField;
50548 Roo.bootstrap.ComboBox      =   Roo.bootstrap.form.ComboBox;
50549 Roo.bootstrap.DateField     =   Roo.bootstrap.form.DateField;
50550 Roo.bootstrap.TimeField     =   Roo.bootstrap.form.TimeField;
50551 Roo.bootstrap.MonthField    =   Roo.bootstrap.form.MonthField;
50552 Roo.bootstrap.CheckBox      =   Roo.bootstrap.form.CheckBox;
50553 Roo.bootstrap.Radio         =   Roo.bootstrap.form.Radio;
50554 Roo.bootstrap.RadioSet      =   Roo.bootstrap.form.RadioSet;
50555 Roo.bootstrap.SecurePass    =   Roo.bootstrap.form.SecurePass;
50556 Roo.bootstrap.FieldLabel    =   Roo.bootstrap.form.FieldLabel;
50557 Roo.bootstrap.DateSplitField=   Roo.bootstrap.form.DateSplitField;
50558 Roo.bootstrap.NumberField   =   Roo.bootstrap.form.NumberField;
50559 Roo.bootstrap.PhoneInput    =   Roo.bootstrap.form.PhoneInput;
50560 Roo.bootstrap.PhoneInputData=   Roo.bootstrap.form.PhoneInputData;
50561 Roo.bootstrap.MoneyField    =   Roo.bootstrap.form.MoneyField;
50562 Roo.bootstrap.HtmlEditor    =   Roo.bootstrap.form.HtmlEditor;
50563 Roo.bootstrap.HtmlEditor.ToolbarStandard =   Roo.bootstrap.form.HtmlEditorToolbarStandard;
50564 Roo.bootstrap.Markdown      = Roo.bootstrap.form.Markdown;
50565 Roo.bootstrap.CardUploader  = Roo.bootstrap.form.CardUploader;// depricated.
50566 Roo.bootstrap.Navbar            = Roo.bootstrap.nav.Bar;
50567 Roo.bootstrap.NavGroup          = Roo.bootstrap.nav.Group;
50568 Roo.bootstrap.NavHeaderbar      = Roo.bootstrap.nav.Headerbar;
50569 Roo.bootstrap.NavItem           = Roo.bootstrap.nav.Item;
50570
50571 Roo.bootstrap.NavProgressBar     = Roo.bootstrap.nav.ProgressBar;
50572 Roo.bootstrap.NavProgressBarItem = Roo.bootstrap.nav.ProgressBarItem;
50573
50574 Roo.bootstrap.NavSidebar        = Roo.bootstrap.nav.Sidebar;
50575 Roo.bootstrap.NavSidebarItem    = Roo.bootstrap.nav.SidebarItem;
50576
50577 Roo.bootstrap.NavSimplebar      = Roo.bootstrap.nav.Simplebar;// deprciated 
50578 Roo.bootstrap.Menu = Roo.bootstrap.menu.Menu;
50579 Roo.bootstrap.MenuItem =  Roo.bootstrap.menu.Item;
50580 Roo.bootstrap.MenuSeparator = Roo.bootstrap.menu.Separator
50581